python - Pyglet:火球射击游戏,每当我按下指定的键时,火球就会不断加速,而不是保持恒定速度

标签 python pyglet

如何使这段代码工作?只需安装 pyglet 并将 "fireball.png" 更改为存储在将此代码保存到文件的目录中的图像名称。

import pyglet

class Fireball(pyglet.sprite.Sprite):
    def __init__(self, batch):
        pyglet.sprite.Sprite.__init__(self, pyglet.resource.image("fireball.png"))
        # replace "fireball.png" with your own image stored in dir of fireball.py
        self.x =  10 # Initial x coordinate of the fireball
        self.y =  10 # Initial y coordinate of the fireball

class Game(pyglet.window.Window):
    def __init__(self):
        pyglet.window.Window.__init__(self, width = 315, height = 220)
        self.batch_draw = pyglet.graphics.Batch()
        self.fps_display = pyglet.clock.ClockDisplay()
        self.fireball = []

    def on_draw(self):
        self.clear()
        self.fps_display.draw()
        self.batch_draw.draw()
        if len(self.fireball) != 0:             # Allow drawing of multiple
            for i in range(len(self.fireball)): # fireballs on screen
                self.fireball[i].draw()         # at the same time

    def on_key_press(self, symbol, modifiers):
        if symbol == pyglet.window.key.A:
            self.fireball.append(Fireball(batch = self.batch_draw))
            pyglet.clock.schedule_interval(func = self.update, interval = 1/60.)
            print "The 'A' key was pressed"

    def update(self, interval):
        for i in range(len(self.fireball)):
            self.fireball[i].x += 1 # why do fireballs get faster and faster?

if __name__ == "__main__":
    window = Game()
    pyglet.app.run()

此代码创建一个黑色背景屏幕,其中显示 fps,并且每当您按下 A 键时,就会从位置 (10, 10) 沿 x 方向发射火球。

您会注意到,您发射的火球越多,所有火球开始移动的速度就越快。

问题:

  1. 为什么每次我按 A 时,火球就会移动得越来越快?

  2. 如何阻止每次按 A 时火球加速?

最佳答案

火球变得越来越快,因为每次按 A 时,都会向调度程序添加另一个 self.update 调用。因此,每次调用 self.update 的次数都会越来越多,从而导致位置的更新次数越来越多。要解决此问题,请将下面的行移至 __init__()

pyglet.clock.schedule_interval(func = self.update, interval = 1/60.)

关于python - Pyglet:火球射击游戏,每当我按下指定的键时,火球就会不断加速,而不是保持恒定速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11222677/

相关文章:

Python Mypy 属性错误

python-3.x - 在Pyglet(Raspberry Pi 4B,Raspbian)中播放音频时听不到声音

python - 鼠洞 : 'scipy.spatial.transform.rotation.Rotation' object has no attribute 'as_dcm'

python - Pyglet vertex_list_indexed 异常

python - 绘制 Sprite 时 openGL/Pyglet 纹理图形消失

python - SymPy 简化关系(不等式)表达式

python - 使用 Passengers 在 Dreamhost 上执行 Django 教程时遇到问题

python - 通过Pyglet在python中播放MP3文件时遇到问题

python - 使用 alphabeta TicTacToe 找到最佳着法

python - 操作字符串数组时为 "TypeError: only integer scalar arrays can be converted to a scalar index"