Python Tic Tac Toe variables not resetting? - python

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

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.

I have made a Tic Tac Toe game but it shows the wrong player when someone has won

I have made a Tic Tac Toe game in python and when X wins it shoes that O has won and when O wins it shows that X has won. I am pretty sure that the problem is that it changes player and after that checks if someone has won, I tried making it so it will switch be before the player switch but it still didn't work.
I also tried to change player in the is_win function but that also didn't fix it.
Could someone please take a look at this and help me fix this.
initial_board = [['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']]
board = initial_board
def empty_board(): #use board = empty_board() everytime you want to empty the board
board = [['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']]
return(board)
def switch_turn(player): #use player = switch_turn(player) everytime you want to switch players
if player == 'X':
return 'O'
return 'X'
def print_board(board):
print(*board, sep = "\n")
def is_full(board):
return all('_' not in box for box in board)
def is_valid(board, row, col):
x = board[row]
if x[col] == '_':
return True
return False
def set_cell(board, row, col, player):
x = board[row]
if is_valid(board,row,col) is True:
x[col] = player
print_board(board)
else:
print("already taken")
def get_user_input():
while True:
while True:
row = int(input("Enter the row you want (0-2): "))
if row > 2 or row < 0:
print("The number you entered is not valid")
continue
break
while True:
col = int(input("Enter the column you want (0-2): "))
if col > 2 or col < 0:
print("The number you entered is not valid")
continue
break
if is_valid(board,row,col) is True:
return row,col
else:
print("This place is taken")
continue
def is_win(board,player):
row1 = board[0]
row2 = board[1]
row3 = board[2]
if row1[0] == row1[1] == row1[2] != '_':
print(player + " Has won!")
return True
elif row2[0] == row2[1] == row2[2] != '_':
print(player + " Has won!")
return True
elif row3[0] == row3[1] == row3[2] != '_':
print(player + " Has won!")
return True
elif row1[0] == row2[0] == row3[0] != '_':
print(player + " Has won!")
return True
elif row1[1] == row2[1] == row3[1] != '_':
print(player + " Has won!")
return True
elif row1[2] == row2[2] == row3[2] != '_':
print(player + " Has won!")
return True
elif row1[0] == row2[1] == row3[2] != '_':
print(player + " Has won!")
return True
elif row1[2] == row2[1] == row3[0] != '_':
print(player + " Has won!")
return True
else:
return False
def game():
player = 'X'
print_board(board)
while is_win(board, player) is False:
if is_full(board) is True and is_win(board, player) is False:
print("draw")
break
elif is_full(board) is True and is_win(board, player) is True:
print(is_win(board, player))
break
row, col = get_user_input()
set_cell(board, row, col, player)
player = switch_turn(player)
game()
I think it is because, before your game ends, the player gets switched at the of the game() function.
player = switch_turn(player)
When X makes its winning move, the player gets switched and the current player is now player 'O'. One idea could be checking is_win before the switch.
Without re-writing too much of your code I would just re-arrange the code a bit. You don't have to check if it is win or draw at start of the loop since it will never be True at start of a game. This means you can ask for input, set the cell, and only then check for win/draw. This makes you write out the winner before you switch turns.
You also don't want to print anything in the is_win function. Since that is your while loop criteria it will run the function after the code is executed and make it run with the wrong player. Solve this by not printing in the is_win function, just print when the if statement is fulfilled.
Another problem is that in your elif (win) statement you check if board is_full AND is_win. This will only happen if you win on the last spot.
You don't really have to write out "is False" or "is True" either. I think it is easier to read if you remove them and use the word not for False instead.
Rough code for the game loop:
def game():
player = 'X'
print_board(board)
while not is_win(board, player):
row, col = get_user_input()
set_cell(board, row, col, player)
if is_full(board) and not is_win(board, player):
print("draw")
break
elif is_win(board, player):
print(player + " has won!")
break
player = switch_turn(player)

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>

how can i fix the undefined error in 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 !!

I have a code that is supposed to replace a random spot in a string with an O [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
def getCSpot():
global board
global cspot
spotchosen = False
while spotchosen == False:
spotchosen = False
cspot = random.randint(0, 8)
if board[cspot] == 'X' or board[cspot] == 'O':
cspot = random.randint(0, 8)
else:
spotchosen = True
board[cspot] = 'O'
I dont really understand why this isn't working. It does not put the O in the string at all. I have another part of the code that determines if there is a winner when there are 3 O's or X's in a row and that doesn't work either, here is that code. Any help is much appreciated.
def didwin(player):
global gameOver
if (board[0] == player and board[1] == player and board[2] == player or
board[3] == player and board[4] == player and board[5] == player or
board[6] == player and board[7] == player and board[8] == player or
board[0] == player and board[3] == player and board[6] == player or
board[1] == player and board[4] == player and board[7] == player or
board[2] == player and board[5] == player and board[8] == player or
board[0] == player and board[4] == player and board[8] == player or
board[2] == player and board[4] == player and board[6] == player):
gameOver = True
if player == 'X':
print 'congratulations! You won!!'
endGame()
else:
print 'Better luck next time, you lost!'
endGame()
And for reference purposes, here is the endGame function.
def endGame():
global board
displayBoard()
answer = ' '
while answer == ' ':
print 'Would you like to play another game?'
answer = raw_input('Y/N')
if answer == 'Y' or answer == 'y' or answer == 'Yes' or answer == 'yes':
board = [0, 1, 2, 3, 4, 5, 6, 7, 8]
game1()
game()
elif answer == 'N' or answer == 'n' or answer == 'No' or answer == 'no':
exit()
Edit: the following is my whole code with no edits from beginning to end.
board = [0, 1, 2,
3, 4, 5,
6, 7, 8]
import random
def displayBoard():
global board
print board[0], '|', board[1], '|', board[2]
print '----------'
print board[3], '|', board[4], '|', board[5]
print '----------'
print board[6], '|', board[7], '|', board[8]
def getspot():
global board
spotchosen = False
while spotchosen == False:
spotchosen = False
playerSpot = int(raw_input('Where would you like to go? '))
if board[playerSpot] != 'X':
board[playerSpot] = 'X'
if board[playerSpot] != 'O':
board[playerSpot] = 'X'
if playerSpot == 'X':
playerSpot = raw_input('You have already chosen that spot. Please choose another. ')
if playerSpot == 'O':
playerSpot = raw_input('The computer chose that spot already. Please choose another. ')
else:
spotchosen = True
def getCSpot():
global board
global cspot
spotchosen = False
while spotchosen == False:
spotchosen = False
cspot = random.randint(0, 8)
if board[cspot] == 'X' or board[cspot] == 'O':
cspot = random.randint(0, 8)
else:
spotchosen = True
board[cspot] = 'O'
def endGame():
global board
displayBoard()
answer = ' '
while answer == ' ':
print 'Would you like to play another game?'
answer = raw_input('Y/N')
if answer == 'Y' or answer == 'y' or answer == 'Yes' or answer == 'yes':
board = [0, 1, 2, 3, 4, 5, 6, 7, 8]
game1()
game()
elif answer == 'N' or answer == 'n' or answer == 'No' or answer == 'no':
exit()
def didwin(player):
global gameOver
if (board[0] == player and board[1] == player and board[2] == player or
board[3] == player and board[4] == player and board[5] == player or
board[6] == player and board[7] == player and board[8] == player or
board[0] == player and board[3] == player and board[6] == player or
board[1] == player and board[4] == player and board[7] == player or
board[2] == player and board[5] == player and board[8] == player or
board[0] == player and board[4] == player and board[8] == player or
board[2] == player and board[4] == player and board[6] == player):
gameOver = True
if player == 'X':
print 'congratulations! You won!!'
endGame()
else:
print 'Better luck next time, you lost!'
endGame()
else:
gameOver = False
def mainGame():
gameOver = False
while gameOver == False:
displayBoard()
getspot()
didwin('X')
didwin('O')
mainGame()
I'm pretty sure that the problem, whatever it is, is in code that you didn't show us.
I didn't test your endGame function, to keep things simple. But I pasted in your other code, and added the following:
board = [0, 1, 2, 3, 4, 5, 6, 7, 8]
gameOver = False
def endGame():
print 'endGame called'
for i in range(9):
getCSpot()
print(board)
didwin('O')
if gameOver:
print 'gameOver'
break
The result was:
[0, 'O', 2, 3, 4, 5, 6, 7, 8]
[0, 'O', 2, 3, 'O', 5, 6, 7, 8]
[0, 'O', 2, 3, 'O', 5, 'O', 7, 8]
[0, 'O', 2, 3, 'O', 5, 'O', 'O', 8]
Better luck next time, you lost!
endGame called
gameOver
Of course the sequence is random, so it's not exactly the same every time, but it always replaces one random number at a time with 'O' until there's a 3-in-a-row, then tells me I lost.
So, it works exactly as intended. If your code doesn't work, you're doing something else wrong. Maybe you're setting up board or something else wrong in the initial setup?
Adding in your displayBoard and endGame code, it works until you say 'y' to play another game, at which point it calls some functions named game1 and game which don't exist, raising a NameError.
I also saw in your start function (from the comment that you since deleted, so this is from memory) that you were calling a function called getspot() in the game loop, instead of calling getCSpot(). If getspot is defined somewhere, the problem is presumably that you've got one correct function and one incorrect one. Or maybe it's not defined anywhere, and by "isn't working" and "does not put the O in the string at all" you mean "doesn't get called because the game halts with an exception before I ever get a chance"?
Now that you've posted the whole thing, there are a few obvious problems.
First, you never call getCSpot anywhere. That's why it doesn't do anything. Presumably you want this:
def mainGame():
gameOver = False
while gameOver == False:
displayBoard()
getspot()
didwin('X')
didwin('O')
getCSpot()
didwin('X')
didwin('O')
Also, in getspot, your if statements are all wrong. You're going to allow the move if board[playerSpot] != 'X', and also allow the move if board[playerSpot] != 'O'—in other words, always. And then you're going to count the player as moved unless playerSpot == 'O' is false—which it always is, because it's supposed to be a number.
I think you want this:
if board[playerSpot] == 'X':
playerSpot = raw_input('You have already chosen that spot. Please choose another. ')
elif board[playerSpot] == 'O':
playerSpot = raw_input('The computer chose that spot already. Please choose another. ')
else:
board[playerSpot] = 'X'
spotchosen = True

Categories