How would I detect NO KEY PRESS / No Input in Python?

Viewed 634

I am making a simple box moving "game" to learn the pygame import, but I would like to set the box back to gray after there are no keys pressed.

import pygame
from pygame.locals import *
pygame.init()
width = 400
height = 400
screen = pygame.display.set_mode((width,height))
done = False
clock = pygame.time.Clock()
color = (150, 150, 150)
x = 0
y = 0
while not done:
    for event in pygame.event.get():
            if event.type == pygame.QUIT:
                    done = True
            if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                    is_blue = not is_blue

    pressed = pygame.key.get_pressed()
    if pressed[pygame.K_UP] or pressed[pygame.K_w] and y > 0:
        y -= 3
        color = (0,0,255)
    if pressed[pygame.K_DOWN] or pressed[pygame.K_s] and y+60 < height: #Adding 60 because height of block = 60
        y += 3
        color = (255,255,0)
    if pressed[pygame.K_LEFT] or pressed[pygame.K_a] and x > 0:
        x -= 3
        color = (0,255,0)
    if pressed[pygame.K_RIGHT] or pressed[pygame.K_d] and x+60 < width: #Adding 60 because width of block = 60
        x += 3
        color = (255,0,0)
    screen.fill((0, 0, 0))
    pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60))

    pygame.display.flip()
    clock.tick(60)
1 Answers

Just add the set of the color=(150,150,150) inside the while loop(: Put it as the first line inside the loop.

Related