pygame super detailed tutorial! ! A must-see framework for making python games!

One: Create a blank form that can be closed

#Import required modules

import sys
import pygame


# Define a general game management class

class GameManage:
    def __init__(self):
# 初始化
pygame.init()
# 建立一个大小为600*600的屏幕(大小根据需求设置)
self.screen = pygame.display.set_mode((600, 600))


# 定义一个check_eventMethod is used to block events and close the window when a "QUIT" event is detected

    def check_event(self):
    # 阻塞事件
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                # 关闭窗体
                pygame.quit()
                # 退出系统
                sys.exit()

# runThe method is the main loop of the game. It continuously calls the check_event method, plus flip(). Every time a new function is added, the canvas can be updated

    def run(self):
        while True:
            self.check_event()
            # 更新画布
            pygame.display.flip()


# Call gm instance


# 调用实例
gm = GameManage()
gm.run()

At this point, we can make a blank black form, as shown below.

Next, add a background to the black form.

 

2. Use sprite pictures to display the background and loop the background infinitely

# First define a basic elf class to manage all elves, and define a background elf class below.

class BaseSprite(pygame.sprite.Sprite):
    def __init__(self,name):
        super().__init__()
        self.image = pygame.image.load(name)
        self.rect = self.image.get_rect()

# Define a background sprite class

class BGSprite(BaseSprite):
    def __init__(self,name,top_left):
    super().__init__(name)
    self.rect.topleft = top_left


# The background class defines an update method for updating the background sprite

    def update(self):
        self.rect.top += 1
        if self.rect.top >= 700:
            self.rect.top = -700

# Define a background management class for adding background sprite pictures

class BGManage:
    def __init__(self,gm):
    # 调用GameManage的实例
    self.gm = gm
    # 建一个背景精灵组
    self.bg_group = pygame.sprite.Group()
    BGSprite("images/img.png",(0,0)).add(self.bg_group)
    BGSprite("images/img.png",(0,-700)).add(self.bg_group)

# Add an update method below the background management class to update and add the sprite picture group to the screen.

    def update(self):
        self.bg_group.update()
        self.bg_group.draw(self.gm.screen)

# Add an instance of the background management class under the def__init__ method of the game general management class for easy calling

self.bg_manage = BGManage(self)

# Add self.bg_manage.update() below the run method of GameManage to update the background

self.bg_manage.update()

# The picture below shows the running effect. You can see that the background screen is continuously updated in a loop.

# Since the frame rate is too fast, we can set the frame rate with it

 # Call the frame rate setting under def __init__ of GameManage

# 设置帧频
        self.clock = pygame.time.Clock()

# And set the frame rate size under run of GameManage

self.clock.tick(200)

3. Use sprite pictures to set up players, players can move

#Set the player sprite class

class PlayerSprite(BaseSprite):
    def __init__(self,name,center,gm):
        super().__init__(name)
        self.rect.center = center
        # 定义玩家速度
        self.speed = 1
        self.gm = gm
    def update(self):
        # 定义上下左右移动按键
        key_pressed = pygame.key.get_pressed()
        # and 后面设置边界
        if key_pressed[pygame.K_LEFT] and self.rect.left > 0:
            self.rect.left -= self.speed
        if key_pressed[pygame.K_RIGHT] and self.rect.right < 480:
            self.rect.right += self.speed
        if key_pressed[pygame.K_UP] and self.rect.top > 0:
            self.rect.top -= self.speed
        if key_pressed[pygame.K_DOWN] and self.rect.bottom < 700:
            self.rect.bottom += self.speed

#Set player management class

class PlayerManage:
    def __init__(self,gm):
        self.gm = gm
        self.player_group = pygame.sprite.Group()
        # 导入玩家图片
        self.player = PlayerSprite("images/me1.png",(240,650),self.gm)
        self.player.add(self.player_group)
    def update(self):
        self.player_group.update()
        self.player_group.draw(self.gm.screen)

# Add an instance of the player management class under the def__init__ method of the game general management class for easy calling

self.player_manage = PlayerManage(self)

# Add self.bg_manage.update() below the run method of GameManage to update the background

self.player_manage.update()

# Player aircraft is implemented as shown in the figure

 

4. Use elves to display props, and detect collisions between players and props

# Define prop class

class PropSprite(BaseSprite):
    def __init__(self,name,speed,type):
        super().__init__(name)
        self.rect.left = random.randint(0,480 - self.rect.width)
        self.rect.bottom = 0
        self.speed = 1
        self.type = type



    def update(self):
        self.rect.top += self.speed
        if self.rect.top > 700:
            self.kill()

#Define prop management class

class PropManage:
    def __init__(self,gm):
        self.gm = gm
        self.prop_group = pygame.sprite.Group()
        self.time_count = 5
    def generate(self):
        value = random.random()
        if value > 0.7:
            PropSprite("images/bomb_supply.png", 8, 1).add(self.prop_group)
        elif value > 0.4:
            PropSprite("images/bullet_supply.png", 8, 2).add(self.prop_group)
        else:
            PropSprite("images/life.png", 8, 3).add(self.prop_group)

    def update(self):
        self.time_count -= 0.1
        if self.time_count <= 0:
            self.time_count = 5
            self.generate()
        self.prop_group.update()
        self.prop_group.draw(self.gm.screen)

# Add an instance of the prop management class under the def__init__ method of the game general management class for easy calling

self.prop_manage = PropManage(self)

 #Add self.prop_manage.update() below the run method of GameManage to update the background

self.prop_manage.update()

# At this time, the prop class can appear on the screen, and then the collision between the player and the prop can be realized

# Define a check_collider method under game management to realize collision between players and props

    def check_collider(self):
        player_prop_collider = pygame.sprite.groupcollide(self.player_manage.player_group, self.prop_manage.prop_group,
                                                          False, True)

# Remember to call the check_collider function below run

self.check_collider()

5. Usage of UI (fonts, mouse click detection)

#Define a detection event

class Util:
    @staticmethod
    def click_check(sprite):
        """
        精灵的点击检测
        """
        if pygame.mouse.get_pressed()[0]:
            if sprite.rect.collidepoint(pygame.mouse.get_pos()):
                return True
        return False

# Define a UI wizard class

class UISprite(BaseSprite):
    """
    UI精灵类
    """

    def __init__(self, name, center):
        super().__init__(name)
        self.rect.center = center

#Define a UI management class

class UIManage:
    def __init__(self, gm):
        self.gm = gm
        # UI字体
        self.font = pygame.font.Font("font/font.ttf", 32)

        # 开始前UI元素
        self.ready_group = pygame.sprite.Group()
        self.begin_btn = UISprite("images/resume_nor.png", (300, 300))
        self.begin_btn.add(self.ready_group)

        # 游戏中UI元素
        self.score_surface = self.font.render(f"Score:{0}", True, "#FF4500")

        # 游戏结束UI元素
        self.end_group = pygame.sprite.Group()
        self.replay_btn = UISprite("images/again.png", (300, 300))
        self.replay_btn.add(self.end_group)

    def update(self):
        if self.gm.state == "ready":
            # print("更新未开始游戏UI")
            self.ready_group.draw(self.gm.screen)
            if Util.click_check(self.begin_btn):
                self.gm.state = "gaming"
        elif self.gm.state == "gaming":
            # print("更新游戏中UI")
            self.gm.screen.blit(self.score_surface, (350, 20))
        elif self.gm.state == "end":
            # print("更新游戏结束UI")

            self.end_group.draw(self.gm.screen)
            self.gm.prop_manage.prop_group.empty()
            if Util.click_check(self.replay_btn):
                self.gm.state = "gaming"
                self.gm.player_manage.birth()

# Add status in GameManage

# 定义初始化状态
        self.state = "ready"

#Add state after collision

    def check_collider(self):
        player_prop_collider = pygame.sprite.groupcollide(self.player_manage.player_group, self.prop_manage.prop_group,
                                                          True, False)
        if player_prop_collider:
            self.state = 'end'

# If status, update and draw

 if self.state == 'gaming':
                self.player_manage.update()
                self.prop_manage.update()

# The game state is realized as shown in the figure

 The above are some processes for making simple games in pygame. More functions can be achieved by adding classes.

Guess you like

Origin blog.csdn.net/weixin_49016330/article/details/132244883