codepad
[
create a new paste
]
login
|
about
Language:
C
C++
D
Haskell
Lua
OCaml
PHP
Perl
Plain Text
Python
Ruby
Scheme
Tcl
def drawboard(board): print "|".join(str(v).center(3) for v in ["", 0, 1, 2]) print "-" * 16 for idx, row in enumerate(board): print "|".join(str(v).center(3) for v in [idx] + row) print "-" * 16 def checkwin(board): for line in wins: marks = set(board[row][col] for row, col in line) if marks == set("X") or marks == set("O"): return list(marks)[0] return None def getfitchecker(board): def fitness(pos): blockers = empty = 0 for line in wins: if pos not in line: continue symbols = set(board[r][c] for r,c in line) print symbols if symbols == set(" "): empty += 1 if symbols == set("X "): blockers += 1 print blockers, empty return blockers, empty return fitness board = [list(" ") for row in range(3)] wins = [ [(0, 0), (0, 1), (0, 2)], [(1, 0), (1, 1), (1, 2)], [(2, 0), (2, 1), (2, 2)], [(0, 0), (1, 0), (2, 0)], [(0, 1), (1, 1), (2, 1)], [(0, 2), (1, 2), (2, 2)], [(0, 0), (1, 1), (2, 2)], [(0, 2), (1, 1), (2, 0)], ] win = False while any(" " in row for row in board): drawboard(board) while True: # user input prompt = "Enter coordinates to place your mark (e.g 0,1): " try: row, col = map(int, raw_input(prompt).split(",")) if board[row][col] != " ": raise "already a piece" board[row][col] = "X" break except: print "Illegal coordinates" win = checkwin(board) if win or not any(" " in row for row in board): break possible = [(row, col) for row in range(3) for col in range(3) if board[row][col] == " "] row, col = max(possible, key = getfitchecker(board)) board[row][col] = "O" win = checkwin(board) if win: break print (win or "cat") + " wins!"
Private
[
?
]
Run code
Submit