Use python to make small games - take shooting games as an example

This blog uses the Pygame library to create game windows and handle game logic.

1. Detailed explanation of the code:
 

Create a game window:
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Bee")

A game window named "Bee" is created, the size of the window is determined by the WIDTHand HEIGHTvariables.

The definition and recurring appearance of bees:
class Enemy():
    # 构造函数
    def __init__(self):
        self.img = pygame.image.load('bee.png')
        self.x = random.randint(200, 600)
        self.y = random.randint(50, 250)
        self.step = random.randint(2, 6)

    # 重置蜜蜂位置
    def reset(self):
        self.x = random.randint(200, 600)
        self.y = random.randint(50, 200)

enemies = []
for i in range(number_of_bee):
    enemies.append(Enemy())

A class named is defined Enemyand each bee object has an image, x-coordinate, y-coordinate and step size. Cycles of bees appear in enemiesthe list with random initial positions.

Display bees and handle collisions:
def show_bee():
    for e in enemies:
        screen.blit(e.img, (e.x, e.y))
        e.x += e.step
        if e.x > 736 or e.x < 0:
            e.step *= -1
            e.y += 40
            if e.y >= 450:
                over, over_rect = init_item('game over.jpg', 0, 0)
                txt_restart, txt_restart_rect = show_text("Restart", 300, 300, 32)
                screen.blit(over, over_rect)  ##显示gameover图片
                screen.blit(txt_restart, txt_restart_rect)
                quit()

This function displays the bee and causes it to change direction and move downward when it reaches the edge of the window. If the bee's y coordinate exceeds 450, the game ends, the "game over" picture and "Restart" text are displayed, and then the game exits.

Define shooter:
play_x = 400
play_y = 500
shoot, shoot_rect = init_item('fighter.png', play_x, play_y)
playerstep = 0

The shooter's initial position is defined and the shooter's image is loaded.

The definition of bullets and handling collisions:
class bullet():
    def __init__(self):
        self.img = pygame.image.load('bullet1.png')
        self.x = play_x
        self.y = play_y + 10
        self.step = 10  # 子弹移动的速度

    def hit(self):
        for e in enemies:
            if distance(self.x, self.y, e.x, e.y) < 30:
                bullets.remove(self)
                e.reset()

bullets = []

def show_bullets():
    for b in bullets:
        screen.blit(b.img, (b.x, b.y))
        b.hit()
        b.y -= b.step
        if b.y < 0:
            bullets.remove(b)

This code defines bulletclasses so that each bullet object has an image, x coordinate, y coordinate, and velocity. In the bullet's hit()method, check whether the bullet collides with the bee. If so, remove the bullet and regenerate the bee. show_bullets()Function to display bullets and remove them when they exit the window.

Function that calculates the distance between two points:
def distance(bx, by, ex, ey):
    a = bx - ex
    b = by - ey
    return math.sqrt(a * a + b * b)

This function is used to calculate the distance between two points, where bxand byrepresents the coordinates of the bullet, exand eyrepresents the coordinates of the bee.

Play background music:
pygame.mixer.music.load('背景音乐.mp3')  # 导入音乐
pygame.mixer.music.play(loops=-1)  # 循环播放

This code loads music named "Background Music.mp3" and sets it to loop.

Main game loop:
clock = pygame.time.Clock()  ##用来设定窗口的刷新频率
while True:
    clock.tick(60)  ##每秒执行60次
    screen.fill((0, 0, 0))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT:
                playerstep = 5
            elif event.key == pygame.K_LEFT:
                playerstep = -5
            elif event.key == pygame.K_SPACE:
                bullets.append(bullet())

        if event.type == pygame.KEYUP:
            playerstep = 0
    screen.blit(shoot, (play_x, play_y))
    play_x += playerstep
    if play_x > 736:
        play_x = 736
    if play_x < 0:
        play_x = 0
    show_bee()
    show_bullets()
    pygame.display.flip()

This is the main loop of the game. The game will perform the following steps in each loop:

Finally, the game will continuously repeat the above steps in the main loop to realize the cyclic appearance of bees, control of the shooter, and collision detection between bullets and bees.

  • Set the window refresh frequency to 60 frames.
  • Fill the window background with black.
  • Handle events, including key events and exit events.
  • Moves the shooter's position based on key events and adds a new bullet object to bulletsthe list if the space bar is pressed.
  • Displays an image of the shooter, moves the shooter's position based on key events, making it move left and right within the window, and constraining it to not exceed the window boundaries.
  • Call show_bee()the function to display the bee and handle the collision between the bee and the window boundary and the collision between the bee and the bullet.
  • Call show_bullets()the function to display the bullet and handle the collision of the bullet with the window boundary and the collision of the bullet with the bee.
  • Use pygame.display.flip()method to update the entire game window.

    2. Complete code display:

    import pygame
    import sys
    import random
    import math
    
    WIDTH = 800
    HEIGHT = 600
    
    
    def pygame_1():
        global event, e
        pygame.init()
        screen = pygame.display.set_mode((WIDTH, HEIGHT))
        pygame.display.set_caption("Bee")
        ##蜜蜂:
        number_of_bee = 6
        ##显示分数
        txt_score, txt_score_rect = show_text("Score:0", 40, 20, 20)
        score = 0
    
        ##蜜蜂的循环出现
        class Enemy():
            def __init__(self):
                self.img = pygame.image.load('bee.png')
                self.x = random.randint(200, 600)
                self.y = random.randint(50, 250)
                self.step = random.randint(2, 6)
    
            def reset(self):
                self.x = random.randint(200, 600)
                self.y = random.randint(50, 200)
    
        enemies = []
        for i in range(number_of_bee):
            enemies.append(Enemy())
    
        def show_bee():
            for e in enemies:
                screen.blit(e.img, (e.x, e.y))
                e.x += e.step
                if e.x > 736 or e.x < 0:
                    e.step *= -1
                    e.y += 40
                    if e.y >= 450:
                        over, over_rect = init_item('game over.jpg', 0, 0)
                        txt_restart, txt_restart_rect = show_text("Restart", 300, 300, 32)
                        screen.blit(over, over_rect)  ##显示gameover图片
                        screen.blit(txt_restart, txt_restart_rect)
                        quit()
    
    
        ##射击器
        play_x = 400
        play_y = 500
        shoot, shoot_rect = init_item('fighter.png', play_x, play_y)
        playerstep = 0
    
        ##子弹
        class bullet():
            def __init__(self):
                self.img = pygame.image.load('bullet1.png')
                self.x = play_x
                self.y = play_y + 10
                self.step = 10  # 子弹移动的速度
    
            def hit(self):
                for e in enemies:
                    if distance(self.x, self.y, e.x, e.y) < 30:
                        bullets.remove(self)
                        e.reset()
    
    
        bullets = []
    
        def show_bullets():
            for b in bullets:
                screen.blit(b.img, (b.x, b.y))
                b.hit()
                b.y -= b.step
                if b.y < 0:
                    bullets.remove(b)
    
        def distance(bx, by, ex, ey):
            a = bx - ex
            b = by - ey
            return math.sqrt(a * a + b * b)
    
        pygame.mixer.music.load('背景音乐.mp3')  # 导入音乐
        pygame.mixer.music.play(loops=-1)  # 循环播放
        clock = pygame.time.Clock()  ##用来设定窗口的刷新频率
        while True:
            clock.tick(60)  ##每秒执行60次
            screen.fill((0, 0, 0))
    
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    exit()
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_RIGHT:
                        playerstep = 5
                    elif event.key == pygame.K_LEFT:
                        playerstep = -5
                    elif event.key == pygame.K_SPACE:
                        bullets.append(bullet())
    
                if event.type == pygame.KEYUP:
                    playerstep = 0
            screen.blit(shoot, (play_x, play_y))
            play_x += playerstep
            if play_x > 736:
                play_x = 736
            if play_x < 0:
                play_x = 0
            show_bee()
            show_bullets()
            pygame.display.flip()
    
    
    def init_item(img_path, pos_x, pos_y):
        ##显示图片
        item = pygame.image.load(img_path)
        item_rect = pygame.Rect((pos_x, pos_y, 0, 0))
        item_rect.size = item.get_size()
        return item, item_rect
    
    
    def show_text(txt, pos_x, pos_y, fontsize=12):
        ##设定显示文本信息
        font = pygame.font.Font(None, fontsize)
        text = font.render(txt, True, (255, 0, 0))
        text_rect = text.get_rect()
        text_rect.centerx = pos_x
        text_rect.centery = pos_y
        return text, text_rect
    
    
    if __name__ == "__main__":
        pygame_1()
    

    3. Video demonstration:
     

    Use python to make small games - taking shooting games as an example

Guess you like

Origin blog.csdn.net/weixin_64890968/article/details/131844496