[source lang = python]
def getValidMoves(boardpos):
result = []
for i in range(9):
if boardpos == 0:
result.append(i)
return result
def checkWin(boardpos):
winning_sets = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6))
for row in winning_sets:
if boardpos[row[0]] == boardpos[row[1]] == boardpos[row[2]] and boardpos[row[0]] != 0:
return boardpos[row[0]]
return 0
def evaluateMoveMax(move, boardpos):
if checkWin(boardpos) != 0:
return checkWin(boardpos)
boardposr = []
for item in boardpos:
boardposr.append(item)
boardposr[move] = 1
evaluations = []
for move in getValidMoves(boardpos):
evaluations.append(evaluateMoveMin(move, boardposr))
boardposr = []
for item in boardpos:
boardposr.append(item)
boardposr[move] = 1
if evaluations == []:
return 0
return max(evaluations)
def evaluateMoveMin(move, boardpos):
if checkWin(boardpos) != 0:
return checkWin(boardpos)
boardposr = []
for item in boardpos:
boardposr.append(item)
boardposr[move] = -1
evaluations = []
for move in getValidMoves(boardpos):
evaluations.append(evaluateMoveMax(move, boardposr))
boardposr = []
for item in boardpos:
boardposr.append(item)
boardposr[move] = -1
if evaluations == []:
return 0
return min(evaluations)
Tic-tac-toe and minimax
Hi! I figured out that, since I'm not a good programmer, a simple tic-tac-tow minimax would be the easiest way up to a more complex AI. I then, programmed these:
However, on positions like
O|X|
|X|
| |
the computer as O prefers to threaten three in a row instead of blocking.
Any clues on why it's behaving that way? Bear in mind that boardpos is a 9-element array, -1 for O, 1 for X. I really need help! I have written 3 different versions of this algorithm, and all of them fail!
[Edited by - aaaaaaaa on July 1, 2006 6:20:28 PM]
hmmh, I'm not quite good at staring at uncommented code and tell what it does in little time..
so.. If you aren't sure your algorithm works.. and you are kind of new in this, maibe you should write/draw it down on paper fist, maybe in pseudo code, but I advice you to use Chapin diagrams, altought some people like flow charts better, I seriously thin they are garbage (unless you want to program in assembler of course).
so.. If you aren't sure your algorithm works.. and you are kind of new in this, maibe you should write/draw it down on paper fist, maybe in pseudo code, but I advice you to use Chapin diagrams, altought some people like flow charts better, I seriously thin they are garbage (unless you want to program in assembler of course).
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement