Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

A tictactoe solution #5

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion test_game.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ class TestAI(unittest.TestCase):

def test_eval(self):
board0 = ttt.Board([
'.', '.', '.'
'.', '.', '.',
'.', 'x', '.',
'.', '.', '.',
])
Expand All @@ -20,6 +20,20 @@ def test_eval(self):
ttt.AI.evaluate(board0, 'x') > ttt.AI.evaluate(board1, 'x')
)

def test_close_to_finish(self):
board2 = ttt.Board([
'x', 'o', 'x',
'x', 'o', 'x',
'o', '.', '.'
])
board3 = ttt.Board([
'o', 'o', 'x',
'.', 'x', 'o',
'.', '.', 'x'
])
self.assertEquals(ttt.AI(board2, 'o').next_move(), (2, 1))
self.assertEquals(ttt.AI(board3, 'x').next_move(), (2, 0))


class TestGame(unittest.TestCase):

Expand Down
40 changes: 38 additions & 2 deletions ttt.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
board is a list of 9 elements from ['x','o','.']. '.' means empty spot.
"""

import copy
import itertools
import math
import operator
import sys
import types

Expand All @@ -30,10 +34,25 @@ def __init__(self, board, who):
self._game = Game(board)
self._who = who


def next_move(self):
"""
Return a 2-tuple representing the row, col of our next move
"""
raw_board = self._game._board._board._board

scores = []
for i in range(len(raw_board)):
if raw_board[i] != '.':
scores.append(-sys.maxint)
else:
potential_board = copy.copy(raw_board)
potential_board[i] = self._who
scores.append(AI.evaluate(Board(potential_board), self._who))

max_index, max_value = max(enumerate(scores), key=operator.itemgetter(1))

return (max_index / 3, max_index % 3)

@staticmethod
def evaluate(board, who):
Expand All @@ -47,11 +66,28 @@ def evaluate(board, who):
if who == 'x' and board.current_state() == GameStates.o_wins:
return -sys.maxint

if who == 'y' and board.current_state() == GameStates.o_wins:
if who == 'o' and board.current_state() == GameStates.o_wins:
return sys.maxint
if who == 'y' and board.current_state() == GameStates.x_wins:
if who == 'o' and board.current_state() == GameStates.x_wins:
return -sys.maxint

blank_spots = board._board.count('.')
plays_left = 'x' * int(math.ceil(blank_spots / 2.0)) + 'o' * int(math.floor(blank_spots / 2.0))
possible_placements = itertools.permutations(plays_left, len(plays_left))

score = 0
other_player = 'o' if who == 'x' else 'x'

for placements in possible_placements:
placements = list(placements)
future_board = map(lambda p: placements.pop() if p == '.' else p, board._board)
if Board(future_board).is_winner(who) == 1:
score += 1
elif Board(future_board).is_winner(other_player) == 1:
score -= 1

return score


class Game(object):
"""
Expand Down