I am trying to move Left and Right and whenever I let go of the right arrow it keeps moving right and same with the left side of things. I have been messing around with this and cant figure it out.
import pygame
# Intialize the pygame
pygame.init()
# create the screen
screen = pygame.display.set_mode((800,600))
# Player
PlayerHealth = 100
Playerinven = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
playerImg = pygame.image.load('001-alien.png')
# Player Movment
playerX = 370
playerY = 480
XLlabel = False
XRlabel = False
playerX_change = 0
def player(x, y):
screen.blit(playerImg, (x , y))
# Game Loop
running = True
while running:
# RGB - Red,Green,Blue
screen.fill((0, 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:
XLlabel = True
elif event.key == pygame.K_RIGHT:
XRlabel = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
XLlabel = False
if event.key == pygame.K_RIGHT:
XRlabel = False
if XLlabel == True and XRlabel == True:
playerX_change = 0
elif XLlabel == True:
playerX_change = -0.3
elif XRlabel == True:
playerX_change = 0.3
elif XLlabel == False and XRlabel == False:
player_change = 0
playerX += playerX_change
if playerX <= 0:
playerX = 0
if playerX >= 736:
playerX = 736
player(playerX, playerY)
pygame.display.update()
This is my first time trying to make a game so it is kinda stressing me out XD
Error:
You have written player_change = 0 where there must be playerX_change = 0.
Code:
# Player
PlayerHealth = 100
Playerinven = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
playerImg = pygame.image.load('001-alien.png')
# Player Movment
playerX = 370
playerY = 480
XLlabel = False
XRlabel = False
playerX_change = 0
def player(x, y):
screen.blit(playerImg, (x , y))
# Game Loop
running = True
while running:
# RGB - Red,Green,Blue
screen.fill((0, 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:
XLlabel = True
elif event.key == pygame.K_RIGHT:
XRlabel = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
XLlabel = False
if event.key == pygame.K_RIGHT:
XRlabel = False
if XLlabel == True and XRlabel == True:
playerX_change = 0
elif XLlabel == True:
playerX_change = -0.3
elif XRlabel == True:
playerX_change = 0.3
elif XLlabel == False and XRlabel == False:
playerX_change = 0 #just a small error you have written player_change = 0
playerX += playerX_change
if playerX <= 0:
playerX = 0
if playerX >= 736:
playerX = 736
player(playerX, playerY)
pygame.display.update()
Not sure if this is the cause of your problem but your handling of the keys seems a little "tortured".
For a start, you should generally never use if XLlabel == True, preferring instead the more succinct if XLlabel.
The key handling can then be made something like:
# Initial left/right key state flags.
left_down, right_down = False, False
for event in pygame.event.get():
# Process events, keys up/down sets flags.
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
left_down = True
elif event.key == pygame.K_RIGHT:
right_down = True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
left_down = False
elif event.key == pygame.K_RIGHT:
right_down = False
# Event processing done, evaluate key states to get velocity.
velocity = 0
if left_down:
velocity -= 0.3
if right_down:
velocity += 0.3
# Adjust player position by velocity.
...
Related
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()
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
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
I'm quite new to python and have recently started game dev with pygame. I wanted to know why my game just freezes and the exitcode -805306369 (0xCFFFFFFF) appears. Do i have errors in my programm? It looks like this:
import pygame
import random
import math
pygame.init()
window = pygame.display.set_mode((1000, 600))
caption = pygame.display.set_caption(
'Test your reaction speed. Shoot the target game!') # sets a caption for the window
run = True
PlayerImg = pygame.image.load('F:\PythonPortable\oscn.png')
PlayerX = 370
PlayerY = 420
PlayerX_change = 0
PlayerY_change = 0
def player():
window.blit(PlayerImg, (PlayerX, PlayerY))
aim_sight = pygame.image.load('F:\PythonPortable\ktarget.png')
aim_sightX = 460
aim_sightY = 300
aim_sight_changeX = 0
aim_sight_changeY = 0
def aim_sight_function(x, y):
window.blit(aim_sight, (x, y))
targetedImg = pygame.image.load('F:\PythonPortable\ktargetedperson.png')
targetedX = random.randint(0, 872)
targetedY = random.randint(0, 200)
def random_target():
window.blit(targetedImg, (targetedX, targetedY))
def iscollision(targetedX, targetedY, aim_sightX, aim_sightY):
distance = math.sqrt((math.pow(targetedX - aim_sightX, 2)) + (math.pow(targetedY - aim_sightY, 2)))
if distance < 70:
return True
else:
return False
while run:
window.fill((255, 255, 255))
random_target()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
aim_sight_changeX = -2
PlayerX_change = -2
elif event.key == pygame.K_RIGHT:
aim_sight_changeX = 2
PlayerX_change = 2
elif event.key == pygame.K_UP:
aim_sight_changeY = -2
PlayerY_change = -2
elif event.key == pygame.K_DOWN:
aim_sight_changeY = 2
PlayerY_change = 2
score = 0
while score < 10:
collision = iscollision(targetedX, targetedY, aim_sightX, aim_sightY)
if collision and event.key == pygame.K_SPACE:
print("HIT") # Just for me to acknowledge that collision is true and space bar was pressed in the right spot
score = score + 1
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
aim_sight_changeX = 0
PlayerX_change = 0
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
aim_sight_changeY = 0
PlayerY_change = 0
aim_sightX += aim_sight_changeX
if aim_sightX <= 46.5:
aim_sight_changeX = 0
elif aim_sightX >= 936:
aim_sight_changeX = 0
aim_sightY += aim_sight_changeY
if aim_sightY <= 0:
aim_sight_changeY = 0
elif aim_sightY >= 400:
aim_sight_changeY = 0
PlayerX += PlayerX_change
if PlayerX <= -50:
PlayerX_change = 0
elif PlayerX >= 850:
PlayerX_change = 0
player()
aim_sight_function(aim_sightX, aim_sightY)
pygame.display.update()
I think there is a mistake in this area as my program runs well without it.
while score < 10:
collision = iscollision(targetedX, targetedY, aim_sightX, aim_sightY)
if collision and event.key == pygame.K_SPACE:
print("HIT") # Just for me to acknowledge that collision is true and space bar was pressed in the right spot
score = score + 1
I've checked other questions but they are mostly for java and other languages.
You have an application loop. You do not need an additional loop to control the game. The loop that increments the score is an infinite loop. Change the loop to a selection (change while to if).
Furthermore, the score has to be initialized before the application loop:
score = 0
while run:
# [...]
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
aim_sight_changeX = -2
PlayerX_change = -2
elif event.key == pygame.K_RIGHT:
# [...]
elif event.key == pygame.K_SPACE:
if score < 10:
collision = iscollision(targetedX, targetedY, aim_sightX, aim_sightY)
if collision:
print("HIT")
score = score + 1
I got this far and it kind of got all confusing and I can't figure out one simple problem with the code.
while not gameExit:
while gameOver == True:
pygame.display.flip()
gameDisplay.fill(white)
display_message("OVER. C to continue, Q to quit", red)
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
gameOver = False
gameExit = True
if event.key == pygame.K_c:
gameLoop()
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_change = -10
lead_y_change = 0
elif event.key == pygame.K_RIGHT:
lead_x_change = 10
lead_y_change = 0
elif event.key == pygame.K_UP:
lead_y_change = -10
lead_x_change = 0
elif event.key == pygame.K_DOWN:
lead_y_change = 10
lead_x_change = 0
if ( lead_x < 0 ) or (lead_x >= 600) or ( lead_y < 0 ) or ( lead_y >= 800):
gameOver = True
So when I run this code, and when the snake goes over the boundary, the C for continue and Q for quit thing doesn't come UNTIL I press a button on the keyboard or move my mouse. Why is that?
Move:
if ( lead_x < 0 ) or (lead_x >= 600) or ( lead_y < 0 ) or ( lead_y >= 800):
gameOver = True
out of the pygame.event.get-loop because it will only run if events have taken place (mouse moved, key pressed). Otherwise the code will not reach the check without your action.