设为首页收藏本站

安徽论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 11176|回复: 0

Python实现人机中国象棋游戏

[复制链接]

110

主题

0

回帖

342

积分

中级会员

Rank: 3Rank: 3

积分
342
发表于 2022-3-26 11:02:11 | 显示全部楼层 |阅读模式
网站内容均来自网络,本站只提供信息平台,如有侵权请联系删除,谢谢!
目录


导语

哈喽!哈喽!我是木木子!今日游戏更新——中国象棋上线啦!
中国象棋是一种古老的棋类游戏,大约有两千年的历史。
是中华文明非物质文化经典产物,艺术价值泛属于整个人类文明进化史的一个分枝。
在中国,可以随处在大街上、小公园儿里等地方经常看到一堆人围在一起下棋,这就足以说明中国象棋的流行性以及普遍性有多高!
早前曾有统计,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 为主文件
  1. import pygame
  2. import time
  3. import Xiangqi.constants as constants
  4. from Xiangqi.button import Button
  5. import Xiangqi.pieces as pieces
  6. import Xiangqi.computer as computer


  7. class MainGame():
  8.     window = None
  9.     Start_X = constants.Start_X
  10.     Start_Y = constants.Start_Y
  11.     Line_Span = constants.Line_Span
  12.     Max_X = Start_X + 8 * Line_Span
  13.     Max_Y = Start_Y + 9 * Line_Span


  14.     player1Color = constants.player1Color
  15.     player2Color = constants.player2Color
  16.     Putdownflag = player1Color
  17.     piecesSelected = None


  18.     button_go = None
  19.     piecesList = []


  20.     def start_game(self):
  21.         MainGame.window = pygame.display.set_mode([constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT])
  22.         pygame.display.set_caption("Python代码大全-中国象棋")
  23.         MainGame.button_go = Button(MainGame.window, "重新开始", constants.SCREEN_WIDTH - 100, 300)  # 创建开始按钮
  24.         self.piecesInit()


  25.         while True:
  26.             time.sleep(0.1)
  27.             # 获取事件
  28.             MainGame.window.fill(constants.BG_COLOR)
  29.             self.drawChessboard()
  30.             #MainGame.button_go.draw_button()
  31.             self.piecesDisplay()
  32.             self.VictoryOrDefeat()
  33.             self.Computerplay()
  34.             self.getEvent()
  35.             pygame.display.update()
  36.             pygame.display.flip()


  37.     def drawChessboard(self): #画象棋盘
  38.         mid_end_y = MainGame.Start_Y + 4 * MainGame.Line_Span
  39.         min_start_y = MainGame.Start_Y + 5 * MainGame.Line_Span
  40.         for i in range(0, 9):
  41.             x = MainGame.Start_X + i * MainGame.Line_Span
  42.             if i==0 or i ==8:
  43.                 y = MainGame.Start_Y + i * MainGame.Line_Span
  44.                 pygame.draw.line(MainGame.window, constants.BLACK, [x, MainGame.Start_Y], [x, MainGame.Max_Y], 1)
  45.             else:
  46.                 pygame.draw.line(MainGame.window, constants.BLACK, [x, MainGame.Start_Y], [x, mid_end_y], 1)
  47.                 pygame.draw.line(MainGame.window, constants.BLACK, [x, min_start_y], [x, MainGame.Max_Y], 1)


  48.         for i in range(0, 10):
  49.             x = MainGame.Start_X + i * MainGame.Line_Span
  50.             y = MainGame.Start_Y + i * MainGame.Line_Span
  51.             pygame.draw.line(MainGame.window, constants.BLACK, [MainGame.Start_X, y], [MainGame.Max_X, y], 1)


  52.         speed_dial_start_x =  MainGame.Start_X + 3 * MainGame.Line_Span
  53.         speed_dial_end_x =  MainGame.Start_X + 5 * MainGame.Line_Span
  54.         speed_dial_y1 = MainGame.Start_Y + 0 * MainGame.Line_Span
  55.         speed_dial_y2 = MainGame.Start_Y + 2 * MainGame.Line_Span
  56.         speed_dial_y3 = MainGame.Start_Y + 7 * MainGame.Line_Span
  57.         speed_dial_y4 = MainGame.Start_Y + 9 * MainGame.Line_Span


  58.         pygame.draw.line(MainGame.window, constants.BLACK, [speed_dial_start_x, speed_dial_y1], [speed_dial_end_x, speed_dial_y2], 1)
  59.         pygame.draw.line(MainGame.window, constants.BLACK, [speed_dial_start_x, speed_dial_y2],
  60.                          [speed_dial_end_x, speed_dial_y1], 1)
  61.         pygame.draw.line(MainGame.window, constants.BLACK, [speed_dial_start_x, speed_dial_y3],
  62.                          [speed_dial_end_x, speed_dial_y4], 1)
  63.         pygame.draw.line(MainGame.window, constants.BLACK, [speed_dial_start_x, speed_dial_y4],
  64.                          [speed_dial_end_x, speed_dial_y3], 1)


  65.     def piecesInit(self):  #加载棋子
  66.         MainGame.piecesList.append(pieces.Rooks(MainGame.player2Color, 0,0))
  67.         MainGame.piecesList.append(pieces.Rooks(MainGame.player2Color,  8, 0))
  68.         MainGame.piecesList.append(pieces.Elephants(MainGame.player2Color,  2, 0))
  69.         MainGame.piecesList.append(pieces.Elephants(MainGame.player2Color,  6, 0))
  70.         MainGame.piecesList.append(pieces.King(MainGame.player2Color, 4, 0))
  71.         MainGame.piecesList.append(pieces.Knighs(MainGame.player2Color,  1, 0))
  72.         MainGame.piecesList.append(pieces.Knighs(MainGame.player2Color,  7, 0))
  73.         MainGame.piecesList.append(pieces.Cannons(MainGame.player2Color,  1, 2))
  74.         MainGame.piecesList.append(pieces.Cannons(MainGame.player2Color, 7, 2))
  75.         MainGame.piecesList.append(pieces.Mandarins(MainGame.player2Color,  3, 0))
  76.         MainGame.piecesList.append(pieces.Mandarins(MainGame.player2Color, 5, 0))
  77.         MainGame.piecesList.append(pieces.Pawns(MainGame.player2Color, 0, 3))
  78.         MainGame.piecesList.append(pieces.Pawns(MainGame.player2Color, 2, 3))
  79.         MainGame.piecesList.append(pieces.Pawns(MainGame.player2Color, 4, 3))
  80.         MainGame.piecesList.append(pieces.Pawns(MainGame.player2Color, 6, 3))
  81.         MainGame.piecesList.append(pieces.Pawns(MainGame.player2Color, 8, 3))


  82.         MainGame.piecesList.append(pieces.Rooks(MainGame.player1Color,  0, 9))
  83.         MainGame.piecesList.append(pieces.Rooks(MainGame.player1Color,  8, 9))
  84.         MainGame.piecesList.append(pieces.Elephants(MainGame.player1Color, 2, 9))
  85.         MainGame.piecesList.append(pieces.Elephants(MainGame.player1Color, 6, 9))
  86.         MainGame.piecesList.append(pieces.King(MainGame.player1Color,  4, 9))
  87.         MainGame.piecesList.append(pieces.Knighs(MainGame.player1Color, 1, 9))
  88.         MainGame.piecesList.append(pieces.Knighs(MainGame.player1Color, 7, 9))
  89.         MainGame.piecesList.append(pieces.Cannons(MainGame.player1Color,  1, 7))
  90.         MainGame.piecesList.append(pieces.Cannons(MainGame.player1Color,  7, 7))
  91.         MainGame.piecesList.append(pieces.Mandarins(MainGame.player1Color,  3, 9))
  92.         MainGame.piecesList.append(pieces.Mandarins(MainGame.player1Color,  5, 9))
  93.         MainGame.piecesList.append(pieces.Pawns(MainGame.player1Color, 0, 6))
  94.         MainGame.piecesList.append(pieces.Pawns(MainGame.player1Color, 2, 6))
  95.         MainGame.piecesList.append(pieces.Pawns(MainGame.player1Color, 4, 6))
  96.         MainGame.piecesList.append(pieces.Pawns(MainGame.player1Color, 6, 6))
  97.         MainGame.piecesList.append(pieces.Pawns(MainGame.player1Color, 8, 6))


  98.     def piecesDisplay(self):
  99.         for item in MainGame.piecesList:
  100.             item.displaypieces(MainGame.window)
  101.             #MainGame.window.blit(item.image, item.rect)


  102.     def getEvent(self):
  103.         # 获取所有的事件
  104.         eventList = pygame.event.get()
  105.         for event in eventList:
  106.             if event.type == pygame.QUIT:
  107.                 self.endGame()
  108.             elif event.type == pygame.MOUSEBUTTONDOWN:
  109.                 pos = pygame.mouse.get_pos()
  110.                 mouse_x = pos[0]
  111.                 mouse_y = pos[1]
  112.                 if (
  113.                         mouse_x > MainGame.Start_X - MainGame.Line_Span / 2 and mouse_x < MainGame.Max_X + MainGame.Line_Span / 2) and (
  114.                         mouse_y > MainGame.Start_Y - MainGame.Line_Span / 2 and mouse_y < MainGame.Max_Y + MainGame.Line_Span / 2):
  115.                     # print( str(mouse_x) + "" + str(mouse_y))
  116.                     # print(str(MainGame.Putdownflag))
  117.                     if MainGame.Putdownflag != MainGame.player1Color:
  118.                         return


  119.                     click_x = round((mouse_x - MainGame.Start_X) / MainGame.Line_Span)
  120.                     click_y = round((mouse_y - MainGame.Start_Y) / MainGame.Line_Span)
  121.                     click_mod_x = (mouse_x - MainGame.Start_X) % MainGame.Line_Span
  122.                     click_mod_y = (mouse_y - MainGame.Start_Y) % MainGame.Line_Span
  123.                     if abs(click_mod_x - MainGame.Line_Span / 2) >= 5 and abs(
  124.                             click_mod_y - MainGame.Line_Span / 2) >= 5:
  125.                         # print("有效点:x="+str(click_x)+" y="+str(click_y))
  126.                         # 有效点击点
  127.                         self.PutdownPieces(MainGame.player1Color, click_x, click_y)
  128.                 else:
  129.                     print("out")
  130.                 if MainGame.button_go.is_click():
  131.                     #self.restart()
  132.                     print("button_go click")
  133.                 else:
  134.                     print("button_go click out")


  135.     def PutdownPieces(self, t, x, y):
  136.         selectfilter=list(filter(lambda cm: cm.x == x and cm.y == y and cm.player == MainGame.player1Color,MainGame.piecesList))
  137.         if len(selectfilter):
  138.             MainGame.piecesSelected = selectfilter[0]
  139.             return


  140.         if MainGame.piecesSelected :
  141.             #print("1111")


  142.             arr = pieces.listPiecestoArr(MainGame.piecesList)
  143.             if MainGame.piecesSelected.canmove(arr, x, y):
  144.                 self.PiecesMove(MainGame.piecesSelected, x, y)
  145.                 MainGame.Putdownflag = MainGame.player2Color
  146.         else:
  147.             fi = filter(lambda p: p.x == x and p.y == y, MainGame.piecesList)
  148.             listfi = list(fi)
  149.             if len(listfi) != 0:
  150.                 MainGame.piecesSelected = listfi[0]


  151.     def PiecesMove(self,pieces,  x , y):
  152.         for item in  MainGame.piecesList:
  153.             if item.x ==x and item.y == y:
  154.                 MainGame.piecesList.remove(item)
  155.         pieces.x = x
  156.         pieces.y = y
  157.         print("move to " +str(x) +" "+str(y))
  158.         return True


  159.     def Computerplay(self):
  160.         if MainGame.Putdownflag == MainGame.player2Color:
  161.             print("轮到电脑了")
  162.             computermove = computer.getPlayInfo(MainGame.piecesList)
  163.             #if computer==None:
  164.                 #return
  165.             piecemove = None
  166.             for item in MainGame.piecesList:
  167.                 if item.x == computermove[0] and item.y == computermove[1]:
  168.                     piecemove= item


  169.             self.PiecesMove(piecemove, computermove[2], computermove[3])
  170.             MainGame.Putdownflag = MainGame.player1Color


  171.     #判断游戏胜利
  172.     def VictoryOrDefeat(self):
  173.         txt =""
  174.         result = [MainGame.player1Color,MainGame.player2Color]
  175.         for item in MainGame.piecesList:
  176.             if type(item) ==pieces.King:
  177.                 if item.player == MainGame.player1Color:
  178.                     result.remove(MainGame.player1Color)
  179.                 if item.player == MainGame.player2Color:
  180.                     result.remove(MainGame.player2Color)


  181.         if len(result)==0:
  182.             return
  183.         if result[0] == MainGame.player1Color :
  184.             txt = "失败!"
  185.         else:
  186.             txt = "胜利!"
  187.         MainGame.window.blit(self.getTextSuface("%s" % txt), (constants.SCREEN_WIDTH - 100, 200))
  188.         MainGame.Putdownflag = constants.overColor


  189.     def getTextSuface(self, text):
  190.         pygame.font.init()
  191.         # print(pygame.font.get_fonts())
  192.         font = pygame.font.SysFont('kaiti', 18)
  193.         txt = font.render(text, True, constants.TEXT_COLOR)
  194.         return txt


  195.     def endGame(self):
  196.         print("exit")
  197.         exit()


  198. if __name__ == '__main__':
  199.     MainGame().start_game()
复制代码
3.2 Constants.py 数据常量
  1. #数据常量
  2. import pygame


  3. SCREEN_WIDTH=900
  4. SCREEN_HEIGHT=650
  5. Start_X = 50
  6. Start_Y = 50
  7. Line_Span = 60


  8. player1Color = 1
  9. player2Color = 2
  10. overColor = 3


  11. BG_COLOR=pygame.Color(200, 200, 200)
  12. Line_COLOR=pygame.Color(255, 255, 200)
  13. TEXT_COLOR=pygame.Color(255, 0, 0)


  14. # 定义颜色
  15. BLACK = ( 0, 0, 0)
  16. WHITE = (255, 255, 255)
  17. RED = (255, 0, 0)
  18. GREEN = ( 0, 255, 0)
  19. BLUE = ( 0, 0, 255)


  20. repeat = 0


  21. pieces_images = {
  22.     'b_rook': pygame.image.load("imgs/s2/b_c.gif"),
  23.     'b_elephant': pygame.image.load("imgs/s2/b_x.gif"),
  24.     'b_king': pygame.image.load("imgs/s2/b_j.gif"),
  25.     'b_knigh': pygame.image.load("imgs/s2/b_m.gif"),
  26.     'b_mandarin': pygame.image.load("imgs/s2/b_s.gif"),
  27.     'b_cannon': pygame.image.load("imgs/s2/b_p.gif"),
  28.     'b_pawn': pygame.image.load("imgs/s2/b_z.gif"),


  29.     'r_rook': pygame.image.load("imgs/s2/r_c.gif"),
  30.     'r_elephant': pygame.image.load("imgs/s2/r_x.gif"),
  31.     'r_king': pygame.image.load("imgs/s2/r_j.gif"),
  32.     'r_knigh': pygame.image.load("imgs/s2/r_m.gif"),
  33.     'r_mandarin': pygame.image.load("imgs/s2/r_s.gif"),
  34.     'r_cannon': pygame.image.load("imgs/s2/r_p.gif"),
  35.     'r_pawn': pygame.image.load("imgs/s2/r_z.gif"),
  36. }
复制代码
3.3 Pieces.py 棋子类,走法
  1. #棋子类,走法
  2. import pygame
  3. import Xiangqi.constants as constants


  4. class  Pieces():
  5.     def __init__(self, player,  x, y):
  6.         self.imagskey = self.getImagekey()
  7.         self.image = constants.pieces_images[self.imagskey]
  8.         self.x = x
  9.         self.y = y
  10.         self.player = player
  11.         self.rect = self.image.get_rect()
  12.         self.rect.left = constants.Start_X + x * constants.Line_Span - self.image.get_rect().width / 2
  13.         self.rect.top = constants.Start_Y + y * constants.Line_Span - self.image.get_rect().height / 2


  14.     def displaypieces(self,screen):
  15.         #print(str(self.rect.left))
  16.         self.rect.left = constants.Start_X + self.x * constants.Line_Span - self.image.get_rect().width / 2
  17.         self.rect.top = constants.Start_Y + self.y * constants.Line_Span - self.image.get_rect().height / 2
  18.         screen.blit(self.image,self.rect);
  19.         #self.image = self.images
  20.         #MainGame.window.blit(self.image,self.rect)


  21.     def canmove(self, arr, moveto_x, moveto_y):
  22.         pass
  23.     def getImagekey(self):
  24.         return None
  25.     def getScoreWeight(self,listpieces):
  26.         return  None


  27. class Rooks(Pieces):
  28.     def __init__(self, player,  x, y):
  29.         self.player = player
  30.         super().__init__(player,  x, y)


  31.     def getImagekey(self):
  32.         if self.player == constants.player1Color:
  33.             return "r_rook"
  34.         else:
  35.             return "b_rook"


  36.     def canmove(self, arr, moveto_x, moveto_y):
  37.         if self.x == moveto_x and self.y == moveto_y:
  38.             return False
  39.         if arr[moveto_x][moveto_y] ==self.player :
  40.             return  False
  41.         if self.x == moveto_x:
  42.             step = -1 if self.y > moveto_y else 1
  43.             for i in range(self.y +step, moveto_y, step):
  44.                 if arr[self.x][i] !=0 :
  45.                     return False
  46.             #print(" move y")
  47.             return True


  48.         if self.y == moveto_y:
  49.             step = -1 if self.x > moveto_x else 1
  50.             for i in range(self.x + step, moveto_x, step):
  51.                 if arr[i][self.y] != 0:
  52.                     return False
  53.             return True


  54.     def getScoreWeight(self, listpieces):
  55.         score = 11
  56.         return score


  57. class Knighs(Pieces):
  58.     def __init__(self, player,  x, y):
  59.         self.player = player
  60.         super().__init__(player,  x, y)
  61.     def getImagekey(self):
  62.         if self.player == constants.player1Color:
  63.             return "r_knigh"
  64.         else:
  65.             return "b_knigh"
  66.     def canmove(self, arr, moveto_x, moveto_y):
  67.         if self.x == moveto_x and self.y == moveto_y:
  68.             return False
  69.         if arr[moveto_x][moveto_y] == self.player:
  70.             return False
  71.         #print(str(self.x) +""+str(self.y))
  72.         move_x = moveto_x-self.x
  73.         move_y = moveto_y - self.y
  74.         if abs(move_x) == 1 and abs(move_y) == 2:
  75.             step = 1 if move_y > 0 else -1
  76.             if arr[self.x][self.y + step] == 0:
  77.                 return True
  78.         if abs(move_x) == 2 and abs(move_y) == 1:
  79.             step = 1 if move_x >0 else -1
  80.             if arr[self.x +step][self.y] ==0 :
  81.                 return  True


  82.     def getScoreWeight(self, listpieces):
  83.         score = 5
  84.         return score


  85. class Elephants(Pieces):
  86.     def __init__(self, player, x, y):
  87.         self.player = player
  88.         super().__init__(player, x, y)
  89.     def getImagekey(self):
  90.         if self.player == constants.player1Color:
  91.             return "r_elephant"
  92.         else:
  93.             return "b_elephant"
  94.     def canmove(self, arr, moveto_x, moveto_y):
  95.         if self.x == moveto_x and self.y == moveto_y:
  96.             return False
  97.         if arr[moveto_x][moveto_y] == self.player:
  98.             return False
  99.         if self.y <=4 and moveto_y >=5 or self.y >=5 and moveto_y <=4:
  100.             return  False
  101.         move_x = moveto_x - self.x
  102.         move_y = moveto_y - self.y
  103.         if abs(move_x) == 2 and abs(move_y) == 2:
  104.             step_x = 1 if move_x > 0 else -1
  105.             step_y = 1 if move_y > 0 else -1
  106.             if arr[self.x + step_x][self.y + step_y] == 0:
  107.                 return True


  108.     def getScoreWeight(self, listpieces):
  109.         score = 2
  110.         return score
  111. class Mandarins(Pieces):


  112.     def __init__(self, player,  x, y):
  113.         self.player = player
  114.         super().__init__(player,  x, y)


  115.     def getImagekey(self):
  116.         if self.player == constants.player1Color:
  117.             return "r_mandarin"
  118.         else:
  119.             return "b_mandarin"
  120.     def canmove(self, arr, moveto_x, moveto_y):
  121.         if self.x == moveto_x and self.y == moveto_y:
  122.             return False
  123.         if arr[moveto_x][moveto_y] == self.player:
  124.             return False
  125.         if moveto_x <3 or moveto_x >5:
  126.             return False
  127.         if moveto_y > 2 and moveto_y < 7:
  128.             return False
  129.         move_x = moveto_x - self.x
  130.         move_y = moveto_y - self.y
  131.         if abs(move_x) == 1 and abs(move_y) == 1:
  132.             return True
  133.     def getScoreWeight(self, listpieces):
  134.         score = 2
  135.         return score


  136. class King(Pieces):
  137.     def __init__(self, player, x, y):
  138.         self.player = player
  139.         super().__init__(player, x, y)
  140.     def getImagekey(self):
  141.         if self.player == constants.player1Color:
  142.             return "r_king"
  143.         else:
  144.             return "b_king"


  145.     def canmove(self, arr, moveto_x, moveto_y):
  146.         if self.x == moveto_x and self.y == moveto_y:
  147.             return False
  148.         if arr[moveto_x][moveto_y] == self.player:
  149.             return False
  150.         if moveto_x < 3 or moveto_x > 5:
  151.             return False
  152.         if moveto_y > 2 and moveto_y < 7:
  153.             return False
  154.         move_x = moveto_x - self.x
  155.         move_y = moveto_y - self.y
  156.         if abs(move_x) + abs(move_y) == 1:
  157.             return True
  158.     def getScoreWeight(self, listpieces):
  159.         score = 150
  160.         return score
  161. class Cannons(Pieces):
  162.     def __init__(self, player,  x, y):
  163.         self.player = player
  164.         super().__init__(player, x, y)
  165.     def getImagekey(self):
  166.         if self.player == constants.player1Color:
  167.             return "r_cannon"
  168.         else:
  169.             return "b_cannon"


  170.     def canmove(self, arr, moveto_x, moveto_y):
  171.         if self.x == moveto_x and self.y == moveto_y:
  172.             return False
  173.         if arr[moveto_x][moveto_y] == self.player:
  174.             return False
  175.         overflag = False
  176.         if self.x == moveto_x:
  177.             step = -1 if self.y > moveto_y else 1
  178.             for i in range(self.y + step, moveto_y, step):
  179.                 if arr[self.x][i] != 0:
  180.                     if overflag:
  181.                         return False
  182.                     else:
  183.                         overflag = True


  184.             if overflag and arr[moveto_x][moveto_y] == 0:
  185.                 return False
  186.             if not overflag and arr[self.x][moveto_y] != 0:
  187.                 return False


  188.             return True


  189.         if self.y == moveto_y:
  190.             step = -1 if self.x > moveto_x else 1
  191.             for i in range(self.x + step, moveto_x, step):
  192.                 if arr[i][self.y] != 0:
  193.                     if overflag:
  194.                         return False
  195.                     else:
  196.                         overflag = True


  197.             if overflag and arr[moveto_x][moveto_y] == 0:
  198.                 return False
  199.             if not overflag and arr[moveto_x][self.y] != 0:
  200.                 return False
  201.             return True
  202.     def getScoreWeight(self, listpieces):
  203.         score = 6
  204.         return score


  205. class Pawns(Pieces):
  206.     def __init__(self, player, x, y):
  207.         self.player = player
  208.         super().__init__(player,  x, y)
  209.     def getImagekey(self):
  210.         if self.player == constants.player1Color:
  211.             return "r_pawn"
  212.         else:
  213.             return "b_pawn"


  214.     def canmove(self, arr, moveto_x, moveto_y):
  215.         if self.x == moveto_x and self.y == moveto_y:
  216.             return False
  217.         if arr[moveto_x][moveto_y] == self.player:
  218.             return False
  219.         move_x = moveto_x - self.x
  220.         move_y = moveto_y - self.y


  221.         if self.player == constants.player1Color:
  222.             if self.y > 4  and move_x != 0 :
  223.                 return  False
  224.             if move_y > 0:
  225.                 return  False
  226.         elif self.player == constants.player2Color:
  227.             if self.y <= 4  and move_x != 0 :
  228.                 return  False
  229.             if move_y < 0:
  230.                 return False


  231.         if abs(move_x) + abs(move_y) == 1:
  232.             return True
  233.     def getScoreWeight(self, listpieces):
  234.         score = 2
  235.         return score


  236. def listPiecestoArr(piecesList):
  237.     arr = [[0 for i in range(10)] for j in range(9)]
  238.     for i in range(0, 9):
  239.         for j in range(0, 10):
  240.             if len(list(filter(lambda cm: cm.x == i and cm.y == j and cm.player == constants.player1Color,
  241.                                piecesList))):
  242.                 arr[i][j] = constants.player1Color
  243.             elif len(list(filter(lambda cm: cm.x == i and cm.y == j and cm.player == constants.player2Color,
  244.                                  piecesList))):
  245.                 arr[i][j] = constants.player2Color


  246.     return arr
复制代码
3.4 Computer.py 电脑走法计算
  1. #电脑走法计算
  2. import Xiangqi.constants as constants
  3. #import time
  4. from Xiangqi.pieces import listPiecestoArr


  5. def getPlayInfo(listpieces):
  6.     pieces = movedeep(listpieces ,1 ,constants.player2Color)
  7.     return [pieces[0].x,pieces[0].y, pieces[1], pieces[2]]


  8. def movedeep(listpieces, deepstep, player):
  9.     arr = listPiecestoArr(listpieces)
  10.     listMoveEnabel = []
  11.     for i in range(0, 9):
  12.         for j in range(0, 10):
  13.             for item in listpieces:
  14.                 if item.player == player and item.canmove(arr, i, j):
  15.                     #标记是否有子被吃 如果被吃 在下次循环时需要补会
  16.                     piecesremove = None
  17.                     for itembefore in listpieces:
  18.                         if itembefore.x == i and itembefore.y == j:
  19.                             piecesremove= itembefore
  20.                             break
  21.                     if piecesremove != None:
  22.                         listpieces.remove(piecesremove)


  23.                     #记录移动之前的位置
  24.                     move_x = item.x
  25.                     move_y = item.y
  26.                     item.x = i
  27.                     item.y = j


  28.                     #print(str(move_x) + "," + str(move_y) + "," + str(item.x) + "  ,  " + str(item.y))
  29.                     scoreplayer1 = 0
  30.                     scoreplayer2 = 0
  31.                     for itemafter in listpieces:
  32.                         if itemafter.player == constants.player1Color:
  33.                             scoreplayer1 += itemafter.getScoreWeight(listpieces)
  34.                         elif  itemafter.player == constants.player2Color:
  35.                             scoreplayer2 += itemafter.getScoreWeight(listpieces)


  36.                     #print("得分:"+item.imagskey +", "+str(len(moveAfterListpieces))+","+str(i)+","+str(j)+"," +str(scoreplayer1) +"  ,  "+ str(scoreplayer2) )
  37.                     #print(str(deepstep))
  38.                     #如果得子 判断对面是否可以杀过来,如果又被杀,而且子力评分低,则不干
  39.                     arrkill = listPiecestoArr(listpieces)


  40.                     if scoreplayer2 > scoreplayer1 :
  41.                         for itemkill in listpieces:
  42.                             if itemkill.player == constants.player1Color and itemkill.canmove(arrkill, i, j):
  43.                                 scoreplayer2=scoreplayer1


  44.                     if deepstep > 0 :
  45.                         nextplayer = constants.player1Color if player == constants.player2Color else constants.player2Color
  46.                         nextpiecesbest= movedeep(listpieces, deepstep -1, nextplayer)
  47.                         listMoveEnabel.append([item, i, j, nextpiecesbest[3], nextpiecesbest[4], nextpiecesbest[5]])
  48.                     else:
  49.                         #print(str(len(listpieces)))
  50.                         #print("得分:" + item.imagskey + ", " + str(len(listpieces)) + "," + str(move_x) + "," + str(move_y) + "," + str(i) + "  ,  " + str(j))
  51.                         if player == constants.player2Color:
  52.                             listMoveEnabel.append([item, i, j, scoreplayer1, scoreplayer2, scoreplayer1 - scoreplayer2])
  53.                         else:
  54.                             listMoveEnabel.append([item, i, j, scoreplayer1, scoreplayer2, scoreplayer2 - scoreplayer1])
  55.                     #print("得分:"+str(scoreplayer1))
  56.                     item.x = move_x
  57.                     item.y = move_y
  58.                     if piecesremove != None:
  59.                         listpieces.append(piecesremove)


  60.     list_scorepalyer1 = sorted(listMoveEnabel, key=lambda tm: tm[5], reverse=True)
  61.     piecesbest = list_scorepalyer1[0]
  62.     if deepstep ==1 :
  63.         print(list_scorepalyer1)
  64.     return piecesbest
复制代码
3.5 Button.py按钮定义
  1. #设置按钮
  2. import pygame
  3. class Button():
  4.     def __init__(self, screen, msg, left,top):  # msg为要在按钮中显示的文本
  5.         """初始化按钮的属性"""
  6.         self.screen = screen
  7.         self.screen_rect = screen.get_rect()


  8.         self.width, self.height = 150, 50  # 这种赋值方式很不错
  9.         self.button_color = (72, 61, 139)  # 设置按钮的rect对象颜色为深蓝
  10.         self.text_color = (255, 255, 255)  # 设置文本的颜色为白色
  11.         pygame.font.init()
  12.         self.font = pygame.font.SysFont('kaiti', 20)  # 设置文本为默认字体,字号为40


  13.         self.rect = pygame.Rect(0, 0, self.width, self.height)
  14.         #self.rect.center = self.screen_rect.center  # 创建按钮的rect对象,并使其居中
  15.         self.left = left
  16.         self.top = top


  17.         self.deal_msg(msg)  # 渲染图像


  18.     def deal_msg(self, msg):
  19.         """将msg渲染为图像,并将其在按钮上居中"""
  20.         self.msg_img = self.font.render(msg, True, self.text_color, self.button_color)  # render将存储在msg的文本转换为图像
  21.         self.msg_img_rect = self.msg_img.get_rect()  # 根据文本图像创建一个rect
  22.         self.msg_img_rect.center = self.rect.center  # 将该rect的center属性设置为按钮的center属性


  23.     def draw_button(self):
  24.         #self.screen.fill(self.button_color, self.rect)  # 填充颜色
  25.         self.screen.blit(self.msg_img, (self.left,self.top))  # 将该图像绘制到屏幕


  26.     def is_click(self):
  27.         point_x, point_y = pygame.mouse.get_pos()
  28.         x = self.left
  29.         y = self.top
  30.         w, h = self.msg_img.get_size()


  31.         in_x = x < point_x < x + w
  32.         in_y = y < point_y < y + h
  33.         return in_x and in_y
复制代码
4.游戏效果



总结

好啦!文章就写到这里了哈,想入门象棋的可以先试着自己研究下,上面的教程也有说走法、行棋的规则,然后后面就是实战,自己动手跟电脑来一场对决吧~
以上就是Python实现人机中国象棋游戏的详细内容,更多关于Python中国象棋的资料请关注脚本之家其它相关文章!
                                                        
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
免责声明
1. 本论坛所提供的信息均来自网络,本网站只提供平台服务,所有账号发表的言论与本网站无关。
2. 其他单位或个人在使用、转载或引用本文时,必须事先获得该帖子作者和本人的同意。
3. 本帖部分内容转载自其他媒体,但并不代表本人赞同其观点和对其真实性负责。
4. 如有侵权,请立即联系,本网站将及时删除相关内容。
懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

快速回复 返回顶部 返回列表