Extending DesignerObjects

Note

You will need to upgrade Designer to at least version 0.5.0 to run this example!

This game demonstrates how to have:

  • A DesignerObject that has additional extra fields using inheritance

By inheriting from a constructor for a DesignerObject, you can add additional fields. One drawback is that when calling the constructor for your new class, you must pass in the field as a keyword argument. This just means you put the name of the field in front of the value you want to pass in.

In this example, we inherit MovingEmoji from Emoji so that we can add speed and direction fields. Now, we can freely access world.dragon.speed the same way we could previously access world.dragon.x or world.dragon.height.

from designer import *
from dataclasses import dataclass


# Note that we have (Emoji) after the name of the new class!
class MovingEmoji(Emoji):
    """ An emoji that can move in a direction at a speed """
    speed: int
    direction: int

@dataclass
class World:
    dragon: MovingEmoji

def create_dragon() -> MovingEmoji:
    """ Create a dragon with initial speed 1, moving to the right"""
    return MovingEmoji('🐉', speed=1, direction=0)

def create_world() -> World:
    """ Create a world with a dragon in it """
    return World(create_dragon())

def accelerate_dragon(world: World, key: str):
    """ Pressing up or down increases or decreases the dragon's speed """
    if key == 'up':
        world.dragon.speed += 1
    elif key == 'down':
        world.dragon.speed -= 1

def spin_dragon(world: World, key: str):
    """ Pressing left or right increases or decreases the dragon's direction """
    if key == 'left':
        world.dragon.direction -= 10
    elif key == 'right':
        world.dragon.direction += 10

def move_dragon(world: World):
    """ Move the dragon forward in its current direction based on its speed """
    move_forward(world.dragon, world.dragon.speed, world.dragon.direction)

when('starting', create_world)
when('updating', move_dragon)
when('typing', spin_dragon)
when('typing', accelerate_dragon)
start()