Classes and Delta Time

Re-implement the earlier “delta time” section, this time with classes.

Code

import arcade


class MyGame(arcade.Window):
    def __init__(self, width, height, title, bg_color):
        super().__init__(width, height, title)
        arcade.set_background_color(bg_color)
        self.width = width
        self.height = height
        self.title = title
        self.position = 0

    def on_draw(self):
        arcade.start_render()
        y = self.height / 2
        message = self.title + ': ' + str(self.position)
        arcade.draw_text(message, self.position, y, arcade.color.BLACK, 12)

    def update(self, delta_time):
        self.position += 1


def main():
    game1 = MyGame(600, 600, 'Drawing Example', arcade.color.WHEAT)
    game1.position = 100
    arcade.run()


if __name__ == '__main__':
    main()

Analysis

  1. Instead of arcade.schedule, we use a method called update
  2. Arcade calls this method every tick
  3. We add another instance attribute named self.position
  4. This is the x coordinate for the text
  5. Every “frame”, we change the value of the position, then redraw
  6. This makes the text move
  7. Like on_draw, arcade.Window has a special method update
  8. Unlike drawing, this is for working on your game data
  9. That’s the workflow – modify the game data, then on the next “tick”, redraw
  10. We also show how to change an instance attribute, game.position = 10

Exercises

  1. Have the initial starting position be 20 instead of 10.
  2. Move by 5 pixels on each animation instead of 1.

Quiz