示例#1
0
def tryMoveAndEval(move):
    tempGame = Game(fen, True)
    tempGame.apply_move(move)
    tempBoard = tempGame.board._position
    score = 0
    for i in range(8):
        for u in range(8):
            if originalBoard[ind(i,u)] != tempBoard[ind(i,u)]:
                score += alignedMap[i][u]
    return score
示例#2
0
 def create(file_name: str, game: str):
     if game == 'chess':
         base_info: GameInformation = GameInformation.create_game_info(str(Game()))
         game_json: str = str(base_info)
         AbsGame.__create_log_file(file_name, game, game_json)
     elif game == 'dga':
         base_info: DGA = DGA(DGA.start_board)
         game_json: str = str(base_info)
         AbsGame.__create_log_file(file_name, game, game_json)
def play_one_game(fen, last_move, rybka, max_tree_depth=3):
    chess_game = Game(fen=fen)
    chess_game.apply_move(last_move)

    print chess_game

    start_new_game(rybka, chess_game, search_depth=8)
    # print "for " + str(chess_game).split()[1] + ", the cp parameter is " + str(200)
    reasonable_moves = find_all_reasonable_moves(rybka, current_depth=0, search_depth=8, cp_parameter=200)   # CP is 200 the first time

    tree_of_moves = FenTree(root=fen, last_move=last_move, score=0)

    first_player_color = str(chess_game).split()[1]
    # print str(chess_game).split()[1]

    if reasonable_moves:  # If there are any reasonable_moves
        build_the_tree(tree_of_moves, reasonable_moves, chess_game, rybka, first_player_color, max_tree_depth)

    #[x.display_the_tree() for x in tree_of_moves.moves]

    return tree_of_moves
示例#4
0
 def _extract_chessgame(self, pgn_in_file):
     # get game model
     chessgame = Game()
     cmd = ('{0} {1} -Wlalg --nomovenumbers --nocomments --nochecks -V --notags -s'
            .format(self.server.pgn_extract_path, pgn_in_file))
     p = get_command_process(cmd)
     stdout_content = p.stdout.readlines()
     # We need to decode the bytes from stdout when running on python 3
     if not b_legacy.get_python_major_version() <= 2:
         temp = []
         for stdout_line in stdout_content:
             temp.append(stdout_line.decode())
         stdout_content = temp
     stdout_content = ''.join(stdout_content)
     moves = re.sub('[\r\n]+', ' ', stdout_content)
     moves = b_legacy.b_filter(self._filter_move, moves.split(' '))
     result = moves[-1]
     del moves[-1]
     for i in range(0, len(moves)):
         chessgame.apply_move(moves[i])
     # extract existing comments
     comments = {}
     # TODO
     return chessgame, moves, result, comments
示例#5
0
    def _validate(self, curr_fen: str) -> bool:
        with open(self.__game_path, 'r')as f:
            lines = f.read().splitlines()

        last_line = lines[-2]
        try:
            prev_ginfo = GameInformation(json.loads(last_line.split('$')[1]))
        except IndexError:
            if last_line.startswith('-'):
                print('Must be a new file, passing through')
                return True

        curr = Game()
        curr.set_fen(curr_fen)

        if str(self.__ginfo) == str(prev_ginfo):
            self.__game_is_updated = False
            return True
        prev = Game()
        prev.set_fen(prev_ginfo.get_fen())
        print(prev)
        print(curr)
        if str(prev) == str(curr):
            self.__game_is_updated = True
            return True

        for move in prev.get_moves():
            tmp: Game = copy.deepcopy(prev)
            tmp.apply_move(move)
            if str(tmp) == str(curr):
                self.__game_is_updated = True
                print('Valid move made: %s' % move)
                return True
        print('Your opponent seems to be cheating... Game aborted. You are the winner.')
        self.__ginfo.set_status(State.CHEATED)
        self.__ginfo.set_winner(self.get_who_am_i())
        self.get_ginfo().set_loser('p1' if self.get_who_am_i() == 'p2' else 'p2')
        self.get_ginfo().inc_seq()
        self._update()
        return False
示例#6
0
    def __init__(self, game_id: str, ip: str):
        """

        :param game_id:
        """
        self.__game_id = game_id
        self.__game_path = 'games/%s.chess' % game_id

        self.__ip = ip

        self.__playable = False
        self.__game_is_updated = False

        self.__curr_game: Game = Game()
        self.__ginfo: GameInformation = None
        if game_id is not None:
            with open(self.__game_path, 'r') as f:
                time, game_info = f.read().splitlines()[-1].split('$')
            # game_fen, self.__dic = self.get_game_file_info(game_info)

            self.__ginfo = gi(json.loads(game_info))
            game_fen = self.__ginfo.get_fen()
            if self._validate(game_fen):
                if not self.__ginfo.game_is_initiated():
                    if self.__ginfo.can_i_update():
                        self._update()
                    print('Starting the loop new')
                    self.is_looping = False

                self.__curr_game.set_fen(game_fen)

                if self.__ginfo.get_player(self._get_turn_of()) == self.get_who_am_i() \
                        and self.get_ginfo().get_status() == State.ONGOING:
                    self.__playable = True

            else:
                self.__curr_game.set_fen(game_fen)
                print('Game is not updated yet. Wait for your opponent.')
def AttackMatrix(sFEN): # This I made
    print("FEN string is: " + sFEN)
    
    sFENnp = sFEN # setting up for sFEN without pawns
    sFENnp = sFENnp.replace('p','1')
    sFENnp = sFENnp.replace('P','1')

    
    ###############
    # DIAGNOSTIC
    #im = draw_board(fen=sFEN)
    #im.save(os.path.join(os.getcwd(),'diagnostics','withpawns.png'))
    #im = draw_board(fen=sFENnp)
    #im.save(os.path.join(os.getcwd(),'diagnostics','withoutpawns.png'))
    ###############\
    chessgame = Game(sFEN) # this and next ...
    possiblem = chessgame.get_moves() # ... get valid moves with all pieces
    chessgamenp = Game(sFENnp) # this and next ...
    possiblemnp = chessgamenp.get_moves() # ... get valid moves without pawns
    vm = rp(possiblem, possiblemnp) # all moves on board with pawns w/o pawn-fwd moves

    #TallyMatrix[row][column]
    TallyMatrix = [[0 for x in range(8)] for x in range(8)]

    for move in vm:
        vr = move[2]
        vc = move[3]
        vr = ''.join([(str(ord(x)-96) if x.isalpha() else x) for x in list(vr)])
        vr = int(vr)-1
        vc = int(vc)-1
        TallyMatrix[vc][vr] = TallyMatrix[vc][vr] + 1
    print('h1 ...... h8')
    for r in range(len(TallyMatrix)):
        print(TallyMatrix[7-r])
    print('a1 ...... a8')
    return TallyMatrix #need this line, d'oh!
示例#8
0
from __future__ import print_function
from Chessnut import Game
from pystockfish import *

import sys, subprocess

if len(sys.argv) < 2 or 'help' in sys.argv[1]:
    print('Usage:\n    python evaluate_move.py [FEN]')
    print('Reply: [best_move] [NEW_FEN] if valid, otherwise error')
    sys.exit(0);

fen = sys.argv[1].strip()

# Throws error if fen is not valid
try :
    chessgame = Game(fen, True)
except:
    print('Invalid fen: %s' % fen, file=sys.stderr)
    sys.exit(1)

### Interface with Stockfish
searcher = Engine(movetime=100)
searcher.setposition_fen(fen)
bestmove = searcher.bestmove_time()['move']

# Throws error if the move is not valid
try:
    chessgame.apply_move(bestmove)
except:
    print('Invalid move: %s' % bestmove, file=sys.stderr)
    sys.exit(1)
示例#9
0
        exit()

    detection_status = {}
    detection_status['board'] = False
    detection_status['corners'] = False

    engage_detection = True
    frame_index = 0

    board_features = {}
    prev_board_features = {}
    cur_board_features = {}

    cv2.namedWindow('output', cv2.WINDOW_AUTOSIZE)
    cv2.namedWindow('corners', cv2.WINDOW_AUTOSIZE)
    chessgame = Game()
    print(chessgame)
    chessboard = chess.Board()
    img_file = sys.argv[1]
    param_file = sys.argv[2]

    cap = cv2.VideoCapture(img_file)
    ret, frame = cap.read()

    # fourcc = cv2.VideoWriter_fourcc(*'XVID')
    # out = cv2.VideoWriter('output.avi', fourcc, 20.0, (692, 692))

    if not ret:
        print 'can\'t open the video'
        exit()
示例#10
0
from Chessnut import Game

chessgame = Game()
print(chessgame)  # 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'

print(chessgame.get_moves())
"""
['a2a3', 'a2a4', 'b2b3', 'b2b4', 'c2c3', 'c2c4', 'd2d3', 'd2d4', 'e2e3', 
 'e2e4', 'f2f3', 'f2f4', 'g2g3', 'g2g4', 'h2h3', 'h2h4', 'b1c3', 'b1a3', 
 'g1h3', 'g1f3']
"""

chessgame.apply_move('e2e4')  # succeeds!
print(chessgame)  # 'rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1'

#chessgame.apply_move('e2e4')  # fails! (raises InvalidMove exception)
示例#11
0

if __name__ == "__main__":

    if USE_DUMP:
        #load data directly using pickle
        f = open(sys.argv[1], 'rb')
        data = pickle.load(f)
        f.close()
        detectMove(data[0], data[1], data[2])

    if (len(sys.argv) < 4):
        print "USAGE: python detect_features file1.png file2.png sample_param.yml"
        exit()

    chessgame = Game()
    chessgame.apply_move('e2e4')
    chessgame.apply_move('e7e5')
    chessgame.apply_move('g1f3')
    chessgame.apply_move('d7d5')
    chessgame.apply_move('e4d5')
    print(chessgame)

    img_file1 = sys.argv[1]
    img_file2 = sys.argv[2]
    param_file = sys.argv[3]

    frames = []
    frames.append(cv2.imread(img_file1))
    frames.append(cv2.imread(img_file2))
示例#12
0
文件: chess.py 项目: idandrei94/SWA
#!/usr/bin/python3.5
from random import randint
from Chessnut import Game
import subprocess
import cgitb
import cgi
cgitb.enable()

print("Content-Type: text/html")
print()
board = Game()
moves = ""
arg_moves = []
#try:
# arg = cgi.FieldStorage()['history']
# arg_moves = arg.value.split(' ')
#except:
# pass
#for move in arg_moves:
# try:
#  board.apply_move(move.strip())
#  moves = moves + " " + move
# except:
#  pass
arg = cgi.FieldStorage()['history']
arg_moves = arg.value.split(' ')
for move in arg_moves:
    board.apply_move(move.strip())

available_moves = board.get_moves()
chosen_move = available_moves[randint(0, len(available_moves) - 1)]
示例#13
0
from __future__ import print_function
from Chessnut import Game

import sys

if len(sys.argv) < 3 or 'help' in sys.argv[1]:
    print('Usage:\n    python make_move.py [FEN] [move]')
    print('Reply: [NEW_FEN] if valid, otherwise error')
    sys.exit(0)

fen = sys.argv[1].strip()
move = sys.argv[2].strip().replace('_', '')

# Throws error if fen is not valid
try:
    chessgame = Game(fen, True)
except:
    print('Invalid fen: %s' % fen, file=sys.stderr)
    sys.exit(1)

# Throws error if the move is not valid
try:
    chessgame.apply_move(move)
except:
    print('Invalid move: %s' % move, file=sys.stderr)
    sys.exit(1)

print("%s" % chessgame)
示例#14
0
        help='Verbose output.')
parser.add_argument('-l', metavar='<LEVEL>', default=1,
        help='Engine level (1-20).')
args = parser.parse_args()

from bptbx.b_logging import setup_logging
from bptbx import b_legacy
setup_logging(args.v)

from Chessnut import Game
from Chessnut.game import InvalidMove
from chesster.core.position import Position
from chesster.core.uci_frontend import ChessterUciFrontend

uci_frontend = ChessterUciFrontend()
chessgame = Game()
options = {
           'setoption name Skill Level value {}'.format(args.l),
           'setoption name Hash value 32',
           'setoption name Threads value 2'
        }
uci_frontend.init_engine(options)
print (Position(chessgame.get_fen()).fen_to_string_board())

while True:
    if not args.b: # if user plays black, skip first user move
        # get move from user
        while True:
            print ('-- Your move: ')
            try:
                raw = b_legacy.b_raw_input().strip()
def add_the_tree(chess_tree, problem_id, fen, prev_move, blitz_rating, std_rating):
    """
    " Tree size, for each level
    """
    global accumulated_distance
    size = {}

    display_the_size(chess_tree, size)

    print size

    nodes = sorted(size.items(), key=lambda y: y[0])

    fathers = [0] * len(nodes)
    sons = [0] * len(nodes)
    branching_factor = {}

    i = 0
    for x in range(len(nodes) - 1):
        fathers[i] += nodes[x][1]
        i += 1
    i = 0
    for x in range(1, len(nodes)):
        sons[i] += nodes[x][1]
        i += 1
    for x in range(len(nodes)):
        if float(fathers[x]) > 0:
            branching_factor[x] = sons[x] / float(fathers[x])
        else:
            branching_factor[x] = 0

    position = fen.split()[0]
    figures = re.findall('[a-zA-Z]', position)
    types_of_pieces = len(set(figures))
    number_of_pieces = len(figures)

    """
    " 13.10.2014
    " Calculate the piece values
    " example: rnbqkbnr would yield 5 + 3 + 3 + 9 + 0 + 3 + 3 + 5 = 31 points for black
    " RNBQKB1R would yield 5 + 3 + 3 + 9 + 0 + 3 + 5 = 28 points for white
    " If it's white to move, the ratio will then be 28 / 31 = 0.9032258
    " The ratio then helps determine the difficulty of the game
    """
    new_fen = Game(fen=fen)
    new_fen.apply_move(prev_move)
    piece_value_w = calculate_values('w', str(new_fen))
    piece_value_b = calculate_values('b', str(new_fen))
    next_to_move = str(new_fen).split()[1]
    if next_to_move == 'w':
        piece_value_ratio = piece_value_w / float(piece_value_b)
    else:
        piece_value_ratio = piece_value_b / float(piece_value_w)
    # End of piece value calculation code

    with open('C:\Users\Simon\Dropbox\FRI\Diplomsko delo\Program\processed_data.csv', 'a+b') as csv_file:
        fen_writer = csv.writer(csv_file, delimiter=',')

        my_buffer = [problem_id, fen, prev_move, blitz_rating, std_rating]

        for i in range(4):
            my_buffer.append(size.get(i, 0))
        average_branching_factor = 0
        for i in range(4):
            my_buffer.append(branching_factor.get(i, 0))
            average_branching_factor += branching_factor.get(i, 0)
        average_branching_factor /= 4.0
        my_buffer.append(average_branching_factor)
        my_buffer.append(number_of_pieces)
        my_buffer.append(types_of_pieces)
        for i in range(4):
            my_buffer.append(accumulated_distance.get(i, 0))
        my_buffer.append(piece_value_ratio)

        fen_writer.writerow(my_buffer)

        # Reset the distance calculator for the moves
        accumulated_distance = {}
示例#16
0
def view():
    keyboard.on_press(key_press)

    arduino_python.connection()
    chessgame = Game()

    coordinate, listxy = chess3.points()

    # _,  = chess3.poinxts()
    cap = cv2.VideoCapture(2)
    diff = []
    diff1 = []
    old_place = np.zeros((64, ), dtype=np.int)
    place = np.zeros((64, ), dtype=np.int)
    place1 = np.zeros((64, ), dtype=np.int)
    aligment = 0
    legal_move = 0
    white_check = 0
    black_check = 0
    emotion_time = time.time()
    timer_a = time.time()
    change = 0
    # count = 0
    black_start = 0
    white_start = 0
    started = 0
    robot_time = time.time()
    robot = 0
    rook = 0
    white_find_rook = 0
    black_find_rook = 0
    rook_control = 0
    stock_fish = stockfish.Stockfish()
    contempt_value = 0
    check2 = 0
    check1 = 0
    contempt_factor = {'Contempt': contempt_value}
    while True:

        # Yuz tanima ve contempt factor degeri ayarlama
        face_emotions = emotions()

        if time.time() - emotion_time > 10:
            emotion_time = time.time()
            if face_emotions == "sad":
                contempt_value = random.randrange(0, 20)
                contempt_factor.update(Contempt=contempt_value)
                stock_fish.__init__(param=contempt_factor)
            elif face_emotions == "fear":
                contempt_value = random.randrange(20, 40)
                contempt_factor.update(Contempt=contempt_value)
                stock_fish.__init__(param=contempt_factor)
            elif face_emotions == "neutral":
                contempt_value = random.randrange(40, 60)
                contempt_factor.update(Contempt=contempt_value)
                stock_fish.__init__(param=contempt_factor)
            elif face_emotions == "angry":
                contempt_value = random.randrange(60, 80)
                contempt_factor.update(Contempt=contempt_value)
                stock_fish.__init__(param=contempt_factor)
            elif face_emotions == "happy":
                contempt_value = random.randrange(80, 100)
                contempt_factor.update(Contempt=contempt_value)
                stock_fish.__init__(param=contempt_factor)
            else:
                contempt_value = random.randrange(0, 100)
                contempt_factor.update(Contempt=contempt_value)
                stock_fish.__init__(param=contempt_factor)
            # print(face_emotions)
        _, img = cap.read()
        img = cv2.resize(img, (640, 400))

        masked = chess3.masked(img, coordinate[0], coordinate[1],
                               coordinate[2], coordinate[3])
        red_pieces, blue_pieces, img1 = pieces_detect(masked)
        cv2.imshow("Pieces Place", img1)

        # Beyaz tas sayaci
        if white_start == 0:
            control(listxy, place, blue_pieces)

            check = 0
            for i in range(0, len(place)):
                if place[i] == 1:

                    check = check + 1
                    old_place[i] = place[i]
                    place[i] = 0
            if check1 != check:
                print("Beyaz Tas Sayisi : " + str(check))
                check1 = check

            if check == 16:
                black_start = 2
                white_start = 1
                print("Beyazlarsiniz")

        # Siyah tas sayaci
        if black_start == 0:
            control(listxy, place, red_pieces)
            check = 0

            for i in range(0, len(place)):
                if place[i] == 1:

                    check = check + 1
                    old_place[i] = place[i]
                    place[i] = 0
            if check2 != check:
                print("Siyah Tas Sayisi : " + str(check))
                check2 = check

            # print(check)
            if check == 16:
                black_start = 1
                white_start = 2
                print("Siyahlarsiniz")

        # Siyah Tas Islemleri
        if black_start == 1:

            if white_check == 0:
                control(listxy, place, blue_pieces)

                check = 0

                for i in range(0, len(place)):
                    if place[i] == 1:
                        check = check + 1
                        old_place[i] = place[i]
                        place[i] = 0
                if check == 16:
                    white_check = 1

            if (started == 0) and white_check == 1:
                robot = 2
                robot_time = time.time()
                best_move, poslist = sfish.black_start_game()
                chessgame.apply_move(best_move)

                if old_place[character.index(best_move[2:], 0)] == 1:
                    arduino_python.push('-' + best_move[:2] + '-fully-' +
                                        best_move[2:] + '_down-' + "empty-")
                    arduino_python.push('-redL-')
                    robot_time = robot_time + 30
                else:
                    arduino_python.push('-' + best_move[:2] + '-fully-' +
                                        best_move[2:] + '_down-' + "empty-")
                    robot_time = robot_time + 30
                    arduino_python.push('-redL-')

                started = 1
            if robot == 2 and time.time() - robot_time > 0:
                robot_time = time.time()
                print("lutfen oynayin 1")

                arduino_python.push('-greenL-')

                robot = 0

            if (change == 0) and white_check == 1 and robot == 0:

                for i in range(0, 64):
                    place[i] = 0

                if aligment == 0:

                    control(listxy, place, red_pieces)
                    for i in range(0, 64):
                        old_place[i] = place[i]
                    aligment = 1

                control(listxy, place, red_pieces)

                for i in range(0, len(place)):

                    if place[i] != old_place[i]:
                        robot = 1
                        print("10 saniye icinde oyna")
                        arduino_python.push('-tenSec-')
                        timer_a = time.time()
                        change = 1
                        break
                    elif old_place.any() == place.any():
                        change = 0
                        robot = 0

            if time.time(
            ) - timer_a > 10 and change == 1 and started == 1 and robot == 1:
                robot = 0
                arduino_python.push('-greenL-')

                for i in range(0, 64):
                    place1[i] = 0

                control(listxy, place1, red_pieces)

                timer_a = time.time()
                # if (count == 0):
                #     for i in range(0, len(place1)):
                #         old_place[i] = place1[i]
                #         count = 1
                # count = 1
                # if count == 1:
                for i in range(0, len(place1)):
                    if place1[i] != old_place[i]:
                        diff.append(i)

                        if len(diff) == 2:

                            if old_place[i] == 0:
                                diff1.append(diff[0])
                                diff1.append(diff[1])

                            elif old_place[i] == 1:
                                diff1.append(diff[1])
                                diff1.append(diff[0])
                        elif len(diff) == 4 and rook == 0:

                            if old_place[i] == 0:
                                diff1.append(diff[0])
                                diff1.append(diff[1])

                            elif old_place[i] == 1:
                                diff1.append(diff[1])
                                diff1.append(diff[0])

                        old_place[i] = place1[i]

                if len(diff1) == 2:
                    robot = 3
                    robot_time = time.time()
                    legal_move = chessgame.apply_move(character[diff1[0]] +
                                                      character[diff1[1]])
                    if legal_move == 0:
                        sfish.position(character[diff1[0]] +
                                       character[diff1[1]])
                        best_move, poslist = sfish.black_start_game()
                        chessgame.apply_move(best_move)

                        if white_find_rook == 0:
                            white_find_rook, rook_control = white_rook_detect(
                                poslist, white_find_rook)
                            if rook_control == 1:
                                robot_time = robot_time + 60
                        try:
                            if old_place[character.index(
                                    best_move[2:],
                                    0)] == 1 and rook_control == 0:

                                arduino_python.push('-redL-' + '-' +
                                                    best_move[2:] + '-fully-' +
                                                    'out-' + 'empty-' +
                                                    best_move[:2] + '-fully-' +
                                                    best_move[2:] + '_down-' +
                                                    'empty-')

                                robot_time = robot_time + 60

                            elif old_place[character.index(
                                    best_move[2:],
                                    0)] == 0 and rook_control == 0:
                                arduino_python.push('-redL-' + '-' +
                                                    best_move[:2] + '-fully-' +
                                                    best_move[2:] + '_down-' +
                                                    "empty-")
                                robot_time = robot_time + 30
                        except ValueError:
                            if len(best_move) == 3:
                                arduino_python.push(
                                    '-redL-' + '-' + best_move[0:1] +
                                    str(int(best_move[1:2]) - 1) + '-fully-' +
                                    best_move[0:2] + '_down-' + '-empty-')
                                robot_time = robot_time + 30
                            else:
                                arduino_python.push('-redL-' + '-' +
                                                    best_move[2:4] +
                                                    '-fully-' + 'out-' +
                                                    'empty-' + best_move[:2] +
                                                    '-fully-' +
                                                    best_move[2:4] + '_down-' +
                                                    'empty-')
                                robot_time = robot_time + 60
                    elif legal_move == 1:
                        print("Yanlis Hamle Oynadiniz" + character[diff1[0]] +
                              character[diff1[1]])
                        arduino_python.push('-illegal_move-')

                    diff1.clear()
                    rook_control = 0

                elif len(diff1) == 4 and character[diff1[0]] + character[
                        diff1[1]] == 'e8f8' and rook == 0:
                    for i in range(0, 64):
                        place1[i] = 0

                    character[diff1[0]] = 'e8'
                    character[diff1[1]] = 'g8'
                    robot = 3
                    robot_time = time.time()
                    legal_move = chessgame.apply_move(character[diff1[0]] +
                                                      character[diff1[1]])
                    if legal_move == 0:
                        sfish.position(character[diff1[0]] +
                                       character[diff1[1]])
                        best_move, poslist = sfish.black_start_game()
                        chessgame.apply_move(best_move)

                        character[diff1[0]] = 'e8'
                        character[diff1[1]] = 'f8'
                        if white_find_rook == 0:
                            white_find_rook, rook_control = white_rook_detect(
                                poslist, white_find_rook)
                            if rook_control == 1:
                                robot_time = robot_time + 60
                        try:
                            if old_place[character.index(
                                    best_move[2:],
                                    0)] == 1 and rook_control == 0:
                                arduino_python.push('-' + '-redL-' +
                                                    best_move[2:] + '-fully-' +
                                                    'out-' + 'empty-' +
                                                    best_move[:2] + '-fully-' +
                                                    best_move[2:] + '_down-' +
                                                    'empty-')
                                robot_time = robot_time + 60

                            elif old_place[character.index(
                                    best_move[2:],
                                    0)] == 0 and rook_control == 0:
                                arduino_python.push('-' + '-redL-' +
                                                    best_move[:2] + '-fully-' +
                                                    best_move[2:] + '_down-' +
                                                    "empty-")
                                robot_time = robot_time + 30
                        except ValueError:
                            if len(best_move) == 3:
                                arduino_python.push(
                                    '-' + '-redL-' + best_move[0:1] +
                                    str(int(best_move[1:2]) - 1) + '-fully-' +
                                    best_move[0:2] + '_down-' + '-empty-')
                                robot_time = robot_time + 30
                            else:
                                arduino_python.push('-' + '-redL-' +
                                                    best_move[2:4] +
                                                    '-fully-' + 'out-' +
                                                    'empty-' + best_move[:2] +
                                                    '-fully-' +
                                                    best_move[2:4] + '_down-' +
                                                    'empty-')
                                robot_time = robot_time + 60
                            robot_time = robot_time + 30
                    elif legal_move == 1:
                        arduino_python.push('-illegal_move-')
                        print("Yanlis Hamle Oynadiniz " + character[diff1[0]] +
                              character[diff1[1]])

                    diff1.clear()
                    rook_control = 0
                    rook = 1

                elif len(diff1) == 4 and character[diff1[0]] + character[
                        diff1[1]] == 'a8c8' and rook == 0:
                    for i in range(0, 64):
                        place1[i] = 0

                    character[diff1[0]] = 'e8'
                    character[diff1[1]] = 'c8'
                    robot = 3
                    robot_time = time.time()
                    legal_move = chessgame.apply_move(character[diff1[0]] +
                                                      character[diff1[1]])
                    if legal_move == 0:
                        sfish.position(character[diff1[0]] +
                                       character[diff1[1]])
                        best_move, poslist = sfish.black_start_game()
                        chessgame.apply_move(best_move)
                        character[diff1[0]] = 'a8'
                        character[diff1[1]] = 'c8'
                        if white_find_rook == 0:
                            white_find_rook, rook_control = white_rook_detect(
                                poslist, white_find_rook)
                            if rook_control == 1:
                                robot_time = robot_time + 60
                        try:
                            if old_place[character.index(
                                    best_move[2:],
                                    0)] == 1 and rook_control == 0:
                                arduino_python.push('-' + '-redL-' +
                                                    best_move[2:] + '-fully-' +
                                                    'out-' + 'empty-' +
                                                    best_move[:2] + '-fully-' +
                                                    best_move[2:] + '_down-' +
                                                    'empty-')
                                robot_time = robot_time + 60

                            elif old_place[character.index(
                                    best_move[2:],
                                    0)] == 0 and rook_control == 0:
                                arduino_python.push('-' + '-redL-' +
                                                    best_move[:2] + '-fully-' +
                                                    best_move[2:] + '_down-' +
                                                    "empty-")
                                robot_time = robot_time + 30
                        except ValueError:
                            if len(best_move) == 3:
                                arduino_python.push(
                                    '-' + '-redL-' + best_move[0:1] +
                                    str(int(best_move[1:2]) - 1) + '-fully-' +
                                    best_move[0:2] + '_down-' + '-empty-')
                                robot_time = robot_time + 30
                            else:
                                arduino_python.push('-' + '-redL-' +
                                                    best_move[2:4] +
                                                    '-fully-' + 'out-' +
                                                    'empty-' + best_move[:2] +
                                                    '-fully-' +
                                                    best_move[2:4] + '_down-' +
                                                    'empty-')
                                robot_time = robot_time + 60
                    elif legal_move == 1:
                        arduino_python.push('-illegal_move-')
                        print("Yanlis Hamle Oynadiniz " + character[diff1[0]] +
                              character[diff1[1]])
                    diff1.clear()
                    rook_control = 0
                    rook = 1

                # elif len(diff1) == 1:
                #     robot = 3
                change = 0
                diff.clear()
                diff1.clear()

            if robot == 3 and time.time() - robot_time > 0:

                robot_time = time.time()
                for i in range(0, 64):
                    place1[i] = 0
                control(listxy, place1, red_pieces)

                for i in range(0, len(place1)):
                    old_place[i] = place1[i]
                print("lutfen oynayin 2")
                if legal_move == 0:
                    arduino_python.push('-greenL-')
                elif legal_move == 1:
                    arduino_python.push('-illegal_move-')
                robot = 0
        # Beyaz Tas islemleri
        elif white_start == 1:

            if black_check == 0:
                control(listxy, place, red_pieces)

                check = 0

                for i in range(0, len(place)):
                    if place[i] == 1:
                        check = check + 1
                        old_place[i] = place[i]
                        place[i] = 0
                if check == 16:
                    black_check = 1

            if change == 0 and robot == 0 and black_check == 1:

                for i in range(0, 64):
                    place[i] = 0

                if aligment == 0:

                    control(listxy, place, blue_pieces)
                    for i in range(0, 64):
                        old_place[i] = place[i]
                    aligment = 1
                control(listxy, place, blue_pieces)

                for i in range(0, len(place)):

                    if place[i] != old_place[i]:
                        robot = 1
                        print("10 saniye icinde oyna")
                        arduino_python.push('-tenSec-')
                        timer_a = time.time()
                        change = 1

                        break
                    elif old_place.any() == place.any():
                        change = 0
                        robot = 0

            if time.time() - timer_a > 10 and change == 1 and robot == 1:
                arduino_python.push('-greenL-')
                robot = 0
                for i in range(0, 64):
                    place1[i] = 0

                control(listxy, place1, blue_pieces)

                timer_a = time.time()
                # if count == 2:
                #     for i in range(0, len(place1)):
                #         old_place[i] = place1[i]
                #         count = 1
                # count = 1
                # if count == 1:

                for i in range(0, len(place1)):

                    if place1[i] != old_place[i]:
                        diff.append(i)

                        if len(diff) == 2:

                            if old_place[i] == 0:
                                diff1.append(diff[0])
                                diff1.append(diff[1])

                            elif old_place[i] == 1:
                                diff1.append(diff[1])
                                diff1.append(diff[0])

                        elif len(diff) == 4 and rook == 0:

                            if old_place[i] == 0:
                                diff1.append(diff[0])
                                diff1.append(diff[1])

                            elif old_place[i] == 1:
                                diff1.append(diff[1])
                                diff1.append(diff[0])

                        old_place[i] = place1[i]

                if len(diff1) == 2:
                    robot = 3
                    robot_time = time.time()
                    legal_move = chessgame.apply_move(character[diff1[0]] +
                                                      character[diff1[1]])
                    if legal_move == 0:
                        sfish.position(character[diff1[0]] +
                                       character[diff1[1]])
                        best_move, poslist = sfish.white_start_game()
                        chessgame.apply_move(best_move)
                        if black_find_rook == 0:
                            black_find_rook, rook_control = black_rook_detect(
                                poslist, white_find_rook)
                            if rook_control == 1:
                                robot_time = robot_time + 60
                        try:
                            if old_place[character.index(
                                    best_move[2:],
                                    0)] == 1 and rook_control == 0:
                                arduino_python.push('-' + '-redL-' +
                                                    best_move[2:] + '-fully-' +
                                                    'out-' + 'empty-' +
                                                    best_move[:2] + '-fully-' +
                                                    best_move[2:] + '_down-' +
                                                    'empty-')

                                robot_time = robot_time + 60

                            elif old_place[character.index(
                                    best_move[2:],
                                    0)] == 0 and rook_control == 0:
                                arduino_python.push('-' + '-redL-' +
                                                    best_move[:2] + '-fully-' +
                                                    best_move[2:] + '_down-' +
                                                    "empty-")
                                robot_time = robot_time + 30
                        except ValueError:
                            if len(best_move) == 3:
                                arduino_python.push(
                                    '-' + '-redL-' + best_move[0:1] +
                                    str(int(best_move[1:2]) - 1) + '-fully-' +
                                    best_move[0:2] + '_down-' + '-empty-')
                                robot_time = robot_time + 30
                            else:
                                arduino_python.push('-' + '-redL-' +
                                                    best_move[2:4] +
                                                    '-fully-' + 'out-' +
                                                    'empty-' + best_move[:2] +
                                                    '-fully-' +
                                                    best_move[2:4] + '_down-' +
                                                    'empty-')
                                robot_time = robot_time + 60
                    elif legal_move == 1:
                        arduino_python.push('-illegal_move-')
                        print("Yanlis Hamle Oynadiniz " + character[diff1[0]] +
                              character[diff1[1]])
                    rook_control = 0
                    diff1.clear()

                elif len(diff1) == 4 and character[diff1[0]] + character[
                        diff1[1]] == 'e1f1' and rook == 0:
                    for i in range(0, 64):
                        place1[i] = 0

                    character[diff1[0]] = 'e1'
                    character[diff1[1]] = 'g1'
                    robot = 3
                    robot_time = time.time()
                    legal_move = chessgame.apply_move(character[diff1[0]] +
                                                      character[diff1[1]])
                    if legal_move == 0:
                        sfish.position(character[diff1[0]] +
                                       character[diff1[1]])
                        best_move, poslist = sfish.white_start_game()
                        chessgame.apply_move(best_move)
                        character[diff1[0]] = 'e1'
                        character[diff1[1]] = 'f1'
                        if black_find_rook == 0:
                            black_find_rook, rook_control = black_rook_detect(
                                poslist, white_find_rook)
                            if rook_control == 1:
                                robot_time = robot_time + 60
                        try:
                            if old_place[character.index(
                                    best_move[2:],
                                    0)] == 1 and rook_control == 0:
                                arduino_python.push('-' + '-redL-' +
                                                    best_move[2:] + '-fully-' +
                                                    'out-' + 'empty-' +
                                                    best_move[:2] + '-fully-' +
                                                    best_move[2:] + '_down-' +
                                                    'empty-')
                                robot_time = robot_time + 60

                            elif old_place[character.index(
                                    best_move[2:],
                                    0)] == 0 and rook_control == 0:
                                arduino_python.push('-' + '-redL-' +
                                                    best_move[:2] + '-fully-' +
                                                    best_move[2:] + '_down-' +
                                                    "empty-")
                                robot_time = robot_time + 30
                        except ValueError:
                            if len(best_move) == 3:
                                arduino_python.push(
                                    '-' + '-redL-' + best_move[0:1] +
                                    str(int(best_move[1:2]) - 1) + '-fully-' +
                                    best_move[0:2] + '_down-' + '-empty-')
                                robot_time = robot_time + 30
                            else:
                                arduino_python.push('-' + '-redL-' +
                                                    best_move[2:4] +
                                                    '-fully-' + 'out-' +
                                                    'empty-' + best_move[:2] +
                                                    '-fully-' +
                                                    best_move[2:4] + '_down-' +
                                                    'empty-')
                                robot_time = robot_time + 60
                    elif legal_move == 1:
                        arduino_python.push('-illegal_move-')
                        print("Yanlis Hamle Oynadiniz " + character[diff1[0]] +
                              character[diff1[1]])
                    rook_control = 0
                    diff1.clear()

                    rook = 1

                elif len(diff1) == 4 and character[diff1[0]] + character[
                        diff1[1]] == 'a1c1' and rook == 0:
                    for i in range(0, 64):
                        place1[i] = 0

                    character[diff1[0]] = 'e1'
                    character[diff1[1]] = 'c1'
                    robot = 3
                    robot_time = time.time()
                    legal_move = chessgame.apply_move(character[diff1[0]] +
                                                      character[diff1[1]])
                    if legal_move == 0:
                        sfish.position(character[diff1[0]] +
                                       character[diff1[1]])
                        best_move, poslist = sfish.white_start_game()
                        chessgame.apply_move(best_move)
                        character[diff1[0]] = 'a1'
                        character[diff1[1]] = 'c1'
                        if black_find_rook == 0:
                            black_find_rook, rook_control = black_rook_detect(
                                poslist, black_find_rook)
                            if rook_control == 1:
                                robot_time = robot_time + 60
                        try:
                            if old_place[character.index(
                                    best_move[2:],
                                    0)] == 1 and rook_control == 0:
                                arduino_python.push('-' + '-redL-' +
                                                    best_move[2:] + '-fully-' +
                                                    'out-' + 'empty-' +
                                                    best_move[:2] + '-fully-' +
                                                    best_move[2:] + '_down-' +
                                                    'empty-')
                                robot_time = robot_time + 60

                            elif old_place[character.index(
                                    best_move[2:],
                                    0)] == 0 and rook_control == 0:
                                arduino_python.push('-' + '-redL-' +
                                                    best_move[:2] + '-fully-' +
                                                    best_move[2:] + '_down-' +
                                                    "empty-")
                                robot_time = robot_time + 30
                        except ValueError:
                            if len(best_move) == 3:
                                arduino_python.push(
                                    '-' + '-redL-' + best_move[0:1] +
                                    str(int(best_move[1:2]) - 1) + '-fully-' +
                                    best_move[0:2] + '_down-' + '-empty-')
                                robot_time = robot_time + 30
                            else:
                                arduino_python.push('-' + '-redL-' +
                                                    best_move[2:4] +
                                                    '-fully-' + 'out-' +
                                                    'empty-' + best_move[:2] +
                                                    '-fully-' +
                                                    best_move[2:4] + '_down-' +
                                                    'empty-')
                                robot_time = robot_time + 60

                    elif legal_move == 1:
                        arduino_python.push('-illegal_move-')
                        print("Yanlis Hamle Oynadiniz " + character[diff1[0]] +
                              character[diff1[1]])

                    rook_control = 0
                    diff1.clear()
                    rook = 1

                change = 0
                diff.clear()
                diff1.clear()
            if robot == 3 and time.time() - robot_time > 0 and black_start == 1:
                robot_time = time.time()
                for i in range(0, 64):
                    place1[i] = 0
                control(listxy, place1, red_pieces)

                for i in range(0, len(place1)):
                    old_place[i] = place1[i]
                print("lutfen oynayin 3")
                if legal_move == 0:
                    arduino_python.push('-greenL-')
                elif legal_move == 1:
                    arduino_python.push('-illegal_move-')
                robot = 0
            elif robot == 3 and time.time(
            ) - robot_time > 0 and white_start == 1:
                robot_time = time.time()
                for i in range(0, 64):
                    place1[i] = 0
                control(listxy, place1, blue_pieces)

                for i in range(0, len(place1)):
                    old_place[i] = place1[i]
                print("lutfen oynayin 4")
                if legal_move == 0:
                    arduino_python.push('-greenL-')
                elif legal_move == 1:
                    arduino_python.push('-illegal_move-')
                robot = 0

        # print(blue_pieces)
        if cv2.waitKey(10) & 0xFF == ord('q'):
            cap.release()
            cv2.destroyAllWindows()
            break
示例#17
0
    sys.exit(1)

heatmap = []
for i in range(8):
    heatmap.append(list(values[8 * i:8 * (i + 1)]))

def rotateHeatmap(heatmap):
    newMap = []
    for i in reversed(range(len(heatmap))):
        newMap.append(list(reversed(heatmap[i])))
    return newMap

alignedMap = rotateHeatmap(heatmap)


originalGame = Game(fen, True)
originalBoard = originalGame.board._position

def ind(a,b):
    return a * 8 + b

def tryMoveAndEval(move):
    tempGame = Game(fen, True)
    tempGame.apply_move(move)
    tempBoard = tempGame.board._position
    score = 0
    for i in range(8):
        for u in range(8):
            if originalBoard[ind(i,u)] != tempBoard[ind(i,u)]:
                score += alignedMap[i][u]
    return score
示例#18
0
from __future__ import print_function
from Chessnut import Game

import sys

if len(sys.argv) < 3 or "help" in sys.argv[1]:
    print("Usage:\n    python make_move.py [FEN] [move]")
    print("Reply: [NEW_FEN] if valid, otherwise error")
    sys.exit(0)

fen = sys.argv[1].strip()
move = sys.argv[2].strip().replace("_", "")

# Throws error if fen is not valid
try:
    chessgame = Game(fen, True)
except:
    print("Invalid fen: %s" % fen, file=sys.stderr)
    sys.exit(1)


# Throws error if the move is not valid
try:
    chessgame.apply_move(move)
except:
    print("Invalid move: %s" % move, file=sys.stderr)
    sys.exit(1)

print("%s" % chessgame)
示例#19
0
from Chessnut import Game
from ChessBoard import *
import random
from Node import Node

#This program models a game of chess with the help of ChessNut, and integrates a GUI and intelligent chess agent
#Authors: Elias Strizower, Henry Kwan, Alex Godziela

################ GLOBAL VARIABLES ########################################

board = ChessBoard(8, 8)
## chessgame = Game() # use this for a NEW GAME, use a fen generator for testing
chessgame = Game()

HumanNextMoves = {
}  #Dictionary that will hold 2 ply of the human player's next moves
AINextMoves = {}  #Dictionary that will hold 2 ply of the AI's next moves
board.updateBoard(str(chessgame))


#This functions checks whether a player is in check, checkmate, or stalemate
def checkStatus():
    if chessgame.status == 1:
        print("CHECK")
    if chessgame.status == 2:
        print("CHECKMATE")
        print("GAME OVER")
    if chessgame.status == 3:
        print("STALEMATE")

示例#20
0
from Chessnut import Game

chessgame = Game()
print(chessgame)  # 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'

print(chessgame.get_moves())
"""
['a2a3', 'a2a4', 'b2b3', 'b2b4', 'c2c3', 'c2c4', 'd2d3', 'd2d4', 'e2e3', 
 'e2e4', 'f2f3', 'f2f4', 'g2g3', 'g2g4', 'h2h3', 'h2h4', 'b1c3', 'b1a3', 
 'g1h3', 'g1f3']
"""

chessgame.apply_move('e2e4')  # succeeds!
print(
    chessgame)  # 'rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1'

#chessgame.apply_move('e2e4')  # fails! (raises InvalidMove exception)