1

I have a basic snake game movement system with Pygame:

clock = pygame.time.Clock()
if timer == MOVE_TICK_INTERVAL:
    timer = 0
    move_snake()

timer += 1 clock.tick(MAX_FPS)

The issue is that the higher MAX_FPS is, the faster timer iterates and thus the faster the snake moves. I'm aware of using some form of delta_time variable to calibrate and adjust the velocity of an object moving continuously but I don't know how to implement this method with discrete, grid-based movement.

In short, I want to move my snake the same amount of units in a direction every interval with frame rate considered but I don't want to modify said distance.

Scene
  • 123
  • 5

1 Answers1

1

It's fairly straightforward to convert this to use the real-time clock. The PyGame time object has a get_ticks() member function which returns a continuously updating count of milliseconds. It's quite handy for timing objects in games.

Basing your movement on a number of milliseconds makes the updating completely independent of the frame rate. So if your FPS drops a fraction because the device needs to do something in the background, the movement is still constant.

MOVE_TICK_INTERVAL = 300   # milliseconds between player movements
next_move_at       = 0     # time in future when player move occurrs

clock = pygame.time.Clock()

in main loop

time_now_ms = pygame.time.get_ticks()

is it time to move the player?

if ( time_now_ms > next_move_at ): new_move_at = time_now_ms + MOVE_TICK_INTERVAL # future time of next move move_snake()

clock.tick(MAX_FPS)

Kingsley
  • 121
  • 2