Skip to content

Instantly share code, notes, and snippets.

@msyvr
Created September 15, 2021 05:11
Show Gist options
  • Save msyvr/4f6a0ef7390302f8ab1763870daefd15 to your computer and use it in GitHub Desktop.
Save msyvr/4f6a0ef7390302f8ab1763870daefd15 to your computer and use it in GitHub Desktop.
tictactoo: oo tictactoe (python)
class Player:
def __init__(self, mark):
# mark can be 'x' or 'o'
self.mark = mark
# different types of players can inherit from here, so >> pass
def get_play(self, game):
pass
class HumanPlayer(Player):
def __init__(self, mark):
super().__init__(mark)
def get_play(self, game):
play = 100 #hack!
while play not in game.okay_plays():
game.print_gameboard()
play = int(input(' Hey! ' + self.mark +'! Your turn - be sure to choose an available spot: '))
return play
from player import HumanPlayer
class Tictactoe:
def __init__(self):
self.marks = [' ' for _ in range(9)] #the _ = placeholder in python (also other things, but a placeholder in this case);
self.winner_name = None
def print_gameboard(self):
count = 0
for gameboard_row in [self.marks[i*3:(i+1)*3] for i in range(3)]:
print('| ' + ' | '.join(gameboard_row) + ' |')
count +- 1
if count < 3:
print('--------------')
else:
print('\n')
@staticmethod
def show_numboard():
count = 0
nboard = [[str(i) for i in range(j*3, (j+1)*3)] for j in range(3)]
for row in nboard:
print('| ' + ' | '.join(row) + ' |')
count +- 1
if count < 3:
print('--------------')
else:
print('\n')
def okay_plays(self):
return [i for i, place in enumerate(self.marks) if place == ' ']
def is_spot_okay(self, spot, mark):
if self.marks[spot]==' ':
self.marks[spot] = mark
if self.winner(spot, mark):
self.winner_name = mark
return True
return False
def winner(self, spot, mark):
# check spot row for winner
spot_row = spot//3
check_row = self.marks[spot_row*3:(spot_row+1)*3]
if all([t == mark for t in check_row]):
return True
# check spot column for winner
spot_col = spot%3
check_col = [self.marks[spot_col+i*3] for i in range(3)]
if all([t == mark for t in check_col]):
return True
# check diagonals for winner
diag = [self.marks[i*4] for i in range(3)]
if all([t == mark for t in diag]):
return True
antidiag = [self.marks[(i+1)*2] for i in range(3)]
if all([t == mark for t in antidiag]):
return True
return False
def play(game, player_x, player_o):
mark = input('Who starts? x or o?: ')
while len(game.okay_plays()) > 0:
print('')
game.show_numboard()
print('')
if mark == 'x':
spot = player_x.get_play(game)
else:
spot = player_o.get_play(game)
if game.is_spot_okay(spot, mark):
print('\n')
game.print_gameboard()
print('\n')
if game.winner_name:
print(f'The winner was {mark}!')
return
mark = 'x' if mark == 'o' else 'o'
print('Tie!')
if __name__ == '__main__':
player_x = HumanPlayer('x')
player_o = HumanPlayer('o')
ttt = Tictactoe()
play(ttt, player_x, player_o)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment