Why won't this tic-tac-toe code execute? - python

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;

Related

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>

Tic-Tac-Toe check win function not working

so i am making a tic tac toe program and the check win functions dont work, it seems as it just skips through it even if its true
this is a new way i wrote and it doesnt work
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 row_1 or row_2 or row_3:
if row_1 or row_2 or row_3 == char:
status = True
check = True
elif row_1 or row_2 or row_3 == ai_char:
status2 = True
check = False
this is the old way i had it doesnt work
if board[0] == board[3] == board[6] == char:
status = True
check = True
if board[1] == board[4] == board[7] == char:
status = True
check = True
if board[2] == board[5] == board[8] == char:
status = True
check = True
if board[0] == board[3] == board[6] == ai_char:
status2 = True
check = False
if board[1] == board[4] == board[7] == ai_char:
status2 = True
check = False
if board[2] == board[5] == board[8] == ai_char:
status2 = True
check = False
both ways looks like it should work but it doesnt
this is the whole code https://pastebin.com/G7Stkk79
why don't you make it much simpler by using this as an option.
row1 = all(board[i] != '-' for i in [0,3,6])
You can also try to use
row1 = all(board[i] != '-' for i in range(0,7,3))
The above code will work as follows:
if board[0] != '-' and board[3] != '-' and board[6] != '-':
row1 = True
else:
row1 = False
In this case, if any of the values in board[0], board[3], board[6] is equal to '-', then it will result in False else True.
In your code, you are checking for an entire row. It is much easier as you are going from 0 through 8 where row1=(0,1,2), row2=(3,4,5), and row3=(6,7,8)
If you want to check if the values in each row is not '-', then this code will work:
row_1_dash = all(board[i] != '-' for i in range(0,3))
row_2_dash = all(board[i] != '-' for i in range(3,6))
row_3_dash = all(board[i] != '-' for i in range(6,9))
If you want to check if each value in a row is the same, then you can check as follows:
row_1_same = all(board[i] == board[i+1] for i in range(0,2))
row_2_same = all(board[i] == board[i+1] for i in range(3,5))
row_3_same = all(board[i] == board[i+1] for i in range(6,8))
You can also check if the values are the same and also not equal to '-' using this:
row_1_win = all(board[i] == board[i+1] and board[i] != '-' for i in range(0,2))
row_2_win = all(board[i] == board[i+1] and board[i] != '-' for i in range(3,5))
row_3_win = all(board[i] == board[i+1] and board[i] != '-' for i in range(6,8))
With these options, you can probably reduce your code to find if the player won.
Let me know if you want to know the full implementation. This may help you look at options to implement your solution.

Why does my check_if_tie() function not working in TicTacToe?

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()

Total beginner wrote a tic tac toe game in Python and would like some feedback

I've decided to learn Python about 2 weeks ago, been going through various books and videos, and I've decided to try my hand at programming a tic tac toe game. I was somewhat successful (it doesn't recognize if there's already a mark in a certain spot and allows overwriting of already placed marks) and I was wondering if any more experienced programmers could give me some general feedback about how I could do things better. Thank you so much and I hope you're all staying safe.
board = ['-'] * 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])
legalMoves = [1,2,3,4,5,6,7,8,9]
print_board()
turnCount = 0
def move():
move = int(input('Pick a number 1-9:'))
while move not in legalMoves:
print('Illegal move')
move = int(input('Pick a number 1-9:'))
marks = ['X','O']
if turnCount % 2 == 0:
board[move - 1] = marks[1]
else:
board[move - 1] = marks[0]
while True:
if board[0] == board[1] == board[2] == 'X'\
or board[3] == board[4] == board[5] == 'X'\
or board[6] == board[7] == board[8] == 'X'\
or board[0] == board[3] == board[6] == 'X'\
or board[1] == board[4] == board[7] == 'X'\
or board[2] == board[5] == board[8] == 'X'\
or board[0] == board[4] == board[8] == 'X'\
or board[2] == board[4] == board[6] == 'X' \
or board[0] == board[1] == board[2] == 'O' \
or board[3] == board[4] == board[5] == 'O' \
or board[6] == board[7] == board[8] == 'O' \
or board[0] == board[3] == board[6] == 'O' \
or board[1] == board[4] == board[7] == 'O' \
or board[2] == board[5] == board[8] == 'O' \
or board[0] == board[4] == board[8] == 'O':
print('Victory')
break
else:
move()
print_board()
turnCount = turnCount + 1
well you need to check if the user has typed
an int or something else, so that breaks your
program, also prevent the user from overwriting
existed cell input, also prevent the user from
typing a number out of range which you have
already taken care of that, so I have written
this small function to give you the correct
input and deals with wrong ones, you can use it
def isInt(strInt):
for c in strInt:
if c not in "0123456789": return False
return True
def getNextMove():
while True:
moveStr = input("Pick a number 1-9: ")
if not isInt(moveStr):
print("Pls write only a number")
continue
move = int(moveStr)
if move < 1 or move > 9:
print("Pls only 1-9 numbers are allowed")
continue
if board[move - 1] != "-":
print("Pls choose an empty cell")
continue
return move
Well, if that helped, I couldn't stop my self from writing the full code for the game, I couldn't sleep anyway, so here it is, you may get some ideas, happy coding!
board = [" "] * 9
winner = ""
def printBoard():
print("-" * 7)
for i in range(3):
print(f"|{board[i * 3]}|{board[i * 3 + 1]}|{board[i * 3 + 2]}|")
print("-" * 7)
def isInt(strInt):
for c in strInt:
if c not in "0123456789": return False
return True
def getNextMove():
while True:
moveStr = input("Pick a number 1-9: ")
if not isInt(moveStr):
print("Pls write only a number")
continue
move = int(moveStr)
if move < 1 or move > 9:
print("Pls only 1-9 numbers are allowed")
continue
if board[move - 1] != " ":
print("Pls choose an empty cell")
continue
return move
def checkHVD():
for i in range(3):
if board[i * 3] == board[i * 3 + 1] == board[i * 3 + 2] and board[i * 3] != " ":
return board[i * 3]
elif board[i] == board[i + 3] == board[i + 6] and board[i] != " ":
return board[i]
if (board[0] == board[4] == board[8] or board[2] == board[4] == board[6]) and board[4] != " ":
return board[4]
return False
for i in range(9):
board[getNextMove() - 1] = i % 2 == 0 and "X" or "O"
printBoard()
winner = checkHVD();
if winner:
identity = winner == "X" and "first" or "second"
print(f"The {identity} player({winner}) won")
break
if not winner:
print("It's a tie")

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()

Categories