def negotiate_first(game, resolved_board, allempty, clientSecretHashed):
    previousMove = game.lastMove
    if previousMove.clientSecret == "":
        raise UnfinishedMove("I was expecting client secret now.")
    previousNumber = previousMove.moveNumber
    serverSecret = rand256hex()
    serverSecretHashed = sha256(serverSecret)
    move = Move(
            belongs_to = game,
            moveNumber = previousNumber + 1,
            board = move_logic.serialize_board(resolved_board),
            allempty = move_logic.serialize_board(allempty),
            serverSecret = serverSecret,
            serverSecretHashed = serverSecretHashed,
            clientSecret = "",
            clientSecretHashed = clientSecretHashed
            )
    move.save()
    game.lastMove = move
    game.save()
    return move
def check_validity(move): # isValid, randomNumber
    clientSecret = move.clientSecret
    clientSecretHashed = move.clientSecretHashed
    valid = (sha256(clientSecret) == clientSecretHashed)
    if valid:
        serverSecret = move.serverSecret
        randomNumber = xorHex(serverSecret, clientSecret)
    else:
        serverSecret = "X"
        randomNumber = rand256hex()
    allempty = move_logic.deserialize_board(move.allempty)
    emptyNo = len(allempty)
    board = move_logic.deserialize_board(move.board)
    position = allempty[int(randomNumber, 16)%emptyNo]
    board[position[0]][position[1]] = move_logic.new_value
    if move.moveNumber != sum(map(sum, board)):
        raise Error("moveNumber != sum(board), database corruption, we're all going to die.")
    gameover = False
    result = move.moveNumber
    game = move.belongs_to
    if emptyNo == 1:
        gameover = not move_logic.has_move(board)
        if gameover:
            result = move.moveNumber + 1
            game.result = result
            #person = game.belongs_to
            #if result > person.bestResult:
            #    person.bestResult = result
    move.board = move_logic.serialize_board(board)
    game.gameover = gameover
    game.save()
    move.save()
    return { "valid": valid,
             "serverSecret": serverSecret,
             "randomNumber": randomNumber,
             "position": position,
             "value": move_logic.new_value,
             "gameover": gameover,
             "moveNumber": result
            }
def newGame(user):
    board = move_logic.create_board(move_logic.size)
    board[1][1] = 1
    move = Move(
            belongs_to = None,
            moveNumber = 1,
            board = move_logic.serialize_board(board),
            serverSecret = "0",
            serverSecretHashed = "0",
            clientSecret = "0",
            clientSecretHashed = "0"
            )
    move.save()
    game = Game(
            gameid = rand256hex(),
            belongs_to = user,
            gameover = False,
            lastMove = move
            )
    game.save()
    move.belongs_to = game
    move.save()
    return game