From 9500a68ae790102bb945e0ec078e664c0bba06d2 Mon Sep 17 00:00:00 2001 From: Cory Date: Wed, 13 Mar 2024 13:38:20 -0400 Subject: [PATCH] Fixed TTTGame.check_winner. What I changed Added 8 cases to check for to see if someone won: three rows, three columns and two diagonals. Why I changed it TTTGame.check_winner always reported false, so the game only ended when the board was full even if someone should have won. Estimate for remaining time to finish assignment: [Like a few hours assuming my students don't rip a door off its hinges in the bathroom again...] --- notes.md | 2 ++ ttt/game.py | 16 ++++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/notes.md b/notes.md index 3750dca..75c8ae2 100644 --- a/notes.md +++ b/notes.md @@ -30,6 +30,8 @@ and it's your turn, which action would you take? Why? ---+---+--- ---+---+--- ---+---+--- ---+---+--- | | | | O | | | | +For the first one, I would put an X on the rightmost cell in the middle row. This would allow me to get a win. For the second one, I would put it in the same position as I would have in the first. This prevents O from winning on the next turn and puts me one turn away from winning, assuming the opponent doesn't block that route. For the third one, I would put it in the top left. This gives me two possible ways to win, and since the opponent only has one turn after mine before I get to go again, they cannot stop me from winning. For the last one, I would put it in the center. The opponent has to block by placing an O in the bottom right, and then I can put an X in the leftmost cell of the middle row. This leads to two possible ways to win again. + ### Initial game state You can get the inital game state using game.get_initial_state(). diff --git a/ttt/game.py b/ttt/game.py index 2f0e302..2ed4150 100644 --- a/ttt/game.py +++ b/ttt/game.py @@ -58,4 +58,20 @@ class TTTGame: def check_winner(self, state, symbol): "Checks whether the player with `symbol` has won the game." + if state["board"][0] == symbol and state["board"][1] == symbol and state["board"][2] == symbol: + return True + elif state["board"][3] == symbol and state["board"][4] == symbol and state["board"][5] == symbol: + return True + elif state["board"][6] == symbol and state["board"][7] == symbol and state["board"][8] == symbol: + return True + elif state["board"][0] == symbol and state["board"][3] == symbol and state["board"][6] == symbol: + return True + elif state["board"][1] == symbol and state["board"][4] == symbol and state["board"][7] == symbol: + return True + elif state["board"][2] == symbol and state["board"][5] == symbol and state["board"][8] == symbol: + return True + elif state["board"][0] == symbol and state["board"][4] == symbol and state["board"][8] == symbol: + return True + elif state["board"][2] == symbol and state["board"][4] == symbol and state["board"][6] == symbol: + return True return False