Skip to content

Instantly share code, notes, and snippets.

@cjanis
Created May 8, 2018 03:25
Show Gist options
  • Save cjanis/897f0511b7d44038858413f5d73ca5c7 to your computer and use it in GitHub Desktop.
Save cjanis/897f0511b7d44038858413f5d73ca5c7 to your computer and use it in GitHub Desktop.
Command line tic tac toe game built in Python
b = ['O',' ',' ',' ',' ',' ',' ',' ',' ',' ']
def play(b,m=0):
# reset board if new game
if m == 0:
b = ['O',' ',' ',' ',' ',' ',' ',' ',' ',' ']
print('new game')
# update board
b[int(m)] = b[0]
board = f'{b[1]}|{b[2]}|{b[3]}\n-----\n{b[4]}|{b[5]}|{b[6]}\n-----\n{b[7]}|{b[8]}|{b[9]}'
# is there a winner?
winner = False
solutions = ['123','456','789','147','258','369','159','357']
for i in solutions:
if (b[int(i[0])] in 'XO') and (b[int(i[0])] == b[int(i[1])] == b[int(i[2])]):
# there's a winner!
winner = b[int(i[0])]
# is there a tie?
tie = True
for i in range(1,10):
if b[i] == ' ':
tie = False
# if no winner or tie, next player's turn
if not winner and not tie:
if b[0] == 'X':
b[0] = 'O'
else:
b[0] = 'X'
# clear display
print('\n'*100)
# print board
print(board)
# next action
if not winner and not tie:
print(f"\nIt's player {b[0]}'s turn. Where will you put your {b[0]}?")
move = 0
# validate
while (not str(move).isdigit()) or (not int(move) in range(1,10)) or (b[int(move)] in 'XO'):
# ask for move
move = str(input('(1-9): '))
else:
# play move
play(b,move)
else:
if winner:
message = f"Congrats player {b[0]}, you won!"
if tie:
message = f"Bummer, you tied."
print(f"\n{message} Play again?\n")
move = 0
# validate
while (not str(move).lower() == 'y') and (not str(move).lower() == 'n'):
# ask for move
move = str(input('(Y/N): '))
else:
if move.lower() == 'y':
play(b)
else:
print('GAME OVER')
play(b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment