Ejemplo n.º 1
0
def key_manager(key, CursorClass):
    if key == ord('w'):
        Cursor.move(0, 1)
    elif key == ord('s'):
        Cursor.move(0, -1)
    elif key == ord('a'):
        Cursor.move(-1, 0)
    elif key == ord('d'):
        Cursor.move(1, 0)
    elif key == ord('g'):
        Cursor.select()
    elif key == ord('h'):
        if Cursor.any_selected() is True:
            Chess.move(*chain(Cursor.selected(), Cursor.pointed()))
Ejemplo n.º 2
0
def PlayerVsPlayer(startState = None):
	chess = Chess()
	chess.print_board()
	
	#Allows play from a specific state
	if (startState != None):
		chess.input_state()
		chess.print_board()
	
	#Play Chess!
	while(True):
		move = input('Input move: ')
		move = chess.convert_move(move)
		game = chess.move(move)
		
		if (game == None
			print(print_move)
			chess.print_board()
			return(chess)
		elif (game == False):
			continue
		else:
			chess.print_board()	
	return(chess)
	
def main():
	PlayerVsPlayer()	
main()
Ejemplo n.º 3
0
def main():
    pos = Chess()
    layers=5
    algorithm=Algorithm(pos,'black',layers)
    print_pos(pos)
    cnt1 = 0
    delayTime = 25;
    while True:
        res = detect()
        move = str(res[0])+str(res[1])
        print("move is")
        print(move)
        match=re.match('([a-h][1-8])'*2,move)

        if not match or (pos.format_move(move) not in pos.legal_moves()):
            print('Illegal Move')
            #move=input('Your move:')
            move = str(res[1])+str(res[0])
            match=re.match('([a-h][1-8])'*2,move)
            if not match or (pos.format_move(move) not in pos.legal_moves()):
                continue

        #move=chb.determine_move()
        pos.move(move)
        print_pos(pos)
        opp_move=algorithm.best_move()
        newMove = str(opp_move[0])+str(ord('9')-ord(opp_move[1]))+str(opp_move[2])+ str(ord('9')-ord(opp_move[3]))
        print(newMove)
        
        start = opp_move[0:2]
        end = opp_move[2:]
        a = 63 - convertMove(newMove[0:2])
        b = 63 - convertMove(newMove[2:])
        if(pos.state.board[b//8][b%8]!='· '):
            ser.write((str(convertMove(newMove[0:2]))+","+str(convertMove(newMove[2:]))+"!").encode())
            delayTime = 60        
        else:
            ser.write((str(convertMove(newMove[0:2]))+","+str(convertMove(newMove[2:]))+".").encode())
        pos.move(opp_move)
        print_pos(pos)
        time.sleep(delayTime)
Ejemplo n.º 4
0
class ChessGame:
    def __init__(self):
        self.chess = Chess()

    def start(self):
        while self.chess.is_in_progress:
            chess_util.print_board(self.chess.board)
            player = "White" if self.chess.in_turn == 1 else "Black"
            print("Player in turn : " + player)
            player_input = input("From: ")
            if player_input == "end":
                print("Game forcefully ended")
                break
            if player_input == "print":
                continue
            if player_input == "moves":
                print(self.chess.legal_moves)
                continue
            try:
                frm = tuple(map(int, player_input.split(' ')))
            except ValueError:
                print(
                    "Illegal Input. Example of legal input: '2 2' to make a move from (2, 2)"
                )
                continue
            player_input = input("To: ")
            try:
                to = tuple(map(int, player_input.split(' ')))
            except ValueError:
                print(
                    "Illegal Input. Example of legal input: '2 2' to make a move to (2, 2). Restarting move stuff. redo from step"
                )
                continue
            success, msg = self.chess.move(frm, to)
            if not success:
                print("Human move failed with message: " + msg)
                continue

        print("Game ended. Winner = " + str(self.chess.winner))
        chess_util.print_board(self.chess.board)
Ejemplo n.º 5
0
class Controller:
    def __init__(self):
        self.chess = Chess()
        self.view = View()

    def on_init(self):
        self.chess.on_init()
        self.view.on_init()

    def select(self):
        # set a piece to be dragged using dragging field in View
        coordinates = pg.mouse.get_pos()
        self.view.setSelectedPiece(coordinates)

    def drag(self):
        # perform a drag operation
        if self.view.dragging != None:
            coordinates = pg.mouse.get_pos()
            self.view.drag(coordinates)

    def drop(self):
        # drop piece being dragged
        # attempt to perform a move on the dragged piece to that square
        if self.view.dragging != None:
            toCoords = pg.mouse.get_pos()
            fromCoords = self.view.dragging.pos
            toCo = viewCoordsToModelIndex(toCoords, self.view.dragging.size)
            fromCo = viewCoordsToModelIndex(fromCoords, self.view.dragging.size)
            moved = self.chess.move(tupleToInt(fromCo), tupleToInt(toCo))
            if moved:
                self.view.removeImageAt(toCoords)
                self.view.drop(toCoords)
            else:
                self.view.drop(self.view.dragging.pos)
            self.view.dragging = None

    def getSurface(self):
        return self.view._display_surf
Ejemplo n.º 6
0
            text = str(counter).rjust(3)
            update_board()
            x_temp = 0
            y_temp = 3
        clock.tick(60)

        if chess.turn() == chess.WHITE:  # human's turn
            if event.type == pygame.MOUSEBUTTONDOWN:  # gets cursor coordinates on mouse button down to select piece
                coordinates_init = pygame.mouse.get_pos()
                if coordinates_init <= (800, 800):
                    x_init = coordinates_init[1] // 100
                    y_init = coordinates_init[0] // 100

            if event.type == pygame.MOUSEBUTTONUP:  # gets cursor coordinates on mouse button up to drop [move] piece
                coordinates_fin = pygame.mouse.get_pos()
                if coordinates_fin <= (800, 800):
                    x_fin = coordinates_fin[1] // 100
                    y_fin = coordinates_fin[0] // 100
                    moveTrue = chess.move((x_init, y_init), (x_fin, y_fin))
                    if moveTrue:
                        pygame.mixer.Sound.play(move)
                    update_board()
        else:  # ai's turn
            next = ai.next_move(chess)
            if next == None:  # checkmate
                print("Checkmate!")
            else:
                chess.move(next[0], next[1])

        # displays GUI
        pygame.display.flip()
Ejemplo n.º 7
0
class MainWindow(QGraphicsView):
    def __init__(self):
        super(MainWindow, self).__init__()

        self.scene = QGraphicsScene(self)
        self.game = Chess(2)
        self.scene.addItem(self.game)
        self.scene.setSceneRect(0, 0, 360, 360)

        view = QGraphicsView(self.scene, self)
        layout = QGridLayout()

        self.info_window = QTextEdit()
        self.info_window.setSizePolicy(QSizePolicy.Preferred,
                                       QSizePolicy.MinimumExpanding)
        self.info_window.setFocusPolicy(Qt.NoFocus)

        self.message_line = QLineEdit()
        self.message_line.setSizePolicy(QSizePolicy.Preferred,
                                        QSizePolicy.MinimumExpanding)
        self.message_line.setFocusPolicy(Qt.StrongFocus)
        self.message_line.returnPressed.connect(self.send_msg)

        connect_button = QPushButton("Connect", self)
        connect_button.setSizePolicy(QSizePolicy.Minimum,
                                     QSizePolicy.MinimumExpanding)
        connect_button.clicked.connect(self.button_actions)
        connect_button.setFocusPolicy(Qt.NoFocus)

        btn_new_game = QPushButton("New game", self)
        btn_new_game.setSizePolicy(QSizePolicy.Minimum,
                                   QSizePolicy.MinimumExpanding)
        btn_new_game.clicked.connect(self.button_actions)
        btn_new_game.setFocusPolicy(Qt.NoFocus)

        btn_exit = QPushButton("Exit", self)
        btn_exit.setSizePolicy(QSizePolicy.Minimum,
                               QSizePolicy.MinimumExpanding)
        btn_exit.clicked.connect(self.button_actions)
        btn_exit.setFocusPolicy(Qt.NoFocus)

        btn_last_game = QPushButton("Resume", self)
        btn_last_game.setSizePolicy(QSizePolicy.Minimum,
                                    QSizePolicy.MinimumExpanding)
        btn_last_game.clicked.connect(self.button_actions)
        btn_last_game.setFocusPolicy(Qt.NoFocus)

        btn_step_resume = QPushButton("Step resume", self)
        btn_step_resume.setSizePolicy(QSizePolicy.Minimum,
                                      QSizePolicy.MinimumExpanding)
        btn_step_resume.clicked.connect(self.button_actions)
        btn_step_resume.setFocusPolicy(Qt.NoFocus)

        layout.addWidget(view, 0, 0, 8, 8)
        layout.addWidget(btn_new_game, 8, 0, 1, 8)
        layout.addWidget(btn_exit, 9, 0, 1, 8)
        layout.addWidget(connect_button, 10, 0, 1, 8)
        layout.addWidget(btn_last_game, 11, 0, 1, 8)
        layout.addWidget(btn_step_resume, 12, 0, 1, 8)
        layout.addWidget(self.info_window, 0, 9, 12, 4)
        layout.addWidget(self.message_line, 12, 9, 1, 4)

        self.setLayout(layout)
        self.setGeometry(1000, 300, 650, 560)
        self.setCacheMode(QGraphicsView.CacheBackground)
        self.setWindowTitle("Chess-server")

        self.socket = None
        self.th1 = None
        self.th2 = None
        self.resume_idx = 0

        self.doc = minidom.Document()

        self.root = self.doc.createElement('game')
        self.doc.appendChild(self.root)

    def write_to_xml(self, move, player):
        move = str(move)
        move = re.findall(r'\d+', move)
        move = list(map(int, move))
        move_to_xml = self.doc.createElement('move')
        move_to_xml.appendChild(self.doc.createTextNode(str(move)))
        move_to_xml.setAttribute('player', str(player))
        self.root.appendChild(move_to_xml)
        xml_str = self.doc.toprettyxml(indent="\t")
        file = open('last_game.xml', 'w')
        file.write(xml_str)
        file.close()

    def wait_for_move(self):
        while self.socket is not None:
            if self.game.move_to_send:
                move = self.game.send_move()
                self.write_to_xml(move, 2)
                self.info_window.append(str(move))
                self.socket.send(str(move).encode())
                self.game.set_move_to_send()

    def button_actions(self):
        sender = self.sender()
        if sender.text() == "Exit":
            self.socket.close()
            self.close()
        elif sender.text() == "New game":
            self.scene.removeItem(self.game)
            del self.game
            self.game = Chess(2)
            self.scene.addItem(self.game)
        elif sender.text() == "Connect":
            self.create_connection()
        elif sender.text() == "Resume":
            self.load_last_game()
        elif sender.text() == "Step resume":
            self.load_one_move()

    def load_last_game(self):
        dom = minidom.parse("last_game.xml")
        moves = dom.getElementsByTagName('move')
        for move_from_xml in moves:
            move = move_from_xml.firstChild.data
            move = re.findall(r'\d+', move)
            move = list(map(int, move))
            player = move_from_xml.getAttribute("player")
            self.write_to_xml(move, int(player))
            if player == '2':
                self.game.move(move[0], move[1], move[2], move[3])
                self.game.set_turn()
            else:
                self.game.update_move(move)

    def load_one_move(self):
        dom = minidom.parse("last_game.xml")
        moves = dom.getElementsByTagName('move')
        if self.resume_idx < len(moves):
            move = moves[self.resume_idx].firstChild.data
            move = re.findall(r'\d+', move)
            move = list(map(int, move))
            player = moves[self.resume_idx].getAttribute("player")
            # self.write_to_xml(move, int(player))
            if player == '1':
                self.game.move(move[0], move[1], move[2], move[3])
                self.game.set_turn()
            else:
                self.game.update_move(move)
            if self.resume_idx < len(moves):
                self.resume_idx += 1
            self.game.update()

    def create_connection(self):
        if self.socket is None:
            TCP_IP = 'localhost'
            TCP_PORT = 50006
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.socket.bind((TCP_IP, TCP_PORT))
            self.socket.listen(1)
            self.socket, self.addr = self.socket.accept()
            self.info_window.append('Connection from: ' + str(self.addr) +
                                    '\n')
            self.th2 = Thread(target=self.wait_for_move)
            self.th1 = Thread(target=self.recv_msg)
            self.th2.start()
            self.th1.start()
        else:
            self.socket.close()
            self.th1.join()
            self.socket = None
            self.th1 = None

    def send_msg(self):
        if self.socket:
            msg = self.message_line.text()
            self.info_window.append("Me : " + msg)
            self.socket.send(msg.encode())
            self.message_line.clear()

    def recv_msg(self):
        while self.socket is not None:
            msg = str(self.socket.recv(1024).decode())
            self.info_window.append("Opponent : " + msg)
            msg = re.findall(r'\d+', msg)
            msg = list(map(int, msg))
            if msg:
                self.write_to_xml(msg, 1)
                self.game.update_move(msg)

    def keyPressEvent(self, event):
        super(MainWindow, self).keyPressEvent(event)
Ejemplo n.º 8
0
def PlayerVsAI(startState, robot=False):	
	chess = Chess()
	
	#Open Serial Port
	if (robot == True):
		port = open_port()
	
	while(True):
		player = input("Input Human Player's Color ('white' or 'black'): ")
	
		if (player == 'white'):	
			computer = 'black'
			break
		elif (player == 'black'): 
			computer = 'white'
			break
		else:
			print("Error incorrect color/n")
			print();

	#Send player color information to Arduino when it is ready to recieve
	if (robot == True):
		ready = ''
		while(ready != 'R'):
			ready = arduino_ready(port)
		send_input(port, player)
	
	#Allows play from a specific state
	if (startState != None):
		chess.input_state()
	chess.print_board()
		
	#Max Recommended Difficulty: 5 layers. Averages around 15 seconds per move.
	layers = 5
	algorithm = Algorithm(chess, computer, layers)
	
	#Play Chess!
	while(True):
		if (chess.state.turn == player):
			
			if (robot == True):
				serial_input = None
				move = recieve_input(port)
				move = chess.coordinate_to_notation(move)
				move = chess.convert_move(move)
			else:
				move = input('Input move: ')
				move = chess.convert_move(move)
			
		else:
			#Comments for move timing
			#start_time = time.time()		
			move = algorithm.best_move()			
			#end_time = time.time()		
			#print("Move time: {}".format(end_time - start_time))
		
			#If ChessBot is connected, send move via serial port
			if (robot == True):
				serial_input = chess.convert_serial_move(move)
		
		print_move = chess.convert_move(move)
		game = chess.move(move)
		
		if (robot == True and serial_input != None):
			send_input(port, serial_input)		
		
		#Ensure game has not ended before
		if (game == None):
			print(print_move)
			chess.print_board()
			return(chess)
		elif (game == False):
			continue
		else:
			print(print_move)
			chess.print_board()
			
	return(chess)