how can i fix the undefined error in python? - python

Hy , i am stuck at the last part were i have to write the place marker(place_marker(the_Board, player2_marker, position)) , it doesn't recognize the marker , it said it is a undefined variable , any ideas ?
Here is my script : (it isn't finished yet because of that problem )
def display_board(board):
print('\n'*3)
print(board[7]+'|'+board[8]+'|'+board[9])
print(board[4]+'|'+board[5]+'|'+board[6])
print(board[1]+'|'+board[2]+'|'+board[3])
#test_board = ['#','X','O','X','O','X','O','X','O','X'] #test
#display_board(test_board) #test
def player_input():
print('\n'*3)
Player1_name=input('What is your name player1 ? : ')
Player2_name=input('What is your name player2 ? : ')
marker = ''
while marker != 'X' and marker != '0' :
Player1=marker = input('{}, please chose X or 0 : '.format(Player1_name))
if Player1 == 'X':
Player2 = '0'
else:
Player2= 'X'
return ('OK, {} is : {}\nAnd {} is : {} ' .format(Player1_name,Player1,Player2_name,Player2))
#print(player_input()) #test
def place_marker(board, marker, position):
board[position] = marker
#print(place_marker(test_board,'2',8))
#print(display_board(test_board))
def win_check(board, mark):
return ((board[7] == mark and board[8] == mark and board[9] == mark) or (board[4] == mark and board[5] == mark and board[6] == mark) or (board[1] == mark and board[2] == mark and board[3] == mark) or (board[7] == mark and board[4] == mark and board[1] == mark) or (board[8] == mark and board[5] == mark and board[2] == mark) or (board[9] == mark and board[6] == mark and board[3] == mark) or (board[7] == mark and board[5] == mark and board[3] == mark) or (board[9] == mark and board[5] == mark and board[1] == mark))
#print(win_check(test_board,'X')) #test
import random
def choose_first():
flip = random.randint(0,1)
if flip == 0 :
return 'Player1'
else:
return 'Player2'
def space_check(board, position):
return board[position] == ''
def full_board_check(board):
for i in range(1, 10) :
if space_check(board, i):
return False
return True
def player_choice(board):
print('\n'*3)
position = 0
while position not in [1,2,3,4,5,6,7,8,9] or not space_check(board,position):
position = int(input('Please chose a position from 1 to 9 : '))
return position
def replay():
choise = input('Do you wnat to play again, yes or no ? : ')
return choise == 'yes'
print('Welcome to Tic Tac Toe!')
while True:
the_board=[' '] *10
player_input()
turn=choose_first()
print(turn+'will go first')
play_game=input('Ready to play ? y or n ? : ')
if play_game == 'y' :
game_on = True
else:
game_on = False
while game_on :
if turn == 'Player1' :
display_board(the_board)
position=player_choice(the_board)
place_marker(the_Board, player2_marker, position) ### HERE
if win_check (the_board ,Player1) :
display_board(the_board)
print('{} has Won !!')
game_on = False
if not replay() :
break
here is the console after i run the code , it don't recognize the number i thick because the final script isn't done ,
Welcome to Tic Tac Toe!
What is your name player1 ? : SALLY
What is your name player2 ? : Sammy
Player1will go first
Ready to play ? y or n ? : y
| |
| |
| |
Please chose a position from 1 to 9 : 1
Please chose a position from 1 to 9 : 2
Please chose a position from 1 to 9 : 3
it is still asking me for a number
i have tried to change some parameters of the place_marker code but it didn't work
def place_marker(board, marker, position):
board[position] = marker
place_marker(the_Board, player2_marker, position)

Your problem is exactly where you mark it:
place_marker(the_Board, player2_marker, position)
This is the first reference to player2_marker. You need to initialise it somewhere before you reference it! I assume this is as simple as setting it to 'O' or 'X' in your case.

Hi thanks for your answer , i realize that , i compared my script with the course solution script and i saw that i made a modify at player input , that was just returning that formatted sentence, so i change my code with that one which return 'x' , '0' or '0', 'x' , that is assigned to the player 1,player 2 = player_input() , i meat player 1 = x and player 2 = o or reverse , so that variable i can introduce in the place_marker function as X (assigned to player 1) or O (assigned to player 2 ) , also little mistakes , and it finally works now !!

Related

Try to code a simple Tic Tac Toe from a Udemy course. What did I do wrong?

Below is the code I used for my simple Tic Tac Toe game. I receive the following error I have no idea how to get around. This program does work in Jupyter notebook, but when I try to run the script in VScode, the error appears. I need guidance on how I can fix this error.
***THE ERROR IS AS FOLLOWS: ***
Traceback (most recent call last):
File "x:\Python\Python_Bootcamp\Complete-Python-3-Bootcamp-master\04-Milestone Project - 1\TIC_TAC_TOE.py", line 105, in <module>
display_board(board)
File "x:\Python\Python_Bootcamp\Complete-Python-3-Bootcamp-master\04-Milestone Project - 1\TIC_TAC_TOE.py", line 8, in display_board
print(board[1] + '|' + board[2] + '|' + board[3])
~~~~~^^^
IndexError: list index out of range
TIC TAC TOE GAME
`
import random
`
Display the board for the game
`def display_board(board):
# print('\n'*100) # Lets you only see one version of the board
print(board[1] + '|' + board[2] + '|' + board[3])
print('-----')
print(board[4] + '|' + board[5] + '|' + board[6])
print('-----')
print(board[7] + '|' + board[8] + '|' + board[9])`
Choose whether player 1 is X or O
`def player_input():
marker = ''
while marker != 'X' and marker != 'O':
marker = input('Player 1 choose X or O: ')
player1 = marker.upper()
if player1 == 'X':
player2 = 'O'
else:
player2 = 'X'
return(player1, player2)`
Takes a position on the board and puts a marker on position
`def place_marker(board,marker,position):
board[position] = marker`
Check to see if win
`def win_check(board, mark):
return ((board[7] == mark and board[8] == mark and board[9] == mark) or # across the bottom
(board[4] == mark and board[5] == mark and board[6] == mark) or # across the middle
(board[1] == mark and board[2] == mark and board[3] == mark) or # across the top
(board[7] == mark and board[4] == mark and board[1] == mark) or # down the left column
(board[2] == mark and board[5] == mark and board[8] == mark) or # down the middle
(board[3] == mark and board[6] == mark and board[9] == mark) or # down the right side
(board[3] == mark and board[5] == mark and board[7] == mark) or # diagonal
(board[9] == mark and board[5] == mark and board[1] == mark)) # diagonal`
Random flip to see if Player 1 or Player 2 goes first
`def choose_first():
flip = random.randint(0,1)
if flip == 0:
return ('Player 1')
else:
return ('Player 2')`
Check to see if position freely available
`def space_check(board, position):
return board[position] == ' ' # If space is empty the return value will be True`
Check to see if the board is full
`def full_board_check(board):
for i in range(1,10):
if space_check(board,i):
return False # Fales meaning the space is empty of marker
else:
return True # True meaning the board is full`
Function for player to choose their next position on the board
`def player_choice(board):
position = 0
while position not in [1,2,3,4,5,6,7,8,9]:
position = int(input('Choose your position: '))
return position
def replay():
choice = input('Do you want to play again?')
return choice == 'Yes'`
GAME SETUP
`print('Welcome to Tic Tac Toe!')
while True:
board = [' '*10]
player1_marker,player2_marker = player_input()
turn = choose_first()
print(turn + ' will go first')
game_on = ''
play_game = input('Are you ready to play Yes or No?: ')
if play_game.lower()[0] == 'y':
game_on == True
else:
game_on == False
# Player 1 Turn
if turn == 'Player 1':
# Show board
display_board(board)
# Choose a position
position = player_choice(board)
# Place marker on choosen position
place_marker(board,player1_marker,position)
# Check if they won
if win_check(board,player1_marker) == True:
display_board(board)
print('Player 1 has won the game!')
game_on = False
# Check to see if Tie
else:
if full_board_check(board):
display_board(board)
print('TIE GAME')
break
# If there's no tie turn to Player 2
else:
turn = 'Player 2'
# Player2's turn.
if turn == 'Player 2':
# Show board
# display_board(board)
# Show position
position = player_choice(board)
#Place marker on position
place_marker(board,player2_marker,position)
# Check to see if win
if win_check(board,player2_marker) == True:
display_board(board)
print('Player 2 has won the game!')
game_on = False
# Check to see if Tie
else:
full_board_check(board)
display_board(board)
print('TIE GAME')
break
else:
turn = 'Player 1'
# If players do not want to play again, quit
if not replay():
break`
I've tried to comment out different lines of code to test some of the board configurations. I can get the board to show, but once I try to play a full game I get an error.
You have init
board = [' '*10]
so board is a list of only one element. so index 1 does not exists.
maybee you wanted to write:
board = 10*[' ']
so you have a list with 10 elements ' ' (10 times one blank/space).
I tested it and it works with your code, and I managed to play my first move.

Python Tic Tac Toe variables not resetting?

I've just started learning Python, and like a lot of beginners I'm working on a simple two player tic tac toe game.
I've managed to get through most of the code and debug everything EXCEPT for some reason when I try and replay the game, it's not resetting my board variable and essentially clearing the board despite re assigning the variable. I'm assuming its a simple fix and has something to do with scope that I'm just missing but I'd really appreciate if someone could give it a look over and let me know how I'd fix this issue.
Currently the code works, the player picks a symbol and goes back and forth until someone wins, then the code asks if they'd like to replay. If no is chosen, the game ends just fine, but if they select yes, the board isn't cleared from the last games markers.
I feel like I've tried a million different things and nothing seems to be clearing it!
Here's the code
#Display board function
#import clear output function - if don't will show entire history of board moves each time
from IPython.display import clear_output
def view_board(board):
clear_output()
print(display_board[6]+'|'+display_board[7]+"|"+display_board[8])
print('-----')
print(display_board[3]+'|'+display_board[4]+"|"+display_board[5])
print('-----')
print(display_board[0]+'|'+display_board[1]+"|"+display_board[2])
#OK function to ask player one if they want to be X or O
def player_icon():
#VARIABLES
icon = 'wrong'
while icon not in ['X', 'O']:
icon = input('Player 1, please choose a symbol (X or O):')
if icon not in ['X', 'O']:
print('Sorry, that is not a valid choice. Please choose either X or O.')
if icon == 'X':
print('Great! Player 1 will go first!')
elif icon == 'O':
print('Great! Player 2 will go first!')
return icon
#now we do the positioning based on the numbers on the board
#take user input position - use that as index value in blank list - replace that value with their marker
def user_position_X(board):
#board will be blank at first - make board variable
#marker will be their chosen icon from player_icon - starts with X - change to O after first move made
#position will be index value 1-9 - make sure to subtract 1 from chosen value as index will start at 0
#board(position) = marker
#VARIABLES
marker = 'X'
position = 'wrong'
while position not in board:
#ASK FOR USER POSITION
position = input('Please choose a position (1-9): ')
#IF NOT IN ACCEPTABLE VALUES (includes not digits I believe)
if position not in board:
print('Sorry! That is not an acceptable position. Please select an avaliable position.')
#MAKE POSITION INT
position_int = int(position)
#MAKING INPUT
index_position = (position_int)-1
#REPLACING ON BOARD - NOT USING X AND O SO CAN'T BE OVERWRITTEN - X=T O=P
board[index_position] = 'T'
#ADDING MARKER TO DISPLAY BOARD
for location in display_board:
display_board[index_position] = marker
return [board, display_board]
#now we do the positioning based on the numbers on the board
#take user input position - use that as index value in blank list - replace that value with their marker
def user_position_O(board):
#board will be blank at first - make board variable
#marker will be their chosen icon from player_icon - starts with X - change to O after first move made
#position will be index value 1-9 - make sure to subtract 1 from chosen value as index will start at 0
#board(position) = marker
#VARIABLES
marker = 'O'
position = 'wrong'
while position not in board:
#ASK FOR USER POSITION
position = input('Please choose a position (1-9): ')
#IF NOT IN ACCEPTABLE VALUES (includes not digits I believe)
if position not in board:
print('Sorry! That is not an acceptable position. Please select an avaliable position.')
#MAKE POSITION INT
position_int = int(position)
#MAKING INPUT
index_position = (position_int)-1
#REPLACING ON BOARD - Not using X and O so they cannot be replaced - X = T O = P
board[index_position] = 'P'
#ADDING MARKER TO DISPLAY BOARD
for location in display_board:
display_board[index_position] = marker
return [board, display_board]
#CHECK TO SEE IF WON - HOW?
#DICTIONARY OF ALL WINNING POSITIONS?
#run check win after each turn? after display board?
#in final code make player_icon = p1_icon
#check wins should jsut contain those items not be them exacly - check section 6 for the similar ones the 007 thing
#WHEN X AT CERTAIN INDEX POSITIONS WHEN O AT CERTAIN INDEX POSITIONS
#USING T AND P
def check_win(board,player1_icon):
#WHEN X AT CERTAIN INDEX POSITIONS WHEN O AT CERTAIN INDEX POSITIONS
#USING T AND P
#HORIZONTAL X
if (board[0] == 'T'and board[1] == 'T' and board[2] == 'T') or (board[3] == 'T'and board[4] == 'T' and board[5] == 'T') or (board[6] == 'T'and board[7] == 'T' and board[8] == 'T'):
if player1_icon == 'X':
win = 'yes'
print('Congrats, Player 1 has won!')
return win
elif player1_icon != 'X':
win = 'yes'
print('Congrats, Player 2 has won!')
return win
else:
pass
else:
pass
#VERTICAL X
if (board[0] == 'T'and board[3] == 'T' and board[6] == 'T') or (board[1] == 'T'and board[4] == 'T' and board[7] == 'T') or (board[2] == 'T'and board[5] == 'T' and board[8] == 'T'):
if player1_icon == 'X':
win = 'yes'
print('Congrats, Player 1 has won!')
return win
elif player1_icon != 'X':
win = 'yes'
print('Congrats, Player 2 has won!')
return win
else:
pass
else:
pass
#DIAGONAL X
if (board[0] == 'T'and board[4] == 'T' and board[8] == 'T') or (board[2] == 'T'and board[4] == 'T' and board[6] == 'T'):
win = 'yes'
if player1_icon == 'X':
win = 'yes'
print('Congrats, Player 1 has won!')
return win
elif player1_icon != 'X':
win = 'yes'
print('Congrats, Player 2 has won!')
return win
else:
pass
else:
pass
#HORIZONTAL O
if (board[0] == 'P'and board[1] == 'P' and board[2] == 'P') or (board[3] == 'P'and board[4] == 'P' and board[5] == 'P') or (board[6] == 'P'and board[7] == 'P' and board[8] == 'P'):
if player1_icon == 'O':
win = 'yes'
print('Congrats, Player 1 has won!')
return win
elif player1_icon != 'O':
win = 'yes'
print('Congrats, Player 2 has won!')
return win
else:
pass
else:
pass
#VERTICAL O
if (board[0] == 'P'and board[3] == 'P' and board[6] == 'P') or (board[1] == 'P'and board[4] == 'P' and board[7] == 'P') or (board[2] == 'P'and board[5] == 'P' and board[8] == 'P'):
if player1_icon == 'O':
win = 'yes'
print('Congrats, Player 1 has won!')
return win
elif player1_icon != 'O':
win = 'yes'
print('Congrats, Player 2 has won!')
return win
else:
pass
else:
pass
#DIAGONAL O
if (board[0] == 'P'and board[4] == 'P' and board[8] == 'P') or (board[2] == 'P'and board[4] == 'P' and board[6] == 'P'):
if player1_icon == 'O':
win = 'yes'
print('Congrats, Player 1 has won!')
return win
elif player1_icon != 'O':
win = 'yes'
print('Congrats, Player 2 has won!')
return win
else:
pass
else:
win = 'no'
return win
#Would you like to replay
def check_replay():
choice = 'wrong'
while choice not in ['Yes', 'No']:
choice = input('Would you like to play again? (Yes or No) ')
if choice not in ['Yes', 'No']:
print("Sorry, I don't understand. Please choose Yes or No.")
if choice == 'Yes':
return True
#aka game keeps playing
else:
print('Thanks for playing!')
return False
#game stops
#bc boolean values can continue to maintain some while loop
#Put it all together
from IPython.display import clear_output
def play_game():
replay = True
while replay == True:
#VARIABLES
win = 'no'
board = ['1','2','3','4','5','6','7','8','9']
display_board = [' ', ' ',' ',' ',' ',' ',' ',' ',' ']
#DISPLAY BOARD
view_board(display_board)
#ASK PLAYER 1 WHAT ICON
player1_icon = player_icon()
while win == 'no':
clear_output
#X SYMBOL POSITION
x_results = user_position_X(board)
x_results[0] = board
x_results [1] = display_board
#DISPLAY BOARD
view_board(display_board)
#CHECK IF WIN
win = check_win(board,player1_icon)
if win == 'yes':
break
#O SYMBOL POSITION
o_results = user_position_O(board)
o_results[0] = board
o_results [1] = display_board
#DISPLAY BOARD
view_board(display_board)
#CHECK IF WIN
win = check_win(board,player1_icon)
if win == 'yes':
replay = False
replay = check_replay()
if replay:
board = ['1','2','3','4','5','6','7','8','9']
display_board = [' ', ' ',' ',' ',' ',' ',' ',' ',' ']
if not replay:
print('Thanks for Playing!')
#need to have updated list with where answers are and then a second seperate list with available numbers
Sorry if its a bit messy, its my first proper big coding project! Also sorry about my notes it was just the best way for me to keep track of everything!
Like I said, everything seems to work except when check_replay() is executed, for some reason board and display_board aren't resetting despite being defined at the top of the function. I've tried moving the location of board and display_boards assignments, tried re assigning them after checking for replay, tried writing a new function that runs play game as a function and replay as its own thing. I'm really not sure why it's not resetting.
Thanks in advance!!

TicTacToe game, trying to find the winner

I'm trying to find the winner in tic-tac-toe game.
I check the indexes of my list if are equal, but it seems that is doesn't work. Here is the code. When the indexes change with the letter x or o I want to check if they are equal.
Sorry for this, but I couldn't upload the question because it has too much code.
board = ['_','_','_',
'_','_','_',
'_','_','_']
player1 = ''
player2 = ''
def board_display ():
global board
index_board = ('0','1','2',
'3','4','5',
'6','7','8 ' )
#Index Board
print("Position Board \n{} |{} |{} |\n{} |{} |{} |\n{} |{} |{}| \n".format(index_board[0],index_board[1],index_board[2],index_board[3],index_board[4],index_board[5],index_board[6],index_board[7],index_board[8]))
#Print The Board
print("{} |{} |{} |\n{} |{} |{} |\n{} |{} |{} |\n".format(board[0],board[1],board[2],board[3],board[4],board[5],board[6],board[7],board[8]))
def player_symbol_choice ():
global player1
global player2
#Accepatbles Signs
acceptable_values = ['X','O']
#Player Input Sign
player1 = input("Please Choose, X or O \n").upper()
player2 = ''
#Check if User Choose Between X or O
while player1 not in acceptable_values:
player1 = input("Please Choose Only X or O \n").upper()
print("Player 1 is " +player1)
if player1 == 'X':
player2= 'O'
elif player1 == 'O':
player2 = 'X'
print("Player 2 is " +player2)
def gameplay ():
print("Select position for your sign between 0 - 8\nYou can check the position board to be sure that your choice is in the place you want")
#The accepatbles index values
acceptables_positions = [0,1,2,3,4,5,6,7,8]
#Player 1 Turn
Turn1 = int(input("Player 1 \nPlease play your move: "))
#Check if the input values is in the range of 0-8
while Turn1 not in acceptables_positions:
Turn1 = int(input("Player 1 \nPlease play your move, between values 0-8: "))
#Change the index value and replace it with Player 1 sign
board[Turn1] = player1
board_display ()
Turn2 = int(input("Player 2 \nPlease play your move: "))
while Turn2 not in acceptables_positions:
Turn2 = int(input("Player 2 \nPlease play your move, between values 0-8: "))
board[Turn2] = player2
board_display ()
In this function i'm trying to find the winner.
def find_winner():
if board[0] == board[1] == board[2]:
print("Player 1 Wins" )
elif board[3] == board[4] == board[5]:
print("Player 1 Wins" )
elif board[6] == board[7] == board[8]:
print("Player 1 Wins" )
elif board[0] == board[4] == board[8]:
print("Player 1 Wins" )
board_display()
player_symbol_choice ()
while True:
gameplay()
find_winner()
You dont need to use the marker.
But this is most likely what you searched for. Got the content from Udemy Course.
Credits # Jose
Hints and tricks:
https://github.com/Pierian-Data/Complete-Python-3-Bootcamp/blob/master/04-Milestone%20Project%20-%201/02-Milestone%20Project%201%20-%20Walkthrough%20Steps%20Workbook.ipynb
Full walkthrough:
https://github.com/Pierian-Data/Complete-Python-3-Bootcamp/blob/master/04-Milestone%20Project%20-%201/03-Milestone%20Project%201%20-%20Complete%20Walkthrough%20Solution.ipynb
def win_check(board,mark):
return ((board[7] == mark and board[8] == mark and board[9] == mark) or # across the top
(board[4] == mark and board[5] == mark and board[6] == mark) or # across the middle
(board[1] == mark and board[2] == mark and board[3] == mark) or # across the bottom
(board[7] == mark and board[4] == mark and board[1] == mark) or # down the middle
(board[8] == mark and board[5] == mark and board[2] == mark) or # down the middle
(board[9] == mark and board[6] == mark and board[3] == mark) or # down the right side
(board[7] == mark and board[5] == mark and board[3] == mark) or # diagonal
(board[9] == mark and board[5] == mark and board[1] == mark)) # diagonal
This function takes the actual board and the marker, so you can just call the function after every move and check if the person with X or 0 has won.
Just call checkWin(,<X||0>

I don't know why my tic tac toe doesn't recognize the winner, I've checked the whole code

I don't know where the mistake to the winner is, it doesn't recognize, but it still recognizes a tie, please help, I'm still a beginner, thanks.
I've been starring to the screen for 3 hours and still couldn't solve this particular problem, also, I've looked in the forum, but found nothing.
#------Global variables -------
# Will hold our game board data
board = ["-", "-", "-",
"-", "-", "-",
"-", "-", "-",]
#If game is still going
game_still_going = True
#Tell us who won
winner = None
#Tell us who goes first, x goes first
current_player = "X"
#---------------FUNCTIONS---------------
#Play a game of tic tac toe
def play_game():
#Display initial board
display_board()
#While the game is still going
while game_still_going:
# Handle a turn
handle_turn(current_player)
# Check if the game is over
check_if_game_over()
# Flip to the other player
flip_player()
# Since the game is over, print the winner or tie
if winner == "X" or winner == "O":
print(winner + " won.")
elif winner == None:
print("Tie.")
# Display the game board to the screen
def display_board():
print("\n")
print(board[0] + " | " + board[1] + " | " + board[2] + " 1 | 2 | 3")
print(board[3] + " | " + board[4] + " | " + board[5] + " 4 | 5 | 6")
print(board[6] + " | " + board[7] + " | " + board[8] + " 7 | 8 | 9")
print("\n")
#Handle a single turn of an arbitrary player
def handle_turn(player):
#get position from player
print(player + "'s turn. ")
position = input("Choose a position from 1-9: ")
print()
# Whatever the user inputs, make sure it is a valid input, and the spot is open
valid = False
while not valid:
#Make sure the input is correct
while position not in ["1", "2", "3", "4", "5", "6", "7", "8", "9"]:
position = input("Choose a position from 1-9: ")
# Get correct index in our board list
position = int(position) - 1
# Then also make sure the spot is available on the board
if board[position] == "-":
valid = True
else:
print("You can't go there, go again. ")
print()
# Put the game piece on the board
board[position] = player
# Show the game board
display_board()
# Check if the game is over
def check_if_game_over():
check_for_winner
check_for_tie()
#Check if someone won the game
def check_for_winner():
# Set global variable
global winner
# Check if there was a winner anywhere
row_winner = check_rows()
column_winner = check_columns()
diagonal_winner = check_diagonals()
#Get the winner
if row_winner:
winner = row_winner
elif column_winner:
winner = column_winner
elif diagonal_winner:
winner = diagonal_winner
else:
winner = None
#Looking for winner in rows
def check_rows():
#Set up global variables
global game_still_going
#Checking if the rows got the same value and are not empty
row_1 = board[0] == board[1] == board[2] != "-"
row_2 = board[3] == board[4] == board[5] != "-"
row_3 = board[6] == board[7] == board[8] != "-"
#If any row does have a match, flag that there is a win
if row_1 or row_2 or row_3:
game_still_going = False
#return the winner X or O
if row_1:
return board[0]
elif row_2:
return board[3]
elif row_3:
return board[6]
else:
return None
#Looking for winner in columns
def check_columns():
#Set up global variables
global game_still_going
#Checking if the column got the same value and are not empty
column_1 = board[0] == board[3] == board[6] != "-"
column_2 = board[1] == board[4] == board[7] != "-"
column_3 = board[2] == board[5] == board[8] != "-"
#If any column does have a match, flag that there is a win
if column_1 or column_2 or column_3:
game_still_going = False
#return the winner X or O
if column_1:
return board[0]
elif column_2:
return board[1]
elif column_3:
return board[2]
# Or return None if there was no winner
else:
return None
#Looking for a winner in diagonals
def check_diagonals():
#Set up global variables
global game_still_going
#Checking if the diagonal got the same value and are not empty
diagonal_1 = board[0] == board[4] == board[8] != "-"
diagonal_2 = board[2] == board[4] == board[6] != "-"
#If any diagonal does have a match, flag that there is a win
if diagonal_1 or diagonal_2:
game_still_going = False
#return the winner X or O
if diagonal_1:
return board[0]
elif diagonal_2:
return board[2]
else:
return None
#Looking if there's a tie
def check_for_tie():
#Global variable
global game_still_going
#if the board is full
if "-" not in board:
game_still_going = False
# Else there is no tie
else:
return False
#Changing players time a time
def flip_player():
#Global variable we need
global current_player
#If the current player was x, then change it to O
if current_player == "X":
current_player = "O"
elif current_player == "O":
current_player = "X"
#--------Start the application----------
play_game()
You have missed global [variable] in most of the functions, I have find some missing variables please refer below code line by line:
#------Global variables -------
# Will hold our game board data
board = ["-", "-", "-",
"-", "-", "-",
"-", "-", "-",]
#If game is still going
game_still_going = True
#Tell us who won
winner = None
#Tell us who goes first, x goes first
current_player = "X"
#---------------FUNCTIONS---------------
#Play a game of tic tac toe
def play_game():
global winner #this is new
#Display initial board
display_board()
#While the game is still going
while game_still_going:
# Handle a turn
handle_turn(current_player)
# Check if the game is over
check_if_game_over()
# Flip to the other player
flip_player()
# Since the game is over, print the winner or tie
if winner == "X" or winner == "O":
print(winner + " won.")
elif winner == None:
print("Tie.")
# Display the game board to the screen
def display_board():
global board
print("\n")
print(board[0] + " | " + board[1] + " | " + board[2] + " 1 | 2 | 3")
print(board[3] + " | " + board[4] + " | " + board[5] + " 4 | 5 | 6")
print(board[6] + " | " + board[7] + " | " + board[8] + " 7 | 8 | 9")
print("\n")
#Handle a single turn of an arbitrary player
def handle_turn(player):
#get position from player
print(player + "'s turn. ")
position = input("Choose a position from 1-9: ")
print()
# Whatever the user inputs, make sure it is a valid input, and the spot is open
valid = False
while not valid:
#Make sure the input is correct
while position not in ["1", "2", "3", "4", "5", "6", "7", "8", "9"]:
position = input("Choose a position from 1-9: ")
# Get correct index in our board list
position = int(position) - 1
# Then also make sure the spot is available on the board
if board[position] == "-":
valid = True
else:
print("You can't go there, go again. ")
print()
# Put the game piece on the board
board[position] = player
# Show the game board
display_board()
# Check if the game is over
def check_if_game_over():
check_for_winner
check_for_tie()
#Check if someone won the game
def check_for_winner():
# Set global variable
global winner
# Check if there was a winner anywhere
row_winner = check_rows()
column_winner = check_columns()
diagonal_winner = check_diagonals()
#Get the winner
if row_winner:
winner = row_winner
elif column_winner:
winner = column_winner
elif diagonal_winner:
winner = diagonal_winner
else:
winner = None
#Looking for winner in rows
def check_rows():
#Set up global variables
global game_still_going
#Checking if the rows got the same value and are not empty
row_1 = board[0] == board[1] == board[2] != "-"
row_2 = board[3] == board[4] == board[5] != "-"
row_3 = board[6] == board[7] == board[8] != "-"
#If any row does have a match, flag that there is a win
if row_1 or row_2 or row_3:
game_still_going = False
#return the winner X or O
if row_1:
return board[0]
elif row_2:
return board[3]
elif row_3:
return board[6]
else:
return None
#Looking for winner in columns
def check_columns():
#Set up global variables
global game_still_going
#Checking if the column got the same value and are not empty
column_1 = board[0] == board[3] == board[6] != "-"
column_2 = board[1] == board[4] == board[7] != "-"
column_3 = board[2] == board[5] == board[8] != "-"
#If any column does have a match, flag that there is a win
if column_1 or column_2 or column_3:
game_still_going = False
#return the winner X or O
if column_1:
return board[0]
elif column_2:
return board[1]
elif column_3:
return board[2]
# Or return None if there was no winner
else:
return None
#Looking for a winner in diagonals
def check_diagonals():
#Set up global variables
global game_still_going
#Checking if the diagonal got the same value and are not empty
diagonal_1 = board[0] == board[4] == board[8] != "-"
diagonal_2 = board[2] == board[4] == board[6] != "-"
#If any diagonal does have a match, flag that there is a win
if diagonal_1 or diagonal_2:
game_still_going = False
#return the winner X or O
if diagonal_1:
return board[0]
elif diagonal_2:
return board[2]
else:
return None
#Looking if there's a tie
def check_for_tie():
#Global variable
global game_still_going
#if the board is full
if "-" not in board:
game_still_going = False
# Else there is no tie
else:
return False
#Changing players time a time
def flip_player():
#Global variable we need
global current_player
#If the current player was x, then change it to O
if current_player == "X":
current_player = "O"
elif current_player == "O":
current_player = "X"
#--------Start the application----------
play_game()
You can read this for more information about global :
https://www.google.com/url?sa=t&source=web&rct=j&url=https://www.geeksforgeeks.org/global-keyword-in-python/amp/&ved=2ahUKEwi2gbeo_fDoAhVo7XMBHZvjAHIQFjAPegQICxAy&usg=AOvVaw0fpoalAG4dROAIz3PlXcQo&ampcf=1
In your check_if_game_over function, you are not calling the check_for_winner function correctly. You need to add parenthesis afterward to call it correctly.
def check_if_game_over():
check_for_winner()
check_for_tie()

How can I implement a search algorithm for a Tic Tac Toe AI in Python? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
We've covered BFS, DFS, iterative deepening, A*, hill climbing, minimax, and alpha-beta pruning in class so far. I'm not sure how I would code any of those searches into my Tic Tac Toe's AI. The computer has a 5-second time limit for this assignment.
This is what I have so far:
#!/usr/bin/env python
import random
# Tic-Tac-Toe Game Against A Computer
# Prints the board for the game to console output
def drawBoard():
print(" | 1 | 2 | 3 ")
print('---------------')
print(' 1 | ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print('---------------')
print(' 2 | ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print('---------------')
print(' 3 | ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
# Lets the player decide which symbol (X or O) he wants to be
def pickSymbol():
symbol = ' '
while not (symbol == 'X' or symbol == 'O'):
print('Do you want to be symbol X, or the symbol O?')
symbol = input().upper()
# Return a list containing the player's symbol (first element) and the computer's symbol (second element)
if symbol == 'X':
return ['X', 'O']
else:
return ['O', 'X']
# Randomly determines if the player or the computer goes first
def pickFirst():
if random.randint(0,1) == 0:
return 'player'
else:
return 'computer'
# Checks that the x-coordinate the player chose is valid
def isValidX(x):
try:
intX = int(x)
if not 1 <= intX <= 3:
raise ValueError()
except ValueError:
return False
return True
# Checks that the y-coordinate the player chose is valid
def isValidY(y):
try:
intY = int(y)
if not 1 <= intY <= 3:
raise ValueError()
except ValueError:
return False
return True
# Converts a player's input coordinates to a move
def convertCoordinates(x, y):
if x == 1:
if y == 1:
return 7
elif y == 2:
return 8
else:
return 9
elif x == 2:
if y == 1:
return 4
elif y == 2:
return 5
else:
return 6
else:
if y == 1:
return 1
elif y == 2:
return 2
else:
return 3
# Checks if a space for a given move is free
def isFree(move):
return board[move] == ' '
# Gets the player's move
def getPlayerMove():
while True:
x = ' ' # arbitrary initial value before player input
while not isValidX(x):
print('Enter input x:')
x = input()
y = ' ' # arbitrary initial value before player input
while not isValidY(y):
print('Enter input y:')
y = input()
move = convertCoordinates(int(x),int(y))
if not isFree(move):
print('That space is taken. Please enter a different coordinate')
continue
else:
break
return move
# Gets the computer's move
def getComputerMove():
return 9
# Places the move onto the board
def placeMove(move, sym):
board[move] = sym
# Determines if the board is in a win state for a given symbol
def isWin(sym):
return ((board[7] == sym and board[8] == sym and board[9] == sym) or # top
(board[4] == sym and board[5] == sym and board[6] == sym) or # middle
(board[1] == sym and board[2] == sym and board[3] == sym) or # bottom
(board[7] == sym and board[5] == sym and board[3] == sym) or # diagonal
(board[1] == sym and board[5] == sym and board[9] == sym) or # diagonal
(board[7] == sym and board[4] == sym and board[1] == sym) or # left
(board[8] == sym and board[5] == sym and board[2] == sym) or # center
(board[9] == sym and board[6] == sym and board[3] == sym)) # right
# Determines if the board is in a tie state
def isTie():
return board.count('X') + board.count('O') == 9
# Prints the final output if the game is in a tie state
def tie():
drawBoard()
print('The game has ended in a tie.')
# Prints the final output if the game is in a win state for the PLAYER
def playerWin():
drawBoard()
print('Congratulations! You beat the computer!')
# Prints the final output if the game is in a win state for the COMPUTER
def computerWin():
drawBoard()
print('Sorry... the computer beat you.')
# The player makes a move
def playerTurn(playerSym):
move = getPlayerMove()
placeMove(move, playerSym)
# The computer makes a move
def computerTurn(computerSym):
move = getComputerMove()
placeMove(move, computerSym)
def main():
print("Welcome to Tic-Tac-Toe!")
playerSym, computerSym = pickSymbol()
turn = pickFirst()
print("The " + turn + " will play first.")
global board
board = [' '] * 10
while True:
if turn == 'player':
drawBoard()
playerTurn(playerSym)
if isWin(playerSym):
playerWin()
break
if isTie():
tie()
break
turn = 'computer'
if turn == 'computer':
drawBoard()
computerTurn(computerSym)
if isWin(computerSym):
computerWin()
break
if isTie():
tie()
break
turn = 'player'
if __name__ == '__main__':
main()
Thanks!
Because I think this is as close to an actual answer as it can get, and taking a wild guess that this is the real source of the difficulty:
I'm not sure how to turn the tic tac toe board into a graph that I can search, if that makes sense
The board is not the graph; the nodes of the graph are the possible board states resulting from taking turns playing moves. So you have a root node representing the current state, and then this is connected to the nodes resulting from each legal move for whoever's turn it is, and then nodes extending from there etc.

Categories