简体   繁体   中英

Need Help in Python Variable updation (Pygame module)

I am trying to increase my speed variable in my pygame code. But as i run this piece of code the speed remain 0.1 (if i press UP key) and 0 (else case). I am unable to debug this. Any help in this would be greatly appreciated.

import pygame
speed = 0

screen = pygame.display.set_mode((400,400),0,32)
pygame.display.update()
clock = pygame.time.Clock()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            break 
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                if speed < 8 :
                    speed+=0.1
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_UP:
                if speed > 0 :
                    speed+= -0.1                    

    pygame.display.update()
    print(speed)
    clock.tick(60)   

pygame.quit()
quit()

You are confusing the event KEYUP with the UP key . The event KEYUP occurs when a key (any key) is released. The event KEYDOWN occurs when any key is pressed down.

In you code, this means that when the UP key is pressed down, the speed is set to 0.1, and when the UP key is release, the speed is set to 0.0.

If you want the speed to keep increasing, and decreasing when a key is released, you should use a timer, like so:

import pygame
speed = 0

screen = pygame.display.set_mode((400,400),0,32)
pygame.display.update()
clock = pygame.time.Clock()

pygame.time.set_timer(pygame.USEREVENT+1, 20)

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            break 
        if event.type == pygame.USEREVENT+1:
            if pygame.key.get_pressed()[pygame.K_UP]:
                if speed < 8 :
                    speed+=0.1
            else:
                if speed > 0.1:
                    speed+= -0.1
                else:
                    speed = 0.0

    pygame.display.update()
    print(speed)
    clock.tick(60)   

pygame.quit()
quit()

Adjust the delay in the set_timer to suit your taste. Also, note the addition to reset the speed to zero. Float operations are not completely exact, so repeated adding and substracting can lead to a 'zero' that is negative.

The way I've seen this done is:

keys_pressed = pygame.key.get_pressed()

if keys_pressed[pygame.K_UP]:
    if speed < 8:
        speed += 0.1
if keys_pressed[pygame.K_DOWN]:
    if speed > 0:
        speed += -0.1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM