how to make object keep moving up - python

I'm making a game with Python. I have a spaceship in this game. The spaceship can move to the left and to the right and it is supposed to shoot bullets from its x-position and it is supposed to fire the bullets up. I am able to move the spaceship and I am able to put it on the screen. The problem is that I am not able to fire the bullet from the spaceship's x-position and I am not able to make the bullet move up. Can somebody help me with this? Please post simple code too if possible.
Here's the code:
import pygame
import sys
pygame.init()
screen_length = 512
screen_width = 288
clock = pygame.time.Clock()
screen = pygame.display.set_mode((screen_width, screen_length))
bg = pygame.image.load(r'C:\Users\Anonymous\Downloads\space game folder\space background3.png').convert()
bg = pygame.transform.scale2x(bg)
spaceship = pygame.image.load(r'C:\Users\Soorya\Anonymous\space game folder\spaceship.png').convert()
missile = pygame.image.load(r'C:\Users\Soorya\Anonymous\space game folder\bullet2.png').convert()
x = 130
y = 480
z = 460
velocity = 30
spaceship_rect = spaceship.get_rect(center=(x, y))
spaceship_x_pos = spaceship_rect.left + 170
bullet_speed = 10
missile_rect = missile.get_rect(center=(round(spaceship_x_pos // 2), z))
spaceship_direction = 10
while True:
for event in pygame.event.get():
if event == pygame.QUIT:
pygame.display.quit()
sys.exit(0)
keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT] and x < 288:
x += velocity
if keys[pygame.K_LEFT] and x > 0:
x -= velocity
if keys[pygame.K_SPACE]:
bg.blit(missile, missile_rect)
screen.fill(0)
screen.blit(bg, (0, 0))
screen.blit(spaceship, (x, y))
pygame.display.update()
clock.tick(120)

The problem with your code is that your indentation is not right.
while True:
for event in pygame.event.get():
if event == pygame.QUIT:
pygame.display.quit()
sys.exit(0)
keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT] and x < 288:
x += velocity
if keys[pygame.K_LEFT] and x > 0:
x -= velocity
if keys[pygame.K_SPACE]:
bg.blit(missile, missile_rect)
screen.fill(0) # THIS
screen.blit(bg, (0, 0)) #THIS
screen.blit(spaceship, (x, y)) #THIS
pygame.display.update() #THIS
clock.tick(120) #THIS
The lines where i commented this have to be indented like this:
while True:
for event in pygame.event.get():
if event == pygame.QUIT:
pygame.display.quit()
sys.exit(0)
keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT] and x < 288:
x += velocity
if keys[pygame.K_LEFT] and x > 0:
x -= velocity
if keys[pygame.K_SPACE]:
bg.blit(missile, missile_rect)
screen.fill(0)
screen.blit(bg, (0, 0))
screen.blit(spaceship, (x, y))
pygame.display.update()
clock.tick(120)
That's because you want to do those things every single frame while the game is running. One more thing, you are filling the screen with black in line screen.fill(0), which is not necessary since you are already rendering a background image, so you basically cannot see it. With that being said, i recommend taking an object oriented approach as well because you wont get very far without it. Also, set velocity to like 0.5 or something. Its currently 30, which means 30 pixels every frame and that's not what you want.
Now to fire bullets. What you are doing right now wont work because you are only "blitting" a missile if space is pressed. Below i wrote a separate code for you that only fires missiles, so hopefully its clear and you can implement in your own code.
import pygame
import sys
pygame.init()
d = pygame.display.set_mode((1200, 600))
# WE WILL USE FIRING BOOLEAN TO KEEP TRACK OF IF WE ARE FIRING MISSILES
firing = False
missile = pygame.Surface((10, 50))
while True:
d.fill((255, 255, 255))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
# Assign initial positions only if it isnt firing
if not firing:
missilex = 600 # This is the initial position of the missile. This will be
missiley = 500 # your player position in your game
if pygame.key.get_pressed()[pygame.K_SPACE]: # if space pressed set firing to true
firing = True
# if firing is true, we want to display the missile and move it.
if firing:
d.blit(missile, (missilex, missiley))
missiley -= 1
# if missile is off the screen, set firing to false so it resets to initial position (600, 500).
if missiley < -20:
firing = False
pygame.display.update()

The way you are approaching it doesn't seem right to me, unless ofc that isn't your whole code. But you are using the same variable to represent the x and y coordinate of your bullet and the spaceship. You want to bullet to move independently from the space ship. So if you change the variable y in your code, that will move space ship up too, and same with the x variable.
What you need to do is to create 2 separate classes. One for you bullet, and the other for the space ship. Here is a simple example of its implementation, which you can improve upon by adding whatever features you want later.
class Spaceship:
image = pygame.image.load(r'C:\Users\Soorya\Anonymous\space game folder\spaceship.png').convert()
def __init__(self, x, y, vel):
self.x = x
self.y = y
self.vel = vel
def draw(self, screen):
screen.blit(Spaceship.image, (self.x, self.y))
class Bullet:
image = pygame.image.load(r'C:\Users\Soorya\Anonymous\space game folder\bullet2.png').convert()
bullet_list = [] # holds the list of bullets in the screen
def __init__(self, x, y, vel):
self.x = x
self.y = y
self.vel = vel
Bullet.bullet_list.append(self)
def move(self):
self.y -= self.vel
if self.y < 0: # remove bullet if it goes beyond screen
Bullet.bullet_list.remove(self)
def draw(self, screen):
screen.blit(Bullet.image, (self.x, self.y))
spaceship = Spaceship(130, 480, 30)
# set up screen and bg as before
while True:
for event in pygame.event.get():
if event == pygame.QUIT:
pygame.display.quit()
sys.exit(0)
keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT] and x < 288:
spaceship.x += spaceship.vel
if keys[pygame.K_LEFT] and x > 0:
spaceship.x -= spaceship.vel
if keys[pygame.K_SPACE]: # create a bullet if space is pressed
Bullet(spaceship.x, spaceship.y, 10)
screen.blit(bg, (0, 0))
spaceship.draw()
for bullet in Bullet.bullet_list():
bullet.move() # actually moves the bullet on each iteration of the loop
bullet.draw()
pygame.display.update()
clock.tick(120)
Important note for future if you want to create games, make everything object oriented lol. Trust me, it will make your life a whole lot easier. Let me know if you have any problems.

Related

How do I make a continuously moving bullet when I'm not holding down the space bar in pygame? [duplicate]

This question already has answers here:
How can i shoot a bullet with space bar?
(1 answer)
How do I stop more than 1 bullet firing at once?
(1 answer)
Closed 1 year ago.
import pygame
# initialize the pygame
pygame.init()
# create the screen
screen = pygame.display.set_mode((800, 600))
# Title and icon
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load('Invader2.xcf')
pygame.display.set_icon(icon)
# Player
playerImg = pygame.image.load('Player.xcf')
player_big = pygame.transform.scale(playerImg, (48, 48))
playerX = 370
playerY = 480
vel = 0.15
# Player Bullets
playerBulletImg = pygame.image.load('Player_bullet.xcf')
playerBulletX = playerX + 16
playerBulletY = playerY + 10
bulletVel = 0.3
def player(x, y):
screen.blit(player_big, (playerX, playerY))
def bullet(x, y):
screen.blit(playerBulletImg, (playerBulletX, playerBulletY))
# Game Loop
running = True
while running:
# RGB
screen.fill((18.8, 83.5, 78.4))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and playerX > 0:
playerX -= vel
playerBulletX -= vel
if keys[pygame.K_RIGHT] and playerX < 800 - 48:
playerX += vel
playerBulletX += vel
if keys[pygame.K_SPACE]:
playerBulletY -= 0.5
if playerBulletY == 0:
playerBulletY = 480
bullet(playerBulletX, playerBulletY)
player(playerX, playerY)
pygame.display.update()
Hi! I'm a beginner who has just started using Pygame. I'm making a Space Invaders / Galaga type game. When I press the space bar, the bullet goes up the y-axis, but only when I hold it down. I want the bullet to continue to move up the screen, even when I'm not holding down the space bar. Also, another problem is that when the bullet is in the air it still follows the x-value for the player. So when the bullet shoots up, It moves around depending on where the player is.
you should run your game as a class it is much more easier to code pygame with classes you can change your b.move to where else
import pygame
# initialize the pygame
pygame.init()
# create the screen
screen = pygame.display.set_mode((800, 600))
# Title and icon
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load('Invader2.xcf')
pygame.display.set_icon(icon)
# Player
class Player:
def __init__(self):
self.Img = pygame.image.load('Player.xcf')
self.big = pygame.transform.scale(playerImg, (48, 48))
self.x = 370
self.y = 480
self.vel = 0.15
def draw(self,screen):
screen.blit(self.big, (self.x, self.y))
class Bullet:
def __init__(self):
self.Img = pygame.image.load('Player_bullet.xcf')
self.x = playerX + 16
self.y = playerY + 10
self.vel = 0.3
def draw(screen):
screen.blit(self.Img, (self.y, self.y))
def move():
self.y -= self.vel
def draw(p,b):
p.draw()
for i in b:
i.draw()
# Game Loop
def main():
running = True
p = Player()
b = []
while running:
screen.fill((18.8, 83.5, 78.4))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and p.x > 0:
p.x -= p.vel
if keys[pygame.K_RIGHT] and p.x < 800 - 48:
p.x += p.vel
if keys[pygame.K_SPACE]:
b.append(Bullet())
draw(p,b)
for bullet in b:
bullet.move()
pygame.display.update()
Use the keyboard event instead of pygame.key.get_pressed() to shoot a bullet.
pygame.key.get_pressed() returns a sequence with the state of each key. If a key is held down, the state for the key is True, otherwise False. Use pygame.key.get_pressed() to evaluate the current state of a button and get continuous movement.
The keyboard events (see pygame.event module) occur only once when the state of a key changes. The KEYDOWN event occurs once every time a key is pressed. KEYUP occurs once every time a key is released. Use the keyboard events for a single action.
Add a shootBullet variable that indicates when the bullet will be fired. Set the state when SPACE is pressed. Move and draw the bullet depending on this state. Set the starting position of the bullet when the bullet is fired.
shootBullet = False
clock = pygame.time.Clock()
running = True
while running:
clock.tick(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
shootBullet = True
playerBulletX = playerX
playerBulletY = 480
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and playerX > 0:
playerX -= vel
if keys[pygame.K_RIGHT] and playerX < 800 - 48:
playerX += vel
if shootBullet:
playerBulletY -= 1
if playerBulletY <= 0:
shoot_bullet = False
screen.fill((18.8, 83.5, 78.4))
if shootBullet:
bullet(playerBulletX, playerBulletY)
player(playerX, playerY)
pygame.display.update()
Use pygame.time.Clock to control the frames per second and thus the game speed.
The method tick() of a pygame.time.Clock object, delays the game in that way, that every iteration of the loop consumes the same period of time. See pygame.time.Clock.tick():
This method should be called once per frame.
That means that the loop:
clock = pygame.time.Clock()
run = True
while run:
clock.tick(100)
runs 100 times per second.

Why sprite isn't showing up in pygame? [duplicate]

im trying to get my image (bird) to move up and down on the screen but i cant figure out how to do it here is what i tried im sure its way off but im trying to figure it out if anyone can help that would be great!
import pygame
import os
screen = pygame.display.set_mode((640, 400))
running = 1
while running:
event = pygame.event.poll()
if event.type == pygame.QUIT:
running = 0
screen.fill([255, 255, 255])
clock = pygame.time.Clock()
clock.tick(0.5)
pygame.display.flip()
bird = pygame.image.load(os.path.join('C:\Python27', 'player.png'))
screen.blit( bird, ( 0, 0 ) )
pygame.display.update()
class game(object):
def move(self, x, y):
self.player.center[0] += x
self.player.center[1] += y
if event.key == K_UP:
player.move(0,5)
if event.key == K_DOWN:
player.move(0,-5)
game()
im trying to get it to move down on the down button press and up on the UP key press
As stated by ecline6, bird is the least of your worries at this point.
Consider reading this book..
For now, First let's clean up your code...
import pygame
import os
# let's address the class a little later..
pygame.init()
screen = pygame.display.set_mode((640, 400))
# you only need to call the following once,so pull them out of the while loop.
bird = pygame.image.load(os.path.join('C:\Python27', 'player.png'))
clock = pygame.time.Clock()
running = True
while running:
event = pygame.event.poll()
if event.type == pygame.QUIT:
running = False
screen.fill((255, 255, 255)) # fill the screen
screen.blit(bird, (0, 0)) # then blit the bird
pygame.display.update() # Just do one thing, update/flip.
clock.tick(40) # This call will regulate your FPS (to be 40 or less)
Now the reason that your "bird" is not moving is:
When you blit the image, ie: screen.blit(bird, (0, 0)),
The (0,0) is constant, so it won't move.
Here's the final code, with the output you want (try it) and read the comments:
import pygame
import os
# it is better to have an extra variable, than an extremely long line.
img_path = os.path.join('C:\Python27', 'player.png')
class Bird(object): # represents the bird, not the game
def __init__(self):
""" The constructor of the class """
self.image = pygame.image.load(img_path)
# the bird's position
self.x = 0
self.y = 0
def handle_keys(self):
""" Handles Keys """
key = pygame.key.get_pressed()
dist = 1 # distance moved in 1 frame, try changing it to 5
if key[pygame.K_DOWN]: # down key
self.y += dist # move down
elif key[pygame.K_UP]: # up key
self.y -= dist # move up
if key[pygame.K_RIGHT]: # right key
self.x += dist # move right
elif key[pygame.K_LEFT]: # left key
self.x -= dist # move left
def draw(self, surface):
""" Draw on surface """
# blit yourself at your current position
surface.blit(self.image, (self.x, self.y))
pygame.init()
screen = pygame.display.set_mode((640, 400))
bird = Bird() # create an instance
clock = pygame.time.Clock()
running = True
while running:
# handle every event since the last frame.
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit() # quit the screen
running = False
bird.handle_keys() # handle the keys
screen.fill((255,255,255)) # fill the screen with white
bird.draw(screen) # draw the bird to the screen
pygame.display.update() # update the screen
clock.tick(40)
The keyboard events (see pygame.event module) occur only once when the state of a key changes. The KEYDOWN event occurs once every time a key is pressed. KEYUP occurs once every time a key is released. Use the keyboard events for a single action or a step-by-step movement.
If you want to achieve a continuously movement, you have to use pygame.key.get_pressed(). pygame.key.get_pressed() returns a list with the state of each key. If a key is held down, the state for the key is True, otherwise False. Use pygame.key.get_pressed() to evaluate the current state of a button and get continuous movement.
See also Key and Keyboard event and How can I make a sprite move when key is held down.
Minimal example:
import pygame
import os
class Bird(object):
def __init__(self):
self.image = pygame.image.load(os.path.join('C:\Python27', 'player.png'))
self.center = [100, 200]
def move(self, x, y):
self.center[0] += x
self.center[1] += y
def draw(self, surf):
surf.blit(self.image, self.center)
class game(object):
def __init__(self):
self.screen = pygame.display.set_mode((640, 400))
self.clock = pygame.time.Clock()
self.player = Bird()
def run(self):
running = 1
while running:
self.clock.tick(60)
event = pygame.event.poll()
if event.type == pygame.QUIT:
running = 0
keys = pygame.key.get_pressed()
move_x = keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]
move_y = keys[pygame.K_DOWN] - keys[pygame.K_UP]
self.player.move(move_x * 5, move_y * 5)
self.screen.fill([255, 255, 255])
self.player.draw(self.screen)
pygame.display.update()
g = game()
g.run()

I'm wondering why my player and my balloon which are both sprites is stuttering when I move the player

My frames drop and the game basically stops whenever I use the WASD keys, which are my movement controls. Its supposed to make the water balloon move but when I stop moving so does the water balloon. They're both sprites.
I might have got them mixed up since there are two sprite families.
main.py:
import pygame
from player import Player
from projectile import WaterBaloon
# Start the game
pygame.init()
game_width = 1000
game_height = 650
screen = pygame.display.set_mode((game_width, game_height))
clock = pygame.time.Clock()
running = True
bg_image = pygame.image.load("../assets/BG_Sand.png")
#make all the sprite groups
playerGroup = pygame.sprite.Group()
projectilesGroup = pygame.sprite.Group()
#put every sprite class in a group
Player.containers = playerGroup
WaterBaloon.containers = projectilesGroup
#tell the sprites where they are gonna be drawn at
mr_player = Player(screen, game_width/2, game_height/2)
# ***************** Loop Land Below *****************
# Everything under 'while running' will be repeated over and over again
while running:
# Makes the game stop if the player clicks the X or presses esc
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
running = False
#player input that detects keys (to move)
keys = pygame.key.get_pressed()
if keys[pygame.K_d]:
mr_player.move(1, 0)
if keys[pygame.K_a]:
mr_player.move(-1, 0)
if keys[pygame.K_w]:
mr_player.move(0, -1)
if keys[pygame.K_s]:
mr_player.move(0, 1)
if pygame.mouse.get_pressed()[0]:
mr_player.shoot()
#blit the bg image
screen.blit((bg_image),(0, 0))
#update the player
mr_player.update()
#update all the projectiles
for projectile in projectilesGroup:
projectile.update()
# Tell pygame to update the screen
pygame.display.flip()
clock.tick(60)
pygame.display.set_caption("ATTACK OF THE ROBOTS fps: " + str(clock.get_fps()))
player.py:
import pygame
import toolbox
import projectile
#Players Brain
class Player(pygame.sprite.Sprite):
#player constructor function
def __init__(self, screen, x, y):
pygame.sprite.Sprite.__init__(self, self.containers)
self.screen = screen
self.x = x
self.y = y
self.image = pygame.image.load("../assets/player_03.png")
#rectangle for player sprite
self.rect = self.image.get_rect()
self.rect.center = (self.x, self.y)
#end of rectangle for player sprite
self.speed = 8
self.angle = 0
#player update function
def update(self):
self.rect.center = (self.x, self.y)
mouse_x, mouse_y = pygame.mouse.get_pos()
self.angle = toolbox.angleBetweenPoints(self.x, self.y, mouse_x, mouse_y)
#get the rotated version of player
image_to_draw, image_rect = toolbox.getRotatedImage(self.image, self.rect, self.angle)
self.screen.blit(image_to_draw, image_rect)
#tells the computer how to make the player move
def move(self, x_movement, y_movement):
self.x += self.speed * x_movement
self.y += self.speed * y_movement
#shoot function to make a WaterBaloon
def shoot(self):
projectile.WaterBaloon(self.screen, self.x, self.y, self.angle)
You're only processing one event per frame. That's because you've put everything you do inside the frame in the event handling loop. That is likely to break down when you start getting events (such as key press and release events) at a higher rate. If events are not all being processed, your program may not update the screen properly.
You probably want your main loop to only do event processing stuff in the for event in pygame.event.get(): loop. Everything else should be unindented by one level, so that it runs within the outer, while running: loop, after all pending events have been handled.
Try something like this:
while running:
# Makes the game stop if the player clicks the X or presses esc
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
running = False
#player input that detects keys (to move) # unindent here (and all the lines below)
keys = pygame.key.get_pressed()
...

Pygame - alien invasion

I'm doing the alien invasion game and my bullets are just appearing and disappearing. I checked my code many times and I don't know why it is not traveling up the screen. can someone please help me. I don't want to try another method I want to learn by seeing the flaws in my code so I don't repeat the same mistakes again
import sys
import pygame
pygame.init()
# Setting up a window
screen = pygame.display.set_mode((1200, 800))
screen_rect = screen.get_rect()
# Caption
pygame.display.set_caption("space shooter".title())
# Setting up the icon
icon = pygame.image.load("undertake.png").convert_alpha()
pygame.display.set_icon(icon)
# Identifying a Background
bg = pygame.image.load("bg.png").convert_alpha()
# Adding the jet
jet = pygame.image.load("jet.png").convert_alpha()
jet_rect = jet.get_rect()
jet_rect.centerx = screen_rect.centerx
jet_rect.bottom = screen_rect.bottom
# Adding bullets to the left of the jet
bullet = pygame.image.load("pixel_laser_red.png").convert_alpha()
bullet_rect = bullet.get_rect()
bullet_state = "ready"
# Moving the jet
def move_jet(x):
jet_rect.centerx += x
# Firing the bullet
def fire_bullet(x, y):
bullet_state = "fire"
screen.blit(bullet, (x, y))
# Adding Boundaries
def boundaries():
if jet_rect.left >= 1200:
jet_rect.right = 0
elif jet_rect.right <= 0:
jet_rect.left = 1200
# Game Loop
while True:
screen.blit(bg, (0, 0))
screen.blit(jet, jet_rect)
# EVENTS
for event in pygame.event.get():
# Quitting
if event.type == pygame.QUIT:
sys.exit()
# KeyStrokes
pressed = pygame.key.get_pressed()
jet_xincrement = 0
if pressed[pygame.K_RIGHT]:
jet_xincrement += 3
if pressed[pygame.K_LEFT]:
jet_xincrement -= 3
if pressed[pygame.K_SPACE]:
bullet_x = jet_rect.centerx
bullet_y = jet_rect.top
fire_bullet(bullet_x - 28, bullet_y + 7)
if bullet_state == "fire" :
bullet_y -= 10
boundaries()
move_jet(jet_xincrement)
pygame.display.flip()
Actually the bullet is just drawn when space is pressed. You have to draw the bullet continuously in every frame.
The function fire_bullet just sets the state and the position of the bullet. The variables are in global namespace. Hence you have to use the global statement to set them:
bullet_state = "ready"
bullet_x = 0
bullet_y = 0
# Firing the bullet
def fire_bullet(x, y):
global bullet_state, bullet_x, bullet_y
bullet_state = "fire"
bullet_x = x
bullet_y = y
When space is pressed, then the fire_bullet is invoked. The arguments are the current position of the jet. When bullet_state is "fire", then the bullet has to be drawn in the main application loop:
while True:
# [...]
if pressed[pygame.K_SPACE]:
fire_bullet(jet_rect.centerx - 28, jet_rect.top + 7)
if bullet_state == "fire":
bullet_y -= 10
screen.blit(bullet, (bullet_x, bullet_y))
# [...]

Can't do projectile stuff in pygame correctly

Trying to enable shooting projectiles with pygame. After I hit space button it shoots only 1 projectile, fps drops from 100 to ~30, player character can't move and does not react to button presses. After projectile stops being animated fps returns back to 100 and I can move&shoot up to 3 projectiles (as planned) but fps drops again and I can't move until the last projectile reaches the border.
I had a bullet image being loaded instead of drawing bullet before and thought that the case was in it. But the result didn't change. I also tried re-ordering blit() functions but nothing changed as well.
class Game():
# Some game stuff and functions
def __init__(self):
self.x_default = 800
self.y_default = 600
self.screen = pygame.display.set_mode((self.x_default, self.y_default))
#self.background = pygame.image.load('IMGs/BCK2.bmp').convert()
self.title = 'Title'
self.fps = 100
class Projectile():
# This class is supposed to make projectiles
def __init__(self, x, y, speed_x=5, direction=1, width=10, height=10):
# x&y - starting positions of projectiles
# speed_x & speed_y - starting moving speeds of projectiles in # oX & oY
# a - speed increase over time (cancelled for now)
# direction - stays for its' name
# Directions: [2, 3, 1, 4, 5, 6, -1, 7] starting from 0:00 and moving towards the right side of the clock
self.x = x
self.y = y
self.speed_x = speed_x
self.direction = direction
self.width = width
self.height = height
self.img = pygame.Rect(self.x, self.y, self.width, self.height)
def move_projectile(self, x, speed_x, direction):
# Moves stuff
# For now direction works only in right-left (1 for right, -1 for left)
x += speed_x * direction
return x
while 1:
if pygame.event.poll().type == pygame.QUIT:
sys.exit()
for pr in projectiles:
if (pr.x >= -pr.width) and (pr.x <= Game().x_default):
pr.x = pr.move_projectile(x=pr.x, speed_x=pr.speed_x, direction=pr.direction)
else:
projectiles.remove(pr)
keys = pygame.key.get_pressed()
# ------------ oX moving --------------
if keys[pygame.K_LEFT]:
P.x -= P.speed
P.direction = -1
if keys[pygame.K_RIGHT]:
P.x += P.speed
P.direction = 1
# ------------ Shooting ----------------
if keys[pygame.K_SPACE]:
if len(projectiles) < 3:
if P.direction > 0:
projectiles.append(Projectile(x=P.x + P.width, y=P.y + P.height//2, direction=1))
else:
projectiles.append(Projectile(x=P.x, y=P.y + P.height//2, direction=-1))
# ---------- The blitting process --------------
G.screen.blit(G.background, (0, 0))
G.screen.blit(Block1.img, (Block1.x, Block1.y))
G.screen.blit(Block2.img, (Block2.x, Block2.y))
for pr in projectiles:
pygame.draw.rect(G.screen, (0, 0, 0), pr.img)
G.screen.blit(P.img, (P.x, P.y))
pygame.display.update()
pygame.time.delay(1000//G.fps)
See How can i shoot a bullet with space bar? and How do I stop more than 1 bullet firing at once?
keys[pygame.K_SPACE] is True as long SPACE is hold. This means multiple bullets are continuously generated as long the key is hold.
If you want to create a single bullet, when SPACE is pressed, then use the KEYDOWN event (see pygame.event).
The event only occurs once, for each time when the key is pressed. e.g.:
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
if len(projectiles) < 3:
if P.direction > 0:
projectiles.append(Projectile(x=P.x + P.width, y=P.y + P.height//2, direction=1))
else:
projectiles.append(Projectile(x=P.x, y=P.y + P.height//2, direction=-1))
keys = pygame.key.get_pressed()
# [...]

Categories

Resources