good day everyone, I’m trying to implement a tic tac toe game project in [Python 3.9] and in my code I have created a sentence to assign which player take which letter whether x or o and I have created many statements but they didn’t work , kindly if anyone could assist to have a look on my code , I would be grateful.
import random
board = [" ", " ", " ", " ", " ", " ", " ", " ", " ", " "]
game_letters = [‘X’, ‘O’]
player1 = 0
player2 = 1
#—±–±–
#—±–±–
def draw_board(board): print(‘---------’) print(board[1] , ‘|’ , board[2] , ‘|’ , board[3]) print(‘---------’) print(board[4] , ‘|’ , board[5] , ‘|’ , board[6]) print(‘---------’) print(board[7] , ‘|’ , board[8] , ‘|’ , board[9]) print(‘---------’)
def main(): player1 = 0 player2 = 1 draw_board(board) print(“Welcome to TIC TAC TOE Game”) player_1 = print("Player 1 please enter your name: ") player_1 = input().upper() player_2 = print("Player 2 please enter your name: ") player_2 = input().upper() turn = input(“Player " + str(player_1) + " would you like to choose X or O?”) .upper() print(str(player_1) + " take : " + str(this_player) + str(player_2) + " take : " + str(this_player))
while True:
draw_board(board)
move = int(input(" Make a move (X): "))
valid_move = [ ]
for position in range(9):
if board[position]==0:
valid_move.append(position)
if move in valid_move:
break
print("illegal move")
board[move] = str("X")
"""if board[move] == str("X") or board[move] == str("O"):
print("Please make another move ")"""
draw_board(board)
move_2 = int(input(" Make a move (O): "))
valid_move= [ ]
for position in range(9):
if board[position]==0:
valid_move.append(position)
if move in valid_move:
break
print("illegal move")
board[move_2] = str("O")
"""if board[move_2] == str("X") or board[move] == str("O"):
print("Please make another move ")"""
# player_1 choices
if board[1] == board[2] == board[3] == "X": #across the top row
print(str(player_1) + "wins" )
break
elif board[4] == board[5] == board[6] == "X": #across the middle row
print(str(player_1) + "wins" )
break
elif board[7] == board[8] == board[9] == "X": #across the bottom row
print(str(player_1) + "wins" )
break
elif board[1] == board[4] == board[7] == "X": #first column
print(str(player_1) + "wins" )
break
elif board[2] == board[5] == board[8] == "X": #second column
print(str(player_1) + "wins" )
break
elif board[3] == board[6] == board[9] == "X": #third column
print(str(player_1) + "wins" )
break
elif board[1] == board[5] == board[9] == "X": #left diagonal
print(str(player_1) + "wins" )
break
elif board[3] == board[5] == board[7] == "X": #right diagonal
print(str(player_1) + "wins" )
break
# player_2 choices
if board[1] == board[2] == board[3] == "O": #across the top row
print(str(player_2) + "wins" )
break
elif board[4] == board[5] == board[6] == "O": #across the middle row
print(str(player_2) + "wins" )
break
elif board[7] == board[8] == board[9] == "O": #across the bottom row
print(str(player_2) + "wins" )
break
elif board[1] == board[4] == board[7] == "O": #first column
print(str(player_2) + "wins" )
break
elif board[2] == board[5] == board[8] == "O": #second column
print(str(player_2) + "wins" )
break
elif board[3] == board[6] == board[9] == "O": #third column
print(str(player_2) + "wins" )
break
elif board[1] == board[5] == board[9] == "O": #left diagonal
print(str(player_2) + "wins" )
break
elif board[3] == board[5] == board[7] == "O": #right diagonal
print(str(player_2) + "wins" )
break
else:
print(" It's a Tie ")
print("Game Over")
def next_player(this_player): return (this_player+1)%2
if name == ‘main’: main()
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Hi,
@mindintelligence wroteI have created a sentence to assign which player take which letter whether x or o
and I have created many statements but they didn’t work
Your function main() assigns a letter to the player but its invocation is put at the end of the script (and it is conditional for some reason). You should move the invocation to the place before the part of the code that carries on the game. I modified your code a bit putting some comments into it. Look at the snippet below.
import random
board = [" ", " ", " ", " ", " ", " ", " ", " ", " ", " "]
game_letters = ['X', 'O']
# Y: players' names are strings rather than integers, so initial values of corresponding variables should be empty strings
player1 = ''
player2 = ''
# Y: I have no idea what this is for, however, interpreter accepts it :-)
# Y: possibly, it is a result of lost of formatting after pasting the code into DO editor
1 | 2 | 3
4 | 5 | 6
7 | 8 | 9
def draw_board(board):
print('———')
print(board[1] , '|' , board[2] , '|' , board[3])
print('———')
print(board[4] , '|' , board[5] , '|' , board[6])
print('———')
print(board[7] , '|' , board[8] , '|' , board[9])
print('———')
# Y: I created this function to simply find opposite letter to the letter held by variable turn
# Y: for learning purposes you could modify this function to find the opposite letter within the letters available under the variable game_letters
def opposite_turn(turn):
if turn == 'X':
return 'O'
else:
return 'X'
def main():
draw_board(board)
print("Welcome to TIC TAC TOE Game")
player1 = print("Player 1 please enter your name: ")
player1 = input().upper()
player2 = print("Player 2 please enter your name: ")
player2 = input().upper()
turn = input("Player " + str(player1) + " would you like to choose X or O?") .upper()
# Y: it checks whether the letter entered by user is acceptable, and if not, then asks for it again
while turn not in game_letters:
turn = input("Player " + player1 + ", please choose just one letter: X or O : ") .upper()
# Y: I swapped the occurrences of variable thisplayer for variable turn and invocation of function opposite_turn() to print the chosen letters
print(player1 + " takes : " + turn + ', ' + player2 + " takes : " + opposite_turn(turn))
# Y: I would invoke main() here to give the players a choice of letters before they start a game
main()
while True:
draw_board(board)
move = int(input(" Make a move (X): "))
valid_move = [ ]
for position in range(9):
if board[position]==0:
valid_move.append(position)
if move in valid_move:
break
print("illegal move")
board[move] = str("X")
"""if board[move] == str("X") or board[move] == str("O"):
print("Please make another move ")"""
draw_board(board)
move_2 = int(input(" Make a move (O): "))
valid_move= [ ]
for position in range(9):
if board[position]==0:
valid_move.append(position)
if move in valid_move:
break
print("illegal move")
board[move_2] = str("O")
"""if board[move_2] == str("X") or board[move] == str("O"):
print("Please make another move ")"""
# player_1 choices
if board[1] == board[2] == board[3] == "X": #across the top row
print(str(player_1) + "wins" )
break
elif board[4] == board[5] == board[6] == "X": #across the middle row
print(str(player_1) + "wins" )
break
elif board[7] == board[8] == board[9] == "X": #across the bottom row
print(str(player_1) + "wins" )
break
elif board[1] == board[4] == board[7] == "X": #first column
print(str(player_1) + "wins" )
break
elif board[2] == board[5] == board[8] == "X": #second column
print(str(player_1) + "wins" )
break
elif board[3] == board[6] == board[9] == "X": #third column
print(str(player_1) + "wins" )
break
elif board[1] == board[5] == board[9] == "X": #left diagonal
print(str(player_1) + "wins" )
break
elif board[3] == board[5] == board[7] == "X": #right diagonal
print(str(player_1) + "wins" )
break
# player_2 choices
if board[1] == board[2] == board[3] == "O": #across the top row
print(str(player_2) + "wins" )
break
elif board[4] == board[5] == board[6] == "O": #across the middle row
print(str(player_2) + "wins" )
break
elif board[7] == board[8] == board[9] == "O": #across the bottom row
print(str(player_2) + "wins" )
break
elif board[1] == board[4] == board[7] == "O": #first column
print(str(player_2) + "wins" )
break
elif board[2] == board[5] == board[8] == "O": #second column
print(str(player_2) + "wins" )
break
elif board[3] == board[6] == board[9] == "O": #third column
print(str(player_2) + "wins" )
break
elif board[1] == board[5] == board[9] == "O": #left diagonal
print(str(player_2) + "wins" )
break
elif board[3] == board[5] == board[7] == "O": #right diagonal
print(str(player_2) + "wins" )
break
else:
print(" It's a Tie ")
print("Game Over")
# Y: ?
def nextplayer(thisplayer):
return (this_player+1)%2
# Y: ?
if name == 'main':
main()
This code sometimes runs to some point and gives another error. Try to fix it by yourself as it is the best way to learn something, IMO. If you stuck, then post another question.
Keep coding :-)
P.S. I noticed that you convert into strings some values that are already the strings, e.g.
# the variable player1 gets string as a result of function input()
player1 = input().upper()
# so it is not needed to convert it into string again with str() function
print(str(player1))
# you can use
print(player1)
# the code is clearer then and runs slightly faster (it is lesser to do for an interpreter)
input() function returns the string (even if a user entered a number), so you do not have to convert it into string again. More info here.
I hope it helps :-)
Heya all,
I see a few issues and areas for improvement in your Tic Tac Toe code. Let’s address them one by one, including the problem of choosing letters for each player and assigning turns correctly.
Syntax and Logical Errors:
‘ and ’ instead of ' or ") can cause syntax errors.board should start with 9 spaces if you want to use 1-based indexing, but your logic starts from index 1, which is good.Variable Initialization and Input Handling:
Here’s a revised version of your code with corrections and enhancements:
import random
def draw_board(board):
print('---------')
print('|', board[1], '|', board[2], '|', board[3], '|')
print('---------')
print('|', board[4], '|', board[5], '|', board[6], '|')
print('---------')
print('|', board[7], '|', board[8], '|', board[9], '|')
print('---------')
def main():
board = [" "] * 10 # Creating an empty board, index 0 is ignored
game_letters = ['X', 'O'] # Valid game letters
print("Welcome to TIC TAC TOE Game")
player_1 = input("Player 1 please enter your name: ").upper()
player_2 = input("Player 2 please enter your name: ").upper()
# Let player 1 choose the letter
player_1_letter = ''
while player_1_letter not in game_letters:
player_1_letter = input(f"{player_1}, would you like to choose X or O? ").upper()
player_2_letter = 'O' if player_1_letter == 'X' else 'X'
print(f"{player_1} takes {player_1_letter}")
print(f"{player_2} takes {player_2_letter}")
current_player = player_1
current_letter = player_1_letter
while True:
draw_board(board)
move = int(input(f"{current_player} make your move (1-9): "))
# Ensure the move is valid
if board[move] == " ":
board[move] = current_letter
else:
print("Illegal move, try again.")
continue
# Check win or tie
if check_winner(board, current_letter):
draw_board(board)
print(f"{current_player} wins!")
break
elif " " not in board[1:]: # Check if the board is full
draw_board(board)
print("It's a tie!")
break
# Switch player and letter
current_player = player_2 if current_player == player_1 else player_1
current_letter = player_2_letter if current_letter == player_1_letter else player_1_letter
def check_winner(b, l):
# Check for a win
return ((b[1] == b[2] == b[3] == l) or # across the top
(b[4] == b[5] == b[6] == l) or # across the middle
(b[7] == b[8] == b[9] == l) or # across the bottom
(b[1] == b[4] == b[7] == l) or # down the left side
(b[2] == b[5] == b[8] == l) or # down the middle
(b[3] == b[6] == b[9] == l) or # down the right side
(b[1] == b[5] == b[9] == l) or # diagonal
(b[3] == b[5] == b[7] == l)) # diagonal
if __name__ == '__main__':
main()
check_winner function to determine if there is a win condition on the board.This should give you a robust starting point for your Tic Tac Toe game in Python.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.