A game of TicTacToe written in JavaScript ⭕

Поделиться
HTML-код
  • Опубликовано: 27 дек 2024

Комментарии •

  • @BroCodez
    @BroCodez  2 года назад +134

    const cells = document.querySelectorAll(".cell");
    const statusText = document.querySelector("#statusText");
    const restartBtn = document.querySelector("#restartBtn");
    const winConditions = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6]
    ];
    let options = ["", "", "", "", "", "", "", "", ""];
    let currentPlayer = "X";
    let running = false;
    initializeGame();
    function initializeGame(){
    cells.forEach(cell => cell.addEventListener("click", cellClicked));
    restartBtn.addEventListener("click", restartGame);
    statusText.textContent = `${currentPlayer}'s turn`;
    running = true;
    }
    function cellClicked(){
    const cellIndex = this.getAttribute("cellIndex");
    if(options[cellIndex] != "" || !running){
    return;
    }
    updateCell(this, cellIndex);
    checkWinner();
    }
    function updateCell(cell, index){
    options[index] = currentPlayer;
    cell.textContent = currentPlayer;
    }
    function changePlayer(){
    currentPlayer = (currentPlayer == "X") ? "O" : "X";
    statusText.textContent = `${currentPlayer}'s turn`;
    }
    function checkWinner(){
    let roundWon = false;
    for(let i = 0; i < winConditions.length; i++){
    const condition = winConditions[i];
    const cellA = options[condition[0]];
    const cellB = options[condition[1]];
    const cellC = options[condition[2]];
    if(cellA == "" || cellB == "" || cellC == ""){
    continue;
    }
    if(cellA == cellB && cellB == cellC){
    roundWon = true;
    break;
    }
    }
    if(roundWon){
    statusText.textContent = `${currentPlayer} wins!`;
    running = false;
    }
    else if(!options.includes("")){
    statusText.textContent = `Draw!`;
    running = false;
    }
    else{
    changePlayer();
    }
    }
    function restartGame(){
    currentPlayer = "X";
    options = ["", "", "", "", "", "", "", "", ""];
    statusText.textContent = `${currentPlayer}'s turn`;
    cells.forEach(cell => cell.textContent = "");
    running = true;
    }



    Document


    Tic Tac Toe












    Restart


    .cell{
    width: 75px;
    height: 75px;
    border: 2px solid;
    box-shadow: 0 0 0 2px;
    line-height: 75px;
    font-size: 50px;
    cursor: pointer;
    }
    #gameContainer{
    font-family: "Permanent Marker", cursive;
    text-align: center;
    }
    #cellContainer{
    display: grid;
    grid-template-columns: repeat(3, auto);
    width: 225px;
    margin: auto;
    }

    • @nouser1715
      @nouser1715 2 года назад +1

      thanks so much !!

    • @cod3ddy74
      @cod3ddy74 Год назад

      thanks bro bro code

    • @user-fb5ob7vs4r
      @user-fb5ob7vs4r Год назад

      hhvv

    • @prathamrai-uv4vl
      @prathamrai-uv4vl Год назад

      index.js:23 Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
      on the line need helppppp...........
      const cells = document.querySelectorAll(".cell");
      const statusText = document.querySelector("#statusText");
      const restartBtn = document.querySelector("#restartBtn");
      const winConditions =[
      [0, 1, 2],
      [3, 4, 5],
      [6, 7, 8],
      [0, 3, 6],
      [1, 4, 7],
      [2, 5, 8],
      [0, 4, 8],
      [2, 4, 6]
      ];
      let options = ["", "", "", "", "", "", "", "", ""];
      let currentPlayer= "X";
      let running = false;
      initializeGame();
      function initializeGame(){
      cells.forEach(cell => cell.addEventListener("click", cellClicked));
      restartBtn.addEventListener("click", restartGame);
      statusText.textContent = `${currentPlayer}'s turn`;
      running = true;
      }
      function cellClicked(){
      const cellIndex = this.getAttribute("cellIndex");
      if(options[cellIndex] != "" || !running) {
      return;
      }
      updateCell(this, cellIndex);
      checkWinner();
      }
      function updateCell(cell, index){
      options[index] = currentPlayer;
      cell.textContent = currentPlayer;
      }
      function changePlayer(){
      currentPlayer = (currentPlayer == "X") ? "O": "X";
      statusText.textContent = `${currentPlayer}'s turn`;
      }
      function checkWinner(){
      let roundWon = false;
      for(let i = 0; i < winConditions.length; i++ ){
      const conditions = winConditions[i];
      const cellA = options[condition[0]];
      const cellB = options[condition[1]];
      const cellC = options[condition[2]];
      if(cellA == "" || cellB == "" || cellC){
      roundWon = true;
      break;
      }
      }
      if(roundWon){
      statusText.textContent = `${currentPlayer} wins!`;
      running = false;
      }
      else if(!options.includes("")){
      statusText.textContent = `Draw!`;
      running = false;
      }
      else{
      changePlayer();
      }
      }
      function restartGame(){
      currentPlayer = "X";
      options = ["", "", "", "", "", "", "", "", ""];
      statusText.textContent = `${currentPlayer}'s turn`;
      celss.forEach(cell => cell.textContent)
      }

    • @myematic
      @myematic Год назад

      Thank you!

  • @eumm11
    @eumm11 Год назад +17

    i'm learning to code and built this game during the last few days but my solution it's so clumsy compared to yours.. thank you for sharing this, is very helpful to learn, your solution is amazing!

  • @pedrocossio9462
    @pedrocossio9462 2 года назад +7

    You have saved my life made understanding Javascript a bit easier for me

  • @ShimmerBodyCream
    @ShimmerBodyCream Год назад +11

    Thank you for including the code in the comment! I had my HTML filed messed up. Thank you for sharing your project with us.

  • @richardchimama8807
    @richardchimama8807 2 года назад +7

    I have learned a lot in a few minutes. Thank you!

  • @samoraselim6338
    @samoraselim6338 9 месяцев назад

    Thanx for your simplicity ,tried to do this game using another video was difficult, too much code lines
    Thank you for including the code in the comment😍

  • @qqszad
    @qqszad 2 года назад +8

    bro your videos help so much. thank 10/10

  • @navidnasr4587
    @navidnasr4587 3 месяца назад

    That was very clean and understandable. Thanks a lot😍

  • @TyronneRatcliff
    @TyronneRatcliff 3 месяца назад

    Awesome content! You couldn't have written this code any better.

  • @cnox910
    @cnox910 2 года назад +3

    Continue dude'

  • @RyanDoi
    @RyanDoi 2 года назад +5

    I love this guy

  • @fr1endsies
    @fr1endsies 2 года назад +2

    Yo Bro Code! Thanks for this play along video. I learned some new things along the way!

  • @santiagovalle450
    @santiagovalle450 2 года назад +1

    BROOO thankyou so much, this really helped and the tutorial was really easy to use as well :)

  • @charlestiffany6533
    @charlestiffany6533 11 месяцев назад

    since we are not saving anything in any kind of storage we can just just do this function restartGame(){
    location.reload();
    }; to reset the game. im pretty new to js so maybe theres a good reason bro didnt do this but it does work.

  • @saiyyaaratrading4432
    @saiyyaaratrading4432 2 года назад +2

    after the end of the match, cant we add any other tag for sharing our result with others in social media apps?

  • @CoriePrater
    @CoriePrater 9 месяцев назад

    Thank you for the learning experience! Is there a way to change the X and O's to an image? Would I have to stare the image in a variable? Thank you again!

    • @michaellariosa3406
      @michaellariosa3406 7 месяцев назад

      const yourCell = document.querySelector(".yourCell"); const insertX = document.createElement("img"); const insertO = document.createElement("img"); insertX.src = imgX.jpg; insertO.src = imgO.jpg; yourCell.append(insertX);

  • @lautaroscolamiero8384
    @lautaroscolamiero8384 Год назад

    Nice code man thanks!

  • @yashu_vocalist
    @yashu_vocalist Год назад

    08:35 is hoisting of the 1st function.

  • @ehidaniel2498
    @ehidaniel2498 2 года назад +4

    please why did you pass in this and cellIndex as arguments in the updateCell() function under the cellClicked() function
    🙂

    • @izikki11499
      @izikki11499 2 года назад +3

      How I understand it:
      Pretty much, THIS is referring to the cell you just clicked (THIS one),
      And the cellIndex comes from the HTML elements we made for the cells, we made that attribute named ‘cellIndex’ and gave it a number for what cell it is in our options[ ] array
      Pretty much, you pass those in to the updateCell( ) and it updates whatever cell you clicked on(THIS), by setting its text content to whatever the current player is (x or o) and uses the cell index attribute to update the options [] array, where all our cells are which are empty to start with
      Hope I explained it okay :-P

    • @michaellariosa3406
      @michaellariosa3406 7 месяцев назад

      It tells the updateCell function which cell to change the textContent for. You're passing it as 'this', calling it 'cell' in the updateCell function, and then updating the text of it via cell.textContent = currentPlayer. He could have done the update of the text and the addition of the clicked sell to the options array in the cellClicked function, but to keep it clean, he did it as a separate function and just passed it along. like this:
      function cellClicked () {
      const cellIndex = this.getAttribute("cellIndex")
      console.log(this)
      if (options[cellIndex] != "" || !running){
      return;
      }
      options[cellIndex] = player;
      this.textContent = player;
      checkWinner();
      }

  • @faiqchanel5001
    @faiqchanel5001 Год назад

    Thanks for help love you bro

  • @classicimaging21
    @classicimaging21 Год назад +1

    Got it 🤩

  • @ashwinr8317
    @ashwinr8317 2 года назад

    please upload a Zero to hero video for wordpress bro ! the way of your teaching was just amazing accept my request bro 😫🙏.

  • @radhikaiyer4119
    @radhikaiyer4119 2 года назад

    excellent

  • @Error-ff2sg
    @Error-ff2sg 2 года назад +3

    Uhh can i ask something
    Does any reason for you not using onclick or you just not want use it ?

    • @zaidkhan_epic
      @zaidkhan_epic Год назад +2

      using addEventListener makes the code look more maintained and readable plus easy

  • @noahnyman4420
    @noahnyman4420 2 года назад

    underrated

  • @rajat-s-kale1771
    @rajat-s-kale1771 2 года назад +1

    Awesome

  • @abdullahjama8404
    @abdullahjama8404 11 месяцев назад

    easy loved it except the last part thats the wining game foreach with some and every method can run through the global variable winning condition, otherwise loved it, wish u implemented some Ai too , amazing and very clean code , can u talk about writing clean code?

  • @stanleyjr-vhokie
    @stanleyjr-vhokie Год назад

    thanks, alot of help.

  • @dragomirpetrov5600
    @dragomirpetrov5600 2 года назад +1

    Are any of these available in Java, or should I just mod it 🤔

  • @sanathrayala2745
    @sanathrayala2745 2 года назад +1

    Great video
    Also do a video on todo list

  • @boratsagdiyev522
    @boratsagdiyev522 6 месяцев назад

    Help! I under some of the logic of this game but I'm confused as to how do you know what you have to do next?

  • @irawadeep.6607
    @irawadeep.6607 Год назад +3

    Hi, I find some error when the game end and got the winner. The current winner is not match with the result ex. the "X" win but it display "O" win. Is there any suggestion to fix that please?

    • @hiba-o9w
      @hiba-o9w Год назад

      Im facing the same problem! Did u fix it?

    • @irawadeep.6607
      @irawadeep.6607 Год назад

      @@hiba-o9w no, not yet🥹

    • @hillarymapondera4122
      @hillarymapondera4122 11 месяцев назад

      Hi @@hiba-o9w I noticed the same issue in my code however I managed to fix the issue. What I understood was that suppose currentPlayer === "X" it means "X" is about to make his move and if "X" wins because of the order our functions are being called the changePlayer() function is called first before Checkwinner() function thus making the currentPlayer === "0" as a result when we display the winner if we use the currentPlayer variable it will be "0" thus it will be the opposite of the true winner.
      so to Fix this issue before displaying who the winner is, I reversed the current player as follows
      winner = (currentPlayer === "X") ? "O": "X"; and then display the winner on winning statusText. hope its gonna be helpful :)

  • @Xan_Mas
    @Xan_Mas 2 месяца назад

    I love the video but I am having so much problems in my code, I am copying like you do but I dont get the same results when I go to live server...

  • @RtzVi_
    @RtzVi_ 2 года назад +5

    I am new in the code things so I have a question. After I made the game how can I see the game like he sees it in the right of the screen

    • @kubitte
      @kubitte 2 года назад +5

      If you are using visual studio code, download ''live server'' extension. Then go to your html file and right click and select ''open with live server''.

    • @rainbowpizza7599
      @rainbowpizza7599 2 года назад

      Open two tabs simultaneously side-by-side, the editor where you code and the browser where it displays. Change the code and refresh after every save or install the live server extension 🥂

  • @lucabinder9829
    @lucabinder9829 2 года назад +1

    🔥

  • @uchennafelix3829
    @uchennafelix3829 2 года назад +2

    Sir, is it possible to change the color of the "X" and the "O"
    I mean "X" can be red and the other green

    • @zaidkhan_epic
      @zaidkhan_epic Год назад

      Yes its actually possible you can do it with css

    • @MeowKiritoMeow
      @MeowKiritoMeow Год назад

      just go to the cell class and change the color attribute

    • @michaellariosa3406
      @michaellariosa3406 7 месяцев назад

      function updateCell (cell, index) {
      options[index] = currentPlayer;
      if (currentPlayer == "X") {
      document.getElementById(`cell${index}`).style.color = "red";
      cell.textContent = currentPlayer;
      } else if (currentPlayer == "O") {
      document.getElementById(`cell${index}`).style.color = "green";
      cell.textContent = currentPlayer;
      }
      }

  • @Joshses
    @Joshses 26 дней назад

    delete current player at restartGame and change it to:
    if (Math.random() < 0.5) {
    currentPlayer = "X";
    } else {
    currentPlayer = "O";
    };
    IF YOU WANT THAT A RANDOM PLAYER GETS CHOOSEN

  • @ji_nvnc4113
    @ji_nvnc4113 2 года назад +5

    when I click on the restartBtn I can't replay, does someone has an idea ?

    • @recursion.
      @recursion. 2 года назад

      post your code it's prob some error somehwere

    • @joyceasante8292
      @joyceasante8292 Год назад

      For anyone who has the same issue, check to see if you made a typo in your code.
      The reason why my code was not working is because I wrote "#restartBn" instead of "#restartBtn".

  • @EnvergadoGames
    @EnvergadoGames 5 месяцев назад

    this was too hard hand too fast to me thb, many things i find confusing, is there anything before this that is easier step? i have done an rps game, blogpost and todolist, any tips on what my next step is?

  • @uuganbayarulziibaatar9
    @uuganbayarulziibaatar9 18 дней назад

    Hi, why on 26row "this" writen ?

  • @noyaaa1904
    @noyaaa1904 2 года назад

    hey, i have a question. Do you maybe have the code just in Pyscript?

  • @wlw113
    @wlw113 2 года назад +13

    I have error at 25 line restartBtn.addEventListener is not a function. Pls help

    • @Megapolis199
      @Megapolis199 2 года назад +1

      Same shit for restartBtn. Cannot read properties of null (reading 'addEventListener')

    • @artenisalija
      @artenisalija 2 года назад +2

      you need to put the script tag after the HTML in the index.html and make sure you have used # when declaring the const and the right id. this solved it for me.

    • @artenisalija
      @artenisalija 2 года назад

      @@Megapolis199 you need to put the script tag after the HTML in the index.html and make sure you have used # when declaring the const and the right id. this solved it for me.

    • @michaellariosa3406
      @michaellariosa3406 7 месяцев назад

      @@artenisalija or put it at the beginning and use "defer".. like this:

    • @nimgol03
      @nimgol03 5 месяцев назад

      Did you fix it by now ?

  • @rahulchaudhary3508
    @rahulchaudhary3508 2 года назад +2

    I'm getting a type error saying this.getAttribute is not a method, any help?

    • @ziga1998
      @ziga1998 2 года назад +1

      Remove the cellClicked function, and write the code directly inside cell.addEventListener()..
      Like this
      cells.forEach((cell) =>
      cell.addEventListener("click", (e) => {
      const cellIndex = e.target.getAttribute("cellIndex");
      console.log(cellIndex);
      if (options[cellIndex] != "" || !running) {
      return;
      }
      updateCell(e.target, cellIndex);
      changePlayer();
      checkWinner();
      })
      );

  • @fireworkcat7786
    @fireworkcat7786 Год назад

    game stops working after one win, gonna try and fix that

  • @gamerfx685
    @gamerfx685 Год назад +1

    am stuck at status text it says handwork.html:71 Uncaught TypeError: Cannot set properties of null (setting 'textContent')
    at initializeGame

    • @zaidkhan_epic
      @zaidkhan_epic Год назад

      The error message you're encountering, "Uncaught TypeError: Cannot set properties of null (setting 'textContent')" typically indicates that you are trying to set the textContent property of a variable that is currently null. This can happen when you're trying to manipulate an element in your HTML document using JavaScript, but the element with the specified identifier doesn't exist in the DOM.

  • @ArpitaChoudhury_00
    @ArpitaChoudhury_00 26 дней назад

    🙏🙏

  • @radhikaiyer4119
    @radhikaiyer4119 2 года назад

    eccellent

  • @Kaylebsyoutube
    @Kaylebsyoutube 7 месяцев назад

    It won’t let me actually play it I tried and copied all of the stuff but it doesn’t work the text, button is there but not working, and board is good though (no errors in vscode though)

  • @EmilianEKAMA
    @EmilianEKAMA 9 месяцев назад

    I tried coping your code words for words but it didn’t work

  • @bodyaoliynik2350
    @bodyaoliynik2350 2 года назад +5

    Please someone give me advise.How I can won't forget what I learned?

  • @Youss02
    @Youss02 2 года назад +1

    hey bro, can you help me? i copied your css like in the video , but the scare wont place as i wanted can you help me? srry for my bad english

    • @Youss02
      @Youss02 2 года назад +1

      square*

  • @ZarifTazwar-j3u
    @ZarifTazwar-j3u Год назад

    bro my tic tac is showing on the website but, all the gaps were autofilled, even the restart buttons are not working.So i checked my whole code,but there is no mistake.how to solve this problem.Any suggetions pls?

  • @samifly2753
    @samifly2753 Год назад

    👍

  • @lavenderhaze-bh4ex
    @lavenderhaze-bh4ex 6 месяцев назад +1

    howww i still dont get it

    • @bsnssmndoble
      @bsnssmndoble 6 месяцев назад +1

      I only get it after several weeks of writing the code by just repeating it 😅

  • @nivethashankar8221
    @nivethashankar8221 Год назад

    RestartGame is not a function. Pls help

  • @lakshcoder
    @lakshcoder 5 месяцев назад

    statusText.textContent = `${currentPlayer}'s turn`
    not showing any text all the spellings are correct can anyone please help me

  • @emersonperalesvillanueva8568
    @emersonperalesvillanueva8568 2 года назад

    and the code in github? xd

  • @user-wy2hn8ul6b
    @user-wy2hn8ul6b Год назад

    Didn’t work😢

  • @supreme-soft
    @supreme-soft 2 года назад +2

    Instead of just writing code in bullet speed please do some explanation as well my Big Bro 💝.

  • @JustinUltamit
    @JustinUltamit 7 месяцев назад

    random comment
    random comment

  • @linelaine3597
    @linelaine3597 2 года назад +1

    why it did not word at “ restartBtn.addEventListener(“click”, resetGame); ”😢

    • @dhiyanabdurazack5257
      @dhiyanabdurazack5257 2 года назад

      it is onclick

    • @fazrikurniawan9643
      @fazrikurniawan9643 2 года назад +1

      Go back to index js, ensure that cons no 2 & 3 "document.queryselector" not "document.queryselectorAll"

    • @artenisalija
      @artenisalija 2 года назад

      you need to put the script tag after the HTML in the index.html and make sure you have used # when declaring the const and the right id. this solved it for me.

    • @yushgisor2125
      @yushgisor2125 8 месяцев назад

      i did it like this ,document.getElementById("restartBtn").onclick = restartGame();

    • @lavenderhaze-bh4ex
      @lavenderhaze-bh4ex 6 месяцев назад

      @@artenisalija how ???