Player not moving in pygame; no error messages - python

I created this program and when I run it the player is not moving. I checked and everything is right. Just in case you need it I am using python 3.8.6. Can you please help me? Here is my code.
# Game Loop
running = True
while running:
screen.fill((128, 20, 128))
for event in pygame.event.get():
player(playerX, playerY)
pygame.display.update()
# Movment
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
player_x_change -= 10
if event.key == pygame.K_d:
player_x_change += 10
if event.key == pygame.K_w:
player_y_change -= 10
if event.key == pygame.K_s:
player_y_change += 10
if event.type == pygame.KEYUP:
if event.key == pygame.K_a:
player_x_change = 0
if event.key == pygame.K_d:
player_x_change = 0
playerX += player_x_change
playerY += player_y_change
# Close the game
if event.type == pygame.QUIT:
running = False

It's probably just an indentation error (perhaps pasting to the question), but none of your events are being handled because of the if event.type clauses are not inside the for event loop.
Simply fixing this indentation alleviates this.
The next problem is that you calculate the player_x_change and player_y_change, but never apply the amounts to playerX and playerY.
Since these changes only happen when pygame.KEYDOWN is received, it's easy to simply add this inside the event handler:
# Movment
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
player_x_change -= 10
elif event.key == pygame.K_d:
player_x_change += 10
elif event.key == pygame.K_w:
player_y_change -= 10
elif event.key == pygame.K_s:
player_y_change += 10
# Move the player
playerX += player_x_change
playerY += player_y_change
Note the use of if .. elif. If the event is one particular type, it cannot possibly be another type too (at the same time). This means it's not necessary to keep re-checking the type. Using elif ("else if") helps with these checks, by stopping the check once a match is found. It is more efficient.
Final code:
import pygame
# Window size
WINDOW_WIDTH = 400
WINDOW_HEIGHT = 400
WINDOW_SURFACE = pygame.HWSURFACE|pygame.DOUBLEBUF
BACKGROUND = (128, 20, 128)
### initialisation
pygame.init()
pygame.mixer.init()
pygame.display.set_caption("Not Moving")
# Game Loop
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
# Close the game
if event.type == pygame.QUIT:
running = False
# Movment
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
player_x_change -= 10
elif event.key == pygame.K_d:
player_x_change += 10
elif event.key == pygame.K_w:
player_y_change -= 10
elif event.key == pygame.K_s:
player_y_change += 10
# Move the player
playerX += player_x_change
playerY += player_y_change
# DON'T REALLY NEED THIS
#elif event.type == pygame.KEYUP:
# if event.key == pygame.K_a:
# player_x_change = 0
# elif event.key == pygame.K_d:
# player_x_change = 0
# Re-draw the screen
screen.fill( BACKGROUND )
player(playerX, playerY)
pygame.display.update()
clock.tick(60) # limit the re-fresh rate to save electricity
pygame.quit()
I also added a frame-rate limiter with a pygame.time.Clock() object, just to save some CPU.

I was able to fix the problem now, if anyone wants the code here it is. :) It turns out I put the "close program" code too early and it doesn't work until the close button is pressed. So my player did move, but only for a second.
# Game Loop
running = True
while running:
if event.type == pygame.QUIT:
running = False
# if keystroke is pressed check whether its right or left
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -5
if event.key == pygame.K_RIGHT:
playerX_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
playerX += playerX_change
if playerX <= 0:
playerX = 0
elif playerX >= 736:
playerX = 736

Related

key.event confusion // pygame.K_a doesn't work

I'm new in this python industry, when i press 'd' my character should go right, but this isn t hapening, same thing to the 'a'. When I change K_a and K_d with K_LEFT and K_RIGHT it works, my character is moving well, but if I wanna make the character move with 'a' and 'd', it doesn't work, what's wrong with my code:
import pygame
import sys
import os
pygame.init()
screen = pygame.display.set_mode((1366,768))
pygame.display.set_caption("Adventure in the Woods")
icon = pygame.image.load('tree.png')
pygame.display.set_icon(icon)
#Player
playerImg = pygame.image.load('ninja.png')
playerX = 100
playerY = 650
velocity = 0.1
run = True
while run:
screen.fill( (9, 66, 2) )
screen.blit(playerImg, (playerX,playerY) )
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
print('a')
playerX -= velocity
if event.key == pygame.K_d:
print('d')
playerX += velocity
pygame.display.update()
Problem Insight
The problem lies in the scope of your if event.type == pygame.KEYDOWN: ... as it should be within the for-loop for event in pygame.event.get(): ... :
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN: #<-------------- From here
if event.key == pygame.K_a:
print('a')
playerX -= velocity
if event.key == pygame.K_d:
print('d')
playerX += velocity #<-------------- to here
Solution
This can be fixed by indenting the code block starting from if event.type == pygame.KEYDOWN: ..., like so:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN: #<-------------- Now inside the for-loop
if event.key == pygame.K_a:
print('a')
playerX -= velocity
if event.key == pygame.K_d:
print('d')
playerX += velocity
Other Remarks
To be more familiar with python code structures and styles, review some of the fundamental syntaxes like Indentation by visiting the style guide # https://www.python.org/dev/peps/pep-0008/
Cheers!

why isnt event.type == pygame.KEYDOWN working [duplicate]

This question already has an answer here:
How to get if a key is pressed pygame [duplicate]
(1 answer)
Closed 1 year ago.
alright so I have been trying to start learning game development in the past couple days and I finally started working on a project. The problem is that for some reason my controls aren't working even when I made everything like it is supposed to be. Please help. (also this is the entire code because I dont know where I am wrong)
#instalize the game VERY IMPORTANT
pygame.init()
# this is the window
screen = pygame.display.set_mode((800, 600))
#title and icon
pygame.display.set_caption("Space invaders")
icon = pygame.image.load('pictures/ufo.png')
pygame.display.set_icon(icon)
#player
playerImg = pygame.image.load('pictures/player.png')
playerX = 370
playerY = 480
PlayerX_change = 0
def player(x,y):
screen.blit(playerImg, (x,y))
#game loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running= False
# if keystroke is pressed move right or left
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -0.1
if event.key == pygame.K_RIGHT:
playerX_change = 0.1
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0.1
#RGB
screen.fill((0, 0, 0))
playerX += PlayerX_change
player(playerX, playerY)
pygame.display.update()
It is a matter of Indentation. You cannot nest events:
unning = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running= False
# INDENTATION
#<--|
# if keystroke is pressed move right or left
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -0.1
if event.key == pygame.K_RIGHT:
playerX_change = 0.1
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0.1
# [...]
Your identation is not correct. I have corrected it and attached the code.
#instalize the game VERY IMPORTANT
pygame.init()
# this is the window
screen = pygame.display.set_mode((800, 600))
#title and icon
pygame.display.set_caption("Space invaders")
icon = pygame.image.load('pictures/ufo.png')
pygame.display.set_icon(icon)
#player
playerImg = pygame.image.load('pictures/player.png')
playerX = 370
playerY = 480
PlayerX_change = 0
def player(x,y):
screen.blit(playerImg, (x,y))
#game loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running= False
# if keystroke is pressed move right or left
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -0.1
if event.key == pygame.K_RIGHT:
playerX_change = 0.1
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0.1
#RGB
screen.fill((0, 0, 0))
playerX += PlayerX_change
player(playerX, playerY)
pygame.display.update()
Your indentation is incorrect
Try usinng this;
if event.type == pygame.QUIT:
running= False
# if keystroke is pressed move right or left
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -0.1
if event.key == pygame.K_RIGHT:
playerX_change = 0.1
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0.1
Also if you use event.KEYDOWN it not checks multiple keys
although you can use pygame.key.get_pressed()
Use:
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
code:

Pygame- Disabling a Key with pygame.event.set_blocked() crashes window and returns error

I tried to add jumping physics to my game but it is necessary that after the player jumps, the Jump-Key has to be disabled until the player lands again.
Now, there isn't any problem with the gravity, but if the player keeps holding K_UP he could fly forever and the he can fly in a paarabola as he should, so I need to disable jump until the character lands and the jump Loop loops out as expected.
I tried pygame.event.set_blocked(pygame.K_UP) but when I jump the window crashes and there is an error code: "pygame.event.set_blocked(pygame.K_UP) ValueError: event type out of range".
As I couldn't find anything about this command expect that it exists I probablay did an mistake in the Game-Loop using .block().
Here is the Game-Loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
#player1 buttons
if event.type == pygame.KEYDOWN:
#move
if event.key == pygame.K_LEFT:
playerX_change = -1
if event.key == pygame.K_RIGHT:
playerX_change = 1
#Jump
if event.key == pygame.K_UP:
playerY_change = -3
player_jump = True
pygame.event.set_blocked(pygame.K_UP)
if player_jump == True:
playerY_change += gravity
# for X player 1
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
#for Y player 1
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
if playerY == 900:
playerY_change = 0
player_jump = False
pygame.event.set_allowed(pygame.K_UP)
I'm new to Pygame (and programming in general) and treid a lot of things and this is the result, so maybe I have also unnecessary code in it. My problem is the part with pygame.event.set_blocked and pygame.event.set_allowed which I don't know how to use.
pygame.event.set_blocked cannot block a key, it can just block an event such as KEYDOWN or KEYUP.
Anyway, you don't have to "block" anything. Uses the Boolean state variable player_jump instead:
if not player_jump and event.key == pygame.K_UP:
playerY_change = -3
player_jump = True
playerY_change += gravity

K_SPACE none responsive

I am writing my first pygame script, but the K_SPACE event does not work. When the script is run, nothing happens when the space bar is pressed. I have changed K_SPACE to K_LEFT and K_LSHIFT and they work absolutely fine, so I don't think the error is in the code itself?
The Input is mid-way through the code but I wanted to include it all to ensure there were no issues above which were causing it.
Any ideas?
import pygame
import random
pygame.init()
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load('spaceship.png')
pygame.display.set_icon(icon)
background = pygame.image.load('space.jpg')
playerImg = pygame.image.load('battleship.png')
playerX = 370
playerY = 480
playerX_change = 0
enemy1Img = pygame.image.load('alien.png')
enemy1X = random.randint(0,800)
enemy1Y = random.randint(50,150)
enemy1X_change = 0.1
enemy1Y_change = 40
laserImg = pygame.image.load('laser.png')
laserX = 0
laserY = 480
laserX_change = 0
laserY_change = 0.5
laser_state = "ready"
def player(x, y):
screen.blit(playerImg, (playerX,playerY))
def enemy1(x, y):
screen.blit(enemy1Img, (enemy1X, enemy1Y))
def fire_laser(x, y):
global laser_state
laser_state = "fire"
screen.blit(laserImg, (x+30, y+10))
running = True
while running:
screen.fill((0, 0, 0))
screen.blit(background, (0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -0.1
elif event.key == pygame.K_RIGHT:
playerX_change = 0.1
elif event.key == pygame.K_SPACE:
if laser_state == 'ready':
laserX = playerX
fire_laser(laserX, laserY)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
playerX += playerX_change
if playerX <= 0:
playerX = 0
if playerX >= 736:
playerX = 736
enemy1X += enemy1X_change
if enemy1X <= 0:
enemy1X_change = 0.1
enemy1Y += enemy1Y_change
elif enemy1X >= 736:
enemy1X_change = -0.1
enemy1Y += enemy1Y_change
if laserY <= 0:
laserY = 480
laser_state = 'ready'
if laser_state == "fire":
fire_laser(laserX,laserY)
laserY -= laserY_change
player(playerX, playerY)
enemy1(enemy1X, enemy1Y)
pygame.display.update()
I can reproduce the issue with your orignal code.
It's a matter of Indentation. You have to handle the events in the event loop not after the event loop.
Move the event handling in the event loop:
running = True
while running:
screen.fill((0, 0, 0))
screen.blit(background, (0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# INDENTATION
#-->|
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -0.1
elif event.key == pygame.K_RIGHT:
playerX_change = 0.1
elif event.key == pygame.K_SPACE:
if laser_state == 'ready':
laserX = playerX
fire_laser(laserX, laserY)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0

Moving an image in pygame?

So, I'm making my first game in pygame, and have done OK up to this point. I just can't move the image. Can I please get some help?
mc_x = 20
mc_y = 20
spider_x = 690
spider_y = 500
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
mc_x -= 5
elif event.key == pygame.K_RIGHT:
mc_x += 5
elif event.key == pygame.K_UP:
mc_y += 5
elif event.key == pygame.K_DOWN:
mc_y -= 5
screen.blit(background,(0,0))#fixed
screen.blit(spider_small,(spider_x,spider_y))#FIXED
screen.blit(mc,(mc_x,mc_y))
pygame.display.update()
Based on your code:
screen.blit(mc,(mc_x,mc_y))
pygame.display.update()
should be inside the loop so that it would update/refresh your game for every keystroke.
You forgot to update the screen. Set the update function inside the main game loop. This is going to work fine!
Here's my sample code
import pygame
pygame.init()
WHITE = (255, 255, 255)
RED = (255, 0, 0)
canvas = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Example')
gameExit = False
lead_x, lead_y = 300, 300
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
lead_x -= 10
elif event.key == pygame.K_RIGHT:
lead_x += 10
elif event.key == pygame.K_DOWN:
lead_y += 10
elif event.key == pygame.K_UP:
lead_y -= 10
canvas.fill(WHITE)
pygame.draw.rect(canvas, RED, [lead_x, lead_y, 30, 30])
pygame.display.update()
pygame.quit()
quit()

Categories

Resources