Use python to make small games - take the pinball game as an example

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

1. Detailed explanation of the code:

First, pygame.init()initialize the Pygame library by calling:

pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Ball")

WIDTHThe sum here HEIGHTis the width and height of the window.

Next, initialize the images of the ball, pole, and score and their positions by calling init_itemfunctions:

ball, ball_rect = init_item('bar.gif', random.randint(50, WIDTH - 50), 0)
bar, bar_rect = init_item('ball.jpg', 200, 400)
txt_score, txt_score_rect = show_text("Score:0", 40, 20, 20)

init_itemThe function is used to load an image file and return an image object and a rectangle object. The rectangle object is used to control the position of the image.

Then set the initial speed of the ball, play background music, create timer objects and scoring variables:

ball_speed = [5, 5]
pygame.mixer.music.load('背景音乐.mp3')
pygame.mixer.music.play(loops=-1)
clock = pygame.time.Clock()
score = 0

ball_speedRepresents the speed of the ball in the horizontal and vertical directions.

Next is the main loop of the game, which is called pygame.event.get()to obtain user input events and process them. For example, control the movement of a pole by checking for key events:

for event in pygame.event.get():
    if event.type == pygame.QUIT:
        exit()
    if event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT:
        # 左移杆子
    if event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
        # 右移杆子
    if event.type == pygame.MOUSEBUTTONDOWN:
        # 处理鼠标点击事件

If the user clicks the close button of the window, exit()the function is called to exit the game.

Then update the position of the ball and handle the collision between the ball and the boundary and the collision between the ball and the pole:

ball_rect = ball_rect.move(ball_speed)

# 处理小球与边界的碰撞
if ball_rect.top < 0:
    ball_speed[1] = -ball_speed[1]
if ball_rect.right > WIDTH or ball_rect.left < 0:
    ball_speed[0] = -ball_speed[0]

# 处理小球与杆子的碰撞
if ball_rect.bottom > bar_rect.top and ball_rect.left > bar_rect.left and ball_rect.right < bar_rect.right:
    # 碰到杆子,反弹并增加分数
    ball_speed[1] = -ball_speed[1]
    score += 1

If the ball hits the upper and lower boundaries, the vertical speed is inverted to make it bounce; if the ball hits the left and right boundaries, the horizontal speed is inverted. If the ball collides with the pole, the vertical velocity is inverted to cause it to bounce and increase the score.

Then update the contents of the window based on the game state:

screen.fill((0, 0, 0))  # 清空窗口
if ball_rect.bottom > HEIGHT:
    # 游戏结束,显示游戏结束的界面
else:
    # 游戏未结束,显示小球、杆子和分数

If the ball exceeds the bottom of the window, the game ends and the game end interface is displayed. Otherwise, the ball, pole, and score are displayed.


2. Complete code display:

import pygame
import random

WIDTH = 640
HEIGHT = 480


def mainGame():
    # 显示窗口
    pygame.init()

    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    pygame.display.set_caption("Ball")

    ##球:
    ball, ball_rect = init_item('bar.gif', random.randint(50, WIDTH - 50), 0)
    ##杆子
    bar, bar_rect = init_item('ball.jpg', 200, 400)
    ##显示分数
    txt_score, txt_score_rect = show_text("Score:0", 40, 20, 20)

    ball_speed = [5, 5]  ##小球的运行速度
    pygame.mixer.music.load('背景音乐.mp3')  # 导入音乐
    pygame.mixer.music.play(loops=-1)  # 循环播放
    clock = pygame.time.Clock()  ##用来设定窗口的刷新频率
    ##记分的变量
    score = 0
    while True:
        clock.tick(60)  ##每秒执行60次

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()
            if event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT:
                if bar_rect.left > 3:
                    bar_rect = bar_rect.move([-80, 0])
                else:
                    bar_rect = bar_rect.move([0, 0])

            if event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
                if bar_rect.right < WIDTH - 3:
                    bar_rect = bar_rect.move([80, 0])
                else:
                    bar_rect = bar_rect.move([0, 0])

            if event.type == pygame.MOUSEBUTTONDOWN:
                if 250 <= event.pos[0] < 350 \
                        and 280 < event.pos[1] < 320:
                    mainGame()

        ball_rect = ball_rect.move(ball_speed)  ##球运动

        if ball_rect.top < 0:  ##遇到上下边界反弹
            ball_speed[1] = -ball_speed[1]
        if ball_rect.right > WIDTH or ball_rect.left < 0:  ##遇到左右边界反弹
            ball_speed[0] = -ball_speed[0]

        ##球和杆子的位置关系
        if ball_rect.bottom > bar_rect.top \
                and ball_rect.left > bar_rect.left \
                and ball_rect.right < bar_rect.right:  ##碰到杆子
            ball_speed[1] = -ball_speed[1]
            score += 1
            # 游戏增加难度
            if score % 5 == 0:
                ball_speed[1] *= 1.2
                ball_speed[0] *= 1.2
            txt_score, txt_score_rect = show_text("Score:" + str(score), 40, 20, 20)

        screen.fill((0, 0, 0))  ##把球停留过的位置颜色涂成黑色
        if ball_rect.bottom > HEIGHT:  ##本次游戏结束的条件
            ball_speed = [0, 0]
            over, over_rect = init_item('game over.jpg', 0, 0)
            txt_score_over, txt_score_rect_over = show_text("Score:" + str(score), screen.get_rect().centerx,
                                                            screen.get_rect().centery, 48)
            txt_restart, txt_restart_rect = show_text("Restart", 300, 300, 32)

            screen.blit(over, over_rect)  ##显示gameover图片
            screen.blit(txt_score_over, txt_score_rect_over)  ##结束的最终分数
            screen.blit(txt_restart, txt_restart_rect)  ##将分数显示在窗口左上脚
        else:
            screen.blit(ball, ball_rect)  ##把球显示在窗口中
            screen.blit(bar, bar_rect)  ##把杆子显示在窗口中
            screen.blit(txt_score, txt_score_rect)  ##将分数显示在窗口左上脚

        pygame.display.flip()


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


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


if __name__ == "__main__":
    mainGame()

3. Video demonstration:

Using python to make small games - taking the pinball game as an example_bilibili_bilibili

Guess you like

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