pygame中的动画

这篇博客介绍了使用pygame库创建基本动画的方法,包括直线运动和斜线运动。通过实例代码展示了如何让图像在屏幕上从左到右移动,并探讨了如何实现从上到下的运动效果,当图像到达屏幕边缘时将其重置。
摘要由CSDN通过智能技术生成

最近沉迷pygame无法自拔,可是总是对动画这块有点懵逼

所以将这段学习到的代码记录下来

 

第一段:最基本的动画

import pygame
from pygame import *
from sys import exit

"""
一段最基本的动画代码
让飞机从屏幕左边飞到右边
"""
air_image = "D:\\workspace\\game\\data\\jet.png"

WIDTH, HEIGHT = 600, 480
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
air = pygame.image.load(air_image)
clock = pygame.time.Clock()

x = 0

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()
    screen.fill((255, 255, 255))
    screen.blit(air, (x, 100))
    # 设置FPS
    clock.tick(60)
    x += 2
    if x > 600:
        x -= 640
    pygame.display.update()

运行以后的效果图:

你可以找一张图片替换我这张图片,然后自己试一下,

想一下 这个是从到右运动,那么从上到下呢 我们只要保持x的值不变

让y的值一直变化就可以了,让y的值到达屏幕下方的时候把它归0

Pygame 是 Python 用于开发游戏的库,它可以用来创建和播放简单的动画。要使用 Pygame 播放动画,你需要做以下几步: 1. **导入模块**: 首先,确保已经安装了 pygame,如果没有,可以通过 `pip install pygame` 来安装。然后,在你的代码开始时导入必要的模块: ```python import pygame from pygame.locals import * ``` 2. **初始化 Pygame**: 在开始操作之前,你需要初始化 pygame: ```python pygame.init() ``` 3. **设置窗口**: 创建一个窗口,这是动画显示的地方: ```python screen = pygame.display.set_mode((width, height)) pygame.display.set_caption("Animation") ``` 4. **加载图片**: 使用 `pygame.image.load()` 函数加载动画序列的每一帧图片。例如,假设你有三个帧的图像文件(frame0.png, frame1.png, frame2.png): ```python images = [pygame.image.load('frame{}.png'.format(i)) for i in range(3)] ``` 5. **定时器或循环**: 创建一个循环来轮流显示每个帧,你可以使用 `pygame.time.wait()` 或者 `pygame.event.get()` 结合一个 while 循环来控制帧率。这可能涉及到使用一个变量来跟踪当前帧的位置: ```python current_frame = 0 clock = pygame.time.Clock() running = True while running: for event in pygame.event.get(): if event.type == QUIT: running = False screen.blit(images[current_frame], (0, 0)) pygame.display.flip() # 更新帧并检查是否到达最后一帧 current_frame = (current_frame + 1) % len(images) clock.tick(10) # 控制每秒多少帧 ``` 6. **关闭窗口**: 当游戏结束时,记得关闭窗口: ```python pygame.quit() ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值