Skip to content

Instantly share code, notes, and snippets.

@theptrk theptrk/tictactoe.py
Last active Sep 4, 2019

Embed
What would you like to do?
import random
# The indices in state represent this tic tac toe board
#
# index 0 | index 1 | index 2
# ---------------------------
# index 3 | index 4 | index 5
# ---------------------------
# index 6 | index 7 | index 8
class TTT:
def __init__(self):
self.state = ['-' for i in range(9)]
self.nothing = '-'
self.computer = 'x'
self.turn = self.computer
self.player = 'o'
self.winner = None
def make_move(self, coord, player):
self.state[coord] = player
if self.turn == self.computer:
self.turn = self.player
else:
self.turn = self.computer
def possible_moves(self):
return [i for (i,val) in enumerate(self.state) if val == self.nothing]
def computer_move(self):
coord = random.choice(self.possible_moves())
self.make_move(coord, self.computer)
self.set_winner()
def random_player_move(self):
coord = random.choice(self.possible_moves())
self.make_move(coord, self.player)
self.set_winner()
def is_live(self):
return self.winner == None and len(self.possible_moves()) > 0
def get_game_result(self):
if self.winner == None:
return 'draw'
else:
return self.winner
def set_winner(self):
if (self.is_winner(self.player)):
self.winner = self.player
if (self.is_winner(self.computer)):
self.winner = self.computer
def is_winner(self, player):
state = self.state
if (
# top horizontal 3
(state[0] == player and state[1] == player and state[2] == player) or
# mid horizontal 3
(state[3] == player and state[4] == player and state[5] == player) or
# bot horizontal 3
(state[6] == player and state[7] == player and state[8] == player) or
# left vertial 3
(state[0] == player and state[3] == player and state[6] == player) or
# mid vertial 3
(state[1] == player and state[4] == player and state[7] == player) or
# right vertial 3
(state[2] == player and state[5] == player and state[8] == player) or
# diagonal from top left
(state[0] == player and state[4] == player and state[8] == player) or
# diagonal from top right
(state[2] == player and state[4] == player and state[6] == player)
):
return True
else:
return False
def print_board(self):
print(f" {self.state[0]} | {self.state[1]} | {self.state[2]} \n" \
f"-----------\n" \
f" {self.state[3]} | {self.state[4]} | {self.state[5]} \n"\
f"-----------\n" \
f" {self.state[6]} | {self.state[7]} | {self.state[8]} \n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.