0

I'm making a very simple python Game and I've been trying to make it determine what action to do when key is pressed down or up, then move the toon to left or right accordingly, I've created a game class where I have specified a dictionary called pressed to return what key has been pressed when I do so, but whenerver i click on any key the game crashes and it returns this error :

Traceback (most recent call last):
  File "C:\Users\dddd\PycharmProjects\game\main.py", line 43, in <module>
    game.pressed[event.key]== True
KeyError: 1073741903

I've no clue why since I believe I fixed all indentation errors, plus the code says that the statement where i specify what to do in case key is pressed up or down, is not being used this is the code to my main class where that statement where i call the other class is :

import pygame
from game import Game

pygame.init()

# generate game window
pygame.display.set_caption("Space Under Attack")
screen = pygame.display.set_mode((1200, 600))
# import background
background = pygame.image.load('assets/resize.jpg').convert()
icon = pygame.image.load('assets/alienicon.png').convert()
# load game
game = Game()

running = True

# loop that will execute while the condition is true
while running:
    # apply background to the wind ow
    screen.blit(background, (0, 0))
    # apply image of player
    screen.blit(game.player.image, game.player.rect)
    # verify if gamer wants to go to right or left
    if game.pressed.get(pygame.K_RIGHT):
        game.player.move_right()
    elif game.pressed.get(pygame.K_LEFT):
        game.player.move_left()

    # apply icon to window
    pygame.display.set_icon(icon)
    # update screen
    pygame.display.flip()
    # if the gamer closes the window
    for event in pygame.event.get():
        # check if event is event of closing window
        if event.type == pygame.QUIT:
            running = False
            pygame.quit()
            print("Quitting the game...")
        elif event.type == pygame.KEYUP:
          game.pressed[event.key] == False
        elif event.type == pygame.KEYDOWN:
          game.pressed[event.key] == True

this is my game and player class :

import pygame
from player import Player


class Game:

    def __init__(self):
        self.pressed={}

        # generate player
        self.player = Player()

&

import pygame


class Player(pygame.sprite.Sprite):

    def __init__(self):
        super().__init__()
        self.health = 100
        self.max_health = 100
        self.attack = 10
        self.velocity = 5
        self.image = pygame.image.load('assets/monster.png').convert_alpha()
        self.rect = self.image.get_rect()
        self.rect.x = 400
        self.rect.y = 410

    def move_right(self):
        self.rect.x += self.velocity

    def move_left(self):
        self.rect.x -= self.velocity

0 Answers0