pygame Sprite Movement - python

Below I have defined a pygame game loop. I am able to move the sprite in 8 directions.
#player position
def player(x,y):
screen.blit(playerImg, (x, y))
#enemy position
def enemy(x,y):
screen.blit(enemyImg, (x, y))
def fire_bullet(x,y):
global bullet_state
bullet_state = "fire"
screen.blit(bulletImg, (x + 16, y + 10))
# Game Loop
running = True
while running:
#fill values RGB - Red, Green, Blue
screen.fill(bc.goodblue)
#background immage
screen.blit(background, (0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
#if keystroke is pressed
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT or event.key == ord('a'):
playerx_change = -movespeed
if event.key == pygame.K_RIGHT or event.key == ord('d'):
playerx_change = movespeed
if event.key == pygame.K_UP or event.key == ord('w'):
playery_change = -movespeed
if event.key == pygame.K_DOWN or event.key == ord('s'):
playery_change = movespeed
if event.key == pygame.K_SPACE and bullet_state == "ready":
bulletx = playerx
fire_bullet(bulletx, bullety)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == ord('a') or event.key == ord('d'):
playerx_change = 0
if event.key == pygame.K_UP or event.key == pygame.K_DOWN or event.key == ord('s') or event.key == ord('w'):
playery_change = 0
#player movement
playery += playery_change
playerx += playerx_change
if playerx <= 0:
playerx = 0
if playerx >= width - PImgWidth:
playerx = width - PImgWidth
if playery <=0:
playery = 0
if playery >=height - PImgHeight:
playery = height - PImgHeight
#enemy movement
enemyx += enemyx_change
if enemyx <= 0:
enemyx_change = enemyspeed
enemyy += enemyy_change
if enemyx >= width - EImgWidth:
enemyx_change = -enemyspeed
enemyy += enemyy_change
player(playerx, playery)
enemy(enemyx, enemyy)
pygame.display.update()
pygame.quit()
However, there is one small issue.
If I press the left arrow key the sprite moves to the left. If I then also press the right arrow key the sprite starts moving to the right.
If I then let go of the left arrow key the sprite stops. I don't want this to happen. If I'm moving in the right direction and I let go of the left arrow key I want to keep moving in the right direction.
I don't know an efficient way to set this up.

If you release the LEFT, RIGHT, a or d you have to check whether one of these keys is still pressed before you can set playerx_change = 0:. Use pygame.key.get_pressed() to evaluate the state of the keys:
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == ord('a') or event.key == ord('d'):
keys = pygame.key.get_pressed()
if not keys[pygame.K_LEFT] and not keys[pygame.K_RIGHT] and not keys[pygame.K_a] and not keys[pygame.K_d]:
playerx_change = 0
Do the same for UP, DOWN, s respectively w
while running:
# [...]
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT or event.key == ord('a'):
playerx_change = -movespeed
if event.key == pygame.K_RIGHT or event.key == ord('d'):
playerx_change = movespeed
if event.key == pygame.K_UP or event.key == ord('w'):
playery_change = -movespeed
if event.key == pygame.K_DOWN or event.key == ord('s'):
playery_change = movespeed
if event.key == pygame.K_SPACE and bullet_state == "ready":
bulletx = playerx
fire_bullet(bulletx, bullety)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == pygame.K_a or event.key == pygame.K_d:
keys = pygame.key.get_pressed()
if not keys[pygame.K_LEFT] and not keys[pygame.K_RIGHT] and not keys[pygame.K_a] and not keys[pygame.K_d]:
playerx_change = 0
if event.key == pygame.K_UP or event.key == pygame.K_DOWN or event.key == pygame.K_s or event.key == pygame.K_w:
keys = pygame.key.get_pressed()
if not keys[pygame.K_UP] and not keys[pygame.K_DOWN] and not keys[pygame.K_s] and not keys[pygame.K_w]:
playery_change = 0

Related

Enemy not showing in screen PyGame

So I'm trying to do a game in python, I'm new to pygame, so I was following some tutorials, the player it's showing perfectly, but the enemy isn't showing. I've tried watching the tutorial multiple times, but I still have no clue of what it's happening.
import pygame
pygame.init()
screen = pygame.display.set_mode((800,600))
#Titulo E Icono
pygame.display.set_caption("Invaders")
icon = pygame.image.load('logo.jpg')
pygame.display.set_icon(icon)
#Player
playerImg = pygame.image.load('spaceship.png')
playerX = 370
playerY = 480
playerX_change = 0
enemyImage = pygame.image.load('enemy.png')
enemyX = 370
enemyY = 48
enemyX_change = 0
def player(x, y):
screen.blit(playerImg, (x, y))
def enemy(x, y):
screen.blit(enemyImg, (x, y))
#Loop
running = True
while running:
screen.fill((59, 59, 59))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
#Right Or Left Checker
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -0.5
if event.key == pygame.K_RIGHT:
playerX_change = 0.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
player(playerX, playerY)
pygame.display.update()
You missed to call the enemy function. In addition, the events must be handled in the event loop:
running = True
while running:
screen.fill((59, 59, 59))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# INDENTATION
#-->|
#Right Or Left Checker
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -0.5
if event.key == pygame.K_RIGHT:
playerX_change = 0.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
player(playerX, playerY)
enemy(enemyX, enemyY) # <--- this is missing
pygame.display.update()

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

How to make enemies fall at random on pygame?

I want enemies to randomly fall from the sky on my game and I do not know how to do this.
I was using this youtube video: Falling Objects in Pygame.
import pygame, random
pygame.init()
screen_width = 800
screen_height = 600
window = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Test')
time = pygame.time.Clock()
bg_color1 = (135, 142, 142) # MAIN BG COLOR
bg_color2 = (255, 0, 0) # red
bg_color3 = (255, 255, 0) # yellow
UFO = pygame.image.load('ufo.png')
bg_pic = pygame.image.load('Letsgo.jpg')
clock = pygame.time.Clock()
playerImg = pygame.image.load('enemy.png')
playerX = random.randrange(0, screen_width)
playerY = -50
playerX_change = 0
player_speed = 5
def player(x, y):
window.blit(playerImg, (playerX, playerY))
crashed = False
rect = UFO.get_rect()
obstacle = pygame.Rect(400, 200, 80, 80)
menu = True
playerY = playerY + player_speed
if playerY > screen_height:
playerX = random.randrange(0,screen_width)
playerY = -10
def ufo(x, y):
window.blit(UFO, (x, y))
while menu:
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
menu = False
window.fill((0, 0, 0))
time.tick(30)
window.blit(bg_pic, (0, 0))
pygame.display.update()
x = (screen_width * 0.45)
y = (screen_height * 0.8)
x_change = 0
car_speed = 0
y_change = 0
while not crashed:
x += x_change
if x < 0:
x = 0
elif x > screen_width - UFO.get_width():
x = screen_width - UFO.get_width()
y += y_change
if y < 0:
y = 0
elif y > screen_height - UFO.get_height():
y = screen_height - UFO.get_height()
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
############SIDE TO SIDE################
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
elif event.key == pygame.K_RIGHT:
x_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
###########UP AND DOWN#################
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
y_change = -5
elif event.key == pygame.K_DOWN:
y_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
y_change = 0
##
x += x_change
y += y_change
##
window.fill(bg_color1)
ufo(x, y)
player(playerX, playerY)
pygame.display.update()
clock.tick(100)
pygame.quit()
quit()
So the code that was supposed to make the image fall was this
if playerY > screen_height:
playerX = random.randrange(0,screen_width)
playerY = -10
Move the following code:
if playerY > screen_height:
playerX = random.randrange(0,screen_width)
playerY = -10
To here so it can be within the game loop:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
############SIDE TO SIDE################
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
elif event.key == pygame.K_RIGHT:
x_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
###########UP AND DOWN#################
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
y_change = -5
elif event.key == pygame.K_DOWN:
y_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
y_change = 0
if playerY > screen_height:
playerX = random.randrange(0,screen_width)
playerY = -10

Player not moving in pygame; no error messages

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

How to fix infinite jump bug in pygame?

I am trying to make a game, but you can keep spamming "w" (jump) for infinite height which is really bad when you are trying to make a platformer game. This is all my code:
GRAVITY = .2
diedorgameover = False
while not diedorgameover:
for event in pygame.event.get():
if event.type == pygame.QUIT:
diedorgameover = 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_s:
y_change = 5
elif event.key == pygame.K_w:
y_change = -5
if event.type == pygame.KEYUP:
if event.key == pygame.K_a or event.key == pygame.K_d:
x_change = 0
if event.key == pygame.K_s or event.key == pygame.K_w:
y_change = 0
#adding gravity to y_value
y_change += GRAVITY
x += x_change
y += y_change
if y >= gameDisplay.get_height() - 68:
y = gameDisplay.get_height() - 68
y_change = 0
#draw everything
gameDisplay.blit(background_image,(0,0))
red(x,y)
pygame.display.update()
clock.tick(60)
pygame.quit()
quit()
I would really appreciate it if you have any insight on this problem.
You can define a on_ground variable that you set to True if the player touches the ground. When the user wants to jump (presses 'w') you first check if on_ground: and then change the y_change and set on_ground to False.
import pygame
pygame.init()
gameDisplay = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
GRAVITY = .5
player_img = pygame.Surface((30, 50))
player_img.fill((40, 120, 200))
x = 100
y = 500
x_change = 0
y_change = 0
on_ground = False
diedorgameover = False
while not diedorgameover:
for event in pygame.event.get():
if event.type == pygame.QUIT:
diedorgameover = True
elif 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_s:
y_change = 5
elif event.key == pygame.K_w:
# Only jump if the player is on the ground.
if on_ground:
y_change = -12
on_ground = False
elif event.type == pygame.KEYUP:
if event.key == pygame.K_a or event.key == pygame.K_d:
x_change = 0
y_change += GRAVITY
x += x_change
y += y_change
# If the player is on the ground.
if y >= gameDisplay.get_height() - 68:
y = gameDisplay.get_height() - 68
y_change = 0
on_ground = True
gameDisplay.fill((30, 30, 30))
gameDisplay.blit(player_img, (x, y))
pygame.display.update()
clock.tick(60)
pygame.quit()
Also delete these lines, otherwise the player can stop while in the air if the key is released:
if event.key == pygame.K_s or event.key == pygame.K_w:
y_change = 0
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == KEYDOWN:
if event.key == K_SPACE and y_change == 0: # if spacebar is pressed and y_change is 0
y_change = 18 # set y_change to 18
if y_change > 0 and player_y == 200: # if y_change is greater than 0 and player_y is 200
player_y -= y_change
y_change -= gravity
if player_y > 200:
player_y = 200
if player_y == 200 and y_change < 0:
y_change = 0

Categories

Resources