This question already has an answer here:
How do I continuously trigger an action at certain time intervals? Enemy shoots constant beam instead of bullets in pygame [duplicate]
(1 answer)
Closed 2 years ago.
So I wrote my code and everything works how I want it to for now.
The only problem is that my bullet or fireball teleports to the location I set it to.
I am wondering if there is a way to make it look like its actually moving towards the destination using pygame and whatnot.
Thanks a ton!
(width, height) = (1300,800)
screen = pygame.display.set_mode((width, height))
playerImage = pygame.image.load('player.png')
fireballImage = pygame.image.load('fireball.png')
pygame.display.set_caption('Game')
transparent = (0, 0, 0, 0)
#Fireball stats
def player(x ,y):
screen.blit(playerImage, (x, y))
pygame.display.flip()
def fireball(x, y):
screen.blit(fireballImage, (fb_x,fb_y))
pygame.display.flip()
fireball_state = "ready"
print('created')
fb_x = x = width * 0.45
fb_y = y = height * 0.8
x_change = 0
y_change = 0
fb_x_change = 0
fb_y_change = 0
pressed = pygame.key.get_pressed()
#mainloop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_d:
x_change = 1
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
x_change = -1
if event.type == pygame.KEYUP:
if event.key == pygame.K_a or event.key == pygame.K_d:
x_change = 0
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
y_change = -2
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_s:
y_change = 2
if event.type == pygame.KEYUP:
if event.key == pygame.K_w or event.key == pygame.K_s:
y_change = 0
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
fb_y_change = -400
if event.type == pygame.KEYUP:
if event.key == pygame.K_SPACE:
fb_y_change = 0
x += x_change
y += y_change
fireball(x,y)
fb_x = x
fb_y = y
screen.fill((255,255,255))
player(x,y)
fb_x += fb_x_change
fb_y += fb_y_change
fireball(fb_x,fb_y)
pygame.display.update()
First of all remove pygame.display.flip() from player and fireball. That casuse flickering. A single pygame.display.update() at the end of the application loop is sufficient.
Note, the fireballs have to be blit at (x, y) rather than (fb_x, fb_y)
def player(x ,y):
screen.blit(playerImage, (x, y))
def fireball(x, y):
screen.blit(fireballImage, (x, y))
fireball_state = "ready"
Further more use pygame.time.Clock() / tick() to control the flops per second (FPS):
clock = pygame.time.Clock()
#mainloop
running = True
while running:
clock.tick(FPS)
Add a list for the fire balls:
fireballs = []
Spawn a new fireball when space is pressed:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
fireballs.append([x, y, 0, -2])
Update and draw the fireballs in a loop:
for fb in fireballs:
fb[0] += fb[2]
fb[1] += fb[3]
for fb in fireballs:
fireball(fb[0],fb[1])
See the example:
fireballs = []
FPS = 60
clock = pygame.time.Clock()
running = True
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
fireballs.append([x, y, 0, -2])
pressed = pygame.key.get_pressed()
if pressed[pygame.K_w]:
y -= 2
if pressed[pygame.K_s]:
y += 2
if pressed[pygame.K_a]:
x -= 2
if pressed[pygame.K_d]:
x += 2
for i in range(len(fireballs)-1, -1, -1):
fb = fireballs[i]
fb[0] += fb[2]
fb[1] += fb[3]
if fb[1] < 0:
del fireballs[i]
screen.fill((255,255,255))
player(x,y)
for fb in fireballs:
fireball(fb[0],fb[1])
pygame.display.update()
I'm trying to make a little game, and I came across a problem which I can't seem to figure out. The problem is that my sprite isn't moving after creating the game loop and the if statements with the keyup's and what not. Can you guys figure it out and tell me why it's not working?
Here's my code so far:
import pygame, sys, random
from pygame.locals import *
pygame.init()
mainClock = pygame.time.Clock()
windowWidth = 600
windowHeight = 400
windowSize = (600, 400)
windowSurface = pygame.display.set_mode((windowWidth, windowHeight), 0, 32)
display = pygame.Surface((300, 200))
black = (0, 0, 0)
white = (225, 225, 255)
green = (0, 255, 0)
moveRight = False
moveLeft = False
moveSpeed = 6
level= [['0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'],
['0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'],
['0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'],
['0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'],
['0','0','0','0','0','0','0','2','2','2','2','2','0','0','0','0','0','0','0'],
['0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0'],
['2','2','0','0','0','0','0','0','0','0','0','0','0','0','0','0','0','2','2'],
['1','1','2','2','2','2','2','2','2','2','2','2','0','0','2','2','2','1','1'],
['1','1','1','1','1','1','1','1','1','1','1','1','0','0','1','1','1','1','1'],
['1','1','1','1','1','1','1','1','1','1','1','1','0','0','1','1','1','1','1'],
['1','1','1','1','1','1','1','1','1','1','1','1','0','0','1','1','1','1','1'],
['1','1','1','1','1','1','1','1','1','1','1','1','0','0','1','1','1','1','1'],
['1','1','1','1','1','1','1','1','1','1','1','1','0','0','1','1','1','1','1']]
grass = pygame.image.load('grass.png')
dirt = pygame.image.load('dirt.png')
player = pygame.image.load('player.png').convert()
playerRect = pygame.Rect(100, 100, 5, 13)
player.set_colorkey((255,255,255))
while True:
display.fill((214, 42, 78))
#display.blit(player,(playerRect.x,playerRect.y))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.type == pygame.K_RIGHT or event.key == pygame.K_d:
moveRight = True
if event.type == pygame.K_LEFT or event.key == pygame.K_a:
moveLeft = False
if event.type == pygame.KEYUP:
if event.type == pygame.K_RIGHT or event.key == pygame.K_d:
moveRight = False
if event.type == pygame.K_LEFT or event.key == pygame.K_a:
moveLeft = False
display.blit(player,(playerRect.x,playerRect.y))
playerMovement = [0, 0]
if moveRight == True:
playerMovement[0] += 2
if moveLeft == True:
playerMovement[0] -= 2
tileRect = []
y = 0
for row in level:
x = 0
for col in row:
if col == '2':
display.blit(grass, (x*16, y*16))
if col == '1':
display.blit(dirt, (x*16, y*16))
if col != '0':
tileRect.append(pygame.Rect(x*16,y*16,16,16))
x += 1
y += 1
#pygame.draw.rect(windowSurface, black, player)
windowSurface.blit(pygame.transform.scale(display, windowSize),(0,0))
pygame.display.update()
mainClock.tick(60)
I've restructured your main loop to fix the problems. I change the playerMovement (velocity) in the event loop now and use it to update the playerRect in the main loop with the pygame.Rect.move_ip method.
By the way, you can pass the playerRect to blit to blit the image at the topleft (x, y) coords.
# The player's velocity. Define it outside of the main loop.
playerMovement = [0, 0]
while True:
# Handle events.
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.type == pygame.K_RIGHT or event.key == pygame.K_d:
playerMovement[0] = 2 # Set the x-velocity to the desired value.
if event.type == pygame.K_LEFT or event.key == pygame.K_a:
playerMovement[0] = -2
if event.type == pygame.KEYUP:
if event.type == pygame.K_RIGHT or event.key == pygame.K_d:
playerMovement[0] = 0 # Stop the player when the button is released.
if event.type == pygame.K_LEFT or event.key == pygame.K_a:
playerMovement[0] = 0
# Game logic.
playerRect.move_ip(playerMovement)
# Draw everything.
display.fill((214, 42, 78))
tileRect = []
y = 0
for row in level:
x = 0
for col in row:
if col == '2':
display.blit(grass, (x*16, y*16))
if col == '1':
display.blit(dirt, (x*16, y*16))
if col != '0':
tileRect.append(pygame.Rect(x*16,y*16,16,16))
x += 1
y += 1
display.blit(player, playerRect)
windowSurface.blit(pygame.transform.scale(display, windowSize), (0, 0))
pygame.draw.rect(windowSurface, black, playerRect)
pygame.display.update()
mainClock.tick(60)
I have started making something on pygame but I have encountered an issue when moving left or right. if I quickly change from pressing the right arrow key to pressing the left one and also let go of the right one the block just stops moving. this is my code
bg = "sky.jpg"
ms = "ms.png"
import pygame, sys
from pygame.locals import *
x,y = 0,0
movex,movey=0,0
pygame.init()
screen=pygame.display.set_mode((664,385),0,32)
background=pygame.image.load(bg).convert()
mouse_c=pygame.image.load(ms).convert_alpha()
m = 0
pygame.event.pump()
while 1:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type==KEYDOWN:
if event.key==K_LEFT:
movex =-0.5
m = m + 1
if event.key==K_RIGHT:
movex=+0.5
m = m + 1
elif event.type == KEYUP:
if event.key==K_LEFT and not event.key==K_RIGHT:
movex = 0
if event.key==K_RIGHT and not event.key==K_LEFT:
movex =0
x+=movex
y=200
screen.blit(background, (0,0))
screen.blit(mouse_c,(x,y))
pygame.display.update()
is there a way I can change this so if the right arrow key is pressed and the left arrow key is released that it will go right instead of stopping?
P.S
I am still learning pygame and am very new to the module. I'm sorry if this seems like a stupid question but i couldn't find any answers to it.
Your problem is that when you test the KEYDOWN events with
if event.key==K_LEFT and not event.key==K_RIGHT:
you always get True, because when event.key==K_LEFT is True,
it also always is not event.key==K_RIGHT (because the key of the event is K_LEFT after all).
My approach to this kind of problem is to separate
the intent from the action. So, for the key
events, I would simply keep track of what action
is supposed to happen, like this:
moveLeft = False
moveRight = False
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_LEFT: moveLeft = True
if event.key == K_RIGHT: moveRight = True
elif event.type == KEYUP:
if event.key == K_LEFT: moveLeft = False
if event.key == K_RIGHT: moveRight = False
Then, in the "main" part of the loop, you can
take action based on the input, such as:
while True:
for event in pygame.event.get():
...
if moveLeft : x -= 0.5
if moveRight : x += 0.5
the problem is that you have overlapping key features; If you hold down first right and then left xmove is first set to 1 and then changes to -1. But then you release one of the keys and it resets xmove to 0 even though you are still holding the other key. What you want to do is create booleans for each key. Here is an example:
demo.py:
import pygame
window = pygame.display.set_mode((800, 600))
rightPressed = False
leftPressed = False
white = 255, 255, 255
black = 0, 0, 0
x = 250
xmove = 0
while True:
window.fill(white)
pygame.draw.rect(window, black, (x, 300, 100, 100))
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
rightPressed = True
if event.key == pygame.K_LEFT:
leftPressed = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
rightPressed = False
if event.key == pygame.K_LEFT:
leftPressed = False
xmove = 0
if rightPressed:
xmove = 1
if leftPressed:
xmove = -1
x += xmove
pygame.display.flip()
One way could be to create a queue that keeps track of the button that was pressed last. If we press the right arrow key we'll put the velocity first in the list, and if we then press the left arrow key we put the new velocity first in the list. So the button that was pressed last will always be first in the list. Then we just remove the button from the list when we release it.
import pygame
pygame.init()
screen = pygame.display.set_mode((720, 480))
clock = pygame.time.Clock()
FPS = 30
rect = pygame.Rect((350, 220), (32, 32)) # Often used to track the position of an object in pygame.
image = pygame.Surface((32, 32)) # Images are Surfaces, so here I create an 'image' from scratch since I don't have your image.
image.fill(pygame.Color('white')) # I fill the image with a white color.
velocity = [0, 0] # This is the current velocity.
speed = 200 # This is the speed the player will move in (pixels per second).
dx = [] # This will be our queue. It'll keep track of the horizontal movement.
while True:
dt = clock.tick(FPS) / 1000.0 # This will give me the time in seconds between each loop.
for event in pygame.event.get():
if event.type == pygame.QUIT:
raise SystemExit
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
dx.insert(0, -speed)
elif event.key == pygame.K_RIGHT:
dx.insert(0, speed)
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
dx.remove(-speed)
elif event.key == pygame.K_RIGHT:
dx.remove(speed)
if dx: # If there are elements in the list.
rect.x += dx[0] * dt
screen.fill((0, 0, 0))
screen.blit(image, rect)
pygame.display.update()
# print dx # Uncomment to see what's happening.
You should of course put everything in neat functions and maybe create a Player class.
I know my answer is pretty late but im new to Pygame to and for beginner like me doing code like some previous answer is easy to understand but i have a solution to.I didn`t use the keydown line code, instead i just put the moving event code nested in the main game while loop, im bad at english so i give you guy an example code.
enter code here
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT or event.type == pygame.K_ESCAPE:
run = False
win.blit(bg, (0, 0))
pressed = pygame.key.get_pressed()
if pressed[pygame.K_LEFT]:
x -= 5
if pressed[pygame.K_RIGHT]:
x += 5
if pressed[pygame.K_UP]:
y -= 5
if pressed[pygame.K_DOWN]:
y += 5
win.blit(image,(x,y))
pygame.display.update()
pygame.quit()
This will make the image move rapidly without repeating pushing the key, at long the code just in the main while loop with out inside any other loop.
I have made a game using Python and Pygame. My ship moves around but I am having trouble making it shoot bullets. I have defined a function called shootBullets() but it is not working. And now, if I press the space bar, my ship moves. It is only supposed to move when I press the left or right arrow keys. I want my ship to shoot bullets towards the bottom of the screen when I press the space bar. here is my code:
import pygame,sys
from pygame.locals import *
pygame.init()
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
bright_blue = (0, 135, 255)
yellow = (255,242,0)
ship_body = (33, 117, 243)
screen = pygame.display.set_mode((500,500))
pygame.display.set_caption("Battleship")
gameExit = False
background = pygame.image.load("Sky Background.png")
bulletImg = pygame.image.load("Bullet.png")
bulletY = 80
def shootBullets():
for event in pygame.event.get():
if event.type == KEYDOWN and event.key == K_SPACE:
bulletY += 5
screen.blit(bulletImg,(247,bulletY))
pygame.key.set_repeat(50,50)
ship_points = [ [100, 50], [180, 95], [320, 95], [400, 50], [250, 35] ]
x = 0
y = 0
while not gameExit:
for event in pygame.event.get():
if event.type == QUIT:
gameExit = True
if event.type == KEYDOWN:
if event.key == pygame.K_LEFT: x = -5
if event.key == pygame.K_RIGHT: x = 5
for point in ship_points:
point[0] += x
for point in ship_points:
if point[0] <= 0 or point[0] >= 500:
gameExit = True
shootBullets()
screen.fill(black)
screen.blit(background, (0,0))
ship = [
pygame.draw.polygon(screen, ship_body, ship_points),
pygame.draw.polygon(screen, black, ship_points, 1)]
pygame.display.update()
pygame.quit()
quit()
In your main loop you are only checking for left and right, not for space. You check in the function shootBullets whether space is pressed, but that is too late, shootBullets will never be executes (actually it will get executed if the for event in get() loop is somehow exited but that is not what you want).
Instead do something like:
while not gameExit:
for event in pygame.event.get():
if event.type == QUIT:
gameExit = True
if event.type == KEYDOWN:
if event.key == pygame.K_LEFT:
move_left()
if event.key == pygame.K_RIGHT:
move_right()
if event.key == pygame.SPACE:
shootBullet()
[...]