2

你如何使这段代码工作?只需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 并在您按下键时从位置 (10, 10) 沿 x 方向发射一个火球A

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

问题:

  1. 为什么每次按 A 时火球飞得越来越快?

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

4

1 回答 1

3

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

pyglet.clock.schedule_interval(func = self.update, interval = 1/60.)
于 2012-06-27T09:04:57.543 回答