Python how to delay bullet shooting - python

Thank you in advance for your time.
If I fire a bullet with space key, a stream of bullets are created. If I would set a delay with time.sleep() inside 'if keys[pygame.K_SPACE]:' it would also freeze the loop for the set amount of seconds. How could I make it so only 1 bullet fires at a time? This is the copy of my game loop, please tell me if more of the code is needed:
def game_loop():
global pause
x = (display_width * 0.2)
y = (display_height * 0.2)
x_change = 0
y_change = 0
blob_speed = 3
velocity = [2, 2]
pos_x = display_width/1.2
pos_y = display_height/1.2
gameExit = False
while not gameExit:
for event in pygame.event.get():#monitors hardware movement/ clicks
if event.type == pygame.QUIT:
pygame.quit()
quit()
pos_x += velocity[0]
pos_y += velocity[1]
if pos_x + blob_width > display_width or pos_x < 601:
velocity[0] = -velocity[0]
if pos_y + blob_height > display_height or pos_y < 0:
velocity[1] = -velocity[1]
# Checks to see if any keys are held down and remembers them with the variable keys.
keys = pygame.key.get_pressed()
for b in range(len(bullets)):
bullets[b][0] += 6
for bullet in bullets:
if bullet[0] > 1005:
bullets.remove(bullet)
if keys[pygame.K_SPACE]:
bullets.append([x+25, y+24])
# If the player is holding down one key or the other the blob moves in that direction
if x < 0:
x = 0
if keys[pygame.K_a]:
x_change = -blob_speed
if x > 401 - blob_width:
x = 401 - blob_width
if keys[pygame.K_d]:
x_change = blob_speed
if keys[pygame.K_p]:
pause = True
paused()
# If the player is holding down both or neither of the keys the blob stops
if keys[pygame.K_a] and keys[pygame.K_d]:
x_change = 0
if not keys[pygame.K_a] and not keys[pygame.K_d]:
x_change = 0
if y < 0:
y = 0
if keys[pygame.K_w]:
y_change = -blob_speed
if y > display_height - blob_height:
y = display_height - blob_height
if keys[pygame.K_s]:
y_change = blob_speed
if keys[pygame.K_w] and keys[pygame.K_s]:
y_change = 0
if not keys[pygame.K_w] and not keys[pygame.K_s]:
y_change = 0
#print(event)
# Reset x and y to new position
x += x_change
y += y_change
gameDisplay.fill(blue) #changes background surface
pygame.draw.line(gameDisplay, black, (601, display_height), (601, 0), 3)
pygame.draw.line(gameDisplay, black, (401, display_height), (401, 0), 3)
blob(pos_x, pos_y)
blob(x, y)
for bullet in bullets:
gameDisplay.blit(bulletpicture, pygame.Rect(bullet[0], bullet[1], 0, 0))
pygame.display.update() #update screen
clock.tick(120)#moves frame on (fps in parameters)

Here's an answer without classes. You just have to store the previous time when a bullet was fired, subtract it from the current time and check if it's above some time limit (500 ms in this example) to see if we're ready to fire.
import pygame
def game_loop():
pygame.init()
gameDisplay = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
bulletpicture = pygame.Surface((10, 5))
bulletpicture.fill(pygame.Color('sienna1'))
bullets = []
x = 50
y = 240
previous_time = pygame.time.get_ticks()
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE]:
current_time = pygame.time.get_ticks()
# We're ready to fire when 500 ms have passed.
if current_time - previous_time > 500:
previous_time = current_time
bullets.append([x+25, y+24])
remaining_bullets = []
for bullet in bullets:
bullet[0] += 6 # Move the bullet.
if bullet[0] < 500: # Filter out the bullets.
remaining_bullets.append(bullet)
bullets = remaining_bullets
gameDisplay.fill((30, 30, 30))
for bullet in bullets:
gameDisplay.blit(bulletpicture, pygame.Rect(bullet[0], bullet[1], 0, 0))
pygame.display.update()
clock.tick(120)
game_loop()
pygame.quit()

Related

I'm trying to make a Galaga game from scratch but I ran into a problem, the spaceship could spam the bullets and my cooldown code doesn't work [duplicate]

import pygame
pygame.init()
red = 255,0,0
blue = 0,0,255
black = 0,0,0
screenWidth = 800
screenHeight = 600
gameDisplay = pygame.display.set_mode((screenWidth,screenHeight)) ## screen width and height
pygame.display.set_caption('JUST SOME BLOCKS') ## set my title of the window
clock = pygame.time.Clock()
class player(): ## has all of my attributes for player 1
def __init__(self,x,y,width,height):
self.x = x
self.y = y
self.height = height
self.width = width
self.vel = 5
self.left = False
self.right = False
self.up = False
self.down = False
class projectile(): ## projectile attributes
def __init__(self,x,y,radius,colour,facing):
self.x = x
self.y = y
self.radius = radius
self.facing = facing
self.colour = colour
self.vel = 8 * facing # speed of bullet * the direction (-1 or 1)
def draw(self,gameDisplay):
pygame.draw.circle(gameDisplay, self.colour , (self.x,self.y),self.radius) ## put a 1 after that to make it so the circle is just an outline
def redrawGameWindow():
for bullet in bullets: ## draw bullets
bullet.draw(gameDisplay)
pygame.display.update()
#mainloop
player1 = player(300,410,50,70) # moves the stuff from the class (when variables are user use player1.var)
bullets = []
run = True
while run == True:
clock.tick(27)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
for bullet in bullets:
if bullet.x < screenWidth and bullet.x > 0 and bullet.y < screenHeight and bullet.y > 0: ## makes sure bullet does not go off screen
bullet.x += bullet.vel
else:
bullets.pop(bullets.index(bullet))
keys = pygame.key.get_pressed() ## check if a key has been pressed
## red player movement
if keys[pygame.K_w] and player1.y > player1.vel: ## check if that key has been pressed down (this will check for w) and checks for boundry
player1.y -= player1.vel ## move the shape in a direction
player1.up = True
player1.down = False
if keys[pygame.K_a] and player1.x > player1.vel: ### this is for a
player1.x -= player1.vel
player1.left = True
player1.right = False
if keys[pygame.K_s] and player1.y < screenHeight - player1.height - player1.vel: ## this is for s
player1.y += player1.vel
player1.down = True
player1.up = False
if keys[pygame.K_d] and player1.x < screenWidth - player1.width - player1.vel: ## this is for d
player1.x += player1.vel
player1.right = True
player1.left = False
if keys[pygame.K_SPACE]: # shooting with the space bar
if player1.left == True: ## handles the direction of the bullet
facing = -1
else:
facing = 1
if len(bullets) < 5: ## max amounts of bullets on screen
bullets.append(projectile(player1.x + player1.width //2 ,player1.y + player1.height//2,6,black,facing)) ##just like calling upon a function
## level
gameDisplay.fill((0,255,0)) ### will stop the shape from spreading around and will have a background
pygame.draw.rect(gameDisplay,(red),(player1.x,player1.y,player1.width,player1.height)) ## draw player
pygame.display.update()
redrawGameWindow()
pygame.quit()
When I shoot more than 1 bullet fires and I only want 1 bullet to fire at a time (but not only 1 bullet on the screen)
They all fire in a large clump and stick together also so I want them to fire at different times
I have tried using a delay clock.tick but that makes the game extremely laggy
I am relatively new to pygame and don't fully understand it any help would be appreciated thanks !
The general approach to firing bullets is to store the positions of the bullets in a list (bullet_list). When a bullet is fired, add the bullet's starting position ([start_x, start_y]) to the list. The starting position is the position of the object (player or enemy) that fires the bullet. Use a for-loop to iterate through all the bullets in the list. Move position of each individual bullet in the loop. Remove a bullet from the list that leaves the screen (bullet_list.remove(bullet_pos)). For this reason, a copy of the list (bullet_list[:]) must be run through (see How to remove items from a list while iterating?). Use another for-loop to blit the remaining bullets on the screen:
bullet_list = []
while run == True:
# [...]
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
bullet_list.append([start_x, start_y])
for bullet_pos in bullet_list[:]:
bullet_pos[0] += move_bullet_x
bullet_pos[1] += move_bullet_y
if not screen.get_rect().colliderect(bullet_image.get_rect(center = bullet_pos))
bullet_list.remove(bullet_pos)
# [...]
for bullet_pos in bullet_list[:]
screen.blit(bullet_image, bullet_image.get_rect(center = bullet_pos))
# [...]
See also Shoot bullet.
The states which are returned by pygame.key.get_pressed() are, set, as long a key is hold down. That is useful for the movement of a player. The player keeps moving as long a key is hold down.
But it contradicts your intention, when you want to fire a bullet. If you want to fire a bullet when a key is pressed, then can use the KEYDOWN event. The event occurs only once when a key is pressed:
while run == True:
clock.tick(27)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
if player1.left == True: ## handles the direction of the bullet
facing = -1
else:
facing = 1
if len(bullets) < 5: ## max amounts of bullets on screen
bx, by = player1.x + player1.width //2 ,player1.y + player1.height//2
bullets.append(projectile(bx, by, 6, black, facing))
# [...]
If you want to implement some kind of rapid fire, then the things get more tricky. If you would use the state of pygame.key.get_pressed() then you would spawn one bullet in every frame. That is far too fast. You have to implement some timeout.
When a bullet is fired, the get the current time by pygame.time.get_ticks(). Define a number of milliseconds for the delay between to bullets. Add the dela to the time and state the time in a variable (next_bullet_threshold). Skip bullets, as long the time is not exceeded:
next_bullet_threshold = 0
run = True
while run == True:
# [...]
current_time = pygame.time.get_ticks()
if keys[pygame.K_SPACE] and current_time > next_bullet_threshold:
bullet_delay = 500 # 500 milliseconds (0.5 seconds)
next_bullet_threshold = current_time + bullet_delay
if player1.left == True: ## handles the direction of the bullet
facing = -1
else:
facing = 1
if len(bullets) < 5:
bx, by = player1.x + player1.width //2 ,player1.y + player1.height//2
bullets.append(projectile(bx, by, 6, black, facing))
Minimal example: repl.it/#Rabbid76/PyGame-ShootBullet
import pygame
pygame.init()
window = pygame.display.set_mode((500, 200))
clock = pygame.time.Clock()
tank_surf = pygame.Surface((60, 40), pygame.SRCALPHA)
pygame.draw.rect(tank_surf, (0, 96, 0), (0, 00, 50, 40))
pygame.draw.rect(tank_surf, (0, 128, 0), (10, 10, 30, 20))
pygame.draw.rect(tank_surf, (32, 32, 96), (20, 16, 40, 8))
tank_rect = tank_surf.get_rect(midleft = (20, window.get_height() // 2))
bullet_surf = pygame.Surface((10, 10), pygame.SRCALPHA)
pygame.draw.circle(bullet_surf, (64, 64, 62), bullet_surf.get_rect().center, bullet_surf.get_width() // 2)
bullet_list = []
max_bullets = 4
next_bullet_time = 0
bullet_delta_time = 200 # milliseconds
run = True
while run:
clock.tick(60)
current_time = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if len(bullet_list) < max_bullets and current_time >= next_bullet_time:
next_bullet_time = current_time + bullet_delta_time
bullet_list.insert(0, tank_rect.midright)
for i, bullet_pos in enumerate(bullet_list):
bullet_list[i] = bullet_pos[0] + 5, bullet_pos[1]
if bullet_surf.get_rect(center = bullet_pos).left > window.get_width():
del bullet_list[i:]
break
window.fill((224, 192, 160))
window.blit(tank_surf, tank_rect)
for bullet_pos in bullet_list:
window.blit(bullet_surf, bullet_surf.get_rect(center = bullet_pos))
pygame.display.flip()
pygame.quit()
exit()

How can I do a double jump in pygame?

Can someone please help me debug my code because I don't get why I cannot make my character do a double jump with multiple spacebars. When I ran the script, I could move up,down,left,right but once I press spacebar one time, the object flies out of the window.
The problem comes with this if statement so I'm guessing that this if statement keeps running and incrementing my jumpCount, which I can't comprehend because after pressing space one time shouldn't the keys[pygame.K_SPACE] evaluate to true and then back to false again so this if statement shouldn't run unless I press another spacebar?
else:
if keys[pygame.K_SPACE]:
jumpCount += 5
number_to_compensate += 1
Here is my script:
import pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("First Game")
x = 50
y = 50
width = 40
height = 60
vel = 5
isJump = False
jumpCount = 5 #To calculate the height I have to rise by
number_to_compensate = 0 #So the more times I press space(higher I jump) the more I have to fall by
run = True
while run:
pygame.time.delay(20)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and x > vel:
x -= vel
if keys[pygame.K_RIGHT] and x < 500 - vel - width:
x += vel
if not (isJump):
if keys[pygame.K_UP] and y > vel:
y -= vel
if keys[pygame.K_DOWN] and y < 500 - height - vel:
y += vel
if keys[pygame.K_SPACE]:
isJump = True
number_to_compensate += 1
else:
if keys[pygame.K_SPACE]:
jumpCount += 5
number_to_compensate += 1
if jumpCount >= -5 *number_to_compensate:
y -= (jumpCount * abs(jumpCount)) * 0.5
jumpCount -= 1
else:
jumpCount = 5
isJump = False
number_to_compensate = 0
win.fill((0, 0, 0))
pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
pygame.display.update()
pygame.quit()
To what you want you need to change some the jump algorithm. Calculate the jump based on an acceleration and a velocity.
Define constants for the gravity and jump acceleration:
PLAYER_ACC = 15
PLAYER_GRAV = 1
Use the keyboard events for the jump, instead of pygame.key.get_pressed(). 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.
Set the jump acceleration when the space is pressed:
acc_y = PLAYER_GRAV
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
acc_y = -PLAYER_ACC
vel_y = 0
Change the velocity depending on the acceleration and the y coordinate depending on the velocity in every frame:
vel_y += acc_y
y += vel_y
Limit the y-coordinate by the ground:
if y + height > ground_y:
y = ground_y - height
vel_y = 0
acc_y = 0
Minimal example:
import pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("First Game")
clock = pygame.time.Clock()
ground_y = 400
x, y = 200, ground_y
width, height = 40, 60
vel_x, vel_y = 5, 0
acc_y = 0
PLAYER_ACC = 15
PLAYER_GRAV = 1
run = True
while run:
acc_y = PLAYER_GRAV
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
acc_y = -PLAYER_ACC
vel_y = 0
keys = pygame.key.get_pressed()
x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel_x
x = max(0, min(500 - width, x))
vel_y += acc_y
y += vel_y
if y + height > ground_y:
y = ground_y - height
vel_y = 0
acc_y = 0
win.fill((0, 0, 0))
pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
pygame.display.update()
clock.tick(60)
pygame.quit()

How would I implement a timer in my game created with pygame? [duplicate]

import pygame
pygame.init()
red = 255,0,0
blue = 0,0,255
black = 0,0,0
screenWidth = 800
screenHeight = 600
gameDisplay = pygame.display.set_mode((screenWidth,screenHeight)) ## screen width and height
pygame.display.set_caption('JUST SOME BLOCKS') ## set my title of the window
clock = pygame.time.Clock()
class player(): ## has all of my attributes for player 1
def __init__(self,x,y,width,height):
self.x = x
self.y = y
self.height = height
self.width = width
self.vel = 5
self.left = False
self.right = False
self.up = False
self.down = False
class projectile(): ## projectile attributes
def __init__(self,x,y,radius,colour,facing):
self.x = x
self.y = y
self.radius = radius
self.facing = facing
self.colour = colour
self.vel = 8 * facing # speed of bullet * the direction (-1 or 1)
def draw(self,gameDisplay):
pygame.draw.circle(gameDisplay, self.colour , (self.x,self.y),self.radius) ## put a 1 after that to make it so the circle is just an outline
def redrawGameWindow():
for bullet in bullets: ## draw bullets
bullet.draw(gameDisplay)
pygame.display.update()
#mainloop
player1 = player(300,410,50,70) # moves the stuff from the class (when variables are user use player1.var)
bullets = []
run = True
while run == True:
clock.tick(27)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
for bullet in bullets:
if bullet.x < screenWidth and bullet.x > 0 and bullet.y < screenHeight and bullet.y > 0: ## makes sure bullet does not go off screen
bullet.x += bullet.vel
else:
bullets.pop(bullets.index(bullet))
keys = pygame.key.get_pressed() ## check if a key has been pressed
## red player movement
if keys[pygame.K_w] and player1.y > player1.vel: ## check if that key has been pressed down (this will check for w) and checks for boundry
player1.y -= player1.vel ## move the shape in a direction
player1.up = True
player1.down = False
if keys[pygame.K_a] and player1.x > player1.vel: ### this is for a
player1.x -= player1.vel
player1.left = True
player1.right = False
if keys[pygame.K_s] and player1.y < screenHeight - player1.height - player1.vel: ## this is for s
player1.y += player1.vel
player1.down = True
player1.up = False
if keys[pygame.K_d] and player1.x < screenWidth - player1.width - player1.vel: ## this is for d
player1.x += player1.vel
player1.right = True
player1.left = False
if keys[pygame.K_SPACE]: # shooting with the space bar
if player1.left == True: ## handles the direction of the bullet
facing = -1
else:
facing = 1
if len(bullets) < 5: ## max amounts of bullets on screen
bullets.append(projectile(player1.x + player1.width //2 ,player1.y + player1.height//2,6,black,facing)) ##just like calling upon a function
## level
gameDisplay.fill((0,255,0)) ### will stop the shape from spreading around and will have a background
pygame.draw.rect(gameDisplay,(red),(player1.x,player1.y,player1.width,player1.height)) ## draw player
pygame.display.update()
redrawGameWindow()
pygame.quit()
When I shoot more than 1 bullet fires and I only want 1 bullet to fire at a time (but not only 1 bullet on the screen)
They all fire in a large clump and stick together also so I want them to fire at different times
I have tried using a delay clock.tick but that makes the game extremely laggy
I am relatively new to pygame and don't fully understand it any help would be appreciated thanks !
The general approach to firing bullets is to store the positions of the bullets in a list (bullet_list). When a bullet is fired, add the bullet's starting position ([start_x, start_y]) to the list. The starting position is the position of the object (player or enemy) that fires the bullet. Use a for-loop to iterate through all the bullets in the list. Move position of each individual bullet in the loop. Remove a bullet from the list that leaves the screen (bullet_list.remove(bullet_pos)). For this reason, a copy of the list (bullet_list[:]) must be run through (see How to remove items from a list while iterating?). Use another for-loop to blit the remaining bullets on the screen:
bullet_list = []
while run == True:
# [...]
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
bullet_list.append([start_x, start_y])
for bullet_pos in bullet_list[:]:
bullet_pos[0] += move_bullet_x
bullet_pos[1] += move_bullet_y
if not screen.get_rect().colliderect(bullet_image.get_rect(center = bullet_pos))
bullet_list.remove(bullet_pos)
# [...]
for bullet_pos in bullet_list[:]
screen.blit(bullet_image, bullet_image.get_rect(center = bullet_pos))
# [...]
See also Shoot bullet.
The states which are returned by pygame.key.get_pressed() are, set, as long a key is hold down. That is useful for the movement of a player. The player keeps moving as long a key is hold down.
But it contradicts your intention, when you want to fire a bullet. If you want to fire a bullet when a key is pressed, then can use the KEYDOWN event. The event occurs only once when a key is pressed:
while run == True:
clock.tick(27)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
if player1.left == True: ## handles the direction of the bullet
facing = -1
else:
facing = 1
if len(bullets) < 5: ## max amounts of bullets on screen
bx, by = player1.x + player1.width //2 ,player1.y + player1.height//2
bullets.append(projectile(bx, by, 6, black, facing))
# [...]
If you want to implement some kind of rapid fire, then the things get more tricky. If you would use the state of pygame.key.get_pressed() then you would spawn one bullet in every frame. That is far too fast. You have to implement some timeout.
When a bullet is fired, the get the current time by pygame.time.get_ticks(). Define a number of milliseconds for the delay between to bullets. Add the dela to the time and state the time in a variable (next_bullet_threshold). Skip bullets, as long the time is not exceeded:
next_bullet_threshold = 0
run = True
while run == True:
# [...]
current_time = pygame.time.get_ticks()
if keys[pygame.K_SPACE] and current_time > next_bullet_threshold:
bullet_delay = 500 # 500 milliseconds (0.5 seconds)
next_bullet_threshold = current_time + bullet_delay
if player1.left == True: ## handles the direction of the bullet
facing = -1
else:
facing = 1
if len(bullets) < 5:
bx, by = player1.x + player1.width //2 ,player1.y + player1.height//2
bullets.append(projectile(bx, by, 6, black, facing))
Minimal example: repl.it/#Rabbid76/PyGame-ShootBullet
import pygame
pygame.init()
window = pygame.display.set_mode((500, 200))
clock = pygame.time.Clock()
tank_surf = pygame.Surface((60, 40), pygame.SRCALPHA)
pygame.draw.rect(tank_surf, (0, 96, 0), (0, 00, 50, 40))
pygame.draw.rect(tank_surf, (0, 128, 0), (10, 10, 30, 20))
pygame.draw.rect(tank_surf, (32, 32, 96), (20, 16, 40, 8))
tank_rect = tank_surf.get_rect(midleft = (20, window.get_height() // 2))
bullet_surf = pygame.Surface((10, 10), pygame.SRCALPHA)
pygame.draw.circle(bullet_surf, (64, 64, 62), bullet_surf.get_rect().center, bullet_surf.get_width() // 2)
bullet_list = []
max_bullets = 4
next_bullet_time = 0
bullet_delta_time = 200 # milliseconds
run = True
while run:
clock.tick(60)
current_time = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if len(bullet_list) < max_bullets and current_time >= next_bullet_time:
next_bullet_time = current_time + bullet_delta_time
bullet_list.insert(0, tank_rect.midright)
for i, bullet_pos in enumerate(bullet_list):
bullet_list[i] = bullet_pos[0] + 5, bullet_pos[1]
if bullet_surf.get_rect(center = bullet_pos).left > window.get_width():
del bullet_list[i:]
break
window.fill((224, 192, 160))
window.blit(tank_surf, tank_rect)
for bullet_pos in bullet_list:
window.blit(bullet_surf, bullet_surf.get_rect(center = bullet_pos))
pygame.display.flip()
pygame.quit()
exit()

How to make my bullets fire when I press my key? [duplicate]

import pygame
pygame.init()
red = 255,0,0
blue = 0,0,255
black = 0,0,0
screenWidth = 800
screenHeight = 600
gameDisplay = pygame.display.set_mode((screenWidth,screenHeight)) ## screen width and height
pygame.display.set_caption('JUST SOME BLOCKS') ## set my title of the window
clock = pygame.time.Clock()
class player(): ## has all of my attributes for player 1
def __init__(self,x,y,width,height):
self.x = x
self.y = y
self.height = height
self.width = width
self.vel = 5
self.left = False
self.right = False
self.up = False
self.down = False
class projectile(): ## projectile attributes
def __init__(self,x,y,radius,colour,facing):
self.x = x
self.y = y
self.radius = radius
self.facing = facing
self.colour = colour
self.vel = 8 * facing # speed of bullet * the direction (-1 or 1)
def draw(self,gameDisplay):
pygame.draw.circle(gameDisplay, self.colour , (self.x,self.y),self.radius) ## put a 1 after that to make it so the circle is just an outline
def redrawGameWindow():
for bullet in bullets: ## draw bullets
bullet.draw(gameDisplay)
pygame.display.update()
#mainloop
player1 = player(300,410,50,70) # moves the stuff from the class (when variables are user use player1.var)
bullets = []
run = True
while run == True:
clock.tick(27)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
for bullet in bullets:
if bullet.x < screenWidth and bullet.x > 0 and bullet.y < screenHeight and bullet.y > 0: ## makes sure bullet does not go off screen
bullet.x += bullet.vel
else:
bullets.pop(bullets.index(bullet))
keys = pygame.key.get_pressed() ## check if a key has been pressed
## red player movement
if keys[pygame.K_w] and player1.y > player1.vel: ## check if that key has been pressed down (this will check for w) and checks for boundry
player1.y -= player1.vel ## move the shape in a direction
player1.up = True
player1.down = False
if keys[pygame.K_a] and player1.x > player1.vel: ### this is for a
player1.x -= player1.vel
player1.left = True
player1.right = False
if keys[pygame.K_s] and player1.y < screenHeight - player1.height - player1.vel: ## this is for s
player1.y += player1.vel
player1.down = True
player1.up = False
if keys[pygame.K_d] and player1.x < screenWidth - player1.width - player1.vel: ## this is for d
player1.x += player1.vel
player1.right = True
player1.left = False
if keys[pygame.K_SPACE]: # shooting with the space bar
if player1.left == True: ## handles the direction of the bullet
facing = -1
else:
facing = 1
if len(bullets) < 5: ## max amounts of bullets on screen
bullets.append(projectile(player1.x + player1.width //2 ,player1.y + player1.height//2,6,black,facing)) ##just like calling upon a function
## level
gameDisplay.fill((0,255,0)) ### will stop the shape from spreading around and will have a background
pygame.draw.rect(gameDisplay,(red),(player1.x,player1.y,player1.width,player1.height)) ## draw player
pygame.display.update()
redrawGameWindow()
pygame.quit()
When I shoot more than 1 bullet fires and I only want 1 bullet to fire at a time (but not only 1 bullet on the screen)
They all fire in a large clump and stick together also so I want them to fire at different times
I have tried using a delay clock.tick but that makes the game extremely laggy
I am relatively new to pygame and don't fully understand it any help would be appreciated thanks !
The general approach to firing bullets is to store the positions of the bullets in a list (bullet_list). When a bullet is fired, add the bullet's starting position ([start_x, start_y]) to the list. The starting position is the position of the object (player or enemy) that fires the bullet. Use a for-loop to iterate through all the bullets in the list. Move position of each individual bullet in the loop. Remove a bullet from the list that leaves the screen (bullet_list.remove(bullet_pos)). For this reason, a copy of the list (bullet_list[:]) must be run through (see How to remove items from a list while iterating?). Use another for-loop to blit the remaining bullets on the screen:
bullet_list = []
while run == True:
# [...]
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
bullet_list.append([start_x, start_y])
for bullet_pos in bullet_list[:]:
bullet_pos[0] += move_bullet_x
bullet_pos[1] += move_bullet_y
if not screen.get_rect().colliderect(bullet_image.get_rect(center = bullet_pos))
bullet_list.remove(bullet_pos)
# [...]
for bullet_pos in bullet_list[:]
screen.blit(bullet_image, bullet_image.get_rect(center = bullet_pos))
# [...]
See also Shoot bullet.
The states which are returned by pygame.key.get_pressed() are, set, as long a key is hold down. That is useful for the movement of a player. The player keeps moving as long a key is hold down.
But it contradicts your intention, when you want to fire a bullet. If you want to fire a bullet when a key is pressed, then can use the KEYDOWN event. The event occurs only once when a key is pressed:
while run == True:
clock.tick(27)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
if player1.left == True: ## handles the direction of the bullet
facing = -1
else:
facing = 1
if len(bullets) < 5: ## max amounts of bullets on screen
bx, by = player1.x + player1.width //2 ,player1.y + player1.height//2
bullets.append(projectile(bx, by, 6, black, facing))
# [...]
If you want to implement some kind of rapid fire, then the things get more tricky. If you would use the state of pygame.key.get_pressed() then you would spawn one bullet in every frame. That is far too fast. You have to implement some timeout.
When a bullet is fired, the get the current time by pygame.time.get_ticks(). Define a number of milliseconds for the delay between to bullets. Add the dela to the time and state the time in a variable (next_bullet_threshold). Skip bullets, as long the time is not exceeded:
next_bullet_threshold = 0
run = True
while run == True:
# [...]
current_time = pygame.time.get_ticks()
if keys[pygame.K_SPACE] and current_time > next_bullet_threshold:
bullet_delay = 500 # 500 milliseconds (0.5 seconds)
next_bullet_threshold = current_time + bullet_delay
if player1.left == True: ## handles the direction of the bullet
facing = -1
else:
facing = 1
if len(bullets) < 5:
bx, by = player1.x + player1.width //2 ,player1.y + player1.height//2
bullets.append(projectile(bx, by, 6, black, facing))
Minimal example: repl.it/#Rabbid76/PyGame-ShootBullet
import pygame
pygame.init()
window = pygame.display.set_mode((500, 200))
clock = pygame.time.Clock()
tank_surf = pygame.Surface((60, 40), pygame.SRCALPHA)
pygame.draw.rect(tank_surf, (0, 96, 0), (0, 00, 50, 40))
pygame.draw.rect(tank_surf, (0, 128, 0), (10, 10, 30, 20))
pygame.draw.rect(tank_surf, (32, 32, 96), (20, 16, 40, 8))
tank_rect = tank_surf.get_rect(midleft = (20, window.get_height() // 2))
bullet_surf = pygame.Surface((10, 10), pygame.SRCALPHA)
pygame.draw.circle(bullet_surf, (64, 64, 62), bullet_surf.get_rect().center, bullet_surf.get_width() // 2)
bullet_list = []
max_bullets = 4
next_bullet_time = 0
bullet_delta_time = 200 # milliseconds
run = True
while run:
clock.tick(60)
current_time = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if len(bullet_list) < max_bullets and current_time >= next_bullet_time:
next_bullet_time = current_time + bullet_delta_time
bullet_list.insert(0, tank_rect.midright)
for i, bullet_pos in enumerate(bullet_list):
bullet_list[i] = bullet_pos[0] + 5, bullet_pos[1]
if bullet_surf.get_rect(center = bullet_pos).left > window.get_width():
del bullet_list[i:]
break
window.fill((224, 192, 160))
window.blit(tank_surf, tank_rect)
for bullet_pos in bullet_list:
window.blit(bullet_surf, bullet_surf.get_rect(center = bullet_pos))
pygame.display.flip()
pygame.quit()
exit()

How do I stop more than 1 bullet firing at once?

import pygame
pygame.init()
red = 255,0,0
blue = 0,0,255
black = 0,0,0
screenWidth = 800
screenHeight = 600
gameDisplay = pygame.display.set_mode((screenWidth,screenHeight)) ## screen width and height
pygame.display.set_caption('JUST SOME BLOCKS') ## set my title of the window
clock = pygame.time.Clock()
class player(): ## has all of my attributes for player 1
def __init__(self,x,y,width,height):
self.x = x
self.y = y
self.height = height
self.width = width
self.vel = 5
self.left = False
self.right = False
self.up = False
self.down = False
class projectile(): ## projectile attributes
def __init__(self,x,y,radius,colour,facing):
self.x = x
self.y = y
self.radius = radius
self.facing = facing
self.colour = colour
self.vel = 8 * facing # speed of bullet * the direction (-1 or 1)
def draw(self,gameDisplay):
pygame.draw.circle(gameDisplay, self.colour , (self.x,self.y),self.radius) ## put a 1 after that to make it so the circle is just an outline
def redrawGameWindow():
for bullet in bullets: ## draw bullets
bullet.draw(gameDisplay)
pygame.display.update()
#mainloop
player1 = player(300,410,50,70) # moves the stuff from the class (when variables are user use player1.var)
bullets = []
run = True
while run == True:
clock.tick(27)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
for bullet in bullets:
if bullet.x < screenWidth and bullet.x > 0 and bullet.y < screenHeight and bullet.y > 0: ## makes sure bullet does not go off screen
bullet.x += bullet.vel
else:
bullets.pop(bullets.index(bullet))
keys = pygame.key.get_pressed() ## check if a key has been pressed
## red player movement
if keys[pygame.K_w] and player1.y > player1.vel: ## check if that key has been pressed down (this will check for w) and checks for boundry
player1.y -= player1.vel ## move the shape in a direction
player1.up = True
player1.down = False
if keys[pygame.K_a] and player1.x > player1.vel: ### this is for a
player1.x -= player1.vel
player1.left = True
player1.right = False
if keys[pygame.K_s] and player1.y < screenHeight - player1.height - player1.vel: ## this is for s
player1.y += player1.vel
player1.down = True
player1.up = False
if keys[pygame.K_d] and player1.x < screenWidth - player1.width - player1.vel: ## this is for d
player1.x += player1.vel
player1.right = True
player1.left = False
if keys[pygame.K_SPACE]: # shooting with the space bar
if player1.left == True: ## handles the direction of the bullet
facing = -1
else:
facing = 1
if len(bullets) < 5: ## max amounts of bullets on screen
bullets.append(projectile(player1.x + player1.width //2 ,player1.y + player1.height//2,6,black,facing)) ##just like calling upon a function
## level
gameDisplay.fill((0,255,0)) ### will stop the shape from spreading around and will have a background
pygame.draw.rect(gameDisplay,(red),(player1.x,player1.y,player1.width,player1.height)) ## draw player
pygame.display.update()
redrawGameWindow()
pygame.quit()
When I shoot more than 1 bullet fires and I only want 1 bullet to fire at a time (but not only 1 bullet on the screen)
They all fire in a large clump and stick together also so I want them to fire at different times
I have tried using a delay clock.tick but that makes the game extremely laggy
I am relatively new to pygame and don't fully understand it any help would be appreciated thanks !
The general approach to firing bullets is to store the positions of the bullets in a list (bullet_list). When a bullet is fired, add the bullet's starting position ([start_x, start_y]) to the list. The starting position is the position of the object (player or enemy) that fires the bullet. Use a for-loop to iterate through all the bullets in the list. Move position of each individual bullet in the loop. Remove a bullet from the list that leaves the screen (bullet_list.remove(bullet_pos)). For this reason, a copy of the list (bullet_list[:]) must be run through (see How to remove items from a list while iterating?). Use another for-loop to blit the remaining bullets on the screen:
bullet_list = []
while run == True:
# [...]
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
bullet_list.append([start_x, start_y])
for bullet_pos in bullet_list[:]:
bullet_pos[0] += move_bullet_x
bullet_pos[1] += move_bullet_y
if not screen.get_rect().colliderect(bullet_image.get_rect(center = bullet_pos))
bullet_list.remove(bullet_pos)
# [...]
for bullet_pos in bullet_list[:]
screen.blit(bullet_image, bullet_image.get_rect(center = bullet_pos))
# [...]
See also Shoot bullet.
The states which are returned by pygame.key.get_pressed() are, set, as long a key is hold down. That is useful for the movement of a player. The player keeps moving as long a key is hold down.
But it contradicts your intention, when you want to fire a bullet. If you want to fire a bullet when a key is pressed, then can use the KEYDOWN event. The event occurs only once when a key is pressed:
while run == True:
clock.tick(27)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
if player1.left == True: ## handles the direction of the bullet
facing = -1
else:
facing = 1
if len(bullets) < 5: ## max amounts of bullets on screen
bx, by = player1.x + player1.width //2 ,player1.y + player1.height//2
bullets.append(projectile(bx, by, 6, black, facing))
# [...]
If you want to implement some kind of rapid fire, then the things get more tricky. If you would use the state of pygame.key.get_pressed() then you would spawn one bullet in every frame. That is far too fast. You have to implement some timeout.
When a bullet is fired, the get the current time by pygame.time.get_ticks(). Define a number of milliseconds for the delay between to bullets. Add the dela to the time and state the time in a variable (next_bullet_threshold). Skip bullets, as long the time is not exceeded:
next_bullet_threshold = 0
run = True
while run == True:
# [...]
current_time = pygame.time.get_ticks()
if keys[pygame.K_SPACE] and current_time > next_bullet_threshold:
bullet_delay = 500 # 500 milliseconds (0.5 seconds)
next_bullet_threshold = current_time + bullet_delay
if player1.left == True: ## handles the direction of the bullet
facing = -1
else:
facing = 1
if len(bullets) < 5:
bx, by = player1.x + player1.width //2 ,player1.y + player1.height//2
bullets.append(projectile(bx, by, 6, black, facing))
Minimal example: repl.it/#Rabbid76/PyGame-ShootBullet
import pygame
pygame.init()
window = pygame.display.set_mode((500, 200))
clock = pygame.time.Clock()
tank_surf = pygame.Surface((60, 40), pygame.SRCALPHA)
pygame.draw.rect(tank_surf, (0, 96, 0), (0, 00, 50, 40))
pygame.draw.rect(tank_surf, (0, 128, 0), (10, 10, 30, 20))
pygame.draw.rect(tank_surf, (32, 32, 96), (20, 16, 40, 8))
tank_rect = tank_surf.get_rect(midleft = (20, window.get_height() // 2))
bullet_surf = pygame.Surface((10, 10), pygame.SRCALPHA)
pygame.draw.circle(bullet_surf, (64, 64, 62), bullet_surf.get_rect().center, bullet_surf.get_width() // 2)
bullet_list = []
max_bullets = 4
next_bullet_time = 0
bullet_delta_time = 200 # milliseconds
run = True
while run:
clock.tick(60)
current_time = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if len(bullet_list) < max_bullets and current_time >= next_bullet_time:
next_bullet_time = current_time + bullet_delta_time
bullet_list.insert(0, tank_rect.midright)
for i, bullet_pos in enumerate(bullet_list):
bullet_list[i] = bullet_pos[0] + 5, bullet_pos[1]
if bullet_surf.get_rect(center = bullet_pos).left > window.get_width():
del bullet_list[i:]
break
window.fill((224, 192, 160))
window.blit(tank_surf, tank_rect)
for bullet_pos in bullet_list:
window.blit(bullet_surf, bullet_surf.get_rect(center = bullet_pos))
pygame.display.flip()
pygame.quit()
exit()

Categories