current position:Home>Python game development, pyGame module, python takes you to realize a magic tower game from scratch (1)

Python game development, pyGame module, python takes you to realize a magic tower game from scratch (1)

2022-01-30 07:08:15 Dai mubai

Little knowledge , Great challenge ! This article is participating in “ A programmer must have a little knowledge ” Creative activities

Preface

The next few issues , I will take you hand in hand to realize the magic tower game from scratch ( It's the picture that old friends used to play when they were young

development tool

Python edition : 3.7.4

Related modules :

pygame modular ;

As well as some python Built in modules .

Environment building

install Python And add to environment variable ,pip Install the relevant modules required .

Introduction of the principle

First , We open the start interface of the original game , It turns out that :

 Start interface

To be specific , Our idea is to define a button class first , To simulate... In the original game “ Start the game ”,“ Game Description ” and “ Leave the game ” The functions of these three keys :

''' Button class '''
class Button(pygame.sprite.Sprite):
    def __init__(self, text, fontpath, fontsize, position, color_selected=(255, 0, 0), color_default=(255, 255, 255)):
        pygame.sprite.Sprite.__init__(self)
        self.text = text
        self.color_selected = color_selected
        self.color_default = color_default
        self.font = pygame.font.Font(fontpath, fontsize)
        self.font_render = self.font.render(text, True, color_default)
        self.rect = self.font_render.get_rect()
        self.rect.center = position
    ''' Update function :  Constantly update to detect whether the mouse is on the button '''
    def update(self):
        mouse_pos = pygame.mouse.get_pos()
        if self.rect.collidepoint(mouse_pos):
            self.font_render = self.font.render(self.text, True, self.color_selected)
        else:
            self.font_render = self.font.render(self.text, True, self.color_default)
    ''' Bind to the screen '''
    def draw(self, screen):
        screen.blit(self.font_render, self.rect)
 Copy code 

The main principle is to constantly detect whether the mouse is in the corresponding button area , If in , Change the color of the button ( Here it turns red ), Otherwise, the button uses the default color ( This is white ), To show the player that this is a clickable button .

then , Let's instantiate it three times to add these three buttons to the game start interface :

''' Game start screen '''
class StartGameInterface():
    def __init__(self, cfg):
        self.cfg = cfg
        self.play_btn = Button(' Start the game ', cfg.FONTPATH_CN, 50, (cfg.SCREENSIZE[0]//2, cfg.SCREENSIZE[1] - 400))
        self.intro_btn = Button(' Game Description ', cfg.FONTPATH_CN, 50, (cfg.SCREENSIZE[0]//2, cfg.SCREENSIZE[1] - 300))
        self.quit_btn = Button(' Leave the game ', cfg.FONTPATH_CN, 50, (cfg.SCREENSIZE[0]//2, cfg.SCREENSIZE[1] - 200))
    ''' External call '''
    def run(self, screen):
        #  Magic tower 
        font = pygame.font.Font(self.cfg.FONTPATH_CN, 80)
        font_render_cn = font.render(' Magic tower ', True, (255, 255, 255))
        rect_cn = font_render_cn.get_rect()
        rect_cn.center = self.cfg.SCREENSIZE[0] // 2, 200
        # Magic Tower
        font = pygame.font.Font(self.cfg.FONTPATH_EN, 80)
        font_render_en = font.render('Magic Tower', True, (255, 255, 255))
        rect_en = font_render_en.get_rect()
        rect_en.center = self.cfg.SCREENSIZE[0] // 2, 350
        # (Ver 1.12)
        font = pygame.font.Font(self.cfg.FONTPATH_CN, 40)
        font_render_version = font.render('(Ver 1.12)', True, (255, 255, 255))
        rect_ver = font_render_version.get_rect()
        rect_ver.center = self.cfg.SCREENSIZE[0] // 2, 400
        clock = pygame.time.Clock()
        while True:
            screen.fill((0, 0, 0))
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit(0)
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    if event.button == 1:
                        mouse_pos = pygame.mouse.get_pos()
                        if self.play_btn.rect.collidepoint(mouse_pos):
                            return True
                        elif self.quit_btn.rect.collidepoint(mouse_pos):
                            pygame.quit()
                            sys.exit(0)
                        elif self.intro_btn.rect.collidepoint(mouse_pos):
                            self.showgameintro(screen)
            for btn in [self.intro_btn, self.play_btn, self.quit_btn]:
                btn.update()
                btn.draw(screen)
            for fr, rect in zip([font_render_cn, font_render_en, font_render_version], [rect_cn, rect_en, rect_ver]):
                screen.blit(fr, rect)
            pygame.display.flip()
            clock.tick(self.cfg.FPS)
    ''' Show game Introduction '''
    def showgameintro(self, screen):
        font = pygame.font.Font(self.cfg.FONTPATH_CN, 20)
        font_renders = [
            font.render(' Magic Tower Games .', True, (255, 255, 255)),
            font.render(' The game material comes from : http://www.4399.com/flash/1749_1.htm.', True, (255, 255, 255)),
            font.render(' The background story of the game is that the princess is captured by the demon king ,  Warriors need to go to the magic tower to rescue them .', True, (255, 255, 255)),
            font.render('python Engineering lion .', True, (255, 255, 255)),
            font.render(' WeChat official account : python Engineering lion .', True, (255, 255, 255)),
            font.render(' copyright .', True, (255, 255, 255)),
        ]
        rects = [fr.get_rect() for fr in font_renders]
        for idx, rect in enumerate(rects):
            rect.center = self.cfg.SCREENSIZE[0] // 2, 50 * idx + 100
        clock = pygame.time.Clock()
        while True:
            screen.fill((0, 0, 0))
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit(0)
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    if event.button == 1:
                        mouse_pos = pygame.mouse.get_pos()
                        if self.play_btn.rect.collidepoint(mouse_pos):
                            return True
                        elif self.quit_btn.rect.collidepoint(mouse_pos):
                            pygame.quit()
                            sys.exit(0)
                        elif self.intro_btn.rect.collidepoint(mouse_pos):
                            return
            for btn in [self.intro_btn, self.play_btn, self.quit_btn]:
                btn.update()
                btn.draw(screen)
            for fr, rect in zip(font_renders, rects):
                screen.blit(fr, rect)
            pygame.display.flip()
            clock.tick(self.cfg.FPS)
 Copy code 

Other additional code mainly displays information such as the title of the game , All very simple. , I won't discuss it in detail , Meeting pygame I'm sure all my friends can write it out

Next , Let's see what the interface looks like after the game starts

 The interface after the game starts 1  The interface after the game starts 2

To be specific , We can first define the appearance of the game map in the text file , Similar to the figure below , Each number represents a game element :

 Game elements

I have also collected the game materials sorted out by others found on the Internet :

 Game material

therefore , We can write a game map file parsing class , Just like this. :

''' Game map analysis class '''
class MapParser():
    def __init__(self, blocksize, filepath, element_images, offset=(0, 0), **kwargs):
        self.count = 0
        self.switch_times = 15
        self.image_pointer = 0
        self.offset = offset
        self.blocksize = blocksize
        self.element_images = element_images
        self.map_matrix = self.parse(filepath)
    ''' analysis '''
    def parse(self, filepath):
        map_matrix = []
        with open(filepath, 'r') as fp:
            for line in fp.readlines():
                line = line.strip()
                if not line: continue
                map_matrix.append([c.strip() for c in line.split(',')])
        return map_matrix
    ''' Draw the game map to the screen '''
    def draw(self, screen):
        self.count += 1
        if self.count == self.switch_times:
            self.count = 0
            self.image_pointer = int(not self.image_pointer)
        for row_idx, row in enumerate(self.map_matrix):
            for col_idx, elem in enumerate(row):
                position = col_idx * self.blocksize + self.offset[0], row_idx * self.blocksize + self.offset[1]
                if elem+'.png' in self.element_images:
                    image = self.element_images[elem+'.png'][self.image_pointer]
                    image = pygame.transform.scale(image, (self.blocksize, self.blocksize))
                    screen.blit(image, position)
 Copy code 

among parse The function is actually to read the text file that stores the game map information , then draw The function is actually based on the read map information , Bind the corresponding game element picture to the map for display . in addition ,image_pointer,switch_times,count These three variables are used to achieve the flickering effect of scene elements in the original map , Just like this. :

 Flashing effect

According to this principle , We can easily draw the original map in all layers of the magic tower , The defined game map file is shown in the figure below :

 Game map file

The effect is shown below :

 effect 1

 effect 2

ok, To sum up , It is this issue that mainly realizes the initial picture of each layer in the magic tower game , For the complete source code of this issue, please refer to the introduction of your home page

This is the end of the article , Thanks for watching ,Python28 A series of small games , The next article shares Magic Tower Games (2)

To thank readers , I want to share with you some of my recent collections of programming dry goods , Give back to every reader , I hope I can help you .

Tomorrow I will take you to further reproduce the magic tower game , Interested partners can pay more attention to ~

copyright notice
author[Dai mubai],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201300708136735.html

Random recommended