这段 Arcade MakeCode 的《弹跳桶游戏》使用 MicroPython 编写,是一个反应类得分游戏,玩家控制一个“桶”接住弹跳球以获得分数。玩家通过按下 A 或 B 键启动游戏,控制底部的“桶”左右移动,接住从上方弹跳下来的球。每接住一个球,根据其水平速度获得相应分数。游戏有时间限制,球也会不断反弹。
代码结构详解
1、精灵种类定义
python
- @namespace
-
- class SpriteKind:
-
- Ball = SpriteKind.create()
复制代码
创建一个新的精灵种类 Ball,用于标记弹跳球。
2、球的图像与列表初始化
python
- balls: List[Image] = []
-
- balls.append(img("""...""")) # 三种不同颜色的球
复制代码
创建三种不同颜色的球图像并存入列表,供后续随机选择。
3、玩家桶设置
python
- catcher = sprites.create(img("""..."""), SpriteKind.player)
-
- catcher.bottom = scene.screen_height() - 1
-
- catcher.set_stay_in_screen(True)
复制代码
创建玩家控制的“桶”精灵,放置在屏幕底部。
限制其不离开屏幕。
4、得分机制与碰撞处理
python
- def on_on_overlap(sprite, otherSprite):
-
- if sprite.x > otherSprite.x - 2 and sprite.x < otherSprite.x + 2:
-
- if sitting > 300:
-
- otherSprite.say("nope", 200)
-
- sprite.vy = sprite.vy * -2
-
- else:
-
- normalScore = abs(sprite.vx)
-
- otherSprite.say(str(normalScore), 200)
-
- info.set_score(info.score() + normalScore)
-
- sprite.destroy()
-
- elif sprite.x <= otherSprite.x:
-
- sprite.vx = sprite.vx * -2
-
- else:
-
- sprite.vx = sprite.vx * 2
复制代码
当球与桶重叠时:
如果桶长时间未移动(sitting > 300),球弹回并显示“nope”。
否则,根据球的水平速度 vx 计算得分。
球被销毁,得分显示在桶上方。
如果碰撞位置偏左或偏右,球会反弹或加速。
5、 倒计时结束处理
python
- def on_countdown_end():
-
- playing = False
-
- game.over(False)
复制代码
游戏时间结束后,游戏失败。
6、球销毁后自动补球
python
- def on_on_destroyed(sprite2):
-
- ...
-
- makeBouncer()
复制代码
当球被销毁时,从列表中移除,并补充一个新球。
7、控制器启动游戏
python
- def on_a_pressed():
-
- makeBouncer()
-
- info.start_countdown(60)
-
-
-
- def on_b_pressed():
-
- for i in range(10):
-
- makeBouncer()
-
- info.start_countdown(30)
复制代码
按 A 键:生成 1 个球,游戏时间 60 秒。
按 B 键:生成 10 个球,游戏时间 30 秒。
8、生成弹跳球函数
python
- def makeBouncer():
-
- ballChoice = randint(0, 2)
-
- bouncer = sprites.create(balls[ballChoice], SpriteKind.Ball)
-
- bouncer.set_flag(SpriteFlag.AUTO_DESTROY, True)
-
- bouncer.x = randint(0, scene.screen_width() / 4)
-
- bouncer.y = randint(0, scene.screen_height() / 3)
-
- bouncer.vx = 10 + ballChoice * 10
-
- bouncer.ay = 100
复制代码
随机选择一种球图像。
设置初始位置、速度和重力加速度。
9、玩家移动与静止检测
python
- def on_on_update():
-
- moveX = controller.dx()
-
- if moveX != 0:
-
- sitting = 0
-
- catcher.x += moveX
复制代码
玩家通过方向键移动桶。
如果桶移动了,sitting 重置为 0。
10、球反弹逻辑与静止计数
python
- def on_update_interval():
-
- for bouncer in bouncers:
-
- if bouncer.bottom >= scene.screen_height() and bouncer.vy > 0:
-
- bouncer.vy = bouncer.vy * -1
-
- bouncer.ay += 20
-
- sitting += 1
复制代码
每 10 毫秒检查球是否触底并反弹。
增加重力加速度使球更难接。
增加 sitting 计数,用于判断桶是否长时间未动。
|