When Blinka isn't jumping, she's happily slithering along. In the code, this is accomplished by quickly switching between two Blinka sprites: one where she is sitting in her usual coiled position and the second where her neck is outstretched. 

Blinka slithers whenever the snake state is True. This state tracks whether or not Blinka is jumping. If you remember back to Blinka's tilegrid setup, her tilegrid is two tiles wide. As a result, the second square, or index 1, of blinka_grid is set to be EMPTY when Blinka is slithering.

#  if Blinka is slithering...
if snake:
  #  Blinka default location
  blinka_grid.y = 32
  #  empty 2nd tile so that the jump sprite can be shown using
  #  the same tilegrid
  blinka_grid[1] = EMPTY

To switch back and forth between the two sprites, you could use time.sleep(x) to alternate between displaying the sprites with a delay. However, doing this actually delays the entire loop and slows everything down.

To get around this, you can use time.monotonic() to count time and change sprites after a certain amount of time has passed; in this case 0.15 seconds. 

Every 0.15 seconds, Blinka's sprite is updated. The variable b holds the sprite index, alternating between 1 and 2 or BLINKA_1 and BLINKA_2.

slither is reset each time to hold time.monotonic() to be able to compare to the current time.monotonic() count.

#  every .15 seconds Blinka's slither sprite changes
  #  so that her slithering is animated
  #  b holds tilegrid position to display correct sprite
  if (slither + 0.15) < time.monotonic():
    blinka_grid[0] = b
    b += 1
    slither = time.monotonic()
    if b > 2:
      b = 1

This guide was first published on Jul 01, 2020. It was last updated on Jul 01, 2020.

This page (Animate Blinka) was last updated on Aug 02, 2021.

Text editor powered by tinymce.