Do something every x (milli) seconds in pygame

I miss Python and Pygame, and my first thing I do is a simple Snake game. I try to make the snake move every 0.25 seconds. Here is the part of my code that changes:

while True:
    check_for_quit()

    clear_screen()

    draw_snake()
    draw_food()

    check_for_direction_change()

    move_snake() #How do I make it so that this loop runs at normal speed, but move_snake() only executes once every 0.25 seconds?

    pygame.display.update()

I want all other functions to execute normally, and move_snake () only every 0.25 seconds. I looked through it and found some answers, but all of them seem too complicated for those who make their first Python script.

Can I really get an example of what my code should look like, and not just tell me which function I need to use? Thank!

+1
source share
2 answers

, , Clock .

- x ms, pygame.time.set_timer():

pygame.time.set_timer()

set_timer(eventid, milliseconds) -> None

, , . , .

, . pygame.USEREVENT pygame.NUMEVENTS.

, 0.

, 250 :

import pygame
pygame.init()
screen = pygame.display.set_mode((300, 300))
player, dir, size = pygame.Rect(100,100,20,20), (0, 0), 20
MOVEEVENT, t, trail = pygame.USEREVENT+1, 250, []
pygame.time.set_timer(MOVEEVENT, t)
while True:
    keys = pygame.key.get_pressed()
    if keys[pygame.K_w]: dir = 0, -1
    if keys[pygame.K_a]: dir = -1, 0
    if keys[pygame.K_s]: dir = 0, 1
    if keys[pygame.K_d]: dir = 1, 0

    if pygame.event.get(pygame.QUIT): break
    for e in pygame.event.get():
        if e.type == MOVEEVENT: # is called every 't' milliseconds
            trail.append(player.inflate((-10, -10)))
            trail = trail[-5:]
            player.move_ip(*[v*size for v in dir])

    screen.fill((0,120,0))
    for t in trail:
        pygame.draw.rect(screen, (255,0,0), t)
    pygame.draw.rect(screen, (255,0,0), player)
    pygame.display.flip()

enter image description here

+3

Pygame, . , tick Clock tick. tick ( ) dt. dt , .

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

while True: # game loop
    # the following method returns the time since its last call in milliseconds
    # it is good practice to store it in a variable called 'dt'
    dt = clock.tick() 

    time_elapsed_since_last_action += dt
    # dt is measured in milliseconds, therefore 250 ms = 0.25 seconds
    if time_elapsed_since_last_action > 250:
        snake.action() # move the snake here
        time_elapsed_since_last_action = 0 # reset it to 0 so you can count again
0

Source: https://habr.com/ru/post/1664837/


All Articles