pygame-KidsCanCode系列jumpy-part4-弹跳
终于要到弹跳环节了,向上弹跳其实很简单,按下空格触发时,只要把y轴速度给一个向上的速度即可。
Player类,新加一个jump()方法:
def jump(self):
self.vel.y = -25
调用该方法,会使方块具有向上25px的速度,然后由于重力依然在起作用,所以二者结合,就会形成向上弹跳的效果。
然后在main.py中按空格键时,调用jump方法,为了更有趣味性,我们多加几个档板,而且为了简化代码,把档板的位置及长宽参数,都定义在settings.py中
# game options SIZE = WIDTH, HEIGHT = 320, 480
FPS = 60
DEBUG = False TITLE = "Jumpy!" # Player properties
PLAYER_ACC = 0.6
PLAYER_GRAVITY = 2
PLAYER_FRICTION = -0.06 # 档板列表
PLATFORM_LIST = [(0, HEIGHT - 30, WIDTH, 30),
(WIDTH / 2 - 50, HEIGHT * 0.75, 100, 15),
(WIDTH * 0.12, HEIGHT * 0.5, 60, 15),
(WIDTH * 0.65, 200, 80, 10),
(WIDTH * 0.5, 100, 50, 10)] # define color
BLACK = 0, 0, 0
WHITE = 255, 255, 255
RED = 255, 0, 0
GREEN = 0, 255, 0
BLUE = 0, 0, 255
YELLOW = 255, 255, 0
main.py内容如下:
from part_04.sprites import *
from part_04.settings import * class Game: def __init__(self):
pg.init()
pg.mixer.init()
self.screen = pg.display.set_mode(SIZE)
pg.display.set_caption(TITLE)
self.clock = pg.time.Clock()
self.running = True
self.playing = False def new(self):
self.all_sprites = pg.sprite.Group()
self.platforms = pg.sprite.Group()
self.player = Player(self)
self.all_sprites.add(self.player) # 多放几块档板
for plat in PLATFORM_LIST:
p = Platform(*plat)
self.all_sprites.add(p)
self.platforms.add(p) self.run() def run(self):
self.playing = True
while self.playing:
self.clock.tick(FPS)
self.events()
self.update()
self.draw() def update(self):
self.all_sprites.update()
hits = pg.sprite.spritecollide(self.player, self.platforms, False)
if hits:
self.player.pos.y = hits[0].rect.top
self.player.vel.y = 0 def events(self):
for event in pg.event.get():
if event.type == pg.QUIT:
if self.playing:
self.playing = False
self.running = False
if event.type == pg.KEYDOWN:
if event.key == pg.K_SPACE:
# 按空格键时,向上跳
self.player.jump() def draw(self):
self.screen.fill(BLACK)
self.all_sprites.draw(self.screen)
self.debug()
pg.display.flip() def debug(self):
if DEBUG:
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))
pg.draw.line(self.screen, WHITE, (0, HEIGHT / 2), (WIDTH, HEIGHT / 2), 1)
pg.draw.line(self.screen, WHITE, (WIDTH / 2, 0), (WIDTH / 2, HEIGHT), 1) def show_start_screen(self):
pass def show_go_screen(self):
pass g = Game()
g.show_start_screen()
while g.running:
g.new()
g.show_go_screen() pg.quit()
效果如下:

基本的弹跳实现了,但是有2个明显的问题:
1. 可以在空中,不借助任何档板的情况下,连环跳,这不太合理,比较贴近现实的预期效果应该是,只在在档板上,才允许起跳,不能凭空跳跃。
2. 向上跳时,如果上方有档板,永远不可能跳过档板,只要一接近档板,就自动吸附上去了(仔细看gif最后那段跳跃),这个看上去比较奇怪。
原因如下:
问题1,是因为jump方法中未作任何约束,不管什么时候调用,总是能获取向上的速度,可以改进为:检测方法是否站在档板上(仍然通过碰撞检测,方块站在档板上,肯定就发生了碰撞),只有站在档板上,调用jump时,才能获取向上的弹跳速度。
问题2,是因为main.py中,一直在检测碰撞,向上跳的过程中,如果头顶有档板,一碰到档板,代码逻辑就强制把方块固定在档板上了(即:认为方块落在档板上了)。改进方法:仅在下降过程中,才做碰撞检测。
调试后的sprites.py代码如下:
from part_04.settings import *
import pygame as pg
import math vec = pg.math.Vector2 class Player(pg.sprite.Sprite):
def __init__(self, game):
pg.sprite.Sprite.__init__(self)
# 初始化时,要把Game类的实例传过来
self.game = game
self.image = pg.Surface((30, 30))
self.image.fill(YELLOW)
self.rect = self.image.get_rect()
self.rect.center = WIDTH / 2, HEIGHT / 2
self.pos = self.rect.center
self.vel = vec(0, 0)
self.acc = vec(0, 0)
self.width = self.rect.width
self.height = self.rect.height def jump(self):
# 只有碰撞了,才能向上跳(即:只有Player站在档板上了,才能起跳)
hits = pg.sprite.spritecollide(self, self.game.platforms, False)
if hits:
self.vel.y = -22 def update(self):
self.acc = vec(0, PLAYER_GRAVITY)
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 self.acc.x += self.vel.x * PLAYER_FRICTION self.vel += self.acc
self.pos += self.vel if self.rect.left > WIDTH:
self.pos.x = 0 - self.width / 2
if self.rect.right < 0:
self.pos.x = WIDTH + self.width / 2 #
if math.fabs(self.rect.bottom - self.pos.y) >= 1:
self.rect.bottom = self.pos.y
self.rect.x = self.pos.x - self.width / 2 class Platform(pg.sprite.Sprite):
def __init__(self, x, y, w, h):
pg.sprite.Sprite.__init__(self)
self.image = pg.Surface((w, h))
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
main.py代码如下:
from part_04.sprites import *
from part_04.settings import * class Game: def __init__(self):
pg.init()
pg.mixer.init()
self.screen = pg.display.set_mode(SIZE)
pg.display.set_caption(TITLE)
self.clock = pg.time.Clock()
self.running = True
self.playing = False def new(self):
self.all_sprites = pg.sprite.Group()
self.platforms = pg.sprite.Group()
self.player = Player(self)
self.all_sprites.add(self.player) for plat in PLATFORM_LIST:
p = Platform(*plat)
self.all_sprites.add(p)
self.platforms.add(p) self.run() def run(self):
self.playing = True
while self.playing:
self.clock.tick(FPS)
self.events()
self.update()
self.draw() def update(self):
self.all_sprites.update()
# 只有向下落时,才做碰撞检测(防止向上跳时,被上方档板自动吸附)
if self.player.vel.y > 0:
hits = pg.sprite.spritecollide(self.player, self.platforms, False)
if hits:
self.player.pos.y = hits[0].rect.top
self.player.vel.y = 0 def events(self):
for event in pg.event.get():
if event.type == pg.QUIT:
if self.playing:
self.playing = False
self.running = False
if event.type == pg.KEYDOWN:
if event.key == pg.K_SPACE:
self.player.jump() def draw(self):
self.screen.fill(BLACK)
self.all_sprites.draw(self.screen)
self.debug()
pg.display.flip() def debug(self):
if DEBUG:
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))
pg.draw.line(self.screen, WHITE, (0, HEIGHT / 2), (WIDTH, HEIGHT / 2), 1)
pg.draw.line(self.screen, WHITE, (WIDTH / 2, 0), (WIDTH / 2, HEIGHT), 1) def show_start_screen(self):
pass def show_go_screen(self):
pass g = Game()
g.show_start_screen()
while g.running:
g.new()
g.show_go_screen() pg.quit()
效果如下:
pygame-KidsCanCode系列jumpy-part4-弹跳的更多相关文章
- [翻译]初识SQL Server 2005 Reporting Services Part 3
原文:[翻译]初识SQL Server 2005 Reporting Services Part 3 这是关于SSRS文章中四部分的第三部分.Part 1提供了一个创建基本报表的递阶教程.Part 2 ...
- pygame系列_原创百度随心听音乐播放器_完整版
程序名:PyMusic 解释:pygame+music 之前发布了自己写的小程序:百度随心听音乐播放器的一些效果图 你可以去到这里再次看看效果: pygame系列_百度随心听_完美的UI设计 这个程序 ...
- pygame系列
在接下来的blog中,会有一系列的文章来介绍关于pygame的内容,pygame系列偷自http://www.cnblogs.com/hongten/p/hongten_pygame_install. ...
- pygame 笔记-2 模仿超级玛丽的弹跳
在上一节的基础上,结合高中物理中的匀加速直线运动位移公式 ,就能做出类似超级玛丽的弹跳效果. import pygame pygame.init() win = pygame.display.set_ ...
- pygame系列_pygame安装
在接下来的blog中,会有一系列的文章来介绍关于pygame的内容,所以把标题设置为pygame系列 在这篇blog中,主要描述一下我们怎样来安装pygame 可能很多人像我一样,发现了pygame是 ...
- pygame系列_小球完全弹性碰撞游戏
之前做了一个基于python的tkinter的小球完全碰撞游戏: 今天利用业余时间,写了一个功能要强大一些的小球完全碰撞游戏: 游戏名称: 小球完全弹性碰撞游戏规则: 1.游戏初始化的时候,有5个不同 ...
- pygame系列_draw游戏画图
说到画图,pygame提供了一些很有用的方法进行draw画图. ''' pygame.draw.rect - draw a rectangle shape draw a rectangle shape ...
- pygame系列_mouse鼠标事件
pygame.mouse提供了一些方法获取鼠标设备当前的状态 ''' pygame.mouse.get_pressed - get the state of the mouse buttons get ...
- pygame系列_font游戏字体
在pygame游戏开发中,一个友好的UI中,漂亮的字体是少不了的 今天就给大伙带来有关pygame中字体的一些介绍说明 首先我们得判断一下我们的pygame中有没有font这个模块 1 if not ...
- pygame系列_游戏窗口显示策略
在这篇blog中,我将给出一个demo演示: 当我们按下键盘的‘f’键的时候,演示的窗口会切换到全屏显示和默认显示两种显示模式 并且在后台我们可以看到相关的信息输出: 上面给出了一个简单的例子,当然在 ...
随机推荐
- alpha冲刺6/10
目录 摘要 团队部分 个人部分 摘要 队名:小白吃 组长博客:hjj 作业博客:感恩节~ 团队部分 后敬甲(组长) 过去两天完成了哪些任务 文字描述 设计了拍照界面和图片上传界面 沟通了前端进度 接下 ...
- [转]启动tensorboard
https://vivekcek.wordpress.com/tag/tensorboard-windows/ Visualise Computational Graphs with Tensor ...
- C语言之指针变量
菜单导航 1.指针变量 2.指针和数组 3.常量指针和指向常量的指针 4.指针和字符串的关系 5.数组越界造成的访问不属于自己的内存空间现象 6.引用数据类型和基本数据类型,形参和实参 7.字符串和字 ...
- Hbase服务报错:splitting is non empty': Directory is not empty
Hbase版本:1.2.0-cdh5.14.0 报错内容: org.apache.hadoop.ipc.RemoteException(org.apache.hadoop.fs.PathIsNotEm ...
- Codeforces 915G Coprime Arrays 莫比乌斯反演 (看题解)
Coprime Arrays 啊,我感觉我更本不会莫比乌斯啊啊啊, 感觉每次都学不会, 我好菜啊. #include<bits/stdc++.h> #define LL long long ...
- Java基础总结01:JDK与JRE概述
1)JRE(Java Runtime Environment,Java运行时环境) 包括Java虚拟机(JVM Java Virtual Machine)和Java程序所需的核心类库等,如果想要运行一 ...
- 【python】异步IO
No1: 协程看上去也是子程序,但执行过程中,在子程序内部可中断,然后转而执行别的子程序,在适当的时候再返回来接着执行. 优势: 1.最大的优势就是协程极高的执行效率.因为子程序切换不是线程切换,而是 ...
- poj 2502 Subway【Dijkstra】
<题目链接> 题目大意: 某学生从家到学校之间有N(<200)条地铁,这个学生可以在任意站点上下车,无论何时都能赶上地铁,可以从一条地铁的任意一站到另一条地跌的任意一站,学生步行速度 ...
- Python库: PrettyTable 模块
一,PrettyTable简介 PrettyTable是python中的一个第三方库,可用来生成美观的ASCII格式的表格: 二,PrettyTable安装 使用PIP即可十分方便的安装PrettyT ...
- Android XML shape 标签使用详解(apk瘦身,减少内存好帮手)
Android XML shape 标签使用详解 一个android开发者肯定懂得使用 xml 定义一个 Drawable,比如定义一个 rect 或者 circle 作为一个 View 的背景. ...