In [1]:
from keras.datasets import cifar10

In [2]:
(X_train, y_train), (X_test, y_test) = cifar10.load_data()

In [2]:
f = open('../data/clean_tactics', 'r')
lines = f.readlines()
f.close()

In [3]:
#param: line from tactics csv
#output: tuple containing sunfish formatted string and to move as either w or b
def csvline2sunfish(line):
    (uglyFEN,toMove) = tuple(line.split(',')[2].split(' '))
    #parse uglyFEN to sunfish format
    board = [" " + uglyFEN[r:r+8].replace('x','.') + '\n' for r in range(0,64,8)]
    edge_buffer = "         \n"
    return (board, ''.join([edge_buffer, edge_buffer, "".join(board), edge_buffer, edge_buffer[:-1]]), toMove)
csvline2sunfish(lines[0])


Out[3]:
([' ......k.\n',
  ' p....p..\n',
  ' .pp...pQ\n',
  ' ...P....\n',
  ' P..P..KP\n',
  ' .BP...P.\n',
  ' ........\n',
  ' .....q..\n'],
 '         \n         \n ......k.\n p....p..\n .pp...pQ\n ...P....\n P..P..KP\n .BP...P.\n ........\n .....q..\n         \n         ',
 'b')

In [ ]:


In [4]:
from sunfish import *

In [5]:
board, test_pos, to_move = csvline2sunfish(lines[0]) 
pos = Position(test_pos, 0, (True,True), (True,True), 0, 0)
#if to_move == 'b' : pos = pos.rotate()
print(pos)

for move in pos.gen_moves():
    print(move)


while True:
    print_pos(pos)

    # We query the user until she enters a legal move.
    move = None
    while move not in pos.gen_moves():
        match = re.match('([a-h][1-8])'*2, input('Your move: ')) 
        if match:
            move = parse(match.group(1)), parse(match.group(2))
        else:
            # Inform the user when invalid input (e.g. "help") is entered
            print("Please enter a move like g8f6")
    pos = pos.move(move)

    # After our move we rotate the board and print it again.
    # This allows us to see the effect of our move.
    print_pos(pos.rotate())

    # Fire up the engine to look for a move.
    move, score = search(pos)
    if score <= -MATE_VALUE:
        print("You won")
        break
    if score >= MATE_VALUE:
        print("You lost")
        break

    # The black player moves from a rotated position, so we have to
    # 'back rotate' the move before printing it.
    print("My move:", render(119-move[0]) + render(119-move[1]))
    pos = pos.move(move)


Position(board='         \n         \n ......k.\n p....p..\n .pp...pQ\n ...P....\n P..P..KP\n .BP...P.\n ........\n .....q..\n         \n         ', score=0, wc=(True, True), bc=(True, True), ep=0, kp=0)
(48, 38)
(48, 28)
(48, 58)
(48, 47)
(48, 57)
(48, 66)
(48, 75)
(48, 84)
(48, 93)
(48, 37)
(48, 26)
(54, 44)
(54, 43)
(61, 51)
(67, 57)
(67, 66)
(67, 58)
(67, 78)
(67, 76)
(67, 56)
(68, 58)
(72, 63)
(72, 83)
(72, 94)
(72, 81)
(73, 63)

  8 · · · · · · ♔ ·
  7 ♙ · · · · ♙ · ·
  6 · ♙ ♙ · · · ♙ ♛
  5 · · · ♟ · · · ·
  4 ♟ · · ♟ · · ♚ ♟
  3 · ♝ ♟ · · · ♟ ·
  2 · · · · · · · ·
  1 · · · · · ♕ · ·
    a b c d e f g h 


Your move: 
Please enter a move like g8f6
Your move: 
Please enter a move like g8f6
Your move: 
Please enter a move like g8f6
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-5-fe719e391892> in <module>()
     14     move = None
     15     while move not in pos.gen_moves():
---> 16         match = re.match('([a-h][1-8])'*2, input('Your move: '))
     17         if match:
     18             move = parse(match.group(1)), parse(match.group(2))

/Users/websterm/anaconda/lib/python2.7/site-packages/ipykernel/kernelbase.pyc in raw_input(self, prompt)
    649             self._parent_ident,
    650             self._parent_header,
--> 651             password=False,
    652         )
    653 

/Users/websterm/anaconda/lib/python2.7/site-packages/ipykernel/kernelbase.pyc in _input_request(self, prompt, ident, parent, password)
    679             except KeyboardInterrupt:
    680                 # re-raise KeyboardInterrupt, to truncate traceback
--> 681                 raise KeyboardInterrupt
    682             else:
    683                 break

KeyboardInterrupt: 

In [6]:
board


Out[6]:
[' ......k.\n',
 ' p....p..\n',
 ' .pp...pQ\n',
 ' ...P....\n',
 ' P..P..KP\n',
 ' .BP...P.\n',
 ' ........\n',
 ' .....q..\n']

In [7]:
#parameters

def apply_move(board, (move_start, move_end)):
    board_copy = [list(row) for row in board]
    start_x, start_y = (move_start / 10 - 2, move_start - move_start / 10 * 10)
    end_x, end_y = (move_end / 10 - 2, move_end - move_end / 10 * 10)
    #print(start_x, start_y)
    #print(end_x, end_y)
    tmp = board[start_x][start_y] # '.'
    #add . to original spot
    board_copy[start_x][start_y] = '.'
    #add piece to end
    #have to do funky stuff because strings are immutable: change to row array the nback
    board_copy[end_x][end_y] = tmp
    return ["".join(row) for row in board_copy]

#move queen h6e3
apply_move(board, (48,75))


Out[7]:
[' ......k.\n',
 ' p....p..\n',
 ' .pp...p.\n',
 ' ...P....\n',
 ' P..P..KP\n',
 ' .BP.Q.P.\n',
 ' ........\n',
 ' .....q..\n']

In [8]:
board


Out[8]:
[' ......k.\n',
 ' p....p..\n',
 ' .pp...pQ\n',
 ' ...P....\n',
 ' P..P..KP\n',
 ' .BP...P.\n',
 ' ........\n',
 ' .....q..\n']

In [26]:
#start move
a = [1 if board[i][j] == p else 0 for i in range(0,8) for j in range (1,9) for p in "PKQNBRpkqnbr"]
#b and c are valid moves from a
b = [1 if apply_move(board, (48,75))[i][j] == p else 0 for i in range(0,8) for j in range (1,9) for p in "PKQNBRpkqnbr"]         
c = [1 if apply_move(board, (48,38))[i][j] == p else 0 for i in range(0,8) for j in range (1,9) for p in "PKQNBRpkqnbr"]
#d and e are not a valid move: it is a pawn moving sideways
d = [1 if apply_move(board, (47,46))[i][j] == p else 0 for i in range(0,8) for j in range (1,9) for p in "PKQNBRpkqnbr"]
e = [1 if apply_move(board, (47,45))[i][j] == p else 0 for i in range(0,8) for j in range (1,9) for p in "PKQNBRpkqnbr"]
X_train = [a + b, a + d]
y_train = [[1], [0]]
X_test = [[a + c], [a + e]];
y_test = [1, 0]

In [1]:
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.optimizers import SGD

model = Sequential()
model.add(Dense(1, input_dim=1536, init='uniform', activation='tanh'))
# model.add(Dropout(0.5))
# model.add(Dense(64, init='uniform', activation='tanh'))
# model.add(Dropout(0.5))
# model.add(Dense(2, init='uniform', activation='softmax'))

sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='mean_squared_error', optimizer=sgd)
model.train_on_batch([X_train], y_train)
classes = model.predict_classes([X_test], batch_size=1)
print("classes: {}".format(classes))
proba = model.predict_proba([X_test], batch_size=1)
print("probabilities: {}".format(proba))


---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-1-ee2c080c30cc> in <module>()
----> 1 from keras.models import Sequential
      2 from keras.layers.core import Dense, Dropout, Activation
      3 from keras.optimizers import SGD
      4 
      5 model = Sequential()

ImportError: No module named keras.models

In [30]:
proba


Out[30]:
array([[ 0.99961775],
       [ 0.99945491]])

In [ ]: