Skip to content

Instantly share code, notes, and snippets.

@asbenjamin
Last active October 29, 2022 11:43
Show Gist options
  • Save asbenjamin/8d2c05b2904e150a3c000387af811c04 to your computer and use it in GitHub Desktop.
Save asbenjamin/8d2c05b2904e150a3c000387af811c04 to your computer and use it in GitHub Desktop.
# print the board
# take user input
# check win or tie
# switch the player
# check win or tie again
board = [
"-","-","-",
"-","-","-",
"-","-","-"
]
current_player = "X"
winner = None
game_running = True
# 1. print board
def print_board(board):
print(board[0] + " | " + board[1] + " | " + board[2])
print(board[3] + " | " + board[4] + " | " + board[5])
print(board[6] + " | " + board[7] + " | " + board[8])
# 2. take user input
def take_player_input(board):
try:
inp = int(input("Enter a number 1-9: "))
if inp >= 1 and inp <= 9 and board[inp-1] == "-":
board[inp-1] = current_player
else:
print("Oops, spot is either taken or out of range")
except:
print("Please enter an actual number")
# 3. check win (horizontal, vertical, diagonal)
def check_horizontal(board):
global winner
if board[0] == board[1] == board[2] and board[0] != "-":
winner = board[0]
return True
elif board[3] == board[4] == board[5] and board[3] != "-":
winner = board[3]
return True
elif board[6] == board[7] == board[8] and board[6] != "-":
winner = board[6]
return True
def check_vertical(board):
global winner
if board[0] == board[3] == board[6] and board[0] != "-":
winner = board[0]
return True
elif board[1] == board[4] == board[7] and board[1] != "-":
winner = board[1]
return True
elif board[2] == board[5] == board[8] and board[2] != "-":
winner = board[2]
return True
def check_diagonal(board):
global winner
if board[0] == board[4] == board[8] and board[0] != "-":
winner = board[0]
return True
elif board[2] == board[4] == board[6] and board[2] != "-":
winner = board[2]
return True
# check winner function
def check_win():
global game_running
if check_diagonal(board) or check_horizontal(board) or check_vertical(board):
print_board(board)
print(f"The winner is {winner}")
game_running = False
def check_tie(board):
global game_running
if "-" not in board:
print_board(board)
print("It's a tie")
game_running = False
# 4. switch the player
def switch_player():
global current_player
if current_player == "X":
current_player = "O"
else:
current_player = "X"
# main game loop
while game_running:
print_board(board)
take_player_input(board)
check_win()
check_tie(board)
switch_player()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment