Skip to content

Instantly share code, notes, and snippets.

@grassfedfarmboi
Created July 19, 2019 12:33
Show Gist options
  • Save grassfedfarmboi/9f370ef01eaedcc822f39e615e30d1b4 to your computer and use it in GitHub Desktop.
Save grassfedfarmboi/9f370ef01eaedcc822f39e615e30d1b4 to your computer and use it in GitHub Desktop.
Terminal Tic Tac Toe
class Game():
'''
Tic Tac Toe terminal game
'''
def __init__(self):
'''Set initial variables and start game'''
self.grid = """
1 2 3
|| ||
A {a1} || {a2} || {a3}
|| ||
=====================
|| ||
B {b1} || {b2} || {b3}
|| ||
=====================
|| ||
C {c1} || {c2} || {c3}
|| ||
"""
self.moves = {
"a1": " ",
"a2": " ",
"a3": " ",
"b1": " ",
"b2": " ",
"b3": " ",
"c1": " ",
"c2": " ",
"c3": " "
}
self.player = 1
self.mark = 'X'
self.print_board() #Start game
def switch_player(self):
self.player = 3 - self.player
if self.player is 1:
self.mark = 'X'
else:
self.mark = 'O'
def print_board(self):
print(self.grid.format(**self.moves))
if self.check_victory():
print('Victory! Player {} wins!'.format(self.player))
self.exit_game()
elif self.check_draw():
print('Draw. Game Over.')
self.exit_game()
else:
self.add_move()
def add_move(self):
prompt = 'Player {}, what\'s your move? '.format(self.player)
move = input(prompt).lower().strip()
move = self.validate(move)
if move and self.moves.get(move) == " ":
self.moves[move] = self.mark #sub into moves dict
self.switch_player()
self.print_board()
else:
print('Invalid move.')
if move and self.moves.get(move) != " ":
print('Space taken.')
self.add_move()
def validate(self, user_input):
if len(user_input) is not 2:
move = False
elif user_input[0] in ['a', 'b', 'c'] and user_input[1] in ['1', '2', '3']:
move = user_input
elif user_input[0] in ['1', '2', '3'] and user_input[1] in ['a', 'b', 'c']:
move = user_input[1] + user_input[0] #switch order if number first
else:
move = False
return move
def check_victory(self):
win = self.moves['a1'] == self.moves['a2'] == self.moves['a3'] != " " or \
self.moves['b1'] == self.moves['b2'] == self.moves['b3'] != " " or \
self.moves['c1'] == self.moves['c2'] == self.moves['c3'] != " " or \
self.moves['a1'] == self.moves['b1'] == self.moves['c1'] != " " or \
self.moves['a2'] == self.moves['b2'] == self.moves['c2'] != " " or \
self.moves['a3'] == self.moves['b3'] == self.moves['c3'] != " " or \
self.moves['a1'] == self.moves['b2'] == self.moves['c3'] != " " or \
self.moves['a3'] == self.moves['b2'] == self.moves['c1'] != " "
return win
def check_draw(self):
if all(val != " " for val in self.moves.values()):
return True
def exit_game(self):
input('Enter any key to exit. ')
if __name__ == "__main__":
Game()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment