JavaScript TicTacToe if… Winner detection

前端 未结 7 1625
借酒劲吻你
借酒劲吻你 2020-12-21 09:22

I just have a small problem.

The final assignment in my computer science class is to write a game of Tic-Tac-Toe in JavaScript. The game works by clicking on cells w

7条回答
  •  醉酒成梦
    2020-12-21 09:46

    I see you said you have searched Stack Overflow for similar questions. I understand how being new to programming, it's not easy to read something in another language but the fundamental idea is there. Here is a link where this is already done: Algorithm for Determining Tic Tac Toe Game Over.

    That being said, there are basically 3 ways to win in the game, and you are headed in the right direction with your vars.

    The three ways to win are

    1. 3 matches across
    2. 3 matches down
    3. 3 matches diagonal.

    The easy parts are the rows and columns, simply for loop through each row/column and see if you get three matches, if you do, then you can declare a winner.

    Non-efficient Pseudo-code Example:

    if pic1, pic2, and pic3 are the same
    alert user X or O has won
    end the game.
    

    Repeat for row 2, and row 3.

    if pic1, pic4, and pic7 are the same
    alert user X or O has won
    end the game.
    

    Repeat for column 2 and 3.

    The diagonal can be done in a simple fashion as well, without using the two dimensional array in the example. There are basically only two diagonal win possibilities:

    1. var 1, 5, 9 match
    2. var 3, 5, 7 match.

    Anything else you can end the game in a draw. I would recommend using the counter as shown in the link example.

    Good luck! -- edit for clarity --

提交回复
热议问题