精华内容
下载资源
问答
  • Pygame游戏代码:中国象棋 包含代码、图片、声音等所有资源,可直接运行
  • Python项目案例开发从入门到实战源代码第15章 中国象棋代码.rar
  • Python中国象棋代码及素材

    千次阅读 多人点赞 2020-06-04 10:45:36
    Python中国象棋源程序共包含五个程序文件一个图片素材包, chinachess.py 为主文件;constants.py 数据常量;pieces.py 棋子类,走法;...提取码请先关注公众号:Python代码大全,然后回复:中国象棋资源。 c

    Python中国象棋源程序共包含五个程序文件一个图片素材包,
    chinachess.py 为主文件;constants.py 数据常量;pieces.py 棋子类,走法;computer.py 电脑走法计算;button.py按钮定义。目前电脑走法比较傻,有兴趣的朋友可以对computer.py 进行升级。中国象棋的素材包请在百度网盘下载,https://pan.baidu.com/s/1iVS3YsZY9mBQLElS4BcHsQ。提取码请先关注公众号:Python代码大全,然后回复:中国象棋资源。
    在这里插入图片描述
    chinachess.py

    import pygame
    import time
    import Xiangqi.constants as constants
    from Xiangqi.button import Button
    import Xiangqi.pieces as pieces
    import Xiangqi.computer as computer
    
    
    class MainGame():
        window = None
        Start_X = constants.Start_X
        Start_Y = constants.Start_Y
        Line_Span = constants.Line_Span
        Max_X = Start_X + 8 * Line_Span
        Max_Y = Start_Y + 9 * Line_Span
    
    
        player1Color = constants.player1Color
        player2Color = constants.player2Color
        Putdownflag = player1Color
        piecesSelected = None
    
    
        button_go = None
        piecesList = []
    
    
        def start_game(self):
            MainGame.window = pygame.display.set_mode([constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT])
            pygame.display.set_caption("Python代码大全-中国象棋")
            MainGame.button_go = Button(MainGame.window, "重新开始", constants.SCREEN_WIDTH - 100, 300)  # 创建开始按钮
            self.piecesInit()
    
    
            while True:
                time.sleep(0.1)
                # 获取事件
                MainGame.window.fill(constants.BG_COLOR)
                self.drawChessboard()
                #MainGame.button_go.draw_button()
                self.piecesDisplay()
                self.VictoryOrDefeat()
                self.Computerplay()
                self.getEvent()
                pygame.display.update()
                pygame.display.flip()
    
    
        def drawChessboard(self): #画象棋盘
            mid_end_y = MainGame.Start_Y + 4 * MainGame.Line_Span
            min_start_y = MainGame.Start_Y + 5 * MainGame.Line_Span
            for i in range(0, 9):
                x = MainGame.Start_X + i * MainGame.Line_Span
                if i==0 or i ==8:
                    y = MainGame.Start_Y + i * MainGame.Line_Span
                    pygame.draw.line(MainGame.window, constants.BLACK, [x, MainGame.Start_Y], [x, MainGame.Max_Y], 1)
                else:
                    pygame.draw.line(MainGame.window, constants.BLACK, [x, MainGame.Start_Y], [x, mid_end_y], 1)
                    pygame.draw.line(MainGame.window, constants.BLACK, [x, min_start_y], [x, MainGame.Max_Y], 1)
    
    
            for i in range(0, 10):
                x = MainGame.Start_X + i * MainGame.Line_Span
                y = MainGame.Start_Y + i * MainGame.Line_Span
                pygame.draw.line(MainGame.window, constants.BLACK, [MainGame.Start_X, y], [MainGame.Max_X, y], 1)
    
    
            speed_dial_start_x =  MainGame.Start_X + 3 * MainGame.Line_Span
            speed_dial_end_x =  MainGame.Start_X + 5 * MainGame.Line_Span
            speed_dial_y1 = MainGame.Start_Y + 0 * MainGame.Line_Span
            speed_dial_y2 = MainGame.Start_Y + 2 * MainGame.Line_Span
            speed_dial_y3 = MainGame.Start_Y + 7 * MainGame.Line_Span
            speed_dial_y4 = MainGame.Start_Y + 9 * MainGame.Line_Span
    
    
            pygame.draw.line(MainGame.window, constants.BLACK, [speed_dial_start_x, speed_dial_y1], [speed_dial_end_x, speed_dial_y2], 1)
            pygame.draw.line(MainGame.window, constants.BLACK, [speed_dial_start_x, speed_dial_y2],
                             [speed_dial_end_x, speed_dial_y1], 1)
            pygame.draw.line(MainGame.window, constants.BLACK, [speed_dial_start_x, speed_dial_y3],
                             [speed_dial_end_x, speed_dial_y4], 1)
            pygame.draw.line(MainGame.window, constants.BLACK, [speed_dial_start_x, speed_dial_y4],
                             [speed_dial_end_x, speed_dial_y3], 1)
    
    
        def piecesInit(self):  #加载棋子
            MainGame.piecesList.append(pieces.Rooks(MainGame.player2Color, 0,0))
            MainGame.piecesList.append(pieces.Rooks(MainGame.player2Color,  8, 0))
            MainGame.piecesList.append(pieces.Elephants(MainGame.player2Color,  2, 0))
            MainGame.piecesList.append(pieces.Elephants(MainGame.player2Color,  6, 0))
            MainGame.piecesList.append(pieces.King(MainGame.player2Color, 4, 0))
            MainGame.piecesList.append(pieces.Knighs(MainGame.player2Color,  1, 0))
            MainGame.piecesList.append(pieces.Knighs(MainGame.player2Color,  7, 0))
            MainGame.piecesList.append(pieces.Cannons(MainGame.player2Color,  1, 2))
            MainGame.piecesList.append(pieces.Cannons(MainGame.player2Color, 7, 2))
            MainGame.piecesList.append(pieces.Mandarins(MainGame.player2Color,  3, 0))
            MainGame.piecesList.append(pieces.Mandarins(MainGame.player2Color, 5, 0))
            MainGame.piecesList.append(pieces.Pawns(MainGame.player2Color, 0, 3))
            MainGame.piecesList.append(pieces.Pawns(MainGame.player2Color, 2, 3))
            MainGame.piecesList.append(pieces.Pawns(MainGame.player2Color, 4, 3))
            MainGame.piecesList.append(pieces.Pawns(MainGame.player2Color, 6, 3))
            MainGame.piecesList.append(pieces.Pawns(MainGame.player2Color, 8, 3))
    
    
            MainGame.piecesList.append(pieces.Rooks(MainGame.player1Color,  0, 9))
            MainGame.piecesList.append(pieces.Rooks(MainGame.player1Color,  8, 9))
            MainGame.piecesList.append(pieces.Elephants(MainGame.player1Color, 2, 9))
            MainGame.piecesList.append(pieces.Elephants(MainGame.player1Color, 6, 9))
            MainGame.piecesList.append(pieces.King(MainGame.player1Color,  4, 9))
            MainGame.piecesList.append(pieces.Knighs(MainGame.player1Color, 1, 9))
            MainGame.piecesList.append(pieces.Knighs(MainGame.player1Color, 7, 9))
            MainGame.piecesList.append(pieces.Cannons(MainGame.player1Color,  1, 7))
            MainGame.piecesList.append(pieces.Cannons(MainGame.player1Color,  7, 7))
            MainGame.piecesList.append(pieces.Mandarins(MainGame.player1Color,  3, 9))
            MainGame.piecesList.append(pieces.Mandarins(MainGame.player1Color,  5, 9))
            MainGame.piecesList.append(pieces.Pawns(MainGame.player1Color, 0, 6))
            MainGame.piecesList.append(pieces.Pawns(MainGame.player1Color, 2, 6))
            MainGame.piecesList.append(pieces.Pawns(MainGame.player1Color, 4, 6))
            MainGame.piecesList.append(pieces.Pawns(MainGame.player1Color, 6, 6))
            MainGame.piecesList.append(pieces.Pawns(MainGame.player1Color, 8, 6))
    
    
        def piecesDisplay(self):
            for item in MainGame.piecesList:
                item.displaypieces(MainGame.window)
                #MainGame.window.blit(item.image, item.rect)
    
    
        def getEvent(self):
            # 获取所有的事件
            eventList = pygame.event.get()
            for event in eventList:
                if event.type == pygame.QUIT:
                    self.endGame()
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    pos = pygame.mouse.get_pos()
                    mouse_x = pos[0]
                    mouse_y = pos[1]
                    if (
                            mouse_x > MainGame.Start_X - MainGame.Line_Span / 2 and mouse_x < MainGame.Max_X + MainGame.Line_Span / 2) and (
                            mouse_y > MainGame.Start_Y - MainGame.Line_Span / 2 and mouse_y < MainGame.Max_Y + MainGame.Line_Span / 2):
                        # print( str(mouse_x) + "" + str(mouse_y))
                        # print(str(MainGame.Putdownflag))
                        if MainGame.Putdownflag != MainGame.player1Color:
                            return
    
    
                        click_x = round((mouse_x - MainGame.Start_X) / MainGame.Line_Span)
                        click_y = round((mouse_y - MainGame.Start_Y) / MainGame.Line_Span)
                        click_mod_x = (mouse_x - MainGame.Start_X) % MainGame.Line_Span
                        click_mod_y = (mouse_y - MainGame.Start_Y) % MainGame.Line_Span
                        if abs(click_mod_x - MainGame.Line_Span / 2) >= 5 and abs(
                                click_mod_y - MainGame.Line_Span / 2) >= 5:
                            # print("有效点:x="+str(click_x)+" y="+str(click_y))
                            # 有效点击点
                            self.PutdownPieces(MainGame.player1Color, click_x, click_y)
                    else:
                        print("out")
                    if MainGame.button_go.is_click():
                        #self.restart()
                        print("button_go click")
                    else:
                        print("button_go click out")
    
    
        def PutdownPieces(self, t, x, y):
            selectfilter=list(filter(lambda cm: cm.x == x and cm.y == y and cm.player == MainGame.player1Color,MainGame.piecesList))
            if len(selectfilter):
                MainGame.piecesSelected = selectfilter[0]
                return
    
    
            if MainGame.piecesSelected :
                #print("1111")
    
    
                arr = pieces.listPiecestoArr(MainGame.piecesList)
                if MainGame.piecesSelected.canmove(arr, x, y):
                    self.PiecesMove(MainGame.piecesSelected, x, y)
                    MainGame.Putdownflag = MainGame.player2Color
            else:
                fi = filter(lambda p: p.x == x and p.y == y, MainGame.piecesList)
                listfi = list(fi)
                if len(listfi) != 0:
                    MainGame.piecesSelected = listfi[0]
    
    
        def PiecesMove(self,pieces,  x , y):
            for item in  MainGame.piecesList:
                if item.x ==x and item.y == y:
                    MainGame.piecesList.remove(item)
            pieces.x = x
            pieces.y = y
            print("move to " +str(x) +" "+str(y))
            return True
    
    
        def Computerplay(self):
            if MainGame.Putdownflag == MainGame.player2Color:
                print("轮到电脑了")
                computermove = computer.getPlayInfo(MainGame.piecesList)
                #if computer==None:
                    #return
                piecemove = None
                for item in MainGame.piecesList:
                    if item.x == computermove[0] and item.y == computermove[1]:
                        piecemove= item
    
    
                self.PiecesMove(piecemove, computermove[2], computermove[3])
                MainGame.Putdownflag = MainGame.player1Color
    
    
        #判断游戏胜利
        def VictoryOrDefeat(self):
            txt =""
            result = [MainGame.player1Color,MainGame.player2Color]
            for item in MainGame.piecesList:
                if type(item) ==pieces.King:
                    if item.player == MainGame.player1Color:
                        result.remove(MainGame.player1Color)
                    if item.player == MainGame.player2Color:
                        result.remove(MainGame.player2Color)
    
    
            if len(result)==0:
                return
            if result[0] == MainGame.player1Color :
                txt = "失败!"
            else:
                txt = "胜利!"
            MainGame.window.blit(self.getTextSuface("%s" % txt), (constants.SCREEN_WIDTH - 100, 200))
            MainGame.Putdownflag = constants.overColor
    
    
        def getTextSuface(self, text):
            pygame.font.init()
            # print(pygame.font.get_fonts())
            font = pygame.font.SysFont('kaiti', 18)
            txt = font.render(text, True, constants.TEXT_COLOR)
            return txt
    
    
        def endGame(self):
            print("exit")
            exit()
    
    
    if __name__ == '__main__':
        MainGame().start_game()
    

    constants.py 数据常量

    
    import pygame
    
    
    SCREEN_WIDTH=900
    SCREEN_HEIGHT=650
    Start_X = 50
    Start_Y = 50
    Line_Span = 60
    
    
    player1Color = 1
    player2Color = 2
    overColor = 3
    
    
    BG_COLOR=pygame.Color(200, 200, 200)
    Line_COLOR=pygame.Color(255, 255, 200)
    TEXT_COLOR=pygame.Color(255, 0, 0)
    
    
    # 定义颜色
    BLACK = ( 0, 0, 0)
    WHITE = (255, 255, 255)
    RED = (255, 0, 0)
    GREEN = ( 0, 255, 0)
    BLUE = ( 0, 0, 255)
    
    
    repeat = 0
    
    
    pieces_images = {
        'b_rook': pygame.image.load("imgs/s2/b_c.gif"),
        'b_elephant': pygame.image.load("imgs/s2/b_x.gif"),
        'b_king': pygame.image.load("imgs/s2/b_j.gif"),
        'b_knigh': pygame.image.load("imgs/s2/b_m.gif"),
        'b_mandarin': pygame.image.load("imgs/s2/b_s.gif"),
        'b_cannon': pygame.image.load("imgs/s2/b_p.gif"),
        'b_pawn': pygame.image.load("imgs/s2/b_z.gif"),
    
    
        'r_rook': pygame.image.load("imgs/s2/r_c.gif"),
        'r_elephant': pygame.image.load("imgs/s2/r_x.gif"),
        'r_king': pygame.image.load("imgs/s2/r_j.gif"),
        'r_knigh': pygame.image.load("imgs/s2/r_m.gif"),
        'r_mandarin': pygame.image.load("imgs/s2/r_s.gif"),
        'r_cannon': pygame.image.load("imgs/s2/r_p.gif"),
        'r_pawn': pygame.image.load("imgs/s2/r_z.gif"),
    }
    

    pieces.py 棋子类,走法

    
    import pygame
    import Xiangqi.constants as constants
    
    
    class  Pieces():
        def __init__(self, player,  x, y):
            self.imagskey = self.getImagekey()
            self.image = constants.pieces_images[self.imagskey]
            self.x = x
            self.y = y
            self.player = player
            self.rect = self.image.get_rect()
            self.rect.left = constants.Start_X + x * constants.Line_Span - self.image.get_rect().width / 2
            self.rect.top = constants.Start_Y + y * constants.Line_Span - self.image.get_rect().height / 2
    
    
        def displaypieces(self,screen):
            #print(str(self.rect.left))
            self.rect.left = constants.Start_X + self.x * constants.Line_Span - self.image.get_rect().width / 2
            self.rect.top = constants.Start_Y + self.y * constants.Line_Span - self.image.get_rect().height / 2
            screen.blit(self.image,self.rect);
            #self.image = self.images
            #MainGame.window.blit(self.image,self.rect)
    
    
        def canmove(self, arr, moveto_x, moveto_y):
            pass
        def getImagekey(self):
            return None
        def getScoreWeight(self,listpieces):
            return  None
    
    
    class Rooks(Pieces):
        def __init__(self, player,  x, y):
            self.player = player
            super().__init__(player,  x, y)
    
    
        def getImagekey(self):
            if self.player == constants.player1Color:
                return "r_rook"
            else:
                return "b_rook"
    
    
        def canmove(self, arr, moveto_x, moveto_y):
            if self.x == moveto_x and self.y == moveto_y:
                return False
            if arr[moveto_x][moveto_y] ==self.player :
                return  False
            if self.x == moveto_x:
                step = -1 if self.y > moveto_y else 1
                for i in range(self.y +step, moveto_y, step):
                    if arr[self.x][i] !=0 :
                        return False
                #print(" move y")
                return True
    
    
            if self.y == moveto_y:
                step = -1 if self.x > moveto_x else 1
                for i in range(self.x + step, moveto_x, step):
                    if arr[i][self.y] != 0:
                        return False
                return True
    
    
        def getScoreWeight(self, listpieces):
            score = 11
            return score
    
    
    class Knighs(Pieces):
        def __init__(self, player,  x, y):
            self.player = player
            super().__init__(player,  x, y)
        def getImagekey(self):
            if self.player == constants.player1Color:
                return "r_knigh"
            else:
                return "b_knigh"
        def canmove(self, arr, moveto_x, moveto_y):
            if self.x == moveto_x and self.y == moveto_y:
                return False
            if arr[moveto_x][moveto_y] == self.player:
                return False
            #print(str(self.x) +""+str(self.y))
            move_x = moveto_x-self.x
            move_y = moveto_y - self.y
            if abs(move_x) == 1 and abs(move_y) == 2:
                step = 1 if move_y > 0 else -1
                if arr[self.x][self.y + step] == 0:
                    return True
            if abs(move_x) == 2 and abs(move_y) == 1:
                step = 1 if move_x >0 else -1
                if arr[self.x +step][self.y] ==0 :
                    return  True
    
    
        def getScoreWeight(self, listpieces):
            score = 5
            return score
    
    
    class Elephants(Pieces):
        def __init__(self, player, x, y):
            self.player = player
            super().__init__(player, x, y)
        def getImagekey(self):
            if self.player == constants.player1Color:
                return "r_elephant"
            else:
                return "b_elephant"
        def canmove(self, arr, moveto_x, moveto_y):
            if self.x == moveto_x and self.y == moveto_y:
                return False
            if arr[moveto_x][moveto_y] == self.player:
                return False
            if self.y <=4 and moveto_y >=5 or self.y >=5 and moveto_y <=4:
                return  False
            move_x = moveto_x - self.x
            move_y = moveto_y - self.y
            if abs(move_x) == 2 and abs(move_y) == 2:
                step_x = 1 if move_x > 0 else -1
                step_y = 1 if move_y > 0 else -1
                if arr[self.x + step_x][self.y + step_y] == 0:
                    return True
    
    
        def getScoreWeight(self, listpieces):
            score = 2
            return score
    class Mandarins(Pieces):
    
    
        def __init__(self, player,  x, y):
            self.player = player
            super().__init__(player,  x, y)
    
    
        def getImagekey(self):
            if self.player == constants.player1Color:
                return "r_mandarin"
            else:
                return "b_mandarin"
        def canmove(self, arr, moveto_x, moveto_y):
            if self.x == moveto_x and self.y == moveto_y:
                return False
            if arr[moveto_x][moveto_y] == self.player:
                return False
            if moveto_x <3 or moveto_x >5:
                return False
            if moveto_y > 2 and moveto_y < 7:
                return False
            move_x = moveto_x - self.x
            move_y = moveto_y - self.y
            if abs(move_x) == 1 and abs(move_y) == 1:
                return True
        def getScoreWeight(self, listpieces):
            score = 2
            return score
    
    
    class King(Pieces):
        def __init__(self, player, x, y):
            self.player = player
            super().__init__(player, x, y)
        def getImagekey(self):
            if self.player == constants.player1Color:
                return "r_king"
            else:
                return "b_king"
    
    
        def canmove(self, arr, moveto_x, moveto_y):
            if self.x == moveto_x and self.y == moveto_y:
                return False
            if arr[moveto_x][moveto_y] == self.player:
                return False
            if moveto_x < 3 or moveto_x > 5:
                return False
            if moveto_y > 2 and moveto_y < 7:
                return False
            move_x = moveto_x - self.x
            move_y = moveto_y - self.y
            if abs(move_x) + abs(move_y) == 1:
                return True
        def getScoreWeight(self, listpieces):
            score = 150
            return score
    class Cannons(Pieces):
        def __init__(self, player,  x, y):
            self.player = player
            super().__init__(player, x, y)
        def getImagekey(self):
            if self.player == constants.player1Color:
                return "r_cannon"
            else:
                return "b_cannon"
    
    
        def canmove(self, arr, moveto_x, moveto_y):
            if self.x == moveto_x and self.y == moveto_y:
                return False
            if arr[moveto_x][moveto_y] == self.player:
                return False
            overflag = False
            if self.x == moveto_x:
                step = -1 if self.y > moveto_y else 1
                for i in range(self.y + step, moveto_y, step):
                    if arr[self.x][i] != 0:
                        if overflag:
                            return False
                        else:
                            overflag = True
    
    
                if overflag and arr[moveto_x][moveto_y] == 0:
                    return False
                if not overflag and arr[self.x][moveto_y] != 0:
                    return False
    
    
                return True
    
    
            if self.y == moveto_y:
                step = -1 if self.x > moveto_x else 1
                for i in range(self.x + step, moveto_x, step):
                    if arr[i][self.y] != 0:
                        if overflag:
                            return False
                        else:
                            overflag = True
    
    
                if overflag and arr[moveto_x][moveto_y] == 0:
                    return False
                if not overflag and arr[moveto_x][self.y] != 0:
                    return False
                return True
        def getScoreWeight(self, listpieces):
            score = 6
            return score
    
    
    class Pawns(Pieces):
        def __init__(self, player, x, y):
            self.player = player
            super().__init__(player,  x, y)
        def getImagekey(self):
            if self.player == constants.player1Color:
                return "r_pawn"
            else:
                return "b_pawn"
    
    
        def canmove(self, arr, moveto_x, moveto_y):
            if self.x == moveto_x and self.y == moveto_y:
                return False
            if arr[moveto_x][moveto_y] == self.player:
                return False
            move_x = moveto_x - self.x
            move_y = moveto_y - self.y
    
    
            if self.player == constants.player1Color:
                if self.y > 4  and move_x != 0 :
                    return  False
                if move_y > 0:
                    return  False
            elif self.player == constants.player2Color:
                if self.y <= 4  and move_x != 0 :
                    return  False
                if move_y < 0:
                    return False
    
    
            if abs(move_x) + abs(move_y) == 1:
                return True
        def getScoreWeight(self, listpieces):
            score = 2
            return score
    
    
    def listPiecestoArr(piecesList):
        arr = [[0 for i in range(10)] for j in range(9)]
        for i in range(0, 9):
            for j in range(0, 10):
                if len(list(filter(lambda cm: cm.x == i and cm.y == j and cm.player == constants.player1Color,
                                   piecesList))):
                    arr[i][j] = constants.player1Color
                elif len(list(filter(lambda cm: cm.x == i and cm.y == j and cm.player == constants.player2Color,
                                     piecesList))):
                    arr[i][j] = constants.player2Color
    
    
        return arr
    

    computer.py 电脑走法计算

    import Xiangqi.constants as constants
    #import time
    from Xiangqi.pieces import listPiecestoArr
    
    
    def getPlayInfo(listpieces):
        pieces = movedeep(listpieces ,1 ,constants.player2Color)
        return [pieces[0].x,pieces[0].y, pieces[1], pieces[2]]
    
    
    def movedeep(listpieces, deepstep, player):
        arr = listPiecestoArr(listpieces)
        listMoveEnabel = []
        for i in range(0, 9):
            for j in range(0, 10):
                for item in listpieces:
                    if item.player == player and item.canmove(arr, i, j):
                        #标记是否有子被吃 如果被吃 在下次循环时需要补会
                        piecesremove = None
                        for itembefore in listpieces:
                            if itembefore.x == i and itembefore.y == j:
                                piecesremove= itembefore
                                break
                        if piecesremove != None:
                            listpieces.remove(piecesremove)
    
    
                        #记录移动之前的位置
                        move_x = item.x
                        move_y = item.y
                        item.x = i
                        item.y = j
    
    
                        #print(str(move_x) + "," + str(move_y) + "," + str(item.x) + "  ,  " + str(item.y))
                        scoreplayer1 = 0
                        scoreplayer2 = 0
                        for itemafter in listpieces:
                            if itemafter.player == constants.player1Color:
                                scoreplayer1 += itemafter.getScoreWeight(listpieces)
                            elif  itemafter.player == constants.player2Color:
                                scoreplayer2 += itemafter.getScoreWeight(listpieces)
    
    
                        #print("得分:"+item.imagskey +", "+str(len(moveAfterListpieces))+","+str(i)+","+str(j)+"," +str(scoreplayer1) +"  ,  "+ str(scoreplayer2) )
                        #print(str(deepstep))
                        #如果得子 判断对面是否可以杀过来,如果又被杀,而且子力评分低,则不干
                        arrkill = listPiecestoArr(listpieces)
    
    
                        if scoreplayer2 > scoreplayer1 :
                            for itemkill in listpieces:
                                if itemkill.player == constants.player1Color and itemkill.canmove(arrkill, i, j):
                                    scoreplayer2=scoreplayer1
    
    
                        if deepstep > 0 :
                            nextplayer = constants.player1Color if player == constants.player2Color else constants.player2Color
                            nextpiecesbest= movedeep(listpieces, deepstep -1, nextplayer)
                            listMoveEnabel.append([item, i, j, nextpiecesbest[3], nextpiecesbest[4], nextpiecesbest[5]])
                        else:
                            #print(str(len(listpieces)))
                            #print("得分:" + item.imagskey + ", " + str(len(listpieces)) + "," + str(move_x) + "," + str(move_y) + "," + str(i) + "  ,  " + str(j))
                            if player == constants.player2Color:
                                listMoveEnabel.append([item, i, j, scoreplayer1, scoreplayer2, scoreplayer1 - scoreplayer2])
                            else:
                                listMoveEnabel.append([item, i, j, scoreplayer1, scoreplayer2, scoreplayer2 - scoreplayer1])
                        #print("得分:"+str(scoreplayer1))
                        item.x = move_x
                        item.y = move_y
                        if piecesremove != None:
                            listpieces.append(piecesremove)
    
    
        list_scorepalyer1 = sorted(listMoveEnabel, key=lambda tm: tm[5], reverse=True)
        piecesbest = list_scorepalyer1[0]
        if deepstep ==1 :
            print(list_scorepalyer1)
        return piecesbest
    

    button.py 设置按钮

    
    import pygame
    class Button():
        def __init__(self, screen, msg, left,top):  # msg为要在按钮中显示的文本
            """初始化按钮的属性"""
            self.screen = screen
            self.screen_rect = screen.get_rect()
    
    
            self.width, self.height = 150, 50  # 这种赋值方式很不错
            self.button_color = (72, 61, 139)  # 设置按钮的rect对象颜色为深蓝
            self.text_color = (255, 255, 255)  # 设置文本的颜色为白色
            pygame.font.init()
            self.font = pygame.font.SysFont('kaiti', 20)  # 设置文本为默认字体,字号为40
    
    
            self.rect = pygame.Rect(0, 0, self.width, self.height)
            #self.rect.center = self.screen_rect.center  # 创建按钮的rect对象,并使其居中
            self.left = left
            self.top = top
    
    
            self.deal_msg(msg)  # 渲染图像
    
    
        def deal_msg(self, msg):
            """将msg渲染为图像,并将其在按钮上居中"""
            self.msg_img = self.font.render(msg, True, self.text_color, self.button_color)  # render将存储在msg的文本转换为图像
            self.msg_img_rect = self.msg_img.get_rect()  # 根据文本图像创建一个rect
            self.msg_img_rect.center = self.rect.center  # 将该rect的center属性设置为按钮的center属性
    
    
        def draw_button(self):
            #self.screen.fill(self.button_color, self.rect)  # 填充颜色
            self.screen.blit(self.msg_img, (self.left,self.top))  # 将该图像绘制到屏幕
    
    
        def is_click(self):
            point_x, point_y = pygame.mouse.get_pos()
            x = self.left
            y = self.top
            w, h = self.msg_img.get_size()
    
    
            in_x = x < point_x < x + w
            in_y = y < point_y < y + h
            return in_x and in_y
    

    更多Python源代码,请关注公众号:Python代码大全,
    在这里插入图片描述

    展开全文
  • python简单实现-中国象棋

    热门讨论 2014-12-11 21:15:44
    用pygame简单实现的一个中国象棋代码
  • 如何用Python开发象棋游戏

    千次阅读 2020-06-12 17:04:01
    如何用Python开发象棋游戏,源代码版本 人生苦短,我用Python! hello 大家好!我是Mark,一个姓马名克的中国人。 最近,我在CSDN当中看到了这一篇文章: 传送门 他详细地讲解了如何用Python开发象棋游戏,...

    如何用Python开发象棋小游戏,源代码版本

    人生苦短,我用Python!

    hello 大家好!我是Mark,一个姓马名克的中国人。
    最近,我在CSDN当中看到了这一篇文章:
    传送门
    他详细地讲解了如何用Python开发象棋小游戏,于是,我在这里贴出源代码和资源供大家学习交流。
    上代码!

    import pygame
    import pygame.font
    import sys
    import traceback
    import copy
    from math import sqrt
    from pygame.locals import *
     
     
    pygame.font.init()
    pygame.init()
     
    #用于控制顺序
    order = True
    #用于结束游戏后阻止落子
    working = True
    #用来存储棋子信息,主要用于悔棋
    backups = []
     
    #定义棋子半径
    r = 40
    #一格代表的像素
    #直接安格子存放,打印时计算像素
    i = 90
     
    #绘制棋盘
    def Draw_a_chessboard(screen):
        #填充背景色
        screen.fill((233,204,138))
        #画外框
        outer_frame_color = (60,20,0)
        pygame.draw.rect(screen,outer_frame_color,[80,80,830,740],5)
        #行
        inner_frame_color = (0,0,0)
        for i in range(1,10):
            pygame.draw.line(screen, inner_frame_color, (90, 90*i), (900, 90*i)) 
        #列
        for i in range(1,11):
            pygame.draw.line(screen,inner_frame_color, (90*i, 90), (90*i, 810))
        #‘将’
        jiang_rote_color = (0,0,0)
        pygame.draw.lines(screen, jiang_rote_color, True,[(90, 360),(270, 360),(270,540),(90,540)],3)
        pygame.draw.lines(screen, jiang_rote_color, True,[(720, 360),(900, 360),(900,540),(720,540)],3)
        #‘士’路线
        shi_rote_color = (0,0,0)
        pygame.draw.line(screen, shi_rote_color, (90, 360), (270, 540),3)
        pygame.draw.line(screen, shi_rote_color, (90, 540), (270, 360),3) 
        pygame.draw.line(screen, shi_rote_color, (720, 360), (900, 540),3)
        pygame.draw.line(screen, shi_rote_color, (720, 540), (900, 360),3)
        #‘象’路线
        xiang_rote_color = (0,0,0)
        pygame.draw.lines(screen, xiang_rote_color, True,[(270, 450),(90, 270),(270,90),(450,270)])
        pygame.draw.lines(screen, xiang_rote_color, True,[(270, 450),(90, 630),(270,810),(450,630)])
        pygame.draw.lines(screen, xiang_rote_color, True,[(720, 450),(900, 270),(720,90),(540,270)])
        pygame.draw.lines(screen, xiang_rote_color, True,[(720, 450),(900, 630),(720,810),(540,630)])
        #‘兵’,用抗锯齿连续线段
        bing_rote_color = (255,0,0)
        for j in range(0,2):
            for k in range(0,4):
                pygame.draw.aalines(screen, bing_rote_color, False,[(330+270*j, 260+180*k),(350+270*j, 260+180*k),(350+270*j,240+180*k)],3)
                pygame.draw.aalines(screen, bing_rote_color, False,[(390+270*j, 260+180*k),(370+270*j, 260+180*k),(370+270*j,240+180*k)],3)
                pygame.draw.aalines(screen, bing_rote_color, False,[(330+270*j, 100+180*k),(350+270*j, 100+180*k),(350+270*j,120+180*k)],3)
                pygame.draw.aalines(screen, bing_rote_color, False,[(390+270*j, 100+180*k),(370+270*j, 100+180*k),(370+270*j,120+180*k)],3)
        #‘炮’
        pao_rote_color = (255,0,0)
        for m in range(0,2):
            for n in range(0,2):
                pygame.draw.aalines(screen, pao_rote_color, False,[(240+450*m, 170+540*n),(260+450*m, 170+540*n),(260+450*m,150+540*n)],3)
                pygame.draw.aalines(screen, pao_rote_color, False,[(300+450*m, 170+540*n),(280+450*m, 170+540*n),(280+450*m,150+540*n)],3)
                pygame.draw.aalines(screen, pao_rote_color, False,[(240+450*m, 190+540*n),(260+450*m, 190+540*n),(260+450*m,210+540*n)],3)
                pygame.draw.aalines(screen, pao_rote_color, False,[(300+450*m, 190+540*n),(280+450*m, 190+540*n),(280+450*m,210+540*n)],3)
     
        #绘制‘楚河汉界’
        pygame.draw.rect(screen,[233,204,138],[451,91,89,719])
        chuhehanjie = pygame.image.load("楚河汉界.png").convert_alpha()
        screen.blit(chuhehanjie,(451,91))
        #画‘悔棋’,‘重新开始’和‘退出’按钮
        button_color = (163,80,21)
        pygame.draw.rect(screen,button_color,[980,300,200,100],5)
        pygame.draw.rect(screen,button_color,[980,500,200,100],5)
        pygame.draw.rect(screen,button_color,[980,700,200,100],5)
     
        s_font = pygame.font.Font('字体管家小南瓜.ttf',45)
     
        text1 = s_font.render("悔    棋",True,button_color)
        text2 = s_font.render("重新开始",True,button_color)
        text3 = s_font.render("退出游戏",True,button_color)
        screen.blit(text1,(1000,320))
        screen.blit(text2,(980,520))
        screen.blit(text3,(980,720))
     
    #绘制棋子
    def Draw_a_chessman(screen,color,qizi,x,y):
        red_color = (255,0,0)
        black_color = (0,0,0)
     
        pygame.draw.circle(screen,(0,0,0),(x,y),46)
        pygame.draw.circle(screen,(247,157,12),(x,y),45)
        pygame.draw.circle(screen,(0,0,0),(x,y),40,3)
        pygame.draw.circle(screen,(181,131,16),(x,y),35)
     
        q_font = pygame.font.Font('字体管家小南瓜.ttf',60)
     
        if color == 'red':
            q_color = red_color
        elif color == 'black':
            q_color = black_color
        screen.blit(q_font.render(qizi[0],True,q_color),(x-30,y-40))
     
    #绘制带有棋盘的棋子
    def Draw_a_chessboard_with_chessman(screen):  
        Draw_a_chessboard(screen)
        for each_qizi in hongqi.keys():
            Draw_a_chessman(screen,hongqi[each_qizi]['color'],each_qizi,hongqi[each_qizi]['now_weizhi'][0],hongqi[each_qizi]['now_weizhi'][1])
        for each_qizi in heiqi.keys():
            Draw_a_chessman(screen,heiqi[each_qizi]['color'],each_qizi,heiqi[each_qizi]['now_weizhi'][0],heiqi[each_qizi]['now_weizhi'][1])
     
    #通过位置寻找棋子
    def find(x,y):
        for key in hongqi.keys():
              if sqrt((hongqi[key]['now_weizhi'][0] - x)**2+(hongqi[key]['now_weizhi'][1]-y)**2) < r:
                  return [key,hongqi[key],'red']
        for key in heiqi.keys():
              if sqrt((heiqi[key]['now_weizhi'][0] - x)**2+(heiqi[key]['now_weizhi'][1]-y)**2) < r:
                  return [key,heiqi[key],'black']
    #判断该位置有无棋子
    def weizhi_panduan(x,y):
        for key in hongqi.keys():
            if [x,y] == hongqi[key]['now_weizhi']:
                return True
        for key in heiqi.keys():
            if [x,y]==heiqi[key]['now_weizhi']:
                return True
        return False
     
    #棋子移动的规则
    def move_rules(qizi,chess_color,x,y):
        can_move =[]
        
        if qizi == '将':
            can_move += [[x+i,y],[x-i,y],[x,y+i],[x,y-i]]
        elif qizi[0] == '士':
            can_move += [[x+i,y+i],[x-i,y-i],[x-i,y+i],[x+i,y-i]]
        elif qizi[0] == '相':
            can_move += [[x+2*i,y+2*i],[x-2*i,y-2*i],[x-2*i,y+2*i],[x+2*i,y-2*i]]
        elif qizi[0] == '马':
            can_move += [[x+i,y+2*i],[x+2*i,y+i],[x-i,y-2*i],[x-2*i,y-i],[x+i,y-2*i],[x+2*i,y-i],[x-i,y+2*i],[x-2*i,y+i]]
        elif qizi[0] == '车':
            for m in range(10):
                can_move.append([x,y+m*i])
                can_move.append([x,y-m*i])
                can_move.append([x+m*i,y])
                can_move.append([x-m*i,y])
        elif qizi[0] == '炮':
            for m in range(10):
                can_move.append([x,y+m*i])
                can_move.append([x,y-m*i])
                can_move.append([x+m*i,y])
                can_move.append([x-m*i,y])
        elif qizi[0] == '兵':
            if chess_color == 'red':
                if i<=x<=5*i: 
                    can_move += [[x+i,y]]
                else:
                    can_move +=[[x+i,y],[x,y-i],[x,y+i]]
            elif chess_color == 'black':
                if 6*i<=x<=10*i:
                    can_move += [[x-i,y]]
                else:
                    can_move += [[x-i,y],[x,y-i],[x,y+i]]
     
        return can_move                
     
    #判断棋子是否可以走该位置
    #(棋子,棋子现在所处位置,判断棋子是否可走的位置)
    def weizhi_able(qizi,chess_color,x,y,d_x,d_y):
        can_move = move_rules(qizi,chess_color,x,y)
        if [d_x,d_y] in can_move:
            #如果第二次点击的位置为自身位置,以不可走处理
            if [d_x,d_y] == [x,y]:
                return False
            elif qizi == '将' or qizi[0] == '士':
                if ((i<=d_x<=3*i and 4*i<=d_y<=6*i) or (8*i<=d_x<=10*i and 4*i<=d_y<=6*i)):
                    return True
            elif qizi[0] == '相':
                #删除相憋腿的情况
                if (chess_color == 'red' and i<=d_x<=5*i) or (chess_color == 'black' and 6*i<=d_x<=10*i):
                    if weizhi_panduan(x-i,y-i) and [d_x,d_y] == [x-2*i,y-2*i]:
                        return False
                    elif weizhi_panduan(x+i,y-i) and [d_x,d_y] == [x+2*i,y-2*i]:
                        return False
                    elif weizhi_panduan(x+i,y+i) and [d_x,d_y] == [x+2*i,y+2*i]:
                        return False
                    elif weizhi_panduan(x-i,y+i) and [d_x,d_y] == [x-2*i,y+2*i]:
                        return False
                    else:
                        return True
            elif qizi[0] == '马':
                #删除马憋腿的情况
                if weizhi_panduan(x,y-i) and ([d_x,d_y] == [x-i,y-2*i] or [d_x,d_y] == [x+i,y-2*i]):
                    return False
                elif weizhi_panduan(x+i,y) and ([d_x,d_y] == [x+2*i,y-i] or [d_x,d_y] == [x+2*i,y+i]):
                    return False
                elif weizhi_panduan(x,y+i) and ([d_x,d_y] == [x-i,y+2*i] or [d_x,d_y] == [x+i,y+2*i]):
                    return False
                elif weizhi_panduan(x-i,y) and ([d_x,d_y] == [x-2*i,y-i] or [d_x,d_y] == [x-2*i,y+i]):
                    return False
                else:
                    return True
            elif qizi[0] == '兵':
                return True
            elif qizi[0] == '车':
                count = 0
                if d_y == y:
                    weizhicha = abs(d_x - x)
                    for each_cha in range(90,weizhicha,90):
                        if weizhi_panduan(min(d_x,x)+each_cha,y):
                            count += 1
                    if count == 0 and weizhi_panduan(d_x,d_y)and find(d_x,d_y)[2]!=chess_color:
                        return True
                    elif count == 0 and not weizhi_panduan(d_x,d_y):
                        return True
                    else:
                        return False
                elif d_x == x:
                    weizhicha = abs(d_y - y)
                    for each_cha in range(90,weizhicha,90):
                        if weizhi_panduan(x,min(d_y,y)+each_cha):
                            count += 1
                    if count == 0 and weizhi_panduan(d_x,d_y)and find(d_x,d_y)[2]!=chess_color:
                        return True
                    elif count == 0 and not weizhi_panduan(d_x,d_y):
                        return True
                    else:
                        return False
            elif qizi[0] == '炮':
                #记录原来位置与所走位置之间的棋子数
                count = 0
                #同一行
                if d_y == y:
                    weizhicha = abs(d_x - x)
                    for each_cha in range(90,weizhicha,90):
                        if weizhi_panduan(min(d_x,x)+each_cha,y):
                            count += 1
                    if count == 1 and weizhi_panduan(d_x,d_y)and find(d_x,d_y)[2]!=chess_color:
                            return True
                    elif count == 0:
                        if weizhi_panduan(d_x,d_y):
                            return False
                        else:
                            return True
                    else:
                        return False
                #同一列
                elif d_x == x:
                    weizhicha = abs(d_y - y)
                    for each_cha in range(90,weizhicha,90):
                        if weizhi_panduan(x,min(d_y,y)+each_cha):
                            count += 1
                    if count == 1 and weizhi_panduan(d_x,d_y)and find(d_x,d_y)[2]!=chess_color:
                        return True
                    elif count == 0:
                        if weizhi_panduan(d_x,d_y):
                            return False
                        else:
                            return True
                    else:
                        return False
        else:
            return False
     
    #绘制提示器(类容,屏幕,字大小)
    def text(s,screen,x):
        #先把上一次的类容用一个矩形覆盖
        pygame.draw.rect(screen,(233,204,138),[980,100,1200,100])
        #定义字体跟大小
        s_font = pygame.font.Font('字体管家小南瓜.ttf',45)
        #定义类容,是否抗锯齿,颜色
        s_text=s_font.render(s,True,(255,0,0))
        #将字放在窗口指定位置
        screen.blit(s_text,(980,100))
        pygame.display.flip()
        
    def main():
        #将'hongqi','heiqi','running','order','backups,设置为可改
        global hongqi,heiqi,running,order,working,backups
     
        #棋子初始位置
        hongqi = {'将':{'color':'red','now_weizhi':[90,450]},'士1':{'color':'red','now_weizhi':[90,360]},'士2':{'color':'red','now_weizhi':[90,540]},'相1':{'color':'red','now_weizhi':[90,270]},
                  '相2':{'color':'red','now_weizhi':[90,630]},'马1':{'color':'red','now_weizhi':[90,180]},'马2':{'color':'red','now_weizhi':[90,720]},'车1':{'color':'red','now_weizhi':[90,90]},
                  '车2':{'color':'red','now_weizhi':[90,810]},'炮1':{'color':'red','now_weizhi':[270,180]},'炮2':{'color':'red','now_weizhi':[270,720]},'兵1':{'color':'red','now_weizhi':[360,90]},
                  '兵2':{'color':'red','now_weizhi':[360,270]},'兵3':{'color':'red','now_weizhi':[360,450]},'兵4':{'color':'red','now_weizhi':[360,630]},'兵5':{'color':'red','now_weizhi':[360,810]}
                 }
        heiqi = {'将':{'color':'black','now_weizhi':[900,450]},'士1':{'color':'black','now_weizhi':[900,360]},'士2':{'color':'black','now_weizhi':[900,540]},'相1':{'color':'black','now_weizhi':[900,270]},
                 '相2':{'color':'black','now_weizhi':[900,630]},'马1':{'color':'black','now_weizhi':[900,180]},'马2':{'color':'black','now_weizhi':[900,720]},'车1':{'color':'black','now_weizhi':[900,90]},
                 '车2':{'color':'black','now_weizhi':[900,810]},'炮1':{'color':'black','now_weizhi':[720,180]},'炮2':{'color':'black','now_weizhi':[720,720]},'兵1':{'color':'black','now_weizhi':[630,90]},
                 '兵2':{'color':'black','now_weizhi':[630,270]},'兵3':{'color':'black','now_weizhi':[630,450]},'兵4':{'color':'black','now_weizhi':[630,630]},'兵5':{'color':'black','now_weizhi':[630,810]}
                }
        #创建一个窗口
        screen = pygame.display.set_mode([1200,900])
        # 设置窗口标题
        pygame.display.set_caption("中国象棋")
        #定义两个存储棋子现在的状态
        backups1 = []
        backups2 = []
        #用于暂存所有棋子状态
        backup=copy.deepcopy([hongqi,heiqi])
        backups = []
        backups.append(backup)
        #鼠标第一次按下选择棋子
        running = True
     
        
         #在窗口画出棋盘以及按钮
        Draw_a_chessboard(screen)
        pygame.display.flip()
        clock = pygame.time.Clock()
     
        while True: 
            Draw_a_chessboard_with_chessman(screen)
            #只有working为真才能落子,主要用于游戏结束后防止再次落子
            if working:
                if order:
                    color = 'red'
                    text('红棋落子',screen,54)
                else:
                    color = 'black'
                    text('黑棋落子',screen,54)
            #监听所有事件
            for event in pygame.event.get():
                #点击x则关闭窗口
                if event.type ==pygame.QUIT:
                    pygame.quit()
                    sys.exit()
     
                #点击窗口里面类容则完成相应指令 
                elif event.type == MOUSEBUTTONDOWN:
                    if event.button == 1:
                        x,y=event.pos[0],event.pos[1]
                        if working:
                            #鼠标第一次按下选择棋子
                            if running:
                                x,y = event.pos[0],event.pos[1]
                                for key in hongqi.keys():
                                    if sqrt((hongqi[key]['now_weizhi'][0] - x)**2+(hongqi[key]['now_weizhi'][1]-y)**2) < r:
                                        backups1 = [key,hongqi[key]]
                                for key in heiqi.keys():
                                    if sqrt((heiqi[key]['now_weizhi'][0] - x)**2+(heiqi[key]['now_weizhi'][1]-y)**2) < r:
                                        backups2 = [key,heiqi[key]]
                                if backups1:
                                    #用于暂存棋子状态
                                    backups3 = copy.deepcopy(backups1)
                                    hongqi.pop(backups1[0])
                                    running = not running
                                elif backups2:
                                    #用于暂存棋子状态
                                    backups4 = copy.deepcopy(backups2)
                                    heiqi.pop(backups2[0])
                                    running = not running
                            #鼠标再次按下,落下棋子
                            else:
                                if r < event.pos[0] < 900+r and r <event.pos[1] < 810+r:
                                    x = (event.pos[0]+r)//90*90
                                    y = (event.pos[1]+r)//90*90
                                    if backups1 :#红棋
                                        #判断是否符合走棋规则
                                        if weizhi_able(backups1[0],backups1[1]['color'],backups1[1]['now_weizhi'][0],backups1[1]['now_weizhi'][1],x,y) and order:
                                            #判断所走位置是否有棋子
                                            if weizhi_panduan(x,y):
                                                #判断是否为敌方棋子
                                                if backups1[1]['color'] != find(x,y)[2]:
                                                    heiqi.pop(find(x,y)[0])
                                                    hongqi[backups1[0]] = backups1[1]
                                                    hongqi[backups1[0]]['now_weizhi'] = [x,y]
                                                    backup=copy.deepcopy([hongqi,heiqi])
                                                    backups.append(backup)
                                                    order = not order
                                                else:
                                                    hongqi[backups3[0]] = backups3[1]
                                            else:
                                                hongqi[backups1[0]] = backups1[1]
                                                hongqi[backups1[0]]['now_weizhi'] = [x,y]
                                                backup=copy.deepcopy([hongqi,heiqi])
                                                backups.append(backup)
                                                order = not order
                                        else:
                                            #若不符合走棋规则,返回原位置
                                            hongqi[backups3[0]] = backups3[1]
                                        backups1 = []
                                        running = not running
                                        if '将' not in heiqi.keys():
                                             Draw_a_chessboard_with_chessman(screen)
                                             text('红棋胜利!',screen,30)
                                             pygame.display.flip()
                                             working = False
                                    
     
                                    elif backups2:#黑棋
                                        if weizhi_able(backups2[0],backups2[1]['color'],backups2[1]['now_weizhi'][0],backups2[1]['now_weizhi'][1],x,y) and not order:
                                            #判断所走位置是否有棋子
                                            if weizhi_panduan(x,y):
                                                #判断是否为敌方棋子
                                                if backups2[1]['color'] != find(x,y)[2]:
                                                    hongqi.pop(find(x,y)[0])
                                                    heiqi[backups2[0]] = backups2[1]
                                                    heiqi[backups2[0]]['now_weizhi'] = [x,y]
                                                    backup=copy.deepcopy([hongqi,heiqi])
                                                    backups.append(backup)
                                                    order = not order
                                                else:
                                                    heiqi[backups4[0]] = backups4[1]
                                            else:
                                                heiqi[backups2[0]] = backups2[1]
                                                heiqi[backups2[0]]['now_weizhi'] = [x,y]
                                                backup=copy.deepcopy([hongqi,heiqi])
                                                backups.append(backup)
                                                order = not order
                                        else:
                                            heiqi[backups4[0]] = backups4[1]
                                        backups2=[]
                                        running=not running
                                        if '将' not in hongqi.keys():
                                            Draw_a_chessboard_with_chessman(screen)
                                            text('黑棋胜利!',screen,30)
                                            pygame.display.flip()
                                            working = False
                                else:
                                    if backups1 :
                                        hongqi[backups1[0]] = backups3[1]
                                        backups1 = []
                                        running = not running
                                    elif backups2:
                                        heiqi[backups2[0]] = backups4[1]
                                        backups2=[]
                                        running=not running
                        #如果点击‘重新开始’
                        if 900<x<1180 and 500<y<600:
                            #取消阻止
                            working=True
           
                            #重新开始
                            main()
                        
                            #点击‘退出游戏’,退出游戏
                        elif 900<x<1180 and 700<y<8000:
                            #播放音效
                            pygame.quit()
                            sys.exit()                 
                        elif 900<x<1080 and 300<y<400 and len(backups)>1:
                            #删除maps里最后一个元素
                            del backups[len(backups)-1]
                            hongqi=copy.deepcopy(backups[-1][0])
                            heiqi=copy.deepcopy(backups[-1][1])
                            #切换顺序
                            order = not order
                            #将map显示出来
                            Draw_a_chessboard_with_chessman(screen)
                            #悔棋完成,阻止再次悔棋
                            x,y=0,0
      
     
    if __name__ == "__main__":
        try:
            main()
        except SystemExit:
            pass
        except:
            traceback.print_exc()
            pygame.quit()
            input()
    
    

    资源文件传送门:
    CSDN下载:https://download.csdn.net/download/zhugezuoyuan/12517251
    蓝奏云:https://wws.lanzous.com/isymOdkxt3i
    下载解压之后会有一个字体文件不需要安装exe文件可以直接运行,源代码就是源码.py

    好了,今天的免费福利就到这里,我们下次再见!

    展开全文
  • Chess:用Python实现的国际象棋游戏
  • Chess:Python国际象棋
  • 先来个温馨提示:不会象棋,或者不是很懂象棋规则的朋友,可以先去下载个象棋游戏,了解一下规则,毕竟后面这些规则都是我们写的啦,但也不能乱写呀,嘎嘎嘎~~~切入正题,在开始之前呢,我们要先缕清思路,下面...

    先来个温馨提示:不会象棋,或者不是很懂象棋规则的朋友,可以先去下载个象棋小游戏,了解一下规则,毕竟后面这些规则都是我们写的啦,但也不能乱写呀,嘎嘎嘎~~~

    切入正题,在开始之前呢,我们要先缕清思路,下面我们一起来分析一下:

    首先,大家要清楚,我们的首要目标是把程序编写出来,至于后期的美化工作,每个人有自己的爱好,可以说,掌握方法之后,你想美成哪样,就美成哪样,只有你想不到,没有做不到。。。

    aa171de71159

    image

    我们的首要目标,就是做成如上图所示的模样。

    1、绘制棋盘,要注意,绘制过程中,全程用像素计数,不要想着用日常尺寸,不好用,还有选择合适的像素大小,因为后面要计算落子位置什么的,如果你选的像素大小很难算,那无非是给后面增加工作量。

    2、绘制棋子,选择合适的像素大小的棋子,当然,不能重位。

    3、绘制带棋子的棋盘(为什么绘制了棋盘和棋子,还要绘制带棋子的棋盘呢?因为后面每次下棋之后都要绘制一次带棋子的棋盘,如果还是想不明白,那就先放着,到后面自然就明白了)

    4、走棋规则:

    马:日字;相:田字;兵:过河前只能直走,过河后只能前,左,右;车:可以任意横走竖走,但所走位置和原位置中间不可有棋子,炮:和车的走法相似,但吃子时要隔一个棋子;士,将:不可出田字格。

    注意:不要忘了"马’和"相’会出现鳖腿的情况!

    5、吃子规则:这个可以在走棋规则的基础上附加,想要吃子,肯定要先符合走棋规则的嘛。

    6、走棋(走棋前我们是不是得判断走的位置有没有棋子呢,如果有棋子,是不是得判断是否符合吃子规则呢)

    7、判断是否赢棋,直接判断对方的老将在不在,对吧,对方老将被吃,本方赢。

    8、按键:其实这个应该在你画棋盘之前就想好的,因为你画棋盘时要给按键留出相应的位置呀,对吧,这里要注意的是,如何判断按键按下呢,就像前面所说的,用像素大小,你要判断的是你鼠标点击的位置,是否在你所定义的按键像素里面,如果你的按键要两次转换,自然,定义一个变量,判断它是’True" 或者’False"就OK了嘛。

    做到这里,其本上可以说已经完成了,美化,音效,那就看自己的审美观和乐感了,对吧,但是,也不可藐视,毕竟,作为一个游戏,没有好的界面和音效,是没有人愿意玩的,所以,还是安安心心做完吧~~~~

    9、美化:事实上,就是用一些唯美的照片,替换掉编程中编写的一些不美观的地方,比如你想把棋子变成带有立体感的棋子等等,这个后面详细解说。

    10、音效:背景音乐、按键音效、落子音效,吃子音效、赢棋音效

    到这儿我们思路就算屡清楚了,知道自己该干嘛了,下一篇博客,我们就开始实现第一部分——绘制棋盘

    文章中有任何不懂的问题,欢迎大家骚扰,博主很愿意和大家共同进步哟,整理不易,喜欢的话就打赏一下吧~~~

    展开全文
  • Sunfish是一个简单但强大的国际象棋引擎,用111行代码Python编写
  • 国际象棋游戏有自己的规则,需要两个人将棋子落在棋盘上。 棋子落在棋盘上事件,在计算机看来,是一段程序,而这些程序又由一系列的指令组成。关心编程语言的使用趋势的人都知道,最近几年,国内最火的两种语言非 ...
  • 不用神经网络强化学习,只用...我们的中国象棋使用python实现,总共2000+行代码,分为走法计算、评估函数与搜索和UI三部分,并采用历史启发算法进行优化,有着不错的效果。可以实现正常的人机对战,有着普通人的棋力。

    摘要

    不用神经网络强化学习,只用搜索实现的下象棋!我们的中国象棋使用python实现,总共2000+行代码,分为走法计算、评估函数与搜索和UI三部分,并采用历史启发算法进行优化,有着不错的效果。可以实现正常的人机对战,有着普通人的棋力。

    源代码下载

    为了方便大家下载,这里提供了两种不同下载方式。
    github完整源代码下载
    百度云完整源代码下载。
    链接:https://pan.baidu.com/s/1OEoUUVGbI81LsaQTdSmy2Q
    提取码:nmd0

    效果

    搜索深度:

    我们的算法在搜索深度为4的时候可以达到立刻出结果的效果,经过优化后平均搜索步数为10000左右,在搜索深度为6的时候平均搜索步数为90万左右,计算较为缓慢。深度不能太深的原因是,这个搜索算法本身就是指数级别复杂度,就算进行优化,也只能减小常数,而且评估函数复杂,所以使用这种方法深度不能太深,不然只能牺牲精度。

    棋力效果:

    我们设计的评估函数较为详细,考虑方面周全,基本具备一个正常人的棋力。

    具体效果如下(6步时):

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Lq15oslj-1590327386300)(C:\Users\46002\AppData\Roaming\Typora\typora-user-images\image-20200524210133242.png)]
    更改搜索深度方式如下:
    指定停止位置:
    在这里插入图片描述
    最大搜索深度
    在这里插入图片描述

    走法计算

    算法流程图如下:
    在这里插入图片描述
    核心代码如下:

        def generate_move(self, who):  # 返回所有可行的走法, 一个step类型的list
            res_list = []
            for x in range(9):
                for y in range(10):
                    if self.board[x][y].chess_type != 0:
                        if self.board[x][y].belong != who:
                            continue
                        list2 = self.get_chess_move(x, y, who)  # 返回每个棋子的走法
                        # print(list2)
                        res_list = res_list + list2
            return res_list
    

    评估函数与搜索

    流程图如下:

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8oAZzSB6-1590327386295)(C:\Users\46002\AppData\Roaming\Typora\typora-user-images\image-20200524173612327.png)]

    Alpha-beta搜索算法介绍

    Alpha-beta搜索使用一颗n叉树来表示整个下棋的流程。电脑在选择走棋的时候,会尽可能选择对自己最有利的走法。可以通过尝试每一种走法,然后对每种局面进行比较,最终选出能够对自己最有利的走法。

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KfSvCUAu-1590327386296)(file:///C:\Users\46002\AppData\Local\Temp\ksohtml25888\wps1.jpg)]

    在使用alpha-beta搜索算法需要遍历整个n叉树,我们可以看出搜索每迭代一层,复杂度就指数级增长。通常中国象棋合理的招数多达50种,所以每增加一层复杂度增加50倍。在搜索六步时的复杂度接近200亿,在搜索10步的时候复杂度超过几千万亿。所以搜索复杂度很高,效率较低。

    象棋是博弈的过程,我们需要让自己的局面最优,让对手的局面最劣。Alpha-beta的算法就是在搜索的过程中利用已知信息进行剪枝的实现方法。它的实现基于一种想法:如果已经有选择比当下选择更好,那么只要能证明当下选择劣于某个更好选择,就可以进行剪枝,不需要对这种选择继续进行考虑。

    Alpha-beta算法在搜索时,始终记录节点的α值和β值。其中α值是该节点的子节点能到达的最大值,β值是该节点的子节点能够到达的最小值。通过比较不同节点之间的α、β值来进行剪枝。例如某个子节点的得分<=α时,可以直接剪枝;某个子节点得分>=β时,也可以进行剪枝,因为对手可以通过之前的某种策略避免这种情况的发生。

    算法核心实现如下

        def alpha_beta(self, depth, alpha, beta):  # alpha-beta剪枝,alpha是大可能下界,beta是最小可能上界
            who = (self.max_depth - depth) % 2  # 那个玩家
            if self.is_game_over(who):  # 判断是否游戏结束,如果结束了就不用搜了
                return cc.min_val
            if depth == 1:  # 搜到指定深度了,也不用搜了
                # print(self.evaluate(who))
                return self.evaluate(who)
            move_list = self.board.generate_move(who)  # 返回所有能走的方法
            # 利用历史表0
            for i in range(len(move_list)):
                move_list[i].score = self.history_table.get_history_score(who, move_list[i])
            move_list.sort()  # 为了让更容易剪枝利用历史表得分进行排序
            best_step = move_list[0]
            score_list = []
            for step in move_list:
                temp = self.move_to(step)
                score = -self.alpha_beta(depth - 1, -beta, -alpha)  # 因为是一层选最大一层选最小,所以利用取负号来实现
                score_list.append(score)
                self.undo_move(step, temp)
                if score > alpha:
                    alpha = score
                    if depth == self.max_depth:
                        self.best_move = step
                    best_step = step
                if alpha >= beta:
                    best_step = step
                    break
            # print(score_list)
            # 更新历史表
            if best_step.from_x != -1:
                self.history_table.add_history_score(who, best_step, depth)
            return alpha
    

    评价函数详解

    如一种所说,在搜索过程中需要记录节点的α值和β值。所以需要在每个叶子节点对当前局面进行评价来表示局面的优劣。评价函数的合理性将直接影响整个程序的性能。好的评价函数能够考虑到场面上的各种配合等等,从而对局面做出最正确的判断,所以在实现评价函数的时候需要考虑种种因素:

    1. 棋子的固定子力值。每种类型的棋子都有各自本身的子力价值。一般而言,子力值越大越重要,哪一方的固定子力值和大,则该方占优;否则处于劣势。具体每个棋子的子力值多少,不同设计者的经验不同,给出的具体值不同,所产生的效果也不同。
    1000025025030050030080
    1. 棋子的位置价值。中国象棋局势不仅仅取决于子力大小,更与棋子位置联系巨大。棋子在不同位置上应该给予不同的评价。例如卒在初始位置时,作用较小,位置值较小;而当卒进入对方九宫格之后对对方威胁极大,位置值较大。再例如,当头炮的威胁值较大,而在其他路的时候威胁则稍微小一些。因此也需要根据设计者的经验,对不同棋子不同位置的价值给予不同的评价。

    2. 棋子灵活度评估值。棋子威力的发挥取决于其灵活度。灵活度高的棋子,例如车,可以在战场上快速发挥作用,评价值较高。而灵活度较差的棋子则评分较低。

    061261115
    1. 棋子威胁、保护评估值。每个棋子可能处于对方威胁下,也可能处于己放棋子保护之中。这将直接影响到这颗棋子的安全系数,进而影响战局。因此需要考虑被威胁和保护的棋子。当棋子处于威胁之中时,应当降低评价值;当棋子处于保护之中时,应当增加评价值。

      我们分了不同数量保护的情况,来进行局面关系评分,核心代码如下:

              for x in range(9):
                  for y in range(10):
                      num_attacked = relation_list[x][y].num_attacked
                      num_guarded = relation_list[x][y].num_guarded
                      now_chess = self.board.board[x][y]
                      type = now_chess.chess_type
                      now = now_chess.belong
                      unit_val = cc.base_val[now_chess.chess_type] >> 3
                      sum_attack = 0  # 被攻击总子力
                      sum_guard = 0
                      min_attack = 999  # 最小的攻击者
                      max_attack = 0  # 最大的攻击者
                      max_guard = 0
                      flag = 999  # 有没有比这个子的子力小的
                      if type == cc.kong:
                          continue
                      # 统计攻击方的子力
                      for i in range(num_attacked):
                          temp = cc.base_val[relation_list[x][y].attacked[i]]
                          flag = min(flag, min(temp, cc.base_val[type]))
                          min_attack = min(min_attack, temp)
                          max_attack = max(max_attack, temp)
                          sum_attack += temp
                      # 统计防守方的子力
                      for i in range(num_guarded):
                          temp = cc.base_val[relation_list[x][y].guarded[i]]
                          max_guard = max(max_guard, temp)
                          sum_guard += temp
                      if num_attacked == 0:
                          relation_val[now] += 5 * relation_list[x][y].num_guarded
                      else:
                          muti_val = 5 if who != now else 1
                          if num_guarded == 0:  # 如果没有保护
                              relation_val[now] -= muti_val * unit_val
                          else:  # 如果有保护
                              if flag != 999:  # 存在攻击者子力小于被攻击者子力,对方将愿意换子
                                  relation_val[now] -= muti_val * unit_val
                                  relation_val[1 - now] -= muti_val * (flag >> 3)
                              # 如果是二换一, 并且最小子力小于被攻击者子力与保护者子力之和, 则对方可能以一子换两子
                              elif num_guarded == 1 and num_attacked > 1 and min_attack < cc.base_val[type] + sum_guard:
                                  relation_val[now] -= muti_val * unit_val
                                  relation_val[now] -= muti_val * (sum_guard >> 3)
                                  relation_val[1 - now] -= muti_val * (flag >> 3)
                              # 如果是三换二并且攻击者子力较小的二者之和小于被攻击者子力与保护者子力之和,则对方可能以两子换三子
                              elif num_guarded == 2 and num_attacked == 3 and sum_attack - max_attack < cc.base_val[type] + sum_guard:
                                  relation_val[now] -= muti_val * unit_val
                                  relation_val[now] -= muti_val * (sum_guard >> 3)
                                  relation_val[1 - now] -= muti_val * ((sum_attack - max_attack) >> 3)
                              # 如果是n换n,攻击方与保护方数量相同并且攻击者子力小于被攻击者子力与保护者子力之和再减去保护者中最大子力,则对方可能以n子换n子
                              elif num_guarded == num_attacked and sum_attack < cc.base_val[now_chess.chess_type] + sum_guard - max_guard:
                                  relation_val[now] -= muti_val * unit_val
                                  relation_val[now] -= muti_val * ((sum_guard - max_guard) >> 3)
                                  relation_val[1 - now] -= sum_attack >> 3
      
    2. 将帅安全评估值。将帅的安全整局游戏的关键。需要从将的位置以及和其他棋子的位置关系中体现出来;例如当头炮、窝心马对将帅的威胁较大,体现在这些棋子的位置价值中。

      pos_val = [
          [  # 空
              0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
              0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
              0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
              0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
              0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
              0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
              0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
              0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
              0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
          [  # 将
              0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
              0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
              0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
              1, -8, -9, 0, 0, 0, 0, 0, 0, 0,
              5, -8, -9, 0, 0, 0, 0, 0, 0, 0,
              1, -8, -9, 0, 0, 0, 0, 0, 0, 0,
              0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
              0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
              0, 0, 0, 0, 0, 0, 0, 0, 0, 0
          ],
          [  # 车
              -6, 5, -2, 4, 8, 8, 6, 6, 6, 6,
              6, 8, 8, 9, 12, 11, 13, 8, 12, 8,
              4, 6, 4, 4, 12, 11, 13, 7, 9, 7,
              12, 12, 12, 12, 14, 14, 16, 14, 16, 13,
              0, 0, 12, 14, 15, 15, 16, 16, 33, 14,
              12, 12, 12, 12, 14, 14, 16, 14, 16, 13,
              4, 6, 4, 4, 12, 11, 13, 7, 9, 7,
              6, 8, 8, 9, 12, 11, 13, 8, 12, 8,
              -6, 5, -2, 4, 8, 8, 6, 6, 6, 6
          ],
          [  # 马
              0, -3, 5, 4, 2, 2, 5, 4, 2, 2,
              -3, 2, 4, 6, 10, 12, 20, 10, 8, 2,
              2, 4, 6, 10, 13, 11, 12, 11, 15, 2,
              0, 5, 7, 7, 14, 15, 19, 15, 9, 8,
              2, -10, 4, 10, 15, 16, 12, 11, 6, 2,
              0, 5, 7, 7, 14, 15, 19, 15, 9, 8,
              2, 4, 6, 10, 13, 11, 12, 11, 15, 2,
              -3, 2, 4, 6, 10, 12, 20, 10, 8, 2,
              0, -3, 5, 4, 2, 2, 5, 4, 2, 2
          ],
          [  # 炮
              0, 0, 1, 0, -1, 0, 0, 1, 2, 4,
              0, 1, 0, 0, 0, 0, 3, 1, 2, 4,
              1, 2, 4, 0, 3, 0, 3, 0, 0, 0,
              3, 2, 3, 0, 0, 0, 2, -5, -4, -5,
              3, 2, 5, 0, 4, 4, 4, -4, -7, -6,
              3, 2, 3, 0, 0, 0, 2, -5, -4, -5,
              1, 2, 4, 0, 3, 0, 3, 0, 0, 0,
              0, 1, 0, 0, 0, 0, 3, 1, 2, 4,
              0, 0, 1, 0, -1, 0, 0, 1, 2, 4
          ],
          [  # 相
              0, 0, -2, 0, 0, 0, 0, 0, 0, 0,
              0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
              0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
              0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
              0, 0, 3, 0, 0, 0, 0, 0, 0, 0,
              0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
              0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
              0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
              0, 0, -2, 0, 0, 0, 0, 0, 0, 0
          ],
          [  # 士
              0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
              0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
              0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
              0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
              0, 3, 0, 0, 0, 0, 0, 0, 0, 0,
              0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
              0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
              0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
              0, 0, 0, 0, 0, 0, 0, 0, 0, 0
          ],
          [  # 兵
              0, 0, 0, -2, 3, 10, 20, 20, 20, 0,
              0, 0, 0, 0, 0, 18, 27, 30, 30, 0,
              0, 0, 0, -2, 4, 22, 30, 45, 50, 0,
              0, 0, 0, 0, 0, 35, 40, 55, 65, 2,
              0, 0, 0, 6, 7, 40, 42, 55, 70, 4,
              0, 0, 0, 0, 0, 35, 40, 55, 65, 2,
              0, 0, 0, -2, 4, 22, 30, 45, 50, 0,
              0, 0, 0, 0, 0, 18, 27, 30, 30, 0,
              0, 0, 0, -2, 3, 10, 20, 20, 20, 0
          ]
      ]
      

    历史启发式算法

    既然Alpha-Beta搜索算法是在“最小-最大”的基础上引入“树的裁剪”的思想以期提高效率,那么它的效率将在很大程度上取决于树的结构——如果搜索了没多久就发现可以进行“裁剪”了,那么需要分析的工作量将大大减少,效率自然也就大大提高;而如果直至分析了所有的可能性之后才能做出“裁剪”操作,那此时“裁剪”也已经失去了它原有的价值(因为你已经分析了所有情况,这时的Alpha-Beta搜索已和“最小-最大”搜索别无二致了)。因而,要想保证Alpha-Beta搜索算法的效率就需要调整树的结构,即调整待搜索的结点的顺序,使得“裁剪”可以尽可能早地发生。

    我们可以根据部分已经搜索过的结果来调整将要搜索的结点的顺序。因为,通常当一个局面经过搜索被认为较好时,其子结点中往往有一些与它相似的局面(如个别无关紧要的棋子位置有所不同)也是较好的。由J.Schaeffer所提出的“历史启发”(History Heuristic)就是建立在这样一种观点之上的。在搜索的过程中,每当发现一个好的走法,我们就给该走法累加一个增量以记录其“历史得分”,一个多次被搜索并认为是好的走法的“历史得分”就会较高。对于即将搜索的结点,按照“历史得分”的高低对它们进行排序,保证较好的走法(“历史得分”高的走法)排在前面,这样Alpha-Beta搜索就可以尽可能早地进行“裁剪”,从而保证了搜索的效率。

    class history_table:  # 历史启发算法
        def __init__(self):
            self.table = np.zeros((2, 90, 90))
    
        def get_history_score(self, who,  step):
            return self.table[who, step.from_x * 9 + step.from_y, step.to_x * 9 + step.to_y]
    
        def add_history_score(self, who,  step, depth):
            self.table[who, step.from_x * 9 + step.from_y, step.to_x * 9 + step.to_y] += 2 << depth
    

    经过我们的测试,加入历史启发式算法后,计算的速度提高了6-7倍。

    UI设计

    算法介绍

    UI设计之需要将棋盘填好,并使得人机对战时,人的走法可以通过鼠标移动位置决定即可,电脑走法 与ai算法有关

    流程图如下:

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-X5WICraX-1590327386299)(C:\Users\46002\AppData\Roaming\Typora\typora-user-images\image-20200524191710400.png)]

    核心代码如下:

        def PutdownPieces(self, t, x, y):
            selectfilter=list(filter(lambda cm: cm.x == x and cm.y == y and cm.player == MainGame.player1Color,MainGame.piecesList))
            if len(selectfilter):
                MainGame.piecesSelected = selectfilter[0]
                return
    
            if MainGame.piecesSelected :
                #print("1111")
    
                arr = pieces.listPiecestoArr(MainGame.piecesList)
                if MainGame.piecesSelected.canmove(arr, x, y):
                    self.PiecesMove(MainGame.piecesSelected, x, y)
                    MainGame.Putdownflag = MainGame.player2Color
            else:
                fi = filter(lambda p: p.x == x and p.y == y, MainGame.piecesList)
                listfi = list(fi)
                if len(listfi) != 0:
                    MainGame.piecesSelected = listfi[0]
    
        def PiecesMove(self,pieces,  x , y):
            for item in  MainGame.piecesList:
                if item.x ==x and item.y == y:
                    MainGame.piecesList.remove(item)
            pieces.x = x
            pieces.y = y
            print("move to " +str(x) +" "+str(y))
            return True
    
        def Computerplay(self):
    
            if MainGame.Putdownflag == MainGame.player2Color:
                print("轮到电脑了")
    
                computermove = computer.getPlayInfo(MainGame.piecesList, self.from_x, self.from_y, self.to_x, self.to_y, self.mgInit)
                if computer==None:
                    return
                piecemove = None
                for item in MainGame.piecesList:
                    if item.x == computermove[0] and item.y == computermove[1]:
                        piecemove= item
    
                self.PiecesMove(piecemove, computermove[2], computermove[3])
                MainGame.Putdownflag = MainGame.player1Color
    
        #判断游戏胜利
        def VictoryOrDefeat(self):
            txt =""
            result = [MainGame.player1Color,MainGame.player2Color]
            for item in MainGame.piecesList:
                if type(item) ==pieces.King:
                    if item.player == MainGame.player1Color:
                        result.remove(MainGame.player1Color)
                    if item.player == MainGame.player2Color:
                        result.remove(MainGame.player2Color)
    
            if len(result)==0:
                return
            if result[0] == MainGame.player1Color :
                txt = "失败!"
            else:
                txt = "胜利!"
            MainGame.window.blit(self.getTextSuface("%s" % txt), (constants.SCREEN_WIDTH - 100, 200))
            MainGame.Putdownflag = constants.overColor
    
    

    可以实现UI与算法的对接,使得坐标与棋子对应,棋子可以正确的根据算法结果或者鼠标坐标来移动

    展开全文
  • Python 中国象棋源码 V1

    千次阅读 2019-12-18 15:53:43
    Pygame 做的中国象棋,一直以来喜欢下象棋,写了 python 就拿来做一个试试,水平有限,电脑走法水平低,需要在下次版本中更新电脑走法,希望源码能帮助大家更好的学习 python。总共分为四个文件,chinachess.py 为主...
  • 运行server软件并运行两次main程序即可进行双人网络通信对战,在config中修改ip地址即可实现两台电脑局域网内对战
  • 界面较为美观 代码注释完整 可继续进行进一步开发 有需要的可自行下载
  • 象棋游戏(pygame)代码汇总

    万次阅读 多人点赞 2018-05-04 16:15:21
    点击查看象棋游戏系列目录导航 流程图: 效果图: 主函数代码: import pygame from pygame.locals import * import sys import time import traceback import ChessPieces import random # 初始化 ...
  • 国际象棋-Pythonpython的国际象棋游戏
  • 基于Python的网络中国象棋游戏设计与实现 摘要中国象棋是一种家喻户晓的棋类游戏,随着互联网时代的到来,人们的娱乐方式也逐渐向PC端和移动端上发展。本文将传统的中国象棋游戏和当下的互联网技术结合作为重点,...
  • 一个简单的Python象棋软件包,仅作为爱好项目编写。 我还编写了具有网络套接字功能的GUI(在此处添加链接),并且可能会在行后创建一些AI。 该软件包还包括4人游戏模式,尽管规则集与经典游戏Checkmate-> Game Over...
  • matlab象棋游戏代码沙特兰尼 Shatranj是基于位板的开源交互式象棋编程模块,它允许操纵象棋位置并使用搜索算法和评估技术进行实验。 该项目的目标是编写一个工具包,以帮助实施Shannon B类国际象棋程序。 这样,执行...
  • 象棋-源码

    2021-02-08 13:27:00
    这是使用TkInter制作的国际象棋游戏。 要运行该游戏,stockfish必须作为可执行文件安装。 该代码使用类系统,并从HostFile.py运行。 当前功能 电脑无法正常播放,但播放器可以与Stockfish或随机移动生成器对战 游戏...
  • python实现中国象棋

    千次阅读 多人点赞 2021-10-31 01:12:14
    中国象棋项目说明一、项目说明本项目使用Python3进行开发用到的模块是Pygame,可以自行安装,命令pip install pygame二、项目运行效果1. 下载完整代码点击如下地址,...
  • 包含游戏代码,bgm,棋子棋盘图片,需安装pygame,内含大量注释,小白可学习,下载即可运行
  • 大家好我是小豪,今天给大家带来的是pygame小游戏-中国象棋 因为看到博客上面很多上传了的中国象棋py文件,都是收费的。所以我大胆的上传个免费的…已经把原码上传了,感兴趣的可以去下载。 pygame小游戏-中国象棋...
  • -- 构成可下棋的基本元素* 第二节:走法生成 -- 实现下棋的规则* 第三节:局面评估 -- 量化一个局面的双方优劣势* 第四节:局面搜索 -- 让电脑具备思考的能力** 本教程主要以便于理解为目标,不追求代码技巧,希望对...
  • 这是使用python构建的国际象棋AI和国际象棋游戏。 当我了解到由Google Deepmind制作的Alpha Go时,便激发了我尝试构建自己的国际象棋的灵感。 请参阅本文以获取更多信息: : 经过训练的卷积网将用作评估功能,以...
  • 中国象棋想必大家都玩过,突发奇想,想着怎么用python把中国国粹的中国象棋做出来呢?????? 首先老样子看看用python做出来的效果: 国粹——中国象棋 第一步:导入资源包 第二步:初始化 第...
  • -- 构成可下棋的基本元素* 第二节:走法生成 -- 实现下棋的规则* 第三节:局面评估 -- 量化一个局面的双方优劣势* 第四节:局面搜索 -- 让电脑具备思考的能力** 本教程主要以便于理解为目标,不追求代码技巧,希望对...
  • 本中国象棋是用Python3+pygame实现的 一、运行效果 ![]( 二、代码 下面的代码用到图片素材(images文件夹),下载地​ 址如下:www.itprojects.cn/detail.html… ​ """ 作者:it项目实例网 网址:...
  • 国际象棋的棋盘是一个正方形,等分为64个方格,因此又被称为“64格”。这些方格有深浅两种颜色,交替排列。深色的方格称为黑格,浅色的方格称为白格,棋子就放在这些格子中移动。 棋盘由64个大小相同方格组成。 ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 1,487
精华内容 594
关键字:

python象棋游戏代码

python 订阅