Sprites¶
Now that we have the background, lets place a single sprite on the screen. Sprites are handled differently than the background, they can be placed anywhere we want on the sceen, not just tiled. We will create a varaible that holds a specific image from the image bank. We will also create a list that will hold all the sprites we want to paint onto the screen. We will take our ship variable and add it to this list.
Painting the entire screen each frame is not practical. The refresh rate just is not fast enough. Instead when the scene loads we will paint the background and then all the sprites on top of it. After that, each frame we will just redraw the sprites in the sprites list. This will let us have a much faster refesh rate. To accomplish this after we first paint the entire screen, we will create a loop, usually known as a gaming loop, that will keep running the code to update our sprites.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | #!/usr/bin/env python3
# Created by: Mr. Coxall
# Created on: Sep 2019
# This file is the "Space Aliens" game
# for CircuitPython
import ugame
import stage
def game_scene():
# this function is the game scene
# create a list fo rall the sprites to be held in
sprites = []
# an image bank for CircuitPython
image_bank_1 = stage.Bank.from_bmp16("./space_aliens.bmp")
# sets the background to image 0 in the bank
background = stage.Grid(image_bank_1, 160, 120)
# the ship sprite(the 5th image, starting to count at 0)
# will show up at location (72,56), which places it in middle of screen
ship = stage.Sprite(image_bank_1, 5, 72, 56)
# add the ship sprite to the sprite list
sprites.append(ship)
# create a stage for the background to show up on
# and set the frame rate to 60fps
game = stage.Stage(ugame.display, 60)
# set the layers, items show up in order, sprites and background behind
game.layers = sprites + [background]
# render the background and inital location of sprites list
# most likely you will only render background once per scene
# it is slow to draw
game.render_block()
# repeat forever, game loop
while True:
# get user input
# update game logic
# redraw sprites list
game.render_sprites(sprites)
game.tick() # wait until refresh rate finishes
if __name__ == "__main__":
game_scene()
|
Note
Full code and assets that can be copied onto PyBadge for this step can be found here.