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>
Related
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'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!!
So I have got this Python code for my TicTacToe. Everything is working normal except when there is no winner the program must return 'Tie' and instead it just continues asking for X and O even if the board is already filled. I'm assuming the problem is in the check_if_tie() function but I can't figure it out.
# -------Global variables--------
# If game is still going
game_still_going = True
# Who won? Or tie
winner = None
# Whose turn it is
current_player = 'X'
# The board displaying function
board = [' '] * 10
def display_board():
print(' ' + board[6] + ' | ' + board[7] + ' | ' + board[8])
print('---+-' '--+--- ')
print(' ' + board[3] + ' | ' + board[4] + ' | ' + board[5])
print('---+-' '--+--- ')
print(' ' + board[0] + ' | ' + board[1] + ' | ' + board[2])
# Checks if game is over
def check_if_game_over():
check_if_tie()
check_if_win()
# Checks if there is a winner
def check_if_win():
global winner
if check_row():
winner = check_row()
elif check_columns():
winner = check_columns()
elif check_diagonals():
winner = check_columns()
else:
winner = None
return
def check_row():
global game_still_going
row1 = board[6] == board[7] == board[8] != " "
row2 = board[3] == board[4] == board[5] != " "
row3 = board[0] == board[1] == board[2] != " "
if row1 or row2 or row3:
game_still_going = False
if row1:
return board[6]
elif row2:
return board[3]
elif row3:
return board[0]
return
def check_columns():
global game_still_going
column1 = board[6] == board[3] == board[0] != " "
column2 = board[7] == board[4] == board[1] != " "
column3 = board[8] == board[5] == board[2] != " "
if column1 or column2 or column3:
game_still_going = False
if column1:
return board[6]
elif column2:
return board[7]
elif column3:
return board[8]
return
def check_diagonals():
global game_still_going
diagonal1 = board[6] == board[4] == board[2] != " "
diagonal2 = board[0] == board[4] == board[8] != " "
if diagonal1 or diagonal2:
game_still_going = False
elif diagonal1:
return board[6]
elif diagonal2:
return board[0]
return
def check_if_tie():
global game_still_going
if ' ' not in board:
game_still_going = False
return
def flip_player():
global current_player
if current_player == 'X':
current_player = 'O'
elif current_player == 'O':
current_player = 'X'
return
# Whose turn it is to play
def handle_turn(player):
print(player + "'s turn")
position = int(input('Please write your position from 1 - 9: ')) - 1
if position not in [0,1,2,3,4,5,6,7,8,9]:
return input('Invalid position. Please write 1-9: ')
board[position] = player
display_board()
# Main gameplay function
def play_game():
global winner
# Displays initial board
display_board()
# Loop running the game
while game_still_going:
handle_turn(current_player)
flip_player()
check_if_game_over()
if winner == 'X' or winner == 'O':
print(winner + ' won.')
elif winner:
print('Tie')
play_game()
You're having quite a lot of issues in this code and most of the problem could be avoided by avoiding the use of globals.
When you use globals you change a global state that makes it difficult to understand what's going on. You have functions that return nothing but change state that will make the game end or not.
One simple change would be to have you check_ method return an actual boolean and use that value in the loop to check if you have a tie or a win.
If you're not in a tie or a win, it means the game isn't finished. So you don't need to store a global value and certainly do not have to modify the state of the is a tie or a win anywhere else.
Keep you functions as simple as possible. I often say that but think how you actually play a game.
In a game you have 2 players and 1 board, in which you set values anywhere.
Each turn adds a piece until the game ends in a tie or a win.
Everytime you add a piece you can check the state of the game. If it's not finished then you can swith the current player and enter a new piece and repeat.
None of this requires a global state and you can always pass the game board to your methods...
In your case it would be as simple as doing this:
def is_tie():
return ' ' not in board
def is_win():
... is_win logic
return result
while not is_tie() or not is_win():
... game logic
To go a step further, instead of having globals you'd have to pass the game state as arugment like this:
def is_tie(game):
return ' ' not in game.board
And to go a step further, entering a new piece in the board would return a new state. So instead of modifying the current state you'd have a main loop that looks like this:
game = Game()
while True:
position = game.prompt_choice()
if not game.position_available(position)
# loop again to select a new position
continue
game = game.execute_turn(position)
if game.is_done()
break
else:
# if game not done switch player and move to next turn
game = game.switch_player()
# current game player is winner
game.print_winner()
The cool thing is that if you wanted to "replay" the game, you'd just have to save the state of the game just before looping again. each "game" being returned is a modified version of the previous game object so you're never modifying the actual object.
The simplest suggestion that I can think of would be to have a variable that holds the amount of available squares left and decrement it after each turn. Once it reaches 0, if there is no win, then there must a tie.
# -------Global variables--------
# If game is still going
game_still_going = True
# Who won? Or tie
winner = None
# Whose turn it is
current_player = 'X'
# The board displaying function
board = [' '] * 10
#board spaces
board_spaces = 9
def display_board():
print(' ' + board[6] + ' | ' + board[7] + ' | ' + board[8])
print('---+-' '--+--- ')
print(' ' + board[3] + ' | ' + board[4] + ' | ' + board[5])
print('---+-' '--+--- ')
print(' ' + board[0] + ' | ' + board[1] + ' | ' + board[2])
# Checks if game is over
def check_if_game_over():
check_if_win()
check_if_tie()
# Checks if there is a winner
def check_if_win():
global winner
if check_row():
winner = check_row()
elif check_columns():
winner = check_columns()
elif check_diagonals():
winner = check_columns()
else:
winner = None
return
def check_row():
global game_still_going
row1 = board[6] == board[7] == board[8] != " "
row2 = board[3] == board[4] == board[5] != " "
row3 = board[0] == board[1] == board[2] != " "
if row1 or row2 or row3:
game_still_going = False
if row1:
return board[6]
elif row2:
return board[3]
elif row3:
return board[0]
return
def check_columns():
global game_still_going
column1 = board[6] == board[3] == board[0] != " "
column2 = board[7] == board[4] == board[1] != " "
column3 = board[8] == board[5] == board[2] != " "
if column1 or column2 or column3:
game_still_going = False
if column1:
return board[6]
elif column2:
return board[7]
elif column3:
return board[8]
return
def check_diagonals():
global game_still_going
diagonal1 = board[6] == board[4] == board[2] != " "
diagonal2 = board[0] == board[4] == board[8] != " "
if diagonal1 or diagonal2:
game_still_going = False
elif diagonal1:
return board[6]
elif diagonal2:
return board[0]
return
def check_if_tie():
global game_still_going
global winner
global board_spaces
if winner == None and board_spaces == 0:
game_still_going = False
return
def flip_player():
global current_player
if current_player == 'X':
current_player = 'O'
elif current_player == 'O':
current_player = 'X'
return
# Whose turn it is to play
def handle_turn(player):
print(player + "'s turn")
position = int(input('Please write your position from 1 - 9: ')) - 1
if position not in [0,1,2,3,4,5,6,7,8,9]:
return input('Invalid position. Please write 1-9: ')
board[position] = player
display_board()
board_spaces -= 1
# Main gameplay function
def play_game():
global winner
# Displays initial board
display_board()
# Loop running the game
while game_still_going:
handle_turn(current_player)
flip_player()
check_if_game_over()
if winner == 'X' or winner == 'O':
print(winner + ' won.')
elif winner:
print('Tie')
play_game()
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&cf=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()
I'm trying to learn python and have been writing a (very) simple tic-tac-toe program. However, I've got stuck because it won't seem to execute beyond letting the user enter a number. After that, nothing happens. I can't figure out where I have gone wrong. Sure there are tons of errors, but help much appreciated!
Thanks!
import random
board = range(0,9)
def print_board():
print board[0], "|", board[1], "|", board[2]
print board[3], "|", board[4], "|", board[5]
print board[6], "|", board[7], "|", board[8]
def checkAll():
if board[0] == board[1] == board[2]:
True
if board[3] == board[4] == board[5]:
True
if board[6] == board[7] == board[8]:
True
if board[0] == board[3] == board[6]:
True
if board[1] == board[4] == board[7]:
True
if board[2] == board[5] == board[8]:
True
if board[0] == board[4] == board[8]:
True
if board[6] == board[4] == board[2]:
True
print_board()
while True:
input = int(raw_input("Choose a number to place your X: "))
if input <= 8:
if board[input] != "x" or board[input] != "o":
board[input] = "x" # places x if board[input] is neither x or o
# Check for winner
if checkAll() == True:
"The game is over!"
break;
finding = True
while finding:
random.seed() # gives a random generator
opponent = random.randrange(0,8) # generates a random integer between 1 and 8
if board[opponent] != "x" or board[opponent] != "o":
board[opponent] = "o"
# Check for winner
if checkAll() == True:
"The game is over!"
break;
else:
print "This spot is taken."
print_board()
else: "Please choose a number between O and 8."
Well there're many things which need improvement in your code (you have to rewrite your CheckAll function at least so it could check board of any size), but two things will help you to debug - first, you have to actually return something from your CheckAll function:
...
if board[0] == board[1] == board[2]:
return True
if board[3] == board[4] == board[5]:
return True
...
second, you may actually want to print output:
if checkAll() == True:
print "The game is over!"
break;