--------- Global Variables -----------
# Will hold our game board data
board = ["-", "-", "-",
"-", "-", "-",
"-", "-", "-"]
# Lets us know if the game is over yet
game_still_going = True
# Tells us who the winner is
winner = None
# Tells us who the current player is (X goes first)
current_player = "X"
# ------------- Functions ---------------
# Play a game of tic tac toe
def play_game():
# Show the initial game board
display_board()
# Loop until the game stops (winner or tie)
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 turn for an arbitrary player
def handle_turn(player):
# Get position from player
print(player + "'s turn.")
position = input("Choose a position from 1-9: ")
# 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 valid
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.")
# 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 to see if somebody has won
def check_for_winner():
# Set global variables
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
# Check the rows for a win
def check_rows():
# Set global variables
global game_still_going
# Check if any of the rows have all the same value (and is 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
if row_1:
return board[0]
elif row_2:
return board[3]
elif row_3:
return board[6]
# Or return None if there was no winner
else:
return None
# Check the columns for a win
def check_columns():
# Set global variables
global game_still_going
# Check if any of the columns have all the same value (and is 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 row 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
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
# Check the diagonals for a win
def check_diagonals():
# Set global variables
global game_still_going
# Check if any of the columns have all the same value (and is not empty)
diagonal_1 = board[0] == board[4] == board[8] != "-"
diagonal_2 = board[2] == board[4] == board[6] != "-"
# If any row does have a match, flag that there is a win
if diagonal_1 or diagonal_2:
game_still_going = False
# Return the winner
if diagonal_1:
return board[0]
elif diagonal_2:
return board[2]
# Or return None if there was no winner
else:
return None
# Check if there is a tie
def check_for_tie():
# Set global variables
global game_still_going
# If board is full
if "-" not in board:
game_still_going = False
return True
# Else there is no tie
else:
return False
# Flip the current player from X to O, or O to X
def flip_player():
# Global variables we need
global current_player
# If the current player was X, make it O
if current_player == "X":
current_player = "O"
# Or if the current player was O, make it X
elif current_player == "O":
current_player = "X"
# ------------ Start Execution -------------
# Play a game of tic tac toe
play_game()
So I am trying to write a unit test for this code, so for example I am trying to check the def check_columns() function.
So far I came up with:
import unittest
import Tic_tac_toe
class TestGame(unittest.TestCase):
def test_check_for_column(self):
columns_1 = None
self.assertEqual(Tic_tac_toe.check_columns(), columns_1)
This checks out because initially, there is no input so I get None but I am trying to input "x" in the column and see if it returns the winner. How would I do that?
Related
So basically I am trying to build a Tic-Tac-Toe game with both single and multiplayer difficulty levels but I am stuck on what code should I write for player vs computer and I am stuck in a forever loop in the def play_game() function. I can't keep the previous stats of the game as well. I really need help with this.
# --------- Global Variables -----------
# Will hold our game board data
board = ["-", "-", "-",
"-", "-", "-",
"-", "-", "-"]
# Lets us know if the game is over yet
game_still_going = True
# Tells us who the winner is
winner = None
# Tells us who the current player is (X goes first)
current_player = "X"
# ------------- Functions ---------------
# Play a game of tic tac toe
def play_game():
# Show the initial game board
display_board()
game_on = True
while True:
print("1.Single Player")
print("2.Multiplayer")
print("3.Game Stats")
print("4.Quit")
input_1 = int(input("Please Select An Option"))
if input_1 == "3" :
print('reading database...')
read_log()
elif input_1 == "4" :
exit()
elif input_1 == "2" :
Player_1 = input("Enter First Player Name:")
Player_2 = input("Enter Second Player Name:")
display_board()
while game_on:
position = input("Choose a position from 1-9: ")
check_for_winner()
display_board()
# Loop until the game stops (winner or tie)
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 turn for an arbitrary player
def handle_turn(player):
# Get position from player
print(player + "'s turn.")
position = input("Choose a position from 1-9: ")
# 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 valid
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.")
# 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 to see if somebody has won
def check_for_winner():
# Set global variables
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
# Check the rows for a win
def check_rows():
# Set global variables
global game_still_going
# Check if any of the rows have all the same value (and is 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
if row_1:
return board[0]
elif row_2:
return board[3]
elif row_3:
return board[6]
# Or return None if there was no winner
else:
return None
# Check the columns for a win
def check_columns():
# Set global variables
global game_still_going
# Check if any of the columns have all the same value (and is 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 row 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
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
# Check the diagonals for a win
def check_diagonals():
# Set global variables
global game_still_going
# Check if any of the columns have all the same value (and is not empty)
diagonal_1 = board[0] == board[4] == board[8] != "-"
diagonal_2 = board[2] == board[4] == board[6] != "-"
# If any row does have a match, flag that there is a win
if diagonal_1 or diagonal_2:
game_still_going = False
# Return the winner
if diagonal_1:
return board[0]
elif diagonal_2:
return board[2]
# Or return None if there was no winner
else:
return None
# Check if there is a tie
def check_for_tie():
# Set global variables
global game_still_going
# If board is full
if "-" not in board:
game_still_going = False
return True
# Else there is no tie
else:
return False
# Flip the current player from X to O, or O to X
def flip_player():
# Global variables we need
global current_player
# If the current player was X, make it O
if current_player == "X":
current_player = "O"
# Or if the current player was O, make it X
elif current_player == "O":
current_player = "X"
def read_log():
log = open('log.txt', 'r')
log.seek(0)
print('\n\n')
print(log.read(),'\n\n')
# ------------ Start Execution -------------
# Play a game of tic tac toe
play_game()
If I understood correctly You can do it like this:
Define functions:
handle_player_move()
handle_computer_move()
as names suggests when you call the function either human player or computer will make a move (make sure that it's certain or add some Errorcodes/Exceptions when player do something unexpected and you want to end program)
Define function:
game_is_over() # returns True if it's the end of game False other wise
Then Your game is just:
Human vs Human:
whos_move = 0 # number of player ( 0 or 1 )
while not game_is_over():
if whos_move == 0:
handle_player_move(player1)
if whos_move == 1:
handle_player_move(player2)
whos_move = (whos_move + 1) % 2
Quite similarly Human vs Bot:
whos_move = 0 # number of player ( 0 or 1 )
while not game_is_over():
if whos_move == 0:
handle_player_move(player1)
if whos_move == 1:
handle_computer_move(player2)
whos_move = (whos_move + 1) % 2
Instead of this you can also check for end of game with your function, and do:
whos_move = 0 # number of player ( 0 or 1 )
while game_still_going:
if whos_move == 0:
handle_player_move(player1)
if whos_move == 1:
handle_computer_move(player2)
whos_move = (whos_move + 1) % 2
check_if_game_over()
if statement: # your ending statement here
game_is_still_going = False
Your method with flip_player() is also good I just put if statements to both so that they are familiar in truth if you would are able to distinguish in handle_turn() between bot and human player you can do it for both cases ;)
As implementing computer moves can be hard here are some tips:
Easiest way you can just randomly choose number between 1 and 9 check if it's unoccupied if it's free computer makes move there if it is not you pick again. Maybe it sounds like being potentially endless loop but statisticly computer shouldn't have any problems with making a move.
You can also create list of free squares and then randomly choose an index (probably better way)
You can also try to add some logic f.e. if there are two in a row block third square.
too choose random integer from given interval you can use:
import random
random.randint(1,9) # choose integer x such that: 1 <= x <= 9
Of course you can and even maybe should use your own function names (name them as you wish!)
Hope that helps, good luck!
I recently took it upon myself to try and code a TicTacToe board in order to test my understanding of the concepts I learned online. However, I encountered a few problems within my code and do not understand why it doesn't work as intended.
While attempting to get the code to print a winner, my code does not work as intended and does not choose a winner based on the values I have inputted. Sometimes the code runs and a winner is detected two turns after someone has already won, and sometimes it exits the code without a 5th move having even been played.
Below is the code I worked on. It includes insurance that you cannot input an X or an O in a position that has already been taken up and prints the Xs and Os where the players choose. I believe that the errors take place somewhere in the row(), column(), and diagonal() parts of the code.
player = 0
player_add = 1
winner = None
already_taken = []
turns_taken = 0
board = [
"-", "-", "-",
"-", "-", "-",
"-", "-", "-"
]
def handle_turn(turn, turn_add):
while turn % 2 == 0:
position = int(input("Choose a position from 1-9 to add an \"X\": ")) - 1
already_taken.append(position)
board[position] = "X"
turn += turn_add
display_board()
while already_taken.count(position) > 1:
print("Position already taken.")
board[position] = "O"
display_board()
already_taken.remove(position)
turn += turn_add
while turn % 2 == 1:
position = int(input("Choose a position from 1-9 to add an \"O\": ")) - 1
already_taken.append(position)
board[position] = "O"
turn += turn_add
display_board()
while already_taken.count(position) > 1:
print("Position already taken.")
board[position] = "X"
display_board()
already_taken.remove(position)
turn += turn_add
def display_board():
print(board[0] + "|" + board[1] + "|" + board[2])
print(board[3] + "|" + board[4] + "|" + board[5])
print(board[6] + "|" + board[7] + "|" + board[8])
def play_game():
display_board()
handle_turn(player, player_add)
def rows():
global running
if board[0] and board[1] and board[2] == board[0] and board[0] != "-":
running = False
return board[0]
if board[3] and board[4] and board[5] == board[3] and board[3] != "-":
running = False
return board[3]
if board[6] and board[7] and board[8] == board[6] and board[6] != "-":
running = False
return board[6]
return
def columns():
global running
if board[0] and board[3] and board[6] == board[0] and board[0] != "-":
running = False
return board[0]
if board[1] and board[4] and board[7] == board[1] and board[1] != "-":
running = False
return board[3]
if board[2] and board[5] and board[8] == board[2] and board[2] != "-":
running = False
return board[6]
return
def diagonals():
global running
if board[0] and board[4] and board[8] == board[0] and board[0] != "-":
running = False
return board[0]
if board[2] and board[4] and board[6] == board[2] and board[2] != "-":
running = False
return board[3]
return
def check_if_win():
global winner
# Rows
row_winner = rows()
# Columns
column_winner = columns()
# Diagonals
diagonal_winner = diagonals()
if row_winner:
winner = row_winner
elif column_winner:
winner = column_winner
elif diagonal_winner:
winner = diagonal_winner
else:
winner = None
def check_if_game_over():
check_if_win()
running = True
while running:
play_game()
check_if_game_over()
if winner == "X":
print("Player " + str(winner) + " has won!")
elif winner == "O":
print("Player " + str(winner) + " has won!")
elif winner is None:
print("Whoops! Looks like you both loose.")
'''
You almost got it right, but you made a typo:
if board[0] and board[3] and board[6] == board[0] and board[0] != "-":
This should be:
if board[0] == board[3] and board[6] == board[0] and board[0] != "-":
I would say, if you fix all of those. It may work - at least a little bit better.
Hope this taught you not to copy-paste code too much, as you can easily copy the same mistake over and over again.
So, what happened? Well, if you have if(board[0] and board[3]) like you did, it checks if board[0] evaluates to true and the same for board[3]. The way true and false is implemented is that false = 0, and true is just the opposite of false: true = !false. So, what you were checking for was pretty much, "is board[0] zero?" No, so that is true. So, no wonder that you were confused.
I am currently learning python and trying to build a tic tac toe game. I wrote a program to prevent the user repeating the same input but when I repeat the same number two times, the program starts looping continuously without stopping. Could someone give me advice on how to rectify this issue? see below the code:
from tabulate import tabulate
# define the board
board = ["_", "_", "_",
"_", "_", "_",
"_", "_", "_"]
# Current player
current_player = "X"
winner = None
game_still_on = True
def play_game():
while game_still_on:
position()
board_display()
handle_player()
winner_check()
winner_check2()
def handle_player():
global current_player
if current_player == "X":
current_player = "O"
elif current_player == "O":
current_player = "X"
def board_display():
board_row1 = [board[0], board[1], board[2]]
board_row2 = [board[3], board[4], board[5]]
board_row3 = [board[6], board[7], board[8]]
com_board = [board_row1,
board_row2,
board_row3]
print(tabulate(com_board, tablefmt="grid"))
# position input
def position():
global board
print(current_player+"'s turn")
positions = input("enter 1-9")
valid = False
while not valid:
while int(positions) >= 10 or 0 >= int(positions):
positions = input("Choose a position from 1 -9")
positions = int(positions)
if board[positions-1] == "_":
valid = True
else:
print("Choose another")
board[positions - 1] = current_player
def winner_check():
if board[0] == board[1] == board[2] != "_":
return board[0]
elif board[3] == board[4] == board[5] != "_":
return board[3]
elif board[6] == board[7] == board[8] != "_":
return board[6]
elif board[0] == board[3] == board[6] != "_":
return board[0]
elif board[1] == board[4] == board[7] != "_":
return board[1]
elif board[2] == board[5] == board[8] != "_":
return board[2]
elif board[0] == board[4] == board[8] != "_":
return board[0]
elif board[2] == board[4] == board[6] != "_":
return board[1]
else:
return None
def winner_check2():
row_winner = winner_check()
if row_winner:
global game_still_on
global winner
winner = row_winner
print((winner+ " won"))
game_still_on = False
play_game()
Let's look at this function:
# position input
def position():
global board
print(current_player+"'s turn")
positions = input("enter 1-9")
valid = False
while not valid:
while int(positions) >= 10 or 0 >= int(positions):
positions = input("Choose a position from 1 -9")
positions = int(positions)
if board[positions-1] == "_":
valid = True
else:
print("Choose another")
board[positions - 1] = current_player
This has nested validation loops. The inner one checks the range of the input integer (if it is an integer -- otherwise it throws an exception) and requests input until it's in range. That's fine.
Then in the outer validation loop, it checks if the requested space is unoccupied. If so, fine. If not, it prompts the user to choose another. But the input call is before the outer loop, so it just tries again to validate the same input that already failed.
Try moving the input into the outer loop:
# position input
def position():
global board
print(current_player+"'s turn")
valid = False
while not valid:
positions = input("enter 1-9")
while int(positions) >= 10 or 0 >= int(positions):
positions = input("Choose a position from 1 -9")
positions = int(positions)
if board[positions-1] == "_":
valid = True
else:
print("Choose another")
board[positions - 1] = current_player
I'd probably also change the inner loop to be just an if with a continue and make the handling of non-integer input more robust.
I am a first semester student and I am trying to restart my game. Problem is I dont really know how even though the game works fine. I assumed the solution would be to call the function play() again but for the life of me im stuck!
Tried creating a while loop to try and loop the game while still playing
while playing == True:
play()
continue_play = input("Continue playing? (y/n)")
if continue_play.lower() == "n":
playing = False
else:
new_game = play()
show_board()
new_game()
This is the while loop....new game returns 'nonetype' not callable....
below is my actual code for entire game:
playing = True
#Global variables to be used
game_active = True
champion = None
active_player = " X "
#Displays board
def show_board():
print(" 1 2 3")
print("1 " + board[0] + " | " + board[1] + " | " + board[2])
print(" ----+-----+----")
print("2 " + board[3] + " | " + board[4] + " | " + board[5])
print(" ----+-----+----")
print("3 " + board[6] + " | " + board[7] + " | " + board[8])
#play game of TIC TAC TOE
def play():
global board
board = [" ", " ", " ",
" ", " ", " ",
" ", " ", " "]
#display the game board to users
show_board()
#while game is still active
while game_active:
#Whos turn is it?
turns(active_player)
#check if game has met finishing requirements
check_game_done()
#Change player turn
change_player()
#game has ended
if champion == " X " or champion == " O ":
print(champion + " Is the winner!")
elif champion == None:
print(" Draw ")
#function for handling player turns
def turns(player):
print(player + "'s Turn.")
player_position = input("Please choose a number for your move between 1-9: ")
ok = False
while not ok:
while player_position not in ["1", "2", "3", "4", "5", "6", "7", "8", "9"]:
player_position = input(" Please choose a number for your move between 1-9: ")
player_position = int(player_position) - 1
if board[player_position] == " ":
ok = True
else:
print("Sorry this spot is taken.")
board[player_position] = player
show_board()
#function to check over game to see if game completed
def check_game_done():
check_win()
check_draw()
def check_win():
#using global variable from above code
global champion
#rows
winning_row = check_rows()
#columns
winning_column = check_columns()
#diagonals
winning_diagonal = check_diagonals()
if winning_row:
#winner found
champion = winning_row
elif winning_column:
#winner found
champion = winning_column
elif winning_diagonal:
#winner found
champion = winning_diagonal
else:
#no winner found
champion = None
def check_rows():
#call global variable to check if game still active
global game_active
#check rows for winning condition
row1 = board[0] == board[1] == board[2] != " "
row2 = board[3] == board[4] == board[5] != " "
row3 = board[6] == board[7] == board[8] != " "
#winning conditions met?
if row1 or row2 or row3:
game_active = False
#who won?
if row1:
return board[0]
elif row2:
return board[3]
elif row3:
return board[6]
else:
return None
def check_columns():
#call global variable to check if game still active
global game_active
#check columns for winning condition
column1 = board[0] == board[3] == board[6] != " "
column2 = board[1] == board[4] == board[7] != " "
column3 = board[2] == board[5] == board[8] != " "
#Win conditions met
if column1 or column2 or column3:
game_active = False
#who won
if column1:
return board[0]
elif column2:
return board[1]
elif column3:
return board[3]
else:
return None
def check_diagonals():
#call global variable to check if game still active
global game_active
#check diagonals for winning condition
diagonal_1 = board[0] == board[4] == board[8] != " "
diagonal_2 = board[2] == board[4] == board[6] != " "
#win conditon met
if diagonal_1 or diagonal_2:
game_active = False
#who won
if diagonal_1:
return board[0]
elif diagonal_2:
return board[2]
else:
return None
# Checking to see if conditions for a draw have been met
def check_draw():
global game_active
if " " not in board:
game_active = False
return True
else:
return False
# Using function to decide whos turn it is
def change_player():
global active_player
if active_player == " X ":
active_player = " O "
elif active_player == " O ":
active_player = " X "
return None
# Restarting game again
while playing == True:
play()
continue_play = input("Continue playing? (y/n)")
if continue_play.lower() == "n":
playing = False
else:
new_game = play()
show_board()
new_game()
play()
Change the while loop to:
...
while playing == True:
play()
continue_play = input("Continue playing? (y/n)")
if continue_play.lower() == "n":
playing = False
else:
game_active = True
champion = None
play()
show_board()
...
Now it will work.
I am attempting to prompt the user the option to save the game, after the first move, during gameplay?
After the game is completed I want to prompt the user to reset the game(Y or N) then call the play game function(with a loop)?
However, I am unsure how to organize the code to accomplish these tasks. I am a beginner to python.
def play_game():
game = True
while game == True:
game_choice = menu()
if game_choice == 1:
choice_one()
elif game_choice ==2:
player1VSai()
elif game_choice ==3:
save_and_exit()
elif game_choice==4:
load_game()
#After the game is completed I want to reset the game and call the play game function(with a loop).
# reset_game()
# play_game()
def choice_one():
# Display initial board
display_board()
while game_still_playing:
# handle a single turn of a arbitrary player
handle_turn(current_player)
# check if win or tie
check_if_game_over()
# flip to other player
alternate_player()
# The game has ended
if winner == 'X' or winner == 'O':
print(winner + " won.")
elif winner == None:
print("Tie.")
# handle a single turn of a random player
def handle_turn(player):
print(player + "'s turn.")
position = input("Choose a position from 1 to 9: ")
# I can index into position with int instead of string
valid = False
while not valid:
while position not in ["1", "2", "3", "4", "5", "6", "7", "8", "9"] or position ==0:
position = input("Choose a position from 1-9: ")
if position == 0:
save_and_exit()
pass
# convert from string to int
position = int(position) - 1
if board[position] == '':
valid = True
else:
print("Space filled. Go again.")
# Board at position equals X
board[position] = player
display_board()
print("Press 0 to save & exit game.")
#then if? or loop? prompt user to save game?
For saving code, your Game has things that you should save:
The state of the board, variable player
Whose turn it is, variable
board
This means you would have to write a function that takes these 2 variables as input argument and writes the content to a file.
#Remy this is what I have for the save function,
which I believe works properly as I've saved the data I need.
def save_and_exit():
global current_player
#save and end loop
turn=current_player
option = menu()
file=open("HW3game.txt", "w")
for x in board:
file.write(x)
file.write(turn)
file.write(str(option))
file.close()
print("You have saved the game and exited")
return
import random
# functions
# board
# display board
# ask if you want to be x or O
# menu
# play game
# take input & alternate turns
# check win
# check rows
# check columns
# check diagonals
# check tie
# is board full
# ---- Global Variables -----
# Game Board
board = [''] * 9
# If game is still going
game_still_playing = True
# Who won? Or Tie?
winner = None
# Prompt user to choose X's or O's
letter = input("Choose a letter X or O: ").upper()
current_player = letter
# Input validation
while current_player not in ('x', 'o', 'X', 'O'):
letter = input("Try again. Choose a letter X or O:").upper()
current_player = letter
if letter.upper() not in ('X', 'O'):
print("Not an appropriate choice.")
else:
break
print("Player 1 will be ", current_player + "'s.\n")
def display_board():
print(board[6], "\t|", board[7] + " | " + board[8])
print("--------------")
print(board[3], "\t|", board[4] + " | " + board[5])
print("--------------")
print(board[0], "\t|", board[1] + " | " + board[2])
# ("1) Player 1 vs Player 2\n2) Player 1 vs AI\n3) Load Game\n0) Save & Exit")
# play tic tac toe
def play_game():
begin = "Y"
while begin == "Y":
game_choice = menu()
if game_choice == 1:
choice_one()
elif game_choice ==2:
player1VSai()
elif game_choice ==3:
save_and_exit()
elif game_choice==4:
load_game()
def choice_one():
# Display initial board
display_board()
while game_still_playing:
# handle a single turn of a arbitrary player
handle_turn(current_player)
# check if win or tie
check_if_game_over()
# flip to other player
alternate_player()
# The game has ended
if winner == 'X' or winner == 'O':
print(winner + " won.")
clear_board = reset_game()
play_game()
elif winner == None:
print("Tie.")
reset_game()
play_game()
# handle a single turn of a random player
def handle_turn(player):
print(player + "'s turn.")
position = input("Choose a position from 1 to 9: ")
# I can index into position with int instead of string
valid = False
while not valid:
while position not in ["1", "2", "3", "4", "5", "6", "7", "8", "9"] or position ==0:
position = input("Choose a position from 1-9: ")
if position == 0:
save_and_exit()
pass
# convert from string to int
position = int(position) - 1
if board[position] == '':
valid = True
else:
print("Space filled. Go again.")
# Board at position equals X
board[position] = player
display_board()
print("Press 0 to save & exit game.")
#then if? or loop? prompt user to save game?
def check_if_game_over():
# 3 in a row
check_for_winner()
# full board
check_if_tie()
def check_for_winner():
# Set up global variables
global winner
# check rows
row_winner = check_rows()
# check columns
column_winner = check_columns()
# check diagonals
diagonal_winner = check_diagonals()
if row_winner:
winner = row_winner
print("There was a ROW win!")
elif column_winner:
winner = column_winner
print("There was a COLUMN win!")
elif diagonal_winner:
winner = diagonal_winner
print("There was a DIAGONAL win!")
else:
winner = None
def check_rows():
# Set up global variables
global game_still_playing
# check rows for all the same values & is not an empty ''
row_1 = board[6] == board[7] == board[8] != ''
row_2 = board[3] == board[4] == board[5] != ''
row_3 = board[0] == board[1] == board[2] != ''
# if any row does have a match, flag that there is a win
if row_1 or row_2 or row_3:
game_still_playing = False
# Return the winner (X or O)
if row_1:
return board[6]
elif row_2:
return board[3]
elif row_3:
return board[0]
# return X or O if winner
# then flag game still playing to false to end loop
def check_columns():
# Set up global variables
global game_still_playing
# check columns for all the same values & is not an empty ''
column_1 = board[6] == board[3] == board[0] != ''
column_2 = board[7] == board[4] == board[1] != ''
column_3 = board[8] == board[5] == board[2] != ''
# if any column does have a match, flag that there is a win
if column_1 or column_2 or column_3:
game_still_playing = False
# Return the winner (X or O)
if column_1:
return board[6]
elif column_2:
return board[7]
elif column_3:
return board[8]
# return X or O if winner
# then flag game still playing to false to end loop
def check_diagonals():
# Set up global variables
global game_still_playing
# check columns for all the same values & is not an empty ''
diagonal_1 = board[0] == board[4] == board[8] != ''
diagonal_2 = board[6] == board[4] == board[2] != ''
# if any row does have a match, flag that there is a win
if diagonal_1 or diagonal_2:
game_still_playing = False
# Return the winner (X or O)
if diagonal_1:
return board[0]
elif diagonal_2:
return board[6]
# return X or O if winner
# then flag game still playing to false to end loop
def check_if_tie():
# declare global variable
global game_still_playing
# check if board full
if '' not in board:
game_still_playing = False
return
def alternate_player():
global current_player
# if current player is == to X then change it to O
if current_player == "X":
current_player = 'O'
# if current player is == to O then change it to X
elif current_player == "O":
current_player = 'X'
def player1VSai():
#random number
return
def save_and_exit():
global current_player
#save and end loop
turn=current_player
option = menu()
file=open("HW3game.txt", "w")
for x in board:
file.write(x)
file.write(turn)
file.write(str(option))
file.close()
print("You have saved the game and exited")
return
def menu():
print("Welcome to Tic Tac Toe")
print("1) Player 1 vs Player 2\n2) Player 1 vs AI\n3) Save & Exit\n4) Load Game")
game_choice = int(input("Choose an option, 0-4: "))
#
return game_choice
def load_game():
#setup global
global current_player
file = open("HW3game.txt", "r")
for i in range(0,8):
board[i]=file.read(1)
current_player=file.read(1)
#current choice of game.
game_choice=int(file.read(1))
file.close()
print("You have called the load function.")
return
def reset_game():
global board
#erase contents in current board
#replay game
clear_board = board.clear()
return clear_board
play_game()