Python version of happy Xiaole is coming. Can you pass the customs?

Posted by lesmckeown on Sat, 29 Jan 2022 00:40:46 +0100

Relevant documents

Pay attention to Xiaobian, and receive private letter Xiaobian!
Of course, don't forget a three in a row~~

Yes, we can pay attention to the official account of Xiaobian yo ~ ~
Python log

development environment

Python version: 3.6.4
Related modules:
pygame module;
And some Python's own modules.

Environment construction

Install Python and add it to the environment variable. pip can install the relevant modules required.

Principle introduction

I believe there are still a lot of little friends who have played Xiaole. Today, we give you the Python version of Amway. The operation is also very simple. You can operate "small animals" by moving the mouse. As long as there are three or more same small animals, you can see the elimination score.
After understanding the rules of the game, we can start to write the game ~ first, initialize the game:

'''brick : 218*218
   animal : 40*40
   bg : 850*600 '''

# print(dir())   # Imported packages
pygame.init()  # initialization
pygame.mixer.init()
pygame.display.set_caption('Happy and happy -- more daring')
tree = manager.ManagerTree()
m = manager.Manager(0, 0)
sound_sign = 0
world_bgm = pygame.mixer.Sound(manager.SoundPlay.world_bgm)
game_bgm = pygame.mixer.Sound(manager.SoundPlay.game_bgm)
while True:
    if m.level == 0:
        if sound_sign == 0:
            game_bgm.stop()
            world_bgm.play(-1)
            sound_sign = 1
    else:
        if sound_sign == 1:
            world_bgm.stop()
            game_bgm.play(-1)
            sound_sign = 0
    if m.level == 0:
        tree.draw_tree(m.energy_num, m.money)
    else:
        m.set_level_mode(m.level)
        sprite_group = m.draw()
        if m.type == 0:
            m.eliminate_animal()
            m.death_map()
            m.exchange(sprite_group)
        m.judge_level()

    for event in pygame.event.get():
        if event.type == KEYDOWN:
            if event.key == pygame.K_q or event.key == pygame.K_ESCAPE:
                exit()
        if event.type == QUIT:
            sys.exit()
        m.level, m.energy_num, m.money = tree.mouse_select(event, m.level, m.energy_num, m.money)
        m.mouse_select(event)

    m.mouse_image()
    pygame.display.flip()

if __name__ == "main":
    main()

Then there are some code diagrams:

Schematic diagram and code implementation of tree interface:

class ManagerTree:
    """Management tree class"""
    __screen_size = (900, 600)
    screen = pygame.display.set_mode(__screen_size, DOUBLEBUF, 32)
    fruit_list = []
    fruit_image = pygame.image.load(Tree.fruit).convert_alpha()
    fruit_width = fruit_image.get_width()
    fruit_height = fruit_image.get_height()
    type = 0  # 0 tree interface, 1 energy interface
    energy_full = False  # Energy full flag initial not full
    money_empty = False  # Insufficient silver coins

    def load_text(self, text, position, txt_size=25, txt_color=(255, 255, 255)):
        my_font = pygame.font.SysFont(None, txt_size)
        text_screen = my_font.render(text, True, txt_color)
        self.screen.blit(text_screen, position)

    def draw_tree(self, energy_num, money_num):
        """painting tree"""
        Tree(Tree.tree, (0, 600)).draw(self.screen)      # Painting tree
        Tree(Tree.energy_num, Tree.energy_num_position).draw(self.screen)  # Painting energy
        # print("energy", energy_num)
        if energy_num > 30:
            self.load_text(str(30) + '/30', (22, 55), 21)
        else:
            self.load_text(str(energy_num)+'/30', (22, 55), 21)
        # print("money", money_num)
        Tree(Tree.money, (15, 135)).draw(self.screen)  # Draw silver coins
        self.load_text(str(money_num), (32, 124), 21)
        for i in range(0, 10):                            # Draw fruit
            Tree(Tree.fruit, Tree.position[i]).draw(self.screen)
            self.load_text(str(i+1), (Tree.position[i][0]+15, Tree.position[i][1]-47))
        if self.type == 1:
            Tree(Tree.energy_buy, Tree.energy_buy_position).draw(self.screen)
            if self.energy_full:
                self.load_text("energy is full!", (430, 310), 30, (255, 0, 0))
                pygame.display.flip()
                pygame.time.delay(500)
                self.energy_full = False
            if self.money_empty:
                self.load_text("money is not enough!", (410, 310), 30, (255, 0, 0))
                pygame.display.flip()
                pygame.time.delay(500)
                self.money_empty = False

    def mouse_select(self, button, level, energy_num, money_num):
        """Mouse click"""
        if button.type == MOUSEBUTTONDOWN:
            mouse_down_x, mouse_down_y = button.pos
            print(button.pos)
            if level == 0:
                if self.type == 0:          # Tree interface
                    for i in range(0, 10):
                        if Tree.position[i][0] < mouse_down_x < Tree.position[i][0] + self.fruit_width \
                                and Tree.position[i][1] - self.fruit_height < mouse_down_y < Tree.position[i][1]:
                            if energy_num <= 0:
                                self.type = 1
                            else:
                                level = i + 1
                    if Tree.energy_num_position[0] < mouse_down_x < Tree.energy_num_position[0]+60 \
                            and Tree.energy_num_position[1]-60 < mouse_down_y < Tree.energy_num_position[1]:  # Energy 60 * 60
                        SoundPlay(SoundPlay.click)
                        self.type = 1
                else:               # Add energy pop-up interface
                    if 408 < mouse_down_x < 600 and 263 < mouse_down_y < 313:    # Click the energize button
                        SoundPlay(SoundPlay.click_button)
                        if money_num < 50:
                            self.money_empty = True
                        if energy_num >= 30:
                            self.energy_full = True
                        elif energy_num < 30 and money_num >= 50:
                            energy_num += 5
                            money_num -= 50
                    elif 619 < mouse_down_x < 638 and 158 < mouse_down_y < 177:   # Dot cross
                        self.type = 0
        if button.type == MOUSEBUTTONUP:
            pass
        return level, energy_num, money_num

Then there is the element class, that is, the small animal we need to click:

class Element(pygame.sprite.Sprite):
    """ Element class """
    # Icon tuple, including 6 small animals,
    animal = ('pic2/fox.png', 'pic2/bear.png', 'pic2/chick.png', 'pic2/eagle.png', 'pic2/frog.png', 'pic2/cow.png')
    ice = 'pic2/ice.png'  # Ice layer
    brick = 'pic2/brick.png'  # brick
    frame = 'pic2/frame.png'   # Check box
    bling = ("pic2/bling1.png", "pic2/bling2.png", "pic2/bling3.png", "pic2/bling4.png", "pic2/bling5.png",\
             "pic2/bling6.png", "pic2/bling7.png", "pic2/bling8.png", "pic2/bling9.png")   # Eliminate animation

    ice_eli = ('pic2/ice0.png', 'pic2/ice1.png', 'pic2/ice2.png', 'pic2/ice3.png', 'pic2/ice4.png', 'pic2/ice5.png',\
               'pic2/ice6.png', 'pic2/ice7.png', 'pic2/ice8.png')    # Eliminate ice animation

    # Score picture
    score_level = ('pic2/good.png', 'pic2/great.png', 'pic2/amazing.png', 'pic2/excellent.png', 'pic2/unbelievable.png')
    none_animal = 'pic2/noneanimal.png'             # No small animals can be eliminated
    stop = 'pic2/exit.png'       # Pause key
    stop_position = (20, 530)

    def __init__(self, icon, position):
        super().__init__()
        self.image = pygame.image.load(icon).convert_alpha()
        self.rect = self.image.get_rect()
        self.rect.topleft = position         # Upper left coordinate
        self.speed = [0, 0]
        self.init_position = position

    def move(self, speed):
        self.speed = speed
        self.rect = self.rect.move(self.speed)
        if self.speed[0] != 0:    # If you move left and right
            if abs(self.rect.left-self.init_position[0]) == self.rect[2]:
                self.init_position = self.rect.topleft
                self.speed = [0, 0]
        else:
            if abs(self.rect.top-self.init_position[1]) == self.rect[3]:
                self.init_position = self.rect.topleft
                self.speed = [0, 0]

    def draw(self, screen):
        screen.blit(self.image, self.rect)

Then, the interaction of small animals is realized, which is called array:

class Manager:
    """  Array class """
    __screen_size = (900, 600)
    screen = pygame.display.set_mode(__screen_size, DOUBLEBUF, 32)
    __brick_size = 50
    __bg = pygame.image.load('pic2/bg.png').convert()
    stop_width = 63
    selected = [-1, -1]   # Now select [row, col]
    exchange_sign = -1  # No exchange flag
    last_sel = [-1, -1]  # Last selected [row, col]
    change_value_sign = False  # Whether to exchange value flag, not initially
    death_sign = True  # Dead map flag. The initial is not a dead map
    boom_sel = [-1, -1]   # Location of small animals with silianxiao special effect row, col
    level = 0  # Initial level 0 of current level
    money = 100  # Gold coins
    energy_num = 30  # Energy value
    num_sign = True
    type = 2  # 0 represents in the game; 1. The representative completes the task and passes the customs- 1 means that the steps are used up, the task is not completed, and the clearance fails; 2 represents no game status, board interface
    reset_mode = True     # Whether to re layout (layout of each level)
    init_step = 15  # Specified steps per level
    step = init_step     # Represents the number of steps left in the game
    score = 0        # Get a number
    min = 20  # Median score 1
    max = 50  # Median score 2
    animal_num = [0, 0, 0, 0, 0, 0]   # Number of small animals eliminated in this level
    ice_num = 0
    success_board = Board(Board.success_board, [200, 0])  # Successful clearance board
    fail_board = Board(Board.fail_board, [200, 0])  # Task failure board
    height, width = 9, 9
    row, col = 5, 5
    ice_list = [[-1 for col in range(21)]for row in range(21)]   # -1 do not draw, 1 draw ice
    animal = [[-1 for col in range(21)]for row in range(21)]   # -2 eliminated, - 1 not drawn, 0-4 small animals
    list_x, list_y = (__screen_size[0] - 11 * __brick_size) / 2, (__screen_size[1] - 11 * __brick_size) / 2  # Matrix coordinates

    def __init__(self, width, height):
        self.height = height
        self.width = width
        self.list_x = (Manager.__screen_size[0] - self.width * Manager.__brick_size) / 2
        self.list_y = (Manager.__screen_size[1] - self.height * Manager.__brick_size) / 2
        self.row, self.col = Manager.xy_rc(self.list_x, self.list_y)
        self.list_x, self.list_y = Manager.rc_xy(self.row, self.col)
        self.ice_list = [[-1 for col in range(21)]for row in range(21)]
        self.animal = [[-1 for col in range(21)]for row in range(21)]
        self.reset_animal()

    def reset_animal(self):
        for row in range(self.row, self.row + self.height):
            for col in range(self.col, self.col + self.width):
                self.animal[row][col] = random.randint(0, 5)

    @staticmethod
    def rc_xy(row, col):
        """row col turn x,y coordinate"""
        return int(Manager.list_x + (col-Manager.col)*Manager.__brick_size), int\
            (Manager.list_y+(row-Manager.row)*Manager.__brick_size)

    @staticmethod
    def xy_rc(x, y):
        """x,y Coordinate rotation row col"""
        return int((y-Manager.list_y)/Manager.__brick_size+Manager.row), int\
            ((x-Manager.list_x)/Manager.__brick_size+Manager.col)

    @staticmethod
    def draw_brick(x, y):
        brick = Element(Element.brick, (x, y))
        Manager.screen.blit(brick.image, brick.rect)

    def draw_task(self, task_animal_num, which_animal, \
                  board_position=(400, 90), animal_position=(430, 35), txt_position=(455, 60)):
        """Draw task board"""
        txt_size = 24
        txt_color = (0, 0, 0)
        Board(Board.task_board, board_position).draw(self.screen)
        if which_animal == 6:
            task_animal = Element(Element.ice, animal_position)
        else:
            task_animal = Element(Element.animal[which_animal], animal_position)
        task_animal.image = pygame.transform.smoothscale(task_animal.image, (40, 40))
        task_animal.draw(self.screen)
        if which_animal == 6:
            if task_animal_num-self.ice_num <= 0:
                Board(Board.ok, (txt_position[0], txt_position[1]+15)).draw(self.screen)
            else:
                self.load_text(str(task_animal_num-self.ice_num), txt_position, txt_size, txt_color)
        else:
            if task_animal_num - self.animal_num[which_animal] <= 0:
                Board(Board.ok, (txt_position[0], txt_position[1]+15)).draw(self.screen)
            else:
                self.load_text(str(task_animal_num - self.animal_num[which_animal]), txt_position, txt_size, txt_color)

Because there are too many codes, I won't introduce them to you one by one. If you need the source code, you can write it privately!!!

An overall implementation interface:
Many children always encounter some problems and bottlenecks when learning python. They don't have a sense of direction and don't know where to start to improve. For this, I have sorted out some materials and hope to help them. You can add Python learning and communication skirt: 773162165

Well, today's game is for everyone here, Amway, what do not understand, you can comment below, you need to find the source code can be found Xiaobian yo, remember to pay attention to Xiaobian official account ha.

Topics: Python Programming Game Development pygame GUI