Hacker News new | ask | show | jobs
by DylanSp 948 days ago
Did you find a clever/elegant way of detecting tic-tac-toe winning moves? I wrote a simple implementation in Typescript several years ago; I tried some approaches with representing the cells as a 2D array and looping over the rows/columns, but I ended up just using a flat array and hardcoding the sets of cells to check [1]. If memory serves, using a flat/1D array made other parts of the code easier, not just the game logic, though that might have been due to my inexperience; I was just starting to learn React/frontend dev at the time.

[1] https://github.com/DylanSp/tic-tac-toe-react/blob/master/src...

2 comments

The most clever way I have found is through a mathematic structure with the same shape, i.e., a magic square:

  2 7 6
  9 5 1
  4 3 8
Here, if a triplet of one player's cells sums to 15, that player has won.
2D array was my approach, it wasn’t super clever or anything, but it got the job done - and it worked for n-size boards with n players, not just the traditional 2 player 3x3 board, that was the fun part