The last, we have already finished eat subfunction, added a few simple rules, but how is that enough, you know, a good game, rigorous rules is essential, therefore, before writing to win and buttons, we need to add some additional rules, such as: horse leg of turtle, turtle leg ah, soldiers can’t out matts… Let’s take a look at the code

import pygame
import pygame.font
import sys
import traceback
import copy
from math import sqrt
from pygame.locals import *


pygame.font.init()
pygame.init()

# used to control the sequence
order = True
# Used to stop shots after ending the game
working = True
# Used to store pawn information, mainly used for regret
backups = []

# Define the radius of the piece
r = 40
# One grid represents pixels
# Directly install grid storage, calculate pixels when printing
i = 90

# draw checkerboard
def Draw_a_chessboard(screen) :
    Fill the background color
    screen.fill((233.204.138))
    # painting outside box
    outer_frame_color = (60.20.0)
    pygame.draw.rect(screen,outer_frame_color,[80.80.830.740].5)
    Line #
    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)) 
    # column
    for i in range(1.11):
        pygame.draw.line(screen,inner_frame_color, (90*i, 90), (90*i, 810))
    # 'to'
    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' route
    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)
    # 'Elephant' route
    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)])
    # 'pawn', use anti-aliasing continuous line segment
    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)
    # 'gun'
    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)

    # Draw 'Chu River and Han Dynasty'
    pygame.draw.rect(screen,[233.204.138], [451.91.89.719])
    chuhehanjie = pygame.image.load(PNG "Chu He Han Jie").convert_alpha()
    screen.blit(chuhehanjie,(451.91))
    # Draw 'Regret', 'Restart' and 'exit' buttons
    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('anjian_font.ttf'.45)

    text1 = s_font.render("Regret is".True,button_color)
    text2 = s_font.render("Start over".True,button_color)
    text3 = s_font.render("Quit the game".True,button_color)
    screen.blit(text1,(1000.320))
    screen.blit(text2,(980.520))
    screen.blit(text3,(980.720))

# Draw chess pieces
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('qizi_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))

# Draw a piece with a checkerboard
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])

# Find pieces by position
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']
# Check if there are chess pieces in this position
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

# Rules for moving pieces
def move_rules(qizi,chess_color,x,y) :
    can_move =[]
    
    if qizi == 'to':
        can_move += [[x+i,y],[x-i,y],[x,y+i],[x,y-i]]
    elif qizi[0] = ='and':
        can_move += [[x+i,y+i],[x-i,y-i],[x-i,y+i],[x+i,y-i]]
    elif qizi[0] = ='phase':
        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] = ='the horse':
        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] = ='car':
        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] = ='gun':
        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] = ='the soldiers':
        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                

# Check whether a piece can move to that position
# (chess piece, the position of the chess piece, to determine whether it can be moved)
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 the position of the second click is its own position, it can not go
        if [d_x,d_y] == [x,y]:
            return False
        elif qizi == 'to' or qizi[0] = ='and':
            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] = ='phase':
            # Remove the situation where your legs are empty
            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] = ='the horse':
            # Remove the situation where the horse has a full leg
            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] = ='the soldiers':
            return True
        elif qizi[0] = ='car':
            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] = ='gun':
            # Record the number of pieces between the original position and the position taken
            count = 0
            # the same line
            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
            # same column
            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

Draw prompt (class size, screen size, word size)
def text(s,screen,x) :
    Overlay the previous class size with a rectangle
    pygame.draw.rect(screen,(233.204.138),980.100.1200.100])
    # define font and size
    s_font = pygame.font.Font('anjian_font.ttf'.45)
    # Define class capacity, anti-aliasing, color
    s_text=s_font.render(s,True, (255.0.0))
    # put the word in the window position
    screen.blit(s_text,(980.100))
    pygame.display.flip()
    
def main() :
    Backups of 'hongqi','heiqi','running','order','backups
    global hongqi,heiqi,running,order,working,backups

    # Initial position of the piece
    hongqi = {'to': {'color':'red'.'now_weizhi': [90.450]},'1' and: {'color':'red'.'now_weizhi': [90.360]},'and 2': {'color':'red'.'now_weizhi': [90.540]},'phase 1': {'color':'red'.'now_weizhi': [90.270]},
              'phase 2': {'color':'red'.'now_weizhi': [90.630]},Horse '1': {'color':'red'.'now_weizhi': [90.180]},Horse '2': {'color':'red'.'now_weizhi': [90.720]},Car '1': {'color':'red'.'now_weizhi': [90.90]},
              'cars 2': {'color':'red'.'now_weizhi': [90.810]},'guns 1': {'color':'red'.'now_weizhi': [270.180]},'gun 2': {'color':'red'.'now_weizhi': [270.720]},Soldiers' 1 ': {'color':'red'.'now_weizhi': [360.90]},
              Soldiers' 2 ': {'color':'red'.'now_weizhi': [360.270]},Soldiers' 3 ': {'color':'red'.'now_weizhi': [360.450]},Soldiers' 4 ': {'color':'red'.'now_weizhi': [360.630]},Soldiers' 5 ': {'color':'red'.'now_weizhi': [360.810]}
             }
    heiqi = {'to': {'color':'black'.'now_weizhi': [900.450]},'1' and: {'color':'black'.'now_weizhi': [900.360]},'and 2': {'color':'black'.'now_weizhi': [900.540]},'phase 1': {'color':'black'.'now_weizhi': [900.270]},
             'phase 2': {'color':'black'.'now_weizhi': [900.630]},Horse '1': {'color':'black'.'now_weizhi': [900.180]},Horse '2': {'color':'black'.'now_weizhi': [900.720]},Car '1': {'color':'black'.'now_weizhi': [900.90]},
             'cars 2': {'color':'black'.'now_weizhi': [900.810]},'guns 1': {'color':'black'.'now_weizhi': [720.180]},'gun 2': {'color':'black'.'now_weizhi': [720.720]},Soldiers' 1 ': {'color':'black'.'now_weizhi': [630.90]},
             Soldiers' 2 ': {'color':'black'.'now_weizhi': [630.270]},Soldiers' 3 ': {'color':'black'.'now_weizhi': [630.450]},Soldiers' 4 ': {'color':'black'.'now_weizhi': [630.630]},Soldiers' 5 ': {'color':'black'.'now_weizhi': [630.810]}}Create a window
    screen = pygame.display.set_mode([1200.900])
    # Set the window title
    pygame.display.set_caption("Chinese Chess")
    # Define the current state of the two storage pieces
    backups1 = []
    backups2 = []
    This is used to temporarily store all the pieces
    backup=copy.deepcopy([hongqi,heiqi])
    backups = []
    backups.append(backup)
    # Select a chess piece by pressing the mouse for the first time
    running = True

    
     # Draw the checkerboard and buttons in the window
    Draw_a_chessboard(screen)
    pygame.display.flip()
    clock = pygame.time.Clock()

    while True: 
        Draw_a_chessboard_with_chessman(screen)
        # Only when working is true can the game be launched, mainly used to prevent the game from being launched again after the game is over
        if working:
            if order:
                color = 'red'
                text('Red game',screen,54)
            else:
                color = 'black'
                text(Black is down.,screen,54)
        # Monitor all events
        for event in pygame.event.get():
            # Click x to close the window
            if event.type ==pygame.QUIT:
                pygame.quit()
                sys.exit()

            Click on the class box in the window to complete the corresponding instruction
            elif event.type == MOUSEBUTTONDOWN:
                if event.button == 1:
                    x,y=event.pos[0],event.pos[1]
                    if working:
                        # Select a chess piece by pressing the mouse for the first time
                        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:
                                # used to temporarily store the status of the pieces
                                backups3 = copy.deepcopy(backups1)
                                hongqi.pop(backups1[0])
                                running = not running
                            elif backups2:
                                # used to temporarily store the status of the pieces
                                backups4 = copy.deepcopy(backups2)
                                heiqi.pop(backups2[0])
                                running = not running
                        # Mouse down again, drop the chess piece
                        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 :# red chess
                                    # Determine if the rules of chess are met
                                    if weizhi_able(backups1[0],backups1[1] ['color'],backups1[1] ['now_weizhi'] [0],backups1[1] ['now_weizhi'] [1],x,y) and order:
                                        # Check if there are chess pieces in the position
                                        if weizhi_panduan(x,y):
                                            # Check if it is an enemy pawn
                                            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:
                                        # If not, return to original position
                                        hongqi[backups3[0]] = backups3[1]
                                    backups1 = []
                                    running = not running
                                    if 'to' not in heiqi.keys():
                                         Draw_a_chessboard_with_chessman(screen)
                                         text('Red wins! ',screen,30)
                                         pygame.display.flip()
                                         working = False
                                

                                elif backups2:# black
                                    if weizhi_able(backups2[0],backups2[1] ['color'],backups2[1] ['now_weizhi'] [0],backups2[1] ['now_weizhi'] [1],x,y) and not order:
                                        # Check if there are chess pieces in the position
                                        if weizhi_panduan(x,y):
                                            # Check if it is an enemy pawn
                                            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 'to' not in hongqi.keys():
                                        Draw_a_chessboard_with_chessman(screen)
                                        text('Black wins! ',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 you click 'Restart'
                    if 900<x<1180 and 500<y<600:
                        # unblock
                        working=True
       
                        # Start over
                        main()
                    
                        # Click 'Exit game' to exit the game
                    elif 900<x<1180 and 700<y<8000:
                        # Play sound
                        pygame.quit()
                        sys.exit()                 
                    elif 900<x<1080 and 300<y<400 and len(backups)>1:
                        Delete the last element in maps
                        del backups[len(backups)-1]
                        hongqi=copy.deepcopy(backups[-1] [0])
                        heiqi=copy.deepcopy(backups[-1] [1])
                        # Switch order
                        order = not order
                        # display the map
                        Draw_a_chessboard_with_chessman(screen)
                        # Contrition complete, prevent contrition again
                        x,y=0.0
  

if __name__ == "__main__":
    try:
        main()
    except SystemExit:
        pass
    except:
        traceback.print_exc()
        pygame.quit()
        input(a)Copy the code

This blog compared to the previous, really add a lot of things, with some additional rules, judge whether to win, and the key of the operation, also added the order of playing chess, but which are compared with the simple things, just the code quantity increased, understand the directly added into it, if still don’t understand, welcome to ask.

As for beautification and sound effects, as I said before, everyone has different aesthetic and musical sense, we can design according to their own way, the next blog, I will show you my beautification and sound effects after the code.

If you don’t understand any questions in this article, you are welcome to harass, the blogger is willing to make progress with you