Weird Keyboard Interrupt error that happens after ending program

Question:

I’m able to run the game and all of the graphics work but I cant get keyboard input to work even though it worked briefly the first time I used it. Additionally, it only gives the error after I close the program. Other pygame features, such as closing the program with the red x also don’t work

import pygame
from essentials import *
import random

pygame.init()

screen_height = 640
screen_width = 640

win = pygame.display.set_mode((screen_width, screen_height))

pygame.display.set_caption("The Room")


# button class
class button:
    def __init__(self, color, x, y, width, height, text=''):
        self.color = color
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.text = text


player_width = 25
player_height = 25
player_pos_x = 600
player_pos_y = 600
vel = 40  # set to ten for release

keys = pygame.key.get_pressed()
run2 = True

while run2:
    win.fill((0, 0, 0))
    # the circle
    circle = pygame.draw.circle(win, GREEN, (50, 50), 5)
    # the player square
    player = pygame.draw.rect(win, RED, (player_pos_x, player_pos_y, player_width, player_height))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
    if keys[pygame.K_LEFT] and player_pos_x > vel:
        player_pos_x -= vel
    if keys[pygame.K_RIGHT] and player_pos_x < screen_width - player_width - vel:
        player_pos_x += vel
    if keys[pygame.K_UP] and player_pos_y > vel:
        player_pos_y -= vel
    if keys[pygame.K_DOWN] and player_pos_y < screen_height - player_height - vel:
        player_pos_y += vel
    if isOver(player, (50, 50)):
        print("Ding!")
    pygame.display.update()

isOver:

def isOver(self, pos):
    if pos[0] > self.x and pos[0] < self.x + self.width:
        if pos[1] > self.y and pos[1] < self.y + self.height:
            return True

*note that I am using Ubuntu and am fairly new to it

Asked By: Techi-Joe

||

Answers:

keys = pygame.key.get_pressed() returns the current state of the keys. You have to retrieve the state of the keys continuously in the main application loop, rather than once before the loop:

# keys = pygame.key.get_pressed() <--- REMOVE

while run2:

    keys = pygame.key.get_pressed() # <--- INSERT

Furthermore there is a type. In the condition of the while loop the variable run2 is evaluated, but in the event loop run is set:

Answered By: Rabbid76
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.