Petunien wrote:Hm, I don't understand much of your code, it's written in a language I don't know.
Could you maybe explain the main function, the logical construction (course of the game)?
It starts a game, with a human player named "Human", who uses "X", and a computer player named "James" who uses "O":
Code: Select all
Game(Human('X', "Human"), Heuristic('O', "James")).play()
After that each player goes a turn until the board is full or someone has won:
Code: Select all
while not self.board.winner() and not self.board.full():
When the human has a turn, at first the board is printed, then it will ask for a place to put your sign repeatedly, until you enter a valid place, after that it plays the move:
Code: Select all
def play(self, board):
print(board)
i = 0
while i < 1 or i > 9 or board.get(i - 1):
i = raw_input(self.name + ": ")
i = i.isdigit() and int(i) or 0
board.play(i - 1, self)
For the computer player, it will first try to figure out what the other player is if it doesn't know that yet, and then find the best move:
Code: Select all
def play(self, board):
if not self.other.name:
for i in range(9):
x = board.get(i)
if x and x != self:
self.other = x
break
board.play(self.findmove(board), self)
In findmove, it will select position 0 (the top left corner) if the board is empty (because the corners are always the best place to start), and otherwise try minimax for each empty spot on the board:
Code: Select all
def findmove(self, board):
if not any(board.inner): #empty board
return 0
for I in range(1, -3, -1): #default to minimax
for i in range(9):
if not board.get(i):
b = board.copy()
b.play(i, self)
if self.minimax(b, min) > I:
return i
Minimax will first check for an endgame condition: if the current player won, return 1, if the enemy won, return -1, and if there is a draw, return 0:
Code: Select all
def minimax(self, board, f):
if board.winner():
return board.winner() == self and 1 or -1
if board.full():
return 0
Then we recursively call minimax, and check if we can force a win or are forced a lose, depending on which part of the algorithm we're running right now:
Code: Select all
m = f == min and 1 or -1
for p in range(9):
if not board.get(p):
b = board.copy()
b.play(p, f == min and self.other or self)
m = f(m, self.minimax(b, f == min and max or min))
if m == (f == min and -1 or 1):
return m
return m
That's it!
Petunien wrote:Also, is it possible to download/play your game (as *.exe, for Windows anyway)?
You can download the file, and if you have Python 3, you can run it with that. Open cmd.exe, enter
Code: Select all
cd C:\whereever\you\put\the\file\
python3 tictactoe.py