I have a basic snake game movement system with Pygame:

clock = pygame.time.Clock()
    timer = 0

timer += 1

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.

  • \$\begingroup\$ Does this answer your question? When should I use a fixed or variable time step? \$\endgroup\$
    – Tyyppi_77
    Sep 22 '20 at 15:37
  • \$\begingroup\$ I'm having trouble relating the article in question with my issue. Potentially due to my lack of game design knowledge. \$\endgroup\$
    – Sean Xie
    Sep 22 '20 at 16:02
  • \$\begingroup\$ Your problem, at least to me, is a very fundamental question about the way a gameloop works, and is usually solved by either a fixed or a variable time step approach described in the linked question. \$\endgroup\$
    – Tyyppi_77
    Sep 22 '20 at 16:30

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


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.