A.J.
A.J.

Reputation: 89

How can i do a for loop with seconds/milliseconds using pygame?

I'm trying to make a snake game, and am having a little trouble getting the snake to move correctly. When i run this code he does go across the screen. but i cant get the display to update every {}'s .

I was wondering if there was a way to set up a for loop like this:

for seconds in { idk}:
    pygame.display.update()
    self.x += self.speed

import pygame
import time
pygame.init()

## creates window
win = pygame.display.set_mode((1000, 1000))
## gives titale to window
pygame.display.set_caption("Snake attempt")

class Character():
    def __init__(self, height= 40, width = 40,x = 50,y= 50,speed = 20):
            self.height = height
        self.width = width
        self.x = x
        self.y = y
        self.speed = 20
    def create(self):
    ## rect(draw on, ( colors) (pos.x , pos.y . width, height))
        pygame.draw.rect(win, (255,0, 0) , (self.x, self.y, 
self.width, self.height))
        pygame.display.update()
    def movement(self):
        self.x += self.speed
        pygame.display.update()


game_on = True
game_off = False

player = Character()

while game_on:
    pygame.time.delay(100)

## gives all events that happen while Game_on = True

        for event in pygame.event.get():

        if event.type == pygame.QUIT:
            pygame.quit()

## call on sys.exit()Caracter class         
    player.create()
    player.movement()

Basically i just want the player to move across the screen by so many spaces every how ever many seconds. while having the display refresh every time

Upvotes: 2

Views: 298

Answers (1)

J_H
J_H

Reputation: 20435

You already have a perfectly nice event loop with 100ms delay. Don't create any additional delay loops.

This runs ten times per second:

    player.movement()

Whatever speed or behavior you want to produce, should happen within that method. You will see the behavior evolving over time due to the method being repeatedly called, ten times a second.

And as furas helpfully points out, there's no need for .update() within the create method, better to defer it until movement is complete.

Note that what's visible on-screen for 100ms is the previous position, before advancing x.

Upvotes: 1

Related Questions