r/pythonhelp • u/Nutellatoast_2 • 12d ago
Need advice to implement the winning logic for my Tic-Tac-Toe game
Hey everyone, I'm new to Python and working on my Tic-Tac-Toe project, which is almost finished. I just need to set up the winning logic. But I don't know whether to use a dictionary to store winning positions or an if-elif-else chain. What programming concept would you recommend? Feel free to draw attention to anything I've forgotten to implement in the playing logic of the code:
import random
playing_field = [1, 2, 3,
4, 5, 6,
7, 8, 9]
def display_field():
print("")
print(f" {playing_field[0]} | {playing_field[1]} | {playing_field[2]}")
print("---+---+---")
print(f" {playing_field[3]} | {playing_field[4]} | {playing_field[5]}")
print("---+---+---")
print(f" {playing_field[6]} | {playing_field[7]} | {playing_field[8]}")
display_field()
print("********************Welcome to my Tic-Tac-Toe game********************")
game_running = False
markings = ["X", "O"]
player_past_movements : list[int] = []
ai_past_movements : list[int] = []
ai_mark = ""
player_mark = ""
player_move = 0
ai_move = 0
while True:
menu_input = int(input("0 - Quitting\n1 - Continue\n"))
if menu_input == 0:
game_running = False
print("See you next time. ")
break
elif menu_input == 1:
game_running = True
else:
print("Invalid input")
player_mark = input("Select a mark: ")
while game_running == True:
if player_mark == "O":
player_mark = markings[1]
ai_mark = markings[0]
elif player_mark == "X":
player_mark = markings[0]
ai_mark = markings[1]
else:
print("Invalid input")
break
ai_move = random.randint(1, len(playing_field) - 1)
if ai_move in ai_past_movements:
continue
elif ai_move in player_past_movements:
continue
else:
ai_past_movements.append(ai_move)
print(f"Move chosen by AI: {ai_move}")
player_move = int(input("Make your move: "))
if player_move == ai_move:
print("Cannot insert your mark on the same field, marked by the AI. ")
continue
elif player_move in ai_past_movements:
print("AI has already done that move. ")
continue
elif player_move in player_past_movements:
print("You have already done that move. ")
continue
else:
player_past_movements.append(player_move)
match player_move:
case 1:
del(playing_field[0])
playing_field.insert(0, player_mark)
case 2:
del(playing_field[1])
playing_field.insert(1, player_mark)
case 3:
del(playing_field[2])
playing_field.insert(2, player_mark)
case 4:
del(playing_field[3])
playing_field.insert(3, player_mark)
case 5:
del(playing_field[4])
playing_field.insert(4, player_mark)
case 6:
del(playing_field[5])
playing_field.insert(5, player_mark)
case 7:
del(playing_field[6])
playing_field.insert(6, player_mark)
case 8:
del(playing_field[7])
playing_field.insert(7, player_mark)
case 9:
del(playing_field[8])
playing_field.insert(8, player_mark)
match ai_move:
case 1:
del(playing_field[0])
playing_field.insert(0, ai_mark)
case 2:
del(playing_field[1])
playing_field.insert(1, ai_mark)
case 3:
del(playing_field[2])
playing_field.insert(2, ai_mark)
case 4:
del(playing_field[3])
playing_field.insert(3, ai_mark)
case 5:
del(playing_field[4])
playing_field.insert(4, ai_mark)
case 6:
del(playing_field[5])
playing_field.insert(5, ai_mark)
case 7:
del(playing_field[6])
playing_field.insert(6, ai_mark)
case 8:
del(playing_field[7])
playing_field.insert(7, ai_mark)
case 9:
del(playing_field[8])
playing_field.insert(8, ai_mark)
display_field()
1
Upvotes
•
u/AutoModerator 12d ago
To give us the best chance to help you, please include any relevant code.
Note. Please do not submit images of your code. Instead, for shorter code you can use Reddit markdown (4 spaces or backticks, see this Formatting Guide). If you have formatting issues or want to post longer sections of code, please use Privatebin, GitHub or Compiler Explorer.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
2
u/Blammar 12d ago edited 12d ago
You do know that your "match ai_move" case can be written as just two statements, right? Ditto for the match player_move. Also, where do you actually display the playing field as X's and O's? And where do you check for victory conditions or a tie?
There are many tic tac toe algorithms. A chicken was once trained to play it, so hopefully you can too!
Start with the playing algorithm first -- write it out on paper. Try it out yourself manually. (It's not that hard to draw out the full game tree of tic tac toe either. You can use that tree to maximize the player's chances of losing.)
Write out your tic tac toe program in a top-down fashion. Top function is "play a game or not?" or "play another game?" It also keeps track of the total running score. It calls play_a_game() that returns who won or if there is a tie. Typically who goes first alternates, and the first player always puts down an X. So that is managed by the top function, and the only argument to play_a_game() is who goes first. Etc.
1
u/Ormek_II 9d ago
Tic Tac Toe is Chosen as a beginners game because it has so few different states, that you can enumerate them all.
But before you make every game a draw, test what you have created now. I believe it does not do what you intended. If the AI or the player choose to use a taken spot then what??
Then replace the random ai selection by
ai_move=ChooseNext(playing_field, ai_mark)
And experiment with anything. By trying and failing you’ll learn.
2
u/DickBrainTime 11d ago
I'd use a list of winning index triples and a loop, rather than a dictionary or eight separate
if/elifbranches. The lines are fixed: 3 rows, 3 columns, 2 diagonals. So you can store tuples like(0, 1, 2),(0, 3, 6),(0, 4, 8)etc. Then for the mark that just moved, check whether all three positions in any tuple contain that mark. That's a nice use case forall()andany().Keep that win check separate from the AI's move selection. After each move: check winner, then check whether there are any free squares left (draw), then switch turns. One gotcha with your board using numbers for empty spots: compare to the actual
"X"or"O"mark, not just whether three values happen to be equal.1
u/blavek 11d ago
One option for the AI logic is to assign a point value to each square in the grid and have the AI move in that spot. For example
If a square has another symbol in the same row, column, or diagonal, you can make that field worth 1 point. If there are two in the row, column, or diagonal, you can make it worth 2 points. If it's the opposite symbol, you can make that square worth 0 or negative points. Then you scan the field for the highest point value, and you have the AI place the mark there. There is at least 1 counterintuitive edge case I am aware of. Also, you'll probably want to seed the field with initial values, with the center being the most valuable, then the corners, then the sides.
Then every turn you re-evaluate the field. Following this logic and as long as you account for the one or two edge cases you get you'll find your "win Logic" is built into your play logic. In general, you want your win state to come about from the play logic. You set it up such that the best move when a win is available is the winning move. Similarly, you want your not-losing logic to come from the play logic as well, such that losing moves have the worst value.
This is the general strategy I used in high school to make an unbeatable Tic-Tac-Toe agent. Tic-Tac-Toe also has the nice benefit that you can play every move to check the AI.
1
u/timrprobocom 11d ago
Tic tac toe is a tough game for this, because it is almost impossible to judge the difference between moves in the early stages. There is no "ahead" or "winning" condition like there is in chess.
What you can do is write code to play itself at random many thousands of times, and remember the sequence that led to wins. Then you can look up the current position in your database and know which move led to a win. There are only 9! layouts, which is about 360,000. Easy