Skip to content

Instantly share code, notes, and snippets.

@akornor
Last active September 15, 2018 12:37
Show Gist options
  • Save akornor/e687d991ec8b47ff3a6f8c100321c524 to your computer and use it in GitHub Desktop.
Save akornor/e687d991ec8b47ff3a6f8c100321c524 to your computer and use it in GitHub Desktop.
tic tac toe. assumes you're running python 3.
import sys
import random
WINNING_COMBINATIONS=[
(1,2,3),
(4,5,6),
(7,8,9),
(1,4,7),
(2,5,8),
(3,6,9),
(1,5,9),
(3,5,7),
]
class Game:
def __init__(self, board):
self.board = board
def get_player_marker(self):
marker = ''
while not (marker in ['X', 'O']):
marker = input('Do you want to be X or O?').upper()
return ('X', 'O') if marker == 'X' else ('O', 'X')
def check_winner(self, mark):
grid = self.board.grid
return any([(grid[a] == grid[b] == grid[c] == mark) for (a,b,c) in WINNING_COMBINATIONS])
def get_player_choice(self):
while True:
try:
pos = int(input('Choose your next position: (1-9)'))
if pos in (self.board.all_positions - self.board.marked_positions):
return pos
else:
print('Someone has already moved to that spot.')
except ValueError:
...
def play(self):
print('Tic Tac Toe')
human_marker, computer_marker = self.get_player_marker()
human = True
while True:
if human:
pos = self.get_player_choice()
self.board.mark_board(human_marker, pos)
self.board.print_board()
if self.check_winner(human_marker):
print(f'Game over. Player {human_marker} wins')
break
else:
empty_positions = list(self.board.all_positions - self.board.marked_positions)
pos = random.choice(empty_positions)
self.board.mark_board(computer_marker, pos)
self.board.print_board()
if self.check_winner(computer_marker):
print(f'Game over. Player {computer_marker} wins')
break
if self.board.is_full:
print('Game ended in a draw')
break
human = not human
class Board:
def __init__(self):
self.grid = [' '] * 10
self.marked_positions = set()
self.all_positions = set(list(range(1,10)))
def mark_board(self, marker, position):
if self.grid[position] in ('X', 'O'):
return
self.grid[position] = marker
self.marked_positions.add(position)
@property
def is_full(self):
return self.marked_positions == self.all_positions
def print_board(self):
grid = self.grid
sys.stdout.write('\033[H')
sys.stdout.write('\033[J')
print(' ' + grid[7] + ' | ' + grid[8] + ' | ' + grid[9])
print('-----------')
print(' ' + grid[4] + ' | ' + grid[5] + ' | ' + grid[6])
print('-----------')
print(' ' + grid[1] + ' | ' + grid[2] + ' | ' + grid[3])
def main():
board = Board()
game = Game(board)
game.play()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment