Python Forum
[PyGame] Input is not defined
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PyGame] Input is not defined
#1
Hello, I'm having a problem. I'm trying to make the "A" key do the basic movement of moving my player to the side. This error occurs that says that 'K_a' is not defined. I'm basing this entirely on my understanding, on the pygame DOC, and on examples from the internet, so I'm not really understanding what happened because in the pygame doc, the A key is written 'K_a'. Could someone explain it to me?

this function is in the player

def _inputs(self, events):
		if events.type == pygame.key.get_pressed()[K_a]:
			self.posX -= speed
this function is in the game

def _events(self):
		for event in pygame.event.get():
			self.player._inputs(event) # player Input (Player is in a player variable)
			if event.type == pygame.QUIT:
				self.running = False
Error:
NameError: name 'K_a' is not defined

Attached Files

Thumbnail(s)
       
Reply
#2
Without seeing all the code kind of hard to help. Here is a basic structure of moving objects in pygame.

import pygame

pygame.init()

window = pygame.display.set_mode((800,600))
clock = pygame.time.Clock()

running = True

class Player(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((50,50))
        self.image.fill('red')
        self.rect = self.image.get_rect()
        self.rect.centerx = 400
        self.rect.centery = 570
        self.speed = 0

    def update(self):
        self.speed = 0
        key = pygame.key.get_pressed()
        if key[pygame.K_a] or key[pygame.K_LEFT]:
            self.speed = -10

        if key[pygame.K_d] or key[pygame.K_RIGHT]:
            self.speed = 10

        self.rect.centerx += self.speed

        if self.rect.left <= 0:
            self.rect.left = 0
        if self.rect.right >= 800:
            self.rect.right = 800

sprites = pygame.sprite.Group()

player = Player()

sprites.add(player)

while running:
    window.fill('black')

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


    sprites.update()
    sprites.draw(window)
    pygame.display.update()
    clock.tick(60)

pygame.quit()
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#3
You don't have a variable called K_a. Did you intend to write the string "K_a"?

Never mind. See below.
Reply
#4
K_a is a variable in the pygame module, not your module.
import pygame

try:
    print(K_a)
except NameError as ex:
    print(ex)

print(pygame.K_a)
Output:
pygame 2.1.3.dev8 (SDL 2.0.22, Python 3.11.1) Hello from the pygame community. https://www.pygame.org/contribute.html name 'K_a' is not defined 97
Use pygame.K_a instead of K_a
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020