Skip to content

Instantly share code, notes, and snippets.

@TylerLeite
Last active October 5, 2016 21:59
Show Gist options
  • Save TylerLeite/ccfe2525ab81bb70fb33b4e9846f1e67 to your computer and use it in GitHub Desktop.
Save TylerLeite/ccfe2525ab81bb70fb33b4e9846f1e67 to your computer and use it in GitHub Desktop.
import random
class TicTacToeNode:
def __init__(self):
self.board = ['.'] * 9
self.win_states = (\
[0,1,2], [3,4,5], [6,7,8],\
[0,3,6], [1,4,7], [2,5,8],\
[0,4,8], [2,4,6]\
)
self.allocations = {'X': 'Human', 'O': 'Cpu'}
self.turn = self.allocations['X']
self.empty = 9
def reset(self):
self.board = ['.'] * 9
self.turn = self.allocations['X']
self.empty = 9
def render(self):
print self.board[0], self.board[1], self.board[2]
print self.board[3], self.board[4], self.board[5]
print self.board[6], self.board[7], self.board[8]
def place(self, x, y):
position = x + 3*y
return self.place(position)
def place(self, position):
if self.empty <= 0:
return False
if self.board[position] != '.':
return False
else:
self.empty -= 1
if self.turn == 'Human':
self.turn = 'Cpu'
piece = 'X'
else:
self.turn = 'Human'
piece = 'O'
self.board[position] = piece
return True
def whoWon(self):
for state in self.win_states:
piece = self.board[state[0]]
if piece == '.':
continue
for position in state:
if self.board[position] != piece:
break
else: # if the loop breaks, else doesn't happen
return self.allocations[piece]
if self.empty <= 0:
return "Draw"
else:
return "No one"
def makeCopy(self):
copy = TicTacToeNode()
for i, tile in enumerate(self.board):
copy.board[i] = tile
copy.turn = self.turn
copy.empty = self.empty
return copy
# Return a list with the game state after each possible move
def children(self):
child_nodes = []
for i, tile in enumerate(self.board):
if tile == '.':
child = self.makeCopy()
child.place(i)
child_nodes.append(child)
return child_nodes
def heuristic(self):
return 0
def makeAIMove(self):
moves = []
for i, tile in enumerate(self.board):
if tile == '.':
moves.append(i)
return game.place(random.choice(moves))
game = TicTacToeNode()
while True:
game.render()
move = int(raw_input('What is your move? (0 - 8): '))
worked = game.place(move)
if worked:
game.makeAIMove()
else:
print 'That is not a legal move!'
victory = game.whoWon()
if victory == 'No one':
continue
else:
game.render()
game.reset()
if victory == 'Human':
print 'Human Wins'
elif victory == 'Cpu':
print 'Computer Wins'
else:
print 'It is a draw'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment