Python实现人机中国象棋游戏

目录
  • 导语
  • 1.游戏规则&基本玩法
    • 1.1 基本玩法
    • 1.2 行棋规则
  • 2.素材文件
  • 3.主要代码
    • 3.1 Chinachess.py 为主文件
    • 3.2 Constants.py 数据常量
    • 3.3 Pieces.py 棋子类,走法
    • 3.4 Computer.py 电脑走法计算
    • 3.5 Button.py按钮定义
  • 4.游戏效果
  • 总结

导语

哈喽!哈喽!我是木木子!今日游戏更新——中国象棋上线啦!

中国象棋是一种古老的棋类游戏,大约有两千年的历史。

是中华文明非物质文化经典产物,艺术价值泛属于整个人类文明进化史的一个分枝。

在中国,可以随处在大街上、小公园儿里等地方经常看到一堆人围在一起下棋,这就足以说明中国象棋的流行性以及普遍性有多高!

早前曾有统计,14、15个中国人当中,就有1个会下中国象棋。中国象棋的受众,可能数以亿计!

今天教大家制作一款中国象棋and想学象棋的话也可以来看看当作新手村吧~

1.游戏规则&基本玩法

1.1 基本玩法

中国象棋的游戏用具由棋盘和棋子组成,对局时,由执红棋的一方先走,双方轮流各走一招,直至分出胜、负、和,对局即终了。轮到走棋的一方,将某个棋子从一个交叉点走到另一个交叉点,或者吃掉对方的棋子而占领其交叉点,都算走了一着。双方各走一着,称为一个回合。

1.2 行棋规则

2.素材文件

3.主要代码

chinachess.py 为主文件;constants.py 数据常量;pieces.py 棋子类,走法;computer.py 电脑走法计算;button.py按钮定义。

目前电脑走法比较傻,有兴趣的朋友可以对computer.py 进行升级!不过这针对大部分的新手刚开始学象棋的话完全够用了哈~哈哈哈 如果你新手入门玩儿的过电脑就说明你入门了!

3.1 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()

3.2 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"),
}

3.3 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

3.4 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

3.5 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

4.游戏效果

总结

好啦!文章就写到这里了哈,想入门象棋的可以先试着自己研究下,上面的教程也有说走法、行棋的规则,然后后面就是实战,自己动手跟电脑来一场对决吧~

以上就是Python实现人机中国象棋游戏的详细内容,更多关于Python中国象棋的资料请关注我们其它相关文章!

(0)

相关推荐

  • C#绘制中国象棋棋盘

    在C#绘制中国象棋棋盘是C#程序设计中GDI+的一个重要组成部分.这也是非常考验编程技巧的操作.在绘制之前首先要对棋盘有一个完整的认识.下面是完成后的输出图案. 1.在制作过程中用到了背景图片如下: 2.棋盘的横竖交叉线的坐标如下图(棋盘横向.竖向都以50象素间距绘制) 3.更细的坐标分布如下图 完整的代码如下图 using System; using System.Collections.Generic; using System.ComponentModel; using System.Da

  • Android实现中国象棋附源码下载

    象棋,很多人多接触过,学者写了一个,大神可以指点一下~直接上代码: 贴出主要代码,想要Demo的点击下载:中国象棋Demo package wyf.ytl; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; impor

  • Python pygame实现中国象棋单机版源码

    Python中国象棋单机版 鼠标点击操作:两天制作,较为粗糙,很多效果还未实现. # -*- coding: utf-8 -*- """ Created on Sun Jun 13 15:41:56 2021 @author: Administrator """ import pygame from pygame.locals import * import sys import math pygame.init() screen=pygame.

  • Python turtle绘画象棋棋盘

    通过使用turtle绘画象棋棋盘,供大家参考,具体内容如下 # 绘制象棋棋盘 import turtle t = turtle.Pen() t.width(2) # 设置画笔粗细 t.speed(1) # 设置画笔移动速度 # 画竖线 t.penup() t.goto(-400, -400) for i in range(9): t.pendown() if i != 0 and i != 8: t.goto(-400+i*100, 0) t.penup() t.goto(-400+i*100,

  • Java棋类游戏实践之中国象棋

    本文实例讲述了java实现的中国象棋游戏代码,分享给大家供大家参考,具体代码如下 一.实践目的: 1.鼠标点击.拖动等事件的应用与区别 2.棋谱文件的保存与读取 3.完善象棋的规则. 二.实践内容: 中国象棋历史悠久,吸引了无数的人研究,现对中国象棋的对战和实现棋谱的制作做如下的设计和说明,供大家参考学习. 1.机机对弈,红方先手.在符合规则的情况下拖动棋子到目的地,松鼠标落子. 人人对弈图 2.制作棋谱,选择制作棋谱菜单后,对弈开始,并记录了下棋过程. 选择"制作棋谱"菜单 棋谱制作

  • java绘制国际象棋与中国象棋棋盘

    JAVA API 中的绘制图形类的paint()方法,我们可以轻松绘制中国象棋与国际象棋的棋盘.详见代码:  一.中国象棋棋盘代码 import java.awt.Font; import java.awt.Frame; import java.awt.Graphics; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class ChineseChese extends Frame{

  • Python实现PIL图像处理库绘制国际象棋棋盘

    目录 1 PIL绘制国际象棋棋盘流程 1.1 思路秒懂 1.2 分块解析 2 完整代码 2.1 方法一 2.2 方法二 2.3 方法三(精简版) 3 结果展示 网页上搜索 "python绘制国际象棋棋盘",索引结果均为调用 turtle 库绘制棋盘结果:为了填充使用 python PIL 图像处理库绘制国际象棋棋盘的空白,今日分享此文. 1 PIL绘制国际象棋棋盘流程 1.1 思路秒懂 步骤1:创建空白图片和绘画对象 步骤2:绘制网格 步骤3:填充颜色 1.2 分块解析 步骤1:创建空

  • C++ 中国象棋的实现流程详解

    中国象棋的中国棋文化,也是中华民族的文化瑰宝,它源远流长,趣味浓厚,基本规则简明易懂.中国象棋在中国的群众中基础远远超过围棋,是普及最广的棋类项目,中国象棋已流传到十几个国家和地区. 中国象棋使用方形格状棋盘,圆形棋子共有32个,红黑二色各有16个棋子,摆放和活动在交叉点上.双方交替行棋,先把对方的将(帅)"将死"的一方获胜. 我们今天就来看看我们自己能不能写出这样一个游戏呢? 今天就不话不多说了,先说一下,今天我们做的是一个简易版的单机中国象棋,希望大家理解,联网对弈的话需要用到的知

  • python输出国际象棋棋盘的实例分享

    国际象棋是当今国际上最流行的智力体育运动项目.青年人下棋可以锻炼思维.增强记忆力和培养坚强的意志:中年人下棋可以享受美学:老年下棋可以很好的休息娱乐.国际象棋游戏有自己的规则,需要两个人将棋子落在棋盘上. 棋子落在棋盘上事件,在计算机看来,是一段程序,而这些程序又由一系列的指令组成.关心编程语言的使用趋势的人都知道,最近几年,国内最火的两种语言非 Python 与 Go 莫属,今天,我们就在计算机上用python开启一段输出国际象棋棋盘的编程之旅. 程序分析:用i控制行,j来控制列,根据i+j的

  • Python实现人机中国象棋游戏

    目录 导语 1.游戏规则&基本玩法 1.1 基本玩法 1.2 行棋规则 2.素材文件 3.主要代码 3.1 Chinachess.py 为主文件 3.2 Constants.py 数据常量 3.3 Pieces.py 棋子类,走法 3.4 Computer.py 电脑走法计算 3.5 Button.py按钮定义 4.游戏效果 总结 导语 哈喽!哈喽!我是木木子!今日游戏更新——中国象棋上线啦! 中国象棋是一种古老的棋类游戏,大约有两千年的历史. 是中华文明非物质文化经典产物,艺术价值泛属于整个人

  • Java+Swing实现中国象棋游戏

    目录 一.系统介绍 1.开发环境 2.技术选型 3.系统功能 二.系统展示 三.部分代码 一.系统介绍 1.开发环境 开发工具:Eclipse2021 JDK版本:jdk1.8 Mysql版本:8.0.13 2.技术选型 Java+Swing 3.系统功能 实现中国象棋游戏,开始游戏,悔棋,退出功能. 二.系统展示 1.首页 2.红旗走 3.黑棋走 三.部分代码 ChineseCheseRule.java package com.sjsq; import java.awt.event.Mouse

  • Android实现中国象棋游戏(局域网版)

    本文实例为大家分享了Android实现中国象棋游戏的具体代码,供大家参考,具体内容如下 实现环境:  android studio 3.2.1, 手机分辨率为: 1920 * 1080 局域网 UDP 连接分主活动类,棋类,主机类 代码如下: 清单文件要添加的权限: <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name=

  • Java实现中国象棋游戏

    目录 一.界面 二.按钮 三.加棋子 四.实现棋子的移动 五.判断胜负 六.按钮“开始游戏”和“重新开始”的实现 七.加规则 八.轮次 九.悔棋 十.背景 及 提示 本文实例为大家分享了Java实现中国象棋游戏的具体代码,供大家参考,具体内容如下 实现一个小游戏需要知道从哪里下手,一步步实现和完善,对于一个中国象棋的小游戏,我们可以按这样的顺序展开: 一.界面 下棋的棋盘首先要准备好,这就是一个合适大小合适比例合适位置的界面,然后在窗体上画上(没错drawLine的那种画上)n条直线和斜线,具体

  • js实现中国象棋游戏

    本文实例为大家分享了js实现中国象棋游戏的具体代码,供大家参考,具体内容如下 使用table元素作表格,div元素作象棋. 效果如下: 代码如下: <html> <head> <title>中国象棋</title> <meta charset="UTF-8"> <style> table{     margin:10px;     border-collapse:collapse; } table.board{  

  • 基于c++的中国象棋游戏设计与实现

    目录 1.文档 2.游戏操作逻辑 3.UI框架 4.网络通信 1.文档 文档分为两部分,一部分在代码中,然后通过doxygen生成HTML.解压本目录下的html.zip后打开index.html即可查看:第二部分在此说明文档内,在这里会介绍一些架构方面的信息. 2.游戏操作逻辑 相关的命名空间有: Chess:这是包含中国象棋的操作逻辑的命名空间 主要操作是possibleMove(int x, int y),通过整个棋盘每个位置上的信息.中国象棋的规则来获得位置(x, y)这个棋子可以移动到

  • python实现人机猜拳小游戏

    今天的这篇文章呢是对人机猜拳小游戏--石头剪刀布的一个描述以及代码展现 石头剪刀布游戏代码的简介:关于石头剪刀布这个小游戏,大致得到思路就是,玩家出一个手势,然后电脑再随机出一个手势,最后再判断是玩家获胜还是电脑获胜.最简单的思路就是将这三个手势是三个代号来表示,然后再去判断代号之间的关系,最后输出胜方. 最一般情况下,最先想到的就是使用1.2.3数字来对三个手势进行代号化,然后再通过代号的大小去判断,如下是对这个方式的简述: 石头   代号   用1来表示 剪刀   代号   用2来表示 布

  • python实现人机对战的井字棋游戏

    本文实例为大家分享了python实现人机对战井字棋的具体代码,供大家参考,具体内容如下 游戏简介:在九宫格内进行,如果一方抢先于另一方向(横.竖.斜)连成3子,则获得胜利.游戏中输入方格位置代号的形式如下: 设计前的思路: 游戏中,board棋盘存储玩家.计算机的落子信息,未落子处未EMPTY.由于人机对战,需要实现计算机智能性,下面是为这个计算机机器人设计的简单策略:如果有一步棋可以让计算机机器人在本轮获胜,那就选那一步走.否则,如果有一步棋可以让玩家在本轮获胜,那就选那一步走.否则,计算机机

随机推荐