Skip to content

Instantly share code, notes, and snippets.

@rtindru
Last active October 29, 2020 16:20
Show Gist options
  • Save rtindru/ba8a176cb1a2aa47f2a8442ff8c35921 to your computer and use it in GitHub Desktop.
Save rtindru/ba8a176cb1a2aa47f2a8442ff8c35921 to your computer and use it in GitHub Desktop.
Python code for a game of Tic Tac Toe
BOARD = dict()
EMPTY_CHAR = "*"
WIN_CHAR = "@"
# Store all possible win combinations
WIN_COMBOS = [
(1, 2, 3),
(4, 5, 6),
(7, 8, 9),
(1, 4, 7),
(2, 5, 8),
(3, 6, 9),
(1, 5, 9),
(3, 5, 7),
]
def setup_game():
# Initialize the board with empty states. We're using a simple dictionary with indices running from 1 through 9
# |1 2 3|
# |4 5 6|
# |7 8 9|
for i in range(1, 10):
BOARD[i] = EMPTY_CHAR
def check_win():
# Check if either player won the game
for i, j, k in WIN_COMBOS:
if BOARD[i] == BOARD[j] == BOARD[k] != EMPTY_CHAR:
winner = BOARD[i]
BOARD[i] = BOARD[j] = BOARD[k] = WIN_CHAR
return winner
return None
def continue_game():
# The game can continue if there's an empty spot
if EMPTY_CHAR in BOARD.values():
return True
return False
def next_turn(current_turn):
# Swap turns between the two players, X & O
if current_turn == "X":
return "O"
else:
return "X"
def print_board(show_index=False):
# Print the board's current state
for i in range(1, 10,):
if i % 3 == 1:
print("|", end=' ')
if show_index:
# Print the cell indices
print(i, end=' ')
else:
# Print the actual board
print(BOARD[i], end=' ')
if i % 3 == 0:
print("|", end=' ')
print()
def get_input(turn):
# Get user input on which cell they want to play
valid = False
while not valid:
try:
num = int(input("Enter a number: "))
assert 1 <= num <= 9
except (ValueError, AssertionError):
print("Please enter a valid number between 1 and 9.")
continue
if BOARD[num] == EMPTY_CHAR:
BOARD[num] = turn
valid = True
else:
print("That cell has already been played, try again.")
def play():
print("Welcome to the game of Tic Tac Toe.")
print("The board is set up with numbers corresponding the the 9 positions.")
print_board(show_index=True)
print("To make a move, enter the cell number on your turn.")
turn = "X"
winner = None
while continue_game():
print_board()
nxt = next_turn(turn)
get_input(turn)
winner = check_win()
if winner:
print("Player {} has won the game".format(winner))
print_board()
break
turn = nxt
if winner is None:
print("The game was drawn, well played both :)")
if __name__ == "__main__":
setup_game()
play()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment