0

I have a quick question to ask - why is it so that the rect is still moving even if the key is no longer pressed? (I'm new to pygame, please have patience with me :D) Thank you

import pygame as pg

pg.init()
clock = pg.time.Clock()
clock.tick(30)
HEIGHT, WIDTH = 400, 400


class Clovik(pg.sprite.Sprite):
    def __init__(self):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.Surface((20, 20))
        self.image.fill((162, 38, 0))
        self.rect = self.image.get_rect()
        self.rect.center = ((HEIGHT / 2, WIDTH / 2))

    def update(self):
        keys = pg.key.get_pressed()
        if keys[pg.K_DOWN]:
            self.rect.y += 2




screen = pg.display.set_mode((HEIGHT, WIDTH))
running = True
all_sprites = pg.sprite.Group()
p = Clovik()
all_sprites.add(p)

while running:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            running = False

    all_sprites.update()
    screen.fill((100, 250, 0))
    all_sprites.draw(screen)
    pg.display.flip()
Kronos
  • 55
  • 4

2 Answers2

1

Actually the rectangle stops when the key is released, but your game runs much too fast. You have to invoke clock.tick(30) in the main application loop:

while running:
    clock.tick(30)

    # [...]

See pygame.time.Clock / tick():

This method should be called once per frame. It will compute how many milliseconds have passed since the previous call. [...]

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
0

Good question. When you press a key it is "Down" for multiple cycles. You need an event handler. Try an experiment. Replace:

    if keys[pg.K_DOWN]:
        self.rect.y += 2

with:

    if keys[pg.K_DOWN]:
        print("Down")

You'll see that each time you press the Key, multiple prints happen, but stop when you stop pressing down.

You can either use a variable to keep track of the state of your key (when it changes), or use an event handler.

    for event in pygame.event.get():
        # handle key press
        if event.type == pygame.KEYDOWN:
Rabbid76
  • 202,892
  • 27
  • 131
  • 174
wchasec
  • 16
  • 2
  • 1
    Please read the question: *" why is it so that the rect is still moving **even if the key is no longer pressed**?"- This answer doesn't answer the question. – Rabbid76 Aug 02 '20 at 17:04