Example #1
0
    def __init__(self):

        self.chess = Chess()

        self.is_game_running = False

        self.get_view('MAIN_MENU')
Example #2
0
    def update_notation(self, chess: Chess, indicate_enpassant: bool = False):
        # Context manager to update notation of the move.
        # Notation needs the state of the chess before applying the move (like to resolve ambiguity in pieces)
        # and after applying the move (game status like check, checkmate).

        ###### BEFORE APPLYING MOVE	###########
        if self.castle_rook:  # in case of castling -- use special notation
            if self.new_square.x == 6:  # king side castling
                self.notation = 'O-O'
            else:  # self.new_square.x == 2	--  queen side castling
                self.notation = 'O-O-O'
        else:
            n_piece = self.piece.notation  # the piece, note in case of pawn, nothing
            n_square = self.new_square.notation  # the destination square
            n_captured = 'x' if self.captured_piece or self.en_passant_pawn else ''  # if capture (including enpassant)
            n_promoted = f'={self.new_piece.notation}' if self.pawn_promoted else ''  # if pawn promotion, the new piece
            n_enpassant = '(ep)' if indicate_enpassant and self.en_passant_pawn else ''  # in case of enpassant
            # if other pieces (of same type) can move to same square, `n_ambiguity` is used for resolving the piece
            n_ambiguity = ''  # if other pieces () also can move to same
            if not n_piece and n_captured:  # if pawn captures a piece, specify file
                n_piece = self.old_square.notation[0]
            elif n_piece:  # if not pawn
                # if two different pieces of the same type could move to the same square,
                # to resolve the ambiguity of which piece had moved, we use the file (x in square) or rank (y in square)
                # to uniquely identify the piece
                other_pieces = [
                    piece
                    for piece in chess.board[type(self.piece)][self.player]
                    if piece != self.piece and any(
                        move for move in piece.possible_moves()
                        if move.new_square == self.new_square)
                ]
                if other_pieces:
                    counter = Counter(''.join(
                        [piece.square.notation for piece in other_pieces]))
                    if self.old_square.notation[0] not in counter:
                        n_ambiguity = self.old_square.notation[0]
                    else:
                        assert self.old_square.notation[1] not in counter
                        n_ambiguity = self.old_square.notation[1]
            self.notation = f"{n_piece}{n_ambiguity}{n_captured}{n_square}{n_promoted}{n_enpassant}"

        yield
        ###### AFTER APPLYING MOVE
        if chess.is_checkmate():
            self.notation += '#'
        elif chess.is_check():
            self.notation += '+'
Example #3
0
    def __init__(self):
        """ Virtually private constructor. """

        if Singleton._chess is not None:
            raise Exception("This class is a singleton!")
        else:
            Singleton._chess = Chess()
Example #4
0
def log():
    root = Tk()
    root.title('17074304')
    root.geometry('600x450')

    var_HOST = StringVar()
    var_HOST.set('127.0.0.1')
    var_PORT = StringVar()
    var_PORT.set('5000')

    # 图片
    canvas = Canvas(root, height=650, width=600)
    image_file = PhotoImage(file='image/back.gif')
    canvas.create_image(0, 0, anchor='nw', image=image_file)
    canvas.pack(side='top')

    Label(root, text='HOST').place(x=50, y=50)
    Label(root, text='PORT').place(x=50, y=90)

    # 输入框
    entry_HOST = Entry(root, textvariable=var_HOST)
    entry_HOST.place(x=160, y=50)
    entry_PORT = Entry(root, textvariable=var_PORT)
    entry_PORT.place(x=160, y=90)

    # 登录注册按钮
    btn_login = Button(root, text='开始', command=lambda: Chess(root, entry_HOST.get(), entry_PORT.get()))# noqaE501
    btn_login.place(x=170, y=130)
    root.mainloop()
Example #5
0
    def __init__(self, size, sample_board):

        self.sample_board = sample_board
        pygame.init()
        self.Chess = Chess()
        self.screenX = size
        self.screenY = size
        flags = FULLSCREEN | DOUBLEBUF
        #flags = DOUBLEBUF
        self.screen = pygame.display.set_mode((size, size), flags)
        self.screen.set_alpha(None)
        self.piece_paths = self.get_piece_paths()
        self.piece_images = self.load_images()
        self.piece_being_held = None
        self.holding_piece = False
        pygame.display.set_caption('Chess')
        self.play_gui()
Example #6
0
    def __init__(self, width, height, gametype):
        """Initialize the GameCanvas and construct the layout

        :param width:  width of the game canvas in pixels
        :type width:  int
        :param height:  height of the game canvas in pixels
        :type height:  int
        :param gametype:  type of game to be loaded
        :type gametype:  str
        """
        DockPanel.__init__(self,HorizontalAlignment=HasAlignment.ALIGN_CENTER,Spacing=10)
        
        if gametype == 'Chess':
            self.game = Chess()
            self.boardtype = self.game.boardtype
            self.images = []
            for i in self.game.pieces:
                self.images.append('./images/Chess/'+str(i.player)+str(i.name)+'.svg')
            self.images = list(set(self.images))  #eliminate duplicates
            
        self.GC = GameCanvas(width, height, self.game)
        loadImages(self.images, self)
        self.GC.addMouseListener(self)
        
        self.b = Button("Make Move", self, StyleName='teststyle')
        self.cell1 = TextBox(StyleName='boxStyle')
        self.cell2 = TextBox(StyleName='boxStyle')

        self.cellPanel = HorizontalPanel(VerticalAlignment=HasAlignment.ALIGN_MIDDLE)
        self.cellPanel.add(self.cell1)
        self.cellPanel.add(self.cell2)

        self.mover = VerticalPanel(HorizontalAlignment=HasAlignment.ALIGN_CENTER)
        self.mover.add(self.cellPanel)
        self.mover.add(self.b)
    
        self.add(self.GC, DockPanel.CENTER)
        self.add(self.mover, DockPanel.EAST)
Example #7
0
    elif name == 'mc':
        return MonteCarloPlayer()
    elif name == 'mcs':
        return MonteCarloSearchPlayer()
    elif name == 'heuristic':
        return HeuristicMinMaxSearchPlayer(weights = 'default')
    elif name == 'genetic':
        return HeuristicMinMaxSearchPlayer()
    elif name == 'svm':
        return TrainedMinMaxSearchPlayer()
    else:
        sys.exit("Invalid player type: " + name)

if __name__ == '__main__':
    player1_type = 'human'
    player2_type = 'svm'
    if len(sys.argv) > 2:
        player2_type = sys.argv[2]
    if len(sys.argv) == 2:
        player2_type = sys.argv[1]
    elif len(sys.argv) > 1:
        player1_type = sys.argv[1]

    print("Playing", player1_type, "vs.", player2_type)

    player1 = get_player(player1_type)
    player2 = get_player(player2_type)

    game = Chess()
    game.play([player1, player2], verbose = True)
Example #8
0
class GamePlayer(DockPanel):
    """ The GamePlayer widget, containing game canvas and controls

    Attributes:
        GC (GameCanvas):  The GameCanvas object, containing game canvas and active game
        b (Button):  The button for submitting moves
        cell1 (TextBox):  Origin cell for a piece move
        cell2 (TextBox):  Destination cell for a piece move
        cellPanel (HorizontalPanel):  Panel containing cell1 and cell2
        mover (VerticalPanel):  Panel containing cellPanel and b
        selectedCell (list):  list of cell IDs that are currently selected
        
    Note:
        it might be a good idea to move the game proper out of the GameCanvas object
        - references and game-functions are kind of long
    """
    selectedCell = []
    
    def __init__(self, width, height, gametype):
        """Initialize the GameCanvas and construct the layout

        :param width:  width of the game canvas in pixels
        :type width:  int
        :param height:  height of the game canvas in pixels
        :type height:  int
        :param gametype:  type of game to be loaded
        :type gametype:  str
        """
        DockPanel.__init__(self,HorizontalAlignment=HasAlignment.ALIGN_CENTER,Spacing=10)
        
        if gametype == 'Chess':
            self.game = Chess()
            self.boardtype = self.game.boardtype
            self.images = []
            for i in self.game.pieces:
                self.images.append('./images/Chess/'+str(i.player)+str(i.name)+'.svg')
            self.images = list(set(self.images))  #eliminate duplicates
            
        self.GC = GameCanvas(width, height, self.game)
        loadImages(self.images, self)
        self.GC.addMouseListener(self)
        
        self.b = Button("Make Move", self, StyleName='teststyle')
        self.cell1 = TextBox(StyleName='boxStyle')
        self.cell2 = TextBox(StyleName='boxStyle')

        self.cellPanel = HorizontalPanel(VerticalAlignment=HasAlignment.ALIGN_MIDDLE)
        self.cellPanel.add(self.cell1)
        self.cellPanel.add(self.cell2)

        self.mover = VerticalPanel(HorizontalAlignment=HasAlignment.ALIGN_CENTER)
        self.mover.add(self.cellPanel)
        self.mover.add(self.b)
    
        self.add(self.GC, DockPanel.CENTER)
        self.add(self.mover, DockPanel.EAST)


    def GUImove(self, piece, cell):
        """Execute a move in the game; redraw the board"""
        didMove = self.game.make_move(piece, cell)
        self.GC.reset(self.game)
                    

    def onMouseUp(self, sender, x, y):
        mousex = float(x)/BOARDWIDTH
        mousey = float(y)/BOARDHEIGHT
        clickcell = self.game.whichCell(mousex,mousey)
        clickpieceID = self.game.state[clickcell]
        #If no cell is selected, make this cell selected.
        if len(self.selectedCell)==0:
            #If piece on this cell is not active or no piece on this cell, don't select
            if len(clickpieceID)==0:
                pass
            elif self.game.pieces[clickpieceID[len(clickpieceID)-1]].player!=self.game.state['player']:
                pass
            else:
                self.selectedCell.append(clickcell)
        #If this cell is selected, unselect this cell
        elif self.selectedCell[0]==clickcell:
            self.selectedCell.remove(clickcell)

        #If another cell is selected, query piece on that cell, call GUImove, clear selected
        else:
            piecelist = self.game.state[self.selectedCell.pop()]
            piece = self.game.pieces[piecelist[len(piecelist)-1]]
            cell = self.game.board[clickcell]
            self.GUImove(piece, cell)

        self.GC.reset(self.game)
        for i in self.selectedCell:
            self.GC.drawSelection(self.game.board[i])
            for j in self.game.state[i]:
                self.GC.drawPiece(self.game.pieces[j], self.game.board[i])
        
    def onClick(self,sender):
        """Call function for the text/button-based move controller"""
        if sender == self.b:
            cell1_txt = self.cell1.getText()
            cell2_txt = self.cell2.getText()
            #Window.alert(str(cell1_txt))
            if cell1_txt and cell2_txt in self.game.board:
                piece = self.game.pieces[self.game.state[cell1_txt][len(self.game.state[cell1_txt])-1]]
                cell = self.game.board[cell2_txt]
                self.GUImove(piece, cell)
            else:
                Window.alert("cell names not recognized!")
            self.cell1.setText("")
            self.cell2.setText("")

    def onImagesLoaded(self, imagesHandles):
        """Associate the correct image handle with each piece type

        :param imageHandles:  handles for the images in self.images
        :type imageHandles:  list
        
        """
        #Window.alert("loading images")
        for i in self.images:
            substr = i.split('/')
            img = substr.pop()
            p = int(img[0])
            name = img[1:img.find('.')]
            self.GC.img_dict[p][name] = imagesHandles[self.images.index(i)]
            
        self.GC.reset(self.game)