Python之pygame基础
发布日期:2021-05-24 00:56:01 浏览次数:23 分类:精选文章

本文共 2763 字,大约阅读时间需要 9 分钟。

Pygame基础教程

基础安装

安装 Pygame 类似于其他 Python 库的使用方法。打开终端,输入以下命令:

pip install pygame

安装完成后,你可以运行 Pygame 事件循环。


生成游戏窗口

打开 Pygame 后,初始化会产生两个窗口。根据需求设置窗口大小:

import pygame# 初始化 Pygamepygame.init()# 设置窗口大小,(宽度,高度)window_size = (800, 600)# 创建窗口并填充screen = pygame.display.set_mode(window_size)screen.fill((255, 255, 255)) # 屏幕初始颜色为白色# 显示屏幕内容pygame.display.flip()

运行以上代码,你可以看到一个黑色窗口。


添加图片

图片的加载和显示是一个基本操作,需要注意路径是否正确:

import pygame# 定义图片路径image_path = r'/path/to/your/image.png'# 加载图片 注意:需要确保路径正确image = pygame.image.load(image_path)# 将图片显示在屏幕上screen.blit(image, (0, 0))

加入声音

添加声音需要加载音乐文件并播放:

import pygame# 定义音乐文件路径music_path = r'/path/to/your/music.mp3'# 加载并播放音乐pygame.mixer.music.load(music_path)pygame.mixer.music.play()

改变颜色

使用内置颜色工具更方便,确保导入了正确的模块:

import pygamefrom pygame.color import THECOLORS# 调整屏幕颜色screen.fill(THECOLORS['red']) # 红色背景

添加图形

画形状需要使用对应的函数:

import pygamefrom pygame.color import THECOLORS# 绘制矩形pygame.draw.rect(screen, THECOLORS['blue'], [0, 0, 200, 400], 0)# 绘制圆形pygame.draw.circle(screen, THECOLORS['green'], (400, 300), 100, 10)

Pygame飞机基础

飞机跳跃

编写一个简单的飞机跳跃动画:

gRunning = Truewhile gRunning:    for event in pygame.event.get():        if event.type == pygame.QUIT:            gRunning = False    pygame.time.delay(1000) # 延迟1秒    # 显示飞机    screen.blit(img, (400, 300)) # 中心位置显示

melee quotes


多飞机模拟

创建多架飞机需要类和初始化函数:

class Plane:    def __init__(self, img, position, speed):        self.img = img        self.rect = img.get_rect()        self.rect.left, self.rect.top = position        self.speed = speed    def move(self):        self.rect = self.rect.move(self.speed)        # 改变速度方向        if self.rect.left < 0 or self.rect.right > 800:            self.speed = (-self.speed.x, self.speed.y)        if self.rect.top < 0 or self.rect.bottom > 600:            self.speed = (-self.speed.x, -self.speed.y)
import pygameimport randomfrom pygame.color import THECOLORS# 初始化pygame.init()window_size = (800, 600)screen = pygame.display.set_mode(window_size)screen.fill(THECOLORS['white'])# 飞机图片加载plane_img = pygame.image.load('plane.png')# 创建多架飞机planes = []for _ in range(5):    x = random.randint(0, 800 - plane_img.get_width())    y = random.randint(0, 600 - plane_img.get_height())    speed = (random.randint(-5, 5), random.randint(-5, 5))    planes.append(Plane(plane_img, (x, y), speed))# 开始游戏循环gRunning = Truewhile gRunning:    for event in pygame.event.get():        if event.type == pygame.QUIT:            gRunning = False    pygame.time.delay(20)    screen.fill(THECOLORS['white']) # 擦去上一帧的影像    # 更新飞机位置    for plane in planes:        plane.move()        # 绘制飞机        screen.blit(plane.img, plane.rect)    pygame.display.flip()pygame.quit()

常见问题

相对路径加载图片失败

确保图片路径是绝对路径:

python -u "路径/pygame项目/pygame.py"

错误信息通常来自路径不通或文件不存在。检查文件存在路径是否正确。


希望以上内容能对你有所帮助!

上一篇:Python图像处理之PIL
下一篇:Python Web基础之Django

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2025年04月17日 12时39分24秒