Hacker News new | ask | show | jobs
by mock-possum 948 days ago
Aside from the article, I do really like the idea of implementing board game rules as a coding exercise. The only one I’ve ever been confronted with was tic tac toe, and I remember really having fun with the detecting winning moves part.
2 comments

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...

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
I've been playing around with making a version of tic-tac-toe that's interesting to grown-ups. Experimenting with rules a lot as you'll see. (I think 1357 is probably the best but not sure.)

https://5-by-5.edjohnsonwilliams.co.uk

https://github.com/edjw/5_by_5_tictactoe

That's really cool! Need to find someone to play this with now :)

Though the counting seems a bit weird. Two overlapping lines of 5 seems to count as "1 two, 2 five". I also managed to get two overlapping fours to count as "2 two, 2 four". Maybe I just don't understand how it's supposed to work?

Thanks! It’s kind of hard to understand what you mean without screenshots. Also there are so many variations that I’m not sure which rules you’re playing with. My dad is the only person who’s played it apart from me and so far if he finds something he thinks is a counting error it’s actually been counting right and it was a UX thing about the rule-writing