Skip to content

Instantly share code, notes, and snippets.

@gudnm
Last active June 15, 2016 16:53
Show Gist options
  • Save gudnm/f6afcf603ab4f209c85cc6c128bd0512 to your computer and use it in GitHub Desktop.
Save gudnm/f6afcf603ab4f209c85cc6c128bd0512 to your computer and use it in GitHub Desktop.
A program that plays Tic-tac-toe with you and tries to lose. Uses Minimax rule to evaluate possible moves.
"""
Write a program that plays Tic-tac-toe with you and tries its best to lose
"""
def printBoard(b):
for i in range(3):
print(b[3*i], b[3*i+1], b[3*i+2])
def getNext(b):
move = int(input("Your move, sir (must be a number from 1 to 9): ")) - 1
if 0 <= move < 9 and b[move] == '-':
b[move] = 'x'
else:
getNext(b)
# Use Minimax to find the worst move
def worstMove(b, player):
if len(set(b)) == 1: # no moves yet, 1 seems bad enough
return 0, 1
if win(b): # the previous player's move won the game
return -1, -1
if '-' not in b: # no more empty cells, game finished
return 0, -1
next_player = 'x' if player == 'o' else 'o'
scores = []
for i in range(len(b)):
if b[i] == '-':
b[i] = player
scores.append((-worstMove(b, next_player)[0], i))
b[i] = '-'
return min(scores)
def win(b):
return (b[0]==b[1]==b[2]!='-' or b[3]==b[4]==b[5]!='-' or
b[6]==b[7]==b[8]!='-' or b[0]==b[3]==b[6]!='-' or
b[1]==b[4]==b[7]!='-' or b[2]==b[5]==b[8]!='-' or
b[0]==b[4]==b[8]!='-' or b[2]==b[4]==b[6]!='-')
def makeMove(b):
move = worstMove(b, 'o')
b[move[1]] = 'o'
if __name__ == '__main__':
ticTacToe = ['-']*9
tricked = False
while not win(ticTacToe):
printBoard(ticTacToe)
getNext(ticTacToe)
if win(ticTacToe):
print("You won! I tricked you.")
tricked = True
else:
makeMove(ticTacToe)
if not tricked:
print("You're too smart, I couldn't trick you to win.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment