NameError: name 'KEYDOWN' is not defined - python

I am new to programming with PyGame and I've made this code:
import sys, pygame
pygame.init()
size = width, height = 800, 600
speed = [2, 2]
black = 1, 1, 1
screen = pygame.display.set_mode(size)
ball = pygame.image.load("ball.bmp")
ballrect = ball.get_rect()
player1 = pygame.image.load("player1.png")
player1rect = player1.get_rect()
mod_x = mod_y = 0
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_W:
movex = 2
if event.key == K_S:
movex = -2
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
screen.fill(black)
screen.blit(ball, ballrect)
screen.blit(player1, player1rect)
pygame.display.flip()
But when I execute my code, I get this error:
File "C:\Users\User\Documents\Pong\pong.py", line 22, in <module>
elif event.type == KEYDOWN:
NameError: name 'KEYDOWN' is not defined
^
SyntaxError: invalid syntax
Please help me. I need it so much, I need an answer quick.

KEYDOWN isn't defined in your code. You can add this to the beginning:
from pygame.locals import *
Or you can do this:
elif event.type == pygame.KEYDOWN

Use this command while using pygame library
...
elif event.type == pygame.KEYDOWN
...

just change this piece, then it should work :)
elif event.type == KEYDOWN: CHANGE TO: elif event.type == pygame.KEYDOWN:

Related

Name 'event' can be undefined but event is clearly defined

I am trying to make a game from a tutorial I found on Youtube and then I come across this error that I cannot fix. I keep getting the error message: Name 'event' can be undefined. Can somebody help me? Thanks!
Here is my full code:
import pygame
from sys import exit
def display_score():
current_time = int(pygame.time.get_ticks() / 1000) - start_time
score_surf = test_font.render(f'{current_time}', False, (64, 64, 64))
score_rect = score_surf.get_rect(center=(400, 50))
screen.blit(score_surf, score_rect)
pygame.init()
screen = pygame.display.set_mode((800, 400))
pygame.display.set_caption('Runner')
clock = pygame.time.Clock()
test_font = pygame.font.Font('Pixeltype.ttf', 50)
game_active = True
start_time = 0
sky_surf = pygame.image.load('Sky.png').convert()
ground_surf = pygame.image.load('ground.png').convert()
snail_surf = pygame.image.load('snail1.png').convert_alpha()
snail_rect = snail_surf.get_rect(bottomright=(600, 300))
player_surf = pygame.image.load('player_walk_1.png').convert_alpha()
player_rect = player_surf.get_rect(midbottom=(80, 300))
player_gravity = 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if game_active:
if event.type == pygame.MOUSEBUTTONDOWN:
if player_rect.collidepoint(event.pos) and player_rect.bottom >= 300:
player_gravity = -20
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and player_rect.bottom >= 300:
player_gravity = -20
else:
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
game_active = True
start_time = int(pygame.time.get_ticks() / 1000)
if game_active:
screen.blit(sky_surf, (0, 0))
screen.blit(ground_surf, (0, 300))
display_score()
snail_rect.x -= 4
if snail_rect.right <= 0: snail_rect.left = 800
screen.blit(player_surf, player_rect)
# Player
player_gravity += 1
player_rect.y += player_gravity
if player_rect.bottom >= 300: player_rect.bottom = 300
screen.blit(snail_surf, snail_rect)
# Collision
if snail_rect.colliderect(player_rect):
game_active = False
else:
screen.fill((94, 129, 162))
pygame.display.update()
clock.tick(60)
It's quite clear I have the variable 'event' defined in the while loop using the get function.
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if game_active:
if event.type == pygame.MOUSEBUTTONDOWN:
if player_rect.collidepoint(event.pos) and player_rect.bottom >= 300:
player_gravity = -20
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and player_rect.bottom >= 300:
player_gravity = -20
else:
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
game_active = True
start_time = int(pygame.time.get_ticks() / 1000)
This is the snippet of the code where the problem is:
Basically, what this else statement is supposed to do is to restart the game when clicked space bar. But it doesn't work because apparently the name event is not defined.
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
The weird thing is, is that I am only getting the error message specifically for this line of code and not any other code that has event.type in it. I believe it has something to do with this else statement and that's why it is not working. I deleted this else statement to see what would happen and the error message went away but it still won't work.
I tried reformatting the code, changing things around, indenting and unindenting, and etc. I tried re-pasting pygame.event.get(): into the else statement. Nothing worked.

Traceback Error (Can Only Concatenate Tuple)

I've just started working with Python and I wanted to program a small game, where you can move a small character around with the w a s d keys, but this error keeps occurring:
Traceback (most recent call last):
File "/home/username/Desktop/Python-project/Game/Game.py", line 53, in <module>
x+=x_change
TypeError: can only concatenate tuple (not "int") to tuple
Here is my code:
import pygame
import os
pygame.init()
display_hight = 800
display_width = 1000
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
gameDisplay = pygame.display.set_mode((display_width,display_hight))
pygame.display.set_caption("ZOMPS")
clock = pygame.time.Clock()
mydir = os.path.dirname('/home/arne/Desktop/Python-project/Game/Demonsave.png')
demonImg = pygame.image.load(os.path.join(mydir,'Demonsave.png'))
demonImg = pygame.transform.scale(demonImg,(140,160))
def demon(x,y):
gameDisplay.blit(demonImg,(x,y))
x = (display_width*0,45)
y = (display_hight*0,8)
x_change=0
y_change=0
dead = False
while not dead:
for event in pygame.event.get():
if event.type == pygame.QUIT:
dead=True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
x_change-=5
elif event.key == pygame.K_d:
x_change+=5
elif event.key == pygame.K_w:
y_change-=5
elif event.key == pygame.K_s:
y_change+=5
if event.type == pygame.KEYUP:
if event.key == pygame.K_a or pygame.K_d:
x_change=0
elif event.key == pygame.K_w or pygame.K_s:
y_change=0
x+=x_change
y+=y_change
gameDisplay.fill(red)
demon(x,y)
pygame.display.update()
clock.tick(60)
pygame.quit()
quit()
Here x = (display_width*0,45), should be x = display_width * 0.45. Because by doing (display_width*0,45) you are creating a tuple like (0,45).

pygame - Key pressed

I am kinda stuck with a supposed to be simple code to check if the user has pressed "w" or "s".
Below you can see my code:
import pygame
pygame.init()
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN and event.key == pygame.K_w:
print('Forward')
elif event.type == pygame.KEYDOWN and event.key == pygame.K_s:
print('Backward')
Am I forgetting something here?
Thanks!
A window needs to be created to receive key presses, the following works.
import pygame
import sys
pygame.init()
pygame.display.set_mode((100, 100))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
print('Forward')
elif event.key == pygame.K_s:
print('Backward')
This is what seems to me the most simple and understandable way to do it:
import pygame
pygame.init()
pygame.display.set_mode((300, 300))
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
print('Forward')
elif event.key == pygame.K_s:
print('Backward')
Instead of using the sys.exit() method I prefer to just use pygame.quit()
it is no good to ask the gamer to keep hitting w to get the response. If you want to read the "pressed" state. You could consider the followings:
from pygame import *
import time
flag = False # The flag is essential.
DONE = False
screen = display.set_mode((500,500)) # 1180, 216
count=0
while not DONE:
event.pump() # process event queue
keys = key.get_pressed() # It gets the states of all keyboard keys.
#print("%d"%count,keys)
count+=1
if keys[ord('w')]: # And if the key is K_DOWN:
print("%d w down"%count)
if keys[ord('s')]: # And if the key is K_DOWN:
print("%d s down"%count)
time.sleep(0.1)
Try this:
import pygame
pygame.init()
key = pygame.key.get_pressed()
while True:
for event in pygame.event.get():
if event.type == KEYDOWN and event.key == pygame.K_w:
print('Forward')
elif event.type == KEYDOWN and event.key == pygame.K_s:
print('Backward')
Sample code to understand how key press events work.
import pygame
from pygame.locals import *
def main():
pygame.init()
pygame.display.set_caption("Move Box With Arrow Keys")
wndsize = (320, 240)
display = pygame.display.set_mode(wndsize)
x = 5
y = 5
black = (0, 0, 0)
white = (255, 255, 255)
rectpos = (x, y)
rectdim = (50, 50)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
x += 5
print("K_RIGHT")
if event.key == pygame.K_LEFT:
x -= 5
print("K_LEFT")
if event.key == pygame.K_UP:
y -= 5
print("K_UP")
if event.key == pygame.K_DOWN:
y += 5
print("K_DOWN")
# Don't allow coords below 0
if 0 > x:
x = 5
if 0 > y:
y = 5
# Don't allow overflow
if x + rectdim[0] > wndsize[0]:
x = wndsize[0] - rectdim[0] - 5
if y + rectdim[1] > wndsize[1]:
y = wndsize[1] - rectdim[1] - 5
rectpos = (x, y)
display.fill(white)
rect = pygame.draw.rect(display, black, ((rectpos), (rectdim)))
pygame.display.update()
main()
This might work:
from pygame import *
init()
if key.get_pressed()[K_w] == True:
print('Forwards')
if key.get_pressed()[K_s] == True:
print('Backwards')`

My character won't move in python

This is the code I used.
import pygame, sys
from pygame.locals import *
pygame.init()
def game():
width, height = 1000, 600
screen = pygame.display.set_mode((width,height))
pygame.display.set_caption('My game far now :P') #This command allows you make a title.
background=pygame.image.load('AE.jpg')
background = pygame.transform.scale(background, (width,height))
screen.blit(background, (0,0))
#Load target image and player
player = pygame.image.load('little.png')
player = pygame.transform.scale(player, (40,40))
px,py = width/2,height/2
screen.blit(player, (px,py))
movex = movey = 0
#Running of the game loop
while True:
screen.blit(background, (0,0))
#screen.blit(target,targetpos)
screen.blit(player, (px,py))
pygame.display.update()
#keyboard an/or mouse movements
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
elif event.type == pygame.KEYDOWN:
if event.key == K_RIGHT:
movex = 2
if event.key == K_LEFT:
movex = -2
if event.key == K_UP:
movey = -2
if event.key == K_DOWN:
movey = 2
elif event.type == pygame.KEYUP:
if event.key == K_RIGHT:
movex = 0
if event.key == K_LEFT:
movex = 0
if event.key == K_UP:
movey = 0
if event.key == K_DOWN:
movey = 0
px = px + movex
py = py + movey
#Python 's way of running the main routine
if __name__=='__main__':
game()
When I run the program it all starts right, the screen opens with background and player spawning in the middle of the screen, but when I try to move nothing happends, no errors nothing.
Would apriciate any help I can get :)
Thx for taking time to help me.
You seem to have code indentation problem in last two lines which may be causing the bug.
Your curent code is equivalent to this if code block:
elif event.type == pygame.KEYUP:
if event.key == K_RIGHT:
movex = 0
if event.key == K_LEFT:
movex = 0
if event.key == K_UP:
movey = 0
if event.key == K_DOWN # IF BLOCK STARTS
movey = 0
px = px + movex # THIS FALLS IN THE PREVIOUS IF BLOCK
py = py + movey
Correct code would be :
elif event.type == pygame.KEYUP:
if event.key == K_RIGHT:
movex = 0
if event.key == K_LEFT:
movex = 0
if event.key == K_UP:
movey = 0
if event.key == K_DOWN # IF BLOCK STARTS
movey = 0 #IF BLOCK ENDS
px = px + movex # NOW THIS IS OUT OF THE IF BLOCK
py = py + movey
Take this code, the movement is optimized. Useles code removed.
I hope you understand it ;)
import pygame, sys
from pygame.locals import *
pygame.init()
width, height = 1000, 600
screen = pygame.display.set_mode((width,height))
pygame.display.set_caption('My game far now :P')
background=pygame.image.load('AE.png')
background = pygame.transform.scale(background, (width,height))
player = pygame.image.load('little.png')
player = pygame.transform.scale(player, (40,40))
px,py = width/2,height/2
movex = movey = 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]: px -= 2
if keys[pygame.K_RIGHT]: px += 2
if keys[pygame.K_UP]: py -= 2
if keys[pygame.K_DOWN]: py += 2
screen.blit(background, (0,0))
screen.blit(player, (px,py))
pygame.display.update()
Two problems.
You don't render in your loop
You are updating the location only in the if statement.
fixed:
while True:
# input
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
elif event.type == pygame.KEYDOWN:
# ...snip...
# physics
px += movex
py += movey
# drawing
screen.blit(background, (0,0))
screen.blit(player, (px,py))
pygame.display.update()

Python-Pygame always crashing and Not Responding when running a module in IDLE

I'm quite new to Pygame or even Python, but i know that when something in the isn't right, it displays some text in the Python Shell telling you that there was some error. I've actually encountered many of them and this time, it finally runs and displays the window, but it does not respond. I know there might be some mistakes in my whole code so please feel free to correct me (and please, kindly explain since I'm still new to this stuff).
The code is below, but if it can help, if you'd ask for it, i'll see if i could post the file as well. Anyway, here's the codes:
#import Modules
import os, sys
import pygame
from pygame.locals import *
background_img="C:/Users/JM/Documents/Python/Pygame_Alpha/background_img.jpg"
cursor_img="C:/Users/JM/Documents/Python/Pygame_Alpha/pygameCursor.png"
def load_image(img_file, colorkey=None):
file_pathname = os.path.join("\Users\JM\Documents\Python\Pygame_Alpha",img_file)
try:
image = pygame.image.load(file_pathname).convert_alpha()
except pygame.error, message:
print "Can't load image:", file_pathname
raise SystemExit, message
image = image.convert()
if colorkey is not None:
if colorkey is -1:
colorkey = image.get_at((0,0))
image.set_colorkey(colorkey, RLEACCEL)
return image, image.get_rect()
#Main character's position and movements
char_x,char_y = 0,0
char_go_x,char_go_y = 0,0
#Main char class
class char(pygame.sprite.Sprite):
"""Main Character"""
def __init__(self):
pygame.sprite.Sprite.__init__(self)#call Sprite initializer
self.image, self.rect = load_image("char_img.png", -1)
self.jumping = 0
def update(self):
self.rect.midtop = char_x,char_y
if self.jumping == 1:
self.rect.move_ip(-35,-3)
def char_no_jump(self):
self.jumping = 0
pygame.init()
pygame.display.set_caption("pygame_Alpha")
screen = pygame.display.set_mode((800,480),0,32)
background = pygame.image.load(background_img).convert()
cursor = pygame.image.load(cursor_img).convert_alpha()
char = char()
clock = pygame.time.Clock()
millisec = clock.tick()
sec = millisec/1000.0
char_fall = sec*25
jump = sec*50
#blit the background
screen.blit(background,(0,0))
#Main Loop
while 1:
#Tell pygame not to exceed 60 FPS
clock.tick(60)
#Events
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
#Events triggered when a key/s is/are pressed
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
elif event.key == K_UP or event.key == K_w:
char.jumping = 1
elif event.key == K_DOWN or event.key == K_s:
char_go_y += 1
elif event.key == K_LEFT or event.key == K_a:
char_go_x -= 0.5
elif event.key == K_RIGHT or event.key == K_d:
char_go_x += 0.75
if char_x > 800:
char_x = 0
#Events triggered when a key/s is/are released
if event.type == KEYUP:
if event.key == K_UP or event.key == K_w:
char_go_y += 1
elif event.key == K_DOWN or event.key == K_s:
char_go_y = 0
elif event.key == K_LEFT or event.key == K_a:
char_go_x = 0
if char_x < 0:
char_x = 0
elif event.key == K_RIGHT or event.key == K_d:
char_go_x = 0
if char_x > 700:
char_x = 0
char.update()
while char_y < 200:
char_go_y += char_fall
if char_y > 200:
char_y = 200
#Update values of position of Main Char
char_x += char_go_x
char_y += char_go_y
#Position Variables of Cursor Image, setting its values equal to cursor pos, and blit it to screen
cursor_x,cursor_y = pygame.mouse.get_pos()
cursor_x -= cursor.get_width()/2
cursor_y -= cursor.get_height()/2
screen.blit(cursor,(cursor_x,cursor_y))
pygame.display.update()
Hmm...
while char_y < 200:
char_go_y += char_fall
Unless you have some interesting aliasing I'm not seeing, if char_y < 200 (which it should be at start, it will always be since you're updating char_go_y.
If that's not the issue, would still suggest adding some prints to figure out if it's getting through the loop or not.
is there any error message in idle when you run it? whenever the screen freezes you have something wrong, but its hard to pinpoint what without knowing the error messages. maybe it is trouble opening the picture, you should try putting .convert() at the end of your picture file name, but that is just a guess.
Calling pygame.quit and sys.exit are probably causing issues. Normally you'd never need them in pygame.
Instead of:
#Main Loop
while 1:
#Tell pygame not to exceed 60 FPS
clock.tick(60)
#Events
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
Do this
#Main Loop
done = False
while not done:
clock.tick(60)
for event in pygame.event.get():
if event.type == QUIT:
done = True
if event.type == KEYDOWN:
if event.key == K_ESC:
done = True

Categories