通过游戏学Python系列之小兔要上天---手把手教你使用Pygame开发平台跳跃类游戏02之物体运动

简介: 通过游戏学Python系列之小兔要上天---手把手教你使用Pygame开发平台跳跃类游戏02之物体运动

配套视频教程


配套视频教程

本节最终效果:


image.png

一个游戏大致可以分为以下几个标准处理过程:

init() 初始化

new() 游戏初次进入(或主角挂了,重新开始时)

update() 游戏逻辑更新

events() 事件处理(响应键盘、鼠标等事件)

draw() 屏幕渲染绘制

show_start_screen() 游戏的启动画面

show_go_screen() 游戏结束时的画面

run() 游戏运行的循环入口

我们将上节的游戏模板,实现成一个Game类:

import pygame as pg
import random
from settings import *
from sprites import *
class Game:
    def __init__(self):
        # initialize game window, etc
        pg.init()
        pg.mixer.init()
        self.screen = pg.display.set_mode((WIDTH, HEIGHT))
        pg.display.set_caption(TITLE)
        self.clock = pg.time.Clock()
        self.running = True
    def new(self):
        # start a new game
        self.all_sprites = pg.sprite.Group()
        self.player = Player()
        self.all_sprites.add(self.player)
        self.run()
    def run(self):
        # Game Loop
        self.playing = True
        while self.playing:
            self.clock.tick(FPS)
            self.events()
            self.update()
            self.draw()
    # 为了方便观察pos,vel,acc这些变量,定义一个debug辅助函数
    def debug(self):
        font = pg.font.SysFont('Menlo', 25, True)
        pos_txt = font.render(
            'Pos:(' + str(round(self.player.pos.x, 2)) + "," + str(round(self.player.pos.y, 2)) + ")", 1, GREEN)
        vel_txt = font.render(
            'Vel:(' + str(round(self.player.vel.x, 2)) + "," + str(round(self.player.vel.y, 2)) + ")", 1, GREEN)
        acc_txt = font.render(
            'Acc:(' + str(round(self.player.acc.x, 2)) + "," + str(round(self.player.acc.y, 2)) + ")", 1, GREEN)
        self.screen.blit(pos_txt, (20, 10))
        self.screen.blit(vel_txt, (20, 40))
        self.screen.blit(acc_txt, (20, 70))
    def update(self):
        # Game Loop - Update
        self.all_sprites.update()
    def events(self):
        # Game Loop - events
        for event in pg.event.get():
            # check for closing window
            if event.type == pg.QUIT:
                if self.playing:
                    self.playing = False
                self.running = False
    def draw(self):
        # Game Loop - draw
        self.screen.fill(BLACK)
        self.all_sprites.draw(self.screen)
        # *after* drawing everything, flip the display
        self.debug()
        pg.display.flip()
    def show_start_screen(self):
        # game splash/start screen
        pass
    def show_go_screen(self):
        # game over/continue
        pass
g = Game()
g.show_start_screen()
while g.running:
    g.new()
    g.show_go_screen()
pg.quit()

注:有2个控制变量,running是控制pygame是否退出,而playing是游戏情节是否继续处理

(即:有可能游戏情况结束,比如:主角挂了,显示game over,但是pygame并不需要退出,可以选择重新开始)

settings.py

TITLE = "Rabbit jump on the sky!"
WIDTH = 480
HEIGHT = 600
FPS = 60
# Player properties
PLAYER_ACC = 0.5
PLAYER_FRICTION = -0.12
# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)

定义游戏的精灵(下面代码命名为sprites.py)

# Sprite classes for platform game
import pygame as pg
from settings import *
vec = pg.math.Vector2
class Player(pg.sprite.Sprite):
    def __init__(self):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.Surface((30, 40))
        self.image.fill(YELLOW)
        self.rect = self.image.get_rect()
        self.rect.center = (WIDTH / 2, HEIGHT / 2)
        self.pos = vec(WIDTH / 2, HEIGHT / 2)
        self.vel = vec(0, 0)
        self.acc = vec(0, 0)
    def update(self):
        self.acc = vec(0, 0)
        keys = pg.key.get_pressed()
        if keys[pg.K_LEFT]:
            self.acc.x = -PLAYER_ACC
        if keys[pg.K_RIGHT]:
            self.acc.x = PLAYER_ACC
        # apply friction
        self.acc += self.vel * PLAYER_FRICTION
        # equations of motion
        self.vel += self.acc
        self.pos += self.vel + 0.5 * self.acc
        # wrap around the sides of the screen
        if self.pos.x > WIDTH:
            self.pos.x = 0
        if self.pos.x < 0:
            self.pos.x = WIDTH
        self.rect.center = self.pos
  1. 在2D游戏中,会大量用到类似(x,y)的结构,pygame中已经把这种结构封装成了Vector2.
  2. 加速度的定义:单位时间内速度的变化量。在游戏中,单位时间就是每帧,所以每一帧,我们在速度self.vel(velocity的缩写)值上的改变即为加速度self.acc( acceleration的缩写),因为

v=a*t

这里t可以理解为1.

3.计算player新位移

self.pos += self.vel + 0.5 * self.acc

使用位移公式(t同样理解为1),1帧

s = v*t+1/2*a*t**2
  1. 摩擦力的效果

PLAYER_FRICTION = -0.12
self.acc += self.vel * PLAYER_FRICTION
self.vel += self.acc

等价于

self.acc = self.acc + self.vel * PLAYER_FRICTION
self.vel = self.vel + self.acc

也即:

PLAYER_FRICTION = -0.12
self.vel = self.vel + self.vel * PLAYER_FRICTION

摩擦力的效果,表现为阻碍物体运动,具体在代码中体现,只要想办法把速度减少一点点。以上代码实现了该效果。


image.png

可以通过调试观察到,方块向右,速度由0变正,再由于摩擦力的作用变为0;反之相反。方块向右,加速度由正及负最后变为0,反之相反。速度为正,方块位置增加(表现为向右移动);速度为负,方块位置减小(表现为向左移动);方块向右,加速度为正,使得速度变大(正的大),方块向左,加速度为负,使得速度变大(负的大,实际上是变小)

目录
相关文章
|
小程序 PHP 图形学
热门小游戏源码(Python+PHP)下载-微信小程序游戏源码Unity发实战指南​
本文详解如何结合Python、PHP与Unity开发并部署小游戏至微信小程序。涵盖技术选型、Pygame实战、PHP后端对接、Unity转换适配及性能优化,提供从原型到发布的完整指南,助力开发者快速上手并发布游戏。
|
存储 算法 区块链
从零实现Python扫雷游戏:完整开发指南与深度解析
扫雷作为Windows经典游戏,承载了许多人的童年回忆。本文将详细介绍如何使用Python和Tkinter库从零开始构建一个功能完整的扫雷游戏,涵盖游戏设计、算法实现和界面开发的全过程。
1067 1
|
人工智能 搜索推荐 数据可视化
用 Python 制作简单小游戏教程:手把手教你开发猜数字游戏
本教程详细讲解了用Python实现经典猜数字游戏的完整流程,涵盖从基础规则到高级功能的全方位开发。内容包括游戏逻辑设计、输入验证与错误处理、猜测次数统计、难度选择、彩色输出等核心功能,并提供完整代码示例。同时,介绍了开发环境搭建及调试方法,帮助初学者快速上手。最后还提出了图形界面、网络对战、成就系统等扩展方向,鼓励读者自主创新,打造个性化游戏版本。适合Python入门者实践与进阶学习。
1817 1
|
存储 算法 数据可视化
用Python开发猜数字游戏:从零开始的手把手教程
猜数字游戏是编程入门经典项目,涵盖变量、循环、条件判断等核心概念。玩家通过输入猜测电脑生成的随机数,程序给出提示直至猜中。项目从基础实现到功能扩展,逐步提升难度,适合各阶段Python学习者。
1400 0
|
存储 人工智能 算法
使用 Python 和 Pygame 制作游戏:第九章到第十章
使用 Python 和 Pygame 制作游戏:第九章到第十章
656 0
使用 Python 和 Pygame 制作游戏:第九章到第十章
|
Python
Python使用pygame播放MP3
Python使用pygame播放MP3
390 0
|
定位技术 Python
【python】pygame实现植物大战僵尸小游戏(附源码 有注释)
【python】pygame实现植物大战僵尸小游戏(附源码 有注释)
3668 1
|
JSON 开发工具 git
基于Python和pygame的植物大战僵尸游戏设计源码
本项目是基于Python和pygame开发的植物大战僵尸游戏,包含125个文件,如PNG图像、Python源码等,提供丰富的游戏开发学习素材。游戏设计源码可从提供的链接下载。关键词:Python游戏开发、pygame、植物大战僵尸、源码分享。
945 6

推荐镜像

更多