使用 Pyxel 入门 2D 游戏(第7部分):控制角色
发布: (2026年1月10日 GMT+8 23:00)
4 min read
原文: Dev.to
Source: Dev.to
Source: …
控制角色
在本章节中,我们检测 Space 键的按下,并翻转玩家的移动方向(左 ↔ 右)。这会带来更强的直接控制感。
设置初始移动方向
在 Game 构造函数中,我们随机选择飞船的初始方向(右 = 0° 或 左 = 180°),并设置其速度。
# main.py – inside Game.__init__()
import random
# Randomly choose left or right
deg = 0 if random.random() < 0.5 else 180
self.ship.move(SHIP_SPD, deg)
翻转 X 方法
在 BaseSprite 中添加 flip_x() 方法,用于反转 x 轴速度。
# sprite.py – added to BaseSprite class
def flip_x(self):
"""Flip movement in the x direction"""
self.vx *= -1
调用 flip_x() 会改变方向:
- 右 → 左
- 左 → 右
处理键盘输入
在 Game 类中创建 control_ship() 方法。它使用 pyxel.btnp() 检测 Space 键被按下的瞬间,然后翻转飞船的方向。
# main.py – added to Game class
def control_ship(self):
"""Handle input"""
if pyxel.btnp(pyxel.KEY_SPACE):
self.ship.flip_x() # Reverse movement
每次按下 Space 都会切换飞船的水平移动方向。
屏幕环绕逻辑
当飞船离开屏幕时,我们将其移动到对侧。可复用的 overlap_spr() 方法适用于任何精灵(例如后续的陨石)。
# main.py – added to Game class
def overlap_spr(self, spr):
"""Wrap sprite around screen edges"""
if spr.x < -spr.w:
spr.x = W
return
if W < spr.x:
spr.x = -spr.w
return
if spr.y < -spr.h:
spr.y = H
return
if H < spr.y:
spr.y = -spr.h
return
完整代码
下面是上述功能的完整实现。
# sprite.py
import pyxel
import math
import random
class BaseSprite:
def __init__(self, x, y, w=8, h=8):
self.x = x
self.y = y
self.w = w
self.h = h
self.vx = 0
self.vy = 0
def update(self):
self.x += self.vx
self.y += self.vy
def draw(self):
pass # Implemented in subclasses
def move(self, spd, deg):
rad = deg * math.pi / 180
self.vx = spd * math.cos(rad)
self.vy = spd * math.sin(rad)
def flip_x(self):
"""Flip movement in the x direction"""
self.vx *= -1
class ShipSprite(BaseSprite):
def __init__(self, x, y):
super().__init__(x, y)
def draw(self):
pyxel.blt(self.x, self.y, 0, 0, 0, self.w, self.h, 0)
# main.py
import pyxel
import random
import sprite
W, H = 160, 120
SHIP_SPD = 1.4 # Player speed
class Game:
def __init__(self):
self.score = 0
self.ship = sprite.ShipSprite(W / 2, H - 40)
# Random initial direction
deg = 0 if random.random() < 0.5 else 180
self.ship.move(SHIP_SPD, deg)
pyxel.init(W, H, title="Hello, Pyxel!!")
pyxel.load("shooter.pyxres")
pyxel.run(self.update, self.draw)
def update(self):
self.ship.update()
self.control_ship()
self.overlap_spr(self.ship)
def draw(self):
pyxel.cls(0)
pyxel.text(10, 10, f"SCORE:{self.score:04}", 12)
self.ship.draw()
def control_ship(self):
if pyxel.btnp(pyxel.KEY_SPACE):
self.ship.flip_x() # Reverse movement
def overlap_spr(self, spr):
if spr.x < -spr.w:
spr.x = W
return
if W < spr.x:
spr.x = -spr.w
return
if spr.y < -spr.h:
spr.y = H
return
if H < spr.y:
spr.y = -spr.h
return
def main():
Game()
if __name__ == "__main__":
main()
运行游戏后可以看到飞船水平移动;按下 Space 键会翻转其方向,并且在离开屏幕边缘时会自动环绕到另一侧。
下一章我们将介绍“让我们生成小行星”。*