第七章:Python中pygame库的使用:开发小游戏

发布于:2025-03-30 ⋅ 阅读:(20) ⋅ 点赞:(0)

一、前言

   pygame是一个功能强大的Python库,用于创建各种游戏和多媒体应用程序。它基于SDL库,提供了丰富的模块来处理图形、声音、输入等,让游戏开发变得更加简单和有趣。本文将带你从零开始,逐步掌握pygame的基本用法,并通过一个小游戏的开发实例,加深对pygame的理解和应用。

二、pygame的安装与初始化

在开始之前,需要先安装pygame库。可以通过以下命令进行安装:

可以快捷键win+R再输入cmd回车可弹出命令行窗口。

pip install pygame

安装完成后,在代码中引入pygame模块:

import pygame

接下来,初始化pygame:

pygame.init()

这一步是必须的,它会初始化pygame内部的各种模块,为后续的操作做好准备。

三、创建游戏窗口

   pygame中,可以通过pygame.display.set_mode()函数来创建一个游戏窗口。该函数接受一个元组参数,指定窗口的宽度和高度。例如,创建一个800x600像素的窗口:

screen = pygame.display.set_mode((800, 600))

这里,screen是一个Surface对象,代表了游戏窗口的绘图表面。我们可以在上面绘制各种图形和图像。

同时,可以使用pygame.display.set_caption()函数为窗口设置标题:

pygame.display.set_caption("我的pygame游戏")

四、游戏主循环

游戏的核心是主循环,它不断更新游戏状态、处理用户输入、渲染画面等。一个典型的游戏主循环结构如下:

running = True
while running:
    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 更新游戏状态

    # 渲染画面
    screen.fill((0, 0, 0))  # 填充背景色
    # 绘制其他元素

    pygame.display.flip()  # 更新整个窗口

pygame.quit()

效果展示: 

 

   主循环中,首先通过pygame.event.get()获取所有事件,包括键盘、鼠标、窗口关闭等。然后根据这些事件更新游戏状态。接着,使用screen.fill()填充背景色,再绘制其他游戏元素。最后,通过pygame.display.flip()更新窗口显示。

五、pygame核心函数用法详解

下面以表格的形式梳理pygame中常用核心函数及其参数用法:

函数名 参数 参数说明
pygame.init() 初始化所有pygame模块
pygame.quit() 退出所有pygame模块
pygame.display.set_mode(size) size:元组,指定窗口宽度和高度 创建一个窗口或屏幕
pygame.display.set_caption(title) title:字符串,窗口标题 设置窗口标题
pygame.display.flip() 更新整个屏幕
pygame.draw.rect(surface, color, rect, width=0) surface:绘制矩形的Surface对象;color:矩形颜色,RGB元组;rect:矩形坐标和大小,元组形式(x, y, width, height)width:可选,矩形边框宽度,0为填充 绘制矩形
pygame.draw.circle(surface, color, center, radius, width=0) surface:绘制圆形的Surface对象;color:圆形颜色,RGB元组;center:圆形中心坐标,元组形式(x, y)radius:圆形半径;width:可选,圆形边框宽度,0为填充 绘制圆形
pygame.draw.line(surface, color, start_pos, end_pos, width=1) surface:绘制线条的Surface对象;color:线条颜色,RGB元组;start_pos:线条起始坐标,元组形式(x, y)end_pos:线条结束坐标,元组形式(x, y)width:可选,线条宽度 绘制直线
pygame.image.load(filename) filename:图像文件名 加载图像文件
screen.blit(image, position) image:要绘制的图像;position:图像左上角位置,元组形式(x, y) 将图像绘制到指定位置
pygame.display.update(rect=None) rect:可选,指定更新的矩形区域 更新窗口的指定区域
pygame.event.get() 获取所有发生的事件

六、开发趣味小游戏:接球游戏

   现在,我们结合以上知识,开发一个简单的趣味小游戏:接球游戏。游戏中,一个球从上方掉落,玩家需要控制一个平台在底部左右移动来接住球。

游戏代码:

​
​
import pygame
import random

# 初始化pygame
pygame.init()

# 设置窗口
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("接球游戏")

# 颜色定义
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
BLACK = (0, 0, 0)

# 球类
class Ball:
    def __init__(self):
        self.radius = 20
        self.x = random.randint(self.radius, screen_width - self.radius)
        self.y = self.radius
        self.speed_y = 3
        self.color = RED

    def update(self):
        self.y += self.speed_y

    def draw(self):
        pygame.draw.circle(screen, self.color, (self.x, self.y), self.radius)

    def is_caught(self, platform):
        if self.y + self.radius >= platform.y and self.y + self.radius <= platform.y + platform.height:
            if self.x >= platform.x and self.x <= platform.x + platform.width:
                return True
        return False

    def is_out(self):
        return self.y - self.radius > screen_height

# 平台类
class Platform:
    def __init__(self):
        self.width = 100
        self.height = 10
        self.x = (screen_width - self.width) // 2
        self.y = screen_height - 20
        self.speed = 5
        self.color = BLUE

    def move(self, direction):
        if direction == "left" and self.x > 0:
            self.x -= self.speed
        if direction == "right" and self.x + self.width < screen_width:
            self.x += self.speed

    def draw(self):
        pygame.draw.rect(screen, self.color, (self.x, self.y, self.width, self.height))

# 初始化游戏元素
platform = Platform()
balls = [Ball()]
score = 0
font = pygame.font.Font(None, 36)

# 游戏主循环
running = True
while running:
    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 获取按键状态
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        platform.move("left")
    if keys[pygame.K_RIGHT]:
        platform.move("right")

    # 更新球的状态
    for ball in balls[:]:
        ball.update()
        if ball.is_caught(platform):
            score += 1
            balls.remove(ball)
        elif ball.is_out():
            balls.remove(ball)

    # 随机添加新球
    if random.random() < 0.02:
        balls.append(Ball())

    # 绘制背景
    screen.fill(BLACK)

    # 绘制平台和球
    platform.draw()
    for ball in balls:
        ball.draw()

    # 绘制分数
    score_text = font.render(f"Score: {score}", True, WHITE)
    screen.blit(score_text, (10, 10))

    # 更新显示
    pygame.display.flip()

# 退出pygame
pygame.quit()

​

​

效果展示:

演示视频:

    放在资源绑定里。

游戏说明:

  • 平台控制:使用左右箭头键控制平台左右移动。

  • 球的掉落:球从上方随机位置掉落,玩家需要接住球来得分。

  • 游戏结束:当球掉出窗口底部时,游戏继续,但未接住的球会消失。

  • 分数统计:每接住一个球,分数加1。

七、总结

   通过本文,我们学习了pygame的基本用法,包括创建窗口、绘制图形、加载图像、处理输入、播放声音等。然后,通过开发一个简单的接球游戏,将这些知识应用到实际游戏中。pygame功能丰富,本文只是入门教程,更多高级功能如精灵、碰撞检测、动画等,可以进一步深入学习。希望本文能帮助你开启pygame游戏开发之旅!