Last active
August 29, 2015 13:57
-
-
Save ericpauley/9578566 to your computer and use it in GitHub Desktop.
30 Line Tic Tac Toe
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
wins = [(0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(6,4,2),] | |
def checkwin(board): | |
for win in wins: | |
if board[win[0]] == board [win[1]] == board[win[2]] is not None: | |
return board[win[0]] | |
return None if None in board else .5 | |
def maximize(board, target, index): | |
moves = [] | |
for i in range(9): | |
if board[i] is None: | |
board2 = board[:] | |
board2[i] = target | |
moves.append((checkwin(board2) if checkwin(board2) is not None else maximize(board2, 1-target, index - 1)[0] ,i)) | |
return (.5, random.choice(moves)[1]) if index <= 0 else sorted(moves,key=lambda x:abs(target-x[0]) + random.random()/10.0)[0] | |
board = [None]*9 | |
move = input("start? (0=start, 1=wait) ") | |
while checkwin(board) is None: | |
if move == 0: | |
space = input("Move? (1-9) ") | |
board[space-1] = 0 | |
else: | |
board[maximize(board, 1, 9)[1]] = 1 | |
move = 1-move | |
for i in range(0,7,3): | |
print "".join([("X","O")[board[j]] if board[j] is not None else "_" for j in range(i,i+3)]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment