
Responsive Tic-tac-toe made with React
Design comparison
Solution retrospective
Last time I did this project I decided to leave it for the future, now that I have more knowledge in react I decided to finish it. I'm happy with the fact that it is functional and responsive and although I'm not very happy with some things in the code. Also I wasn't sure how to do one feature specified in the design (highlighting the winning row / col / diagonal) so I left it unimplemented.
What challenges did you encounter, and how did you overcome them?In fact, the whole project surprisingly wasn't that easy. The state management in the application was probably the most challanging for me. For a while I used only jotai, but later I abstracted some states in reducer because the code became hard to read.
What specific areas of your project would you like help with?I would like to hear how you dealt with state management and determining the winner of the game as I think these are things I could improve on.
Please log in to post a comment
Log in with GitHubCommunity feedback
- P@kim-fransson
Hi!
Nice work on completing the challenge! For tic tac toe I actually think its easier to "calculate" a winner by hard coding the "winning combinations" and then check if all values are the same for a "line".
export function calculateWinner(squares: Squares) { const lines = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6], ]; for (let i = 0; i < lines.length; i++) { const [a, b, c] = lines[i]; if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) { return squares[a]; } } return null; }
Then the game is over when we have a winner or if there are not more turns.
export function calculateTurnsLeft(squares: Squares) { return squares.filter((square) => !square).length; }
Making the code a bit simpler and easier to understand, and reason with.
But for a more complex game like four in a row, hard coding the winning lines will probably not suffice :D
Marked as helpful - @tsotneforester
generally favourable work! 👍
Join our Discord community
Join thousands of Frontend Mentor community members taking the challenges, sharing resources, helping each other, and chatting about all things front-end!
Join our Discord