Bullets Not Appearing in Simple Space Invader Game - python

I'm a new programmer and am trying to figure out why my bullets aren't showing up. It seems that the Y coordinate changes, but for some reason the bullets are not showing up. This is my code in Python:
#Importing necessary modules
import random
import pygame
import sys
#Setting up pygame
pygame.init()
shooting = False
n = 0
keys = [False,False,False,False]
clock = pygame.time.Clock()
screen = pygame.display.set_mode([500,500])
font = pygame.font.Font(None,50)
#Creating class for player
class Player:
def __init__(self,x,y,width,height):
self.x = x
self.y = y
self.width = width
self.height = height
def draw(self):
pygame.draw.rect(screen,[0,255,0],
[int(self.x),int(self.y),int(self.width),int(self.height)],0)
def move(self):
if keys[1] == True:
self.x -= 1
elif keys[3] == True:
self.x += 1
if self.x < 0:
print(self.x)
self.x = 0
if self.x > 500 - self.width:
print(self.x)
self.x = 500 - self.width
def shoot(self):
return
class Bullet:
def __init__(self,x,y):
self.x = x
self.y = y
def update(self,y_amount = 5):
self.y += y_amount
return
def draw(self):
pygame.draw.rect(screen,[0,255,0],[int(self.x),int(self.y),10,30],0)
bullets = []
#Creating a player
player = Player(200,450,40,20)
#Main Loop
while True:
clock.tick(60)
#Background
screen.fill([0,0,0])
#Letting Player move
player.move()
#Drawing Player
player.draw()
#Updating screen
pygame.display.flip()
#Checking for events
for event in pygame.event.get():
#Checking for quit
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
#Checking for keys
if event.key == pygame.K_w:
keys[0] = True
elif event.key == pygame.K_a:
keys[1]=True
elif event.key == pygame.K_s:
keys[2]=True
elif event.key == pygame.K_d:
keys[3]=True
elif event.key == pygame.K_SPACE:
shooting = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_w:
keys[0]=False
elif event.key == pygame.K_a:
keys[1]=False
elif event.key == pygame.K_s:
keys[2]=False
elif event.key == pygame.K_d:
keys[3]=False
elif event.key == pygame.K_SPACE:
shooting = False
if shooting == True:
bullets.append(Bullet(player.x, player.y))
for bullet in bullets:
bullet.update()
bullet.draw()

Rule 1: Check your coordinate system.
Pygame has (0,0) at the top left, your player is at (x, 450) - at the bottom. When you create a bullet, you do so at the player coordinate and then update the position to increase Y, i.e. move downwards rather than upwards.

I believe that you need to update your screen at the end of the while-loop, not at the beginning:
while True:
#fill screen
for event in pygame.event.get():
#get user input
pygame.display().flip()

Related

In my Escape Room Game, I'm having trouble showing one of the keys [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 7 months ago.
So basically I'm making an escape room game. In the game, you have to interact with a desk and a key would spawn on the map. Then you would interact with the key and pick it up and it would go on top of your head, and you are free to take it anywhere to escape the escape room. Now the problem I'm having, is I'm able to interact with the desk, and the collision works. But the key doesn't spawn.
Here is my code:
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((600,600))
#VARIABLES
velocity = 1
yellow = (255,255,0)
clock = pygame.time.Clock()
white = (255,255,255)
blue = (0,0,255)
black = (0,0,0)
brown = (110,38,14)
x = 300
y = 300
#VARIABLES
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit()
def Room():
global Player
global x
global y
screen.fill(black)
Player = pygame.draw.rect(screen,blue,(x,y,50,50))
wall_1 = pygame.draw.rect(screen,white,(10,50,20,500))
wall_2 = pygame.draw.rect(screen,white,(10,30,580,20))
wall_3 = pygame.draw.rect(screen,white,(570,40,20,520))
wall_4 = pygame.draw.rect(screen,white,(10,540,580,20))
if Player.colliderect(wall_1):
x = x + 70
if Player.colliderect(wall_2):
y = y + 70
if Player.colliderect(wall_3):
x = x - 70
if Player.colliderect(wall_4):
y = y - 70
def Movement():
global velocity
global x
global y
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT or event.key == ord('a'):
x = x - velocity
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT or event.key == ord('d'):
x = x + velocity
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP or event.key == ord('w'):
y = y - velocity
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_DOWN or event.key == ord('s'):
y = y + velocity
def Text():
font = pygame.font.Font("freesansbold.ttf",15)
interact = font.render("E To Interact!",True, (255,255,255))
screen.blit(interact,(75,275))
def FirstKey():
global Player
global x
global y
KeyX = 300
KeyY = 400
key = pygame.draw.rect(screen,yellow,(KeyX,KeyY,15,15))
if Player.colliderect(key) == True:
if key[K_e]:
KeyX = x
KeyY = y - 35
def Desk():
global x
global velocity
Desk = pygame.draw.rect(screen,brown,(75,300,20,60))
if Player.colliderect(Desk) == True:
velocity = 0
Text()
keys = pygame.key.get_pressed()
if keys[K_e]:
x = 300
velocity = 1
FirstKey()
else:
None
#Function Calls#
Room()
Movement()
Desk()
#Function Calls#
pygame.display.update()
#FPS#
clock.tick(120)
#FPS#
I would appreciate an answer as well as an explanation on what I'm doing wrong.
P.S. I'm using the latest version of Python(3.10.5) and the Pygame module.
Try to encapsulate things in a class,
instead of calling the functions secuentially, as it happens in the game, split the functions on what they need to do, and call them on every cycle.
So you need to check for input, check for collisions, check inventary, check states, draw the objects, and so on.
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((600,600))
#VARIABLES
velocity = 1
yellow = (255,255,0)
clock = pygame.time.Clock()
white = (255,255,255)
blue = (0,0,255)
black = (0,0,0)
brown = (110,38,14)
#VARIABLES
class mygame():
x = 300
y = 300
velocity = 1
state = 'idle'
draw_key = False
def draw_objects(self):
screen.fill(black)
self.player = pygame.draw.rect(screen,blue,(self.x,self.y,50,50))
self.wall_1 = pygame.draw.rect(screen,white,(10,50,20,500))
self.wall_2 = pygame.draw.rect(screen,white,(10,30,580,20))
self.wall_3 = pygame.draw.rect(screen,white,(570,40,20,520))
self.wall_4 = pygame.draw.rect(screen,white,(10,540,580,20))
self.desk = pygame.draw.rect(screen,brown,(75,300,20,60))
if self.draw_key:
self.key = pygame.draw.rect(screen,yellow,(200,200,20,20))
def check_collisions(self):
if self.player.colliderect(self.desk) == True:
font = pygame.font.Font("freesansbold.ttf",15)
interact = font.render("E To Interact!",True, (255,255,255))
screen.blit(interact,(75,275))
if self.player.colliderect(self.wall_1) == True:
self.x = 10
if self.player.colliderect(self.wall_2) == True:
self.y = 10
if self.player.colliderect(self.wall_3) == True:
self.x = 570
if self.player.colliderect(self.wall_4) == True:
self.y = 540
def check_buttons(self):
events = pygame.event.get()
for event in events:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_e:
self.state = 'interacting'
self.draw_key = False
if event.key == pygame.K_w or event.key == pygame.K_UP:
self.state = 'up'
if event.key == pygame.K_s or event.key == pygame.K_DOWN:
self.state = 'down'
if event.key == pygame.K_a or event.key == pygame.K_LEFT:
self.state = 'left'
if event.key == pygame.K_d or event.key == pygame.K_RIGHT:
self.state = 'right'
if event.key == pygame.K_ESCAPE:
pygame.quit()
exit()
if event.type == pygame.KEYUP:
self.state = 'idle'
def move(self):
if self.state == 'up':
self.y -= self.velocity
if self.state == 'down':
self.y += self.velocity
if self.state == 'left':
self.x -= self.velocity
if self.state == 'right':
self.x += self.velocity
if self.state == 'idle':
pass
if self.state == 'interacting':
self.draw_key = True
def play(self):
while True:
self.draw_objects()
self.check_buttons()
self.check_collisions()
self.move()
pygame.display.update()
clock.tick(120)
game = mygame()
game.play()

Why doesn't my shoot code in pygame work? [duplicate]

This question already has an answer here:
How to get if a key is pressed pygame [duplicate]
(1 answer)
Closed 2 years ago.
I'm making a submarine game in pygame and I tried to make my submarine shoot bullets. I've tried the code, that I used in my other pygame project, however it doesn't work in this one. Compiler doesn't give any error, but when I press space, it won't shoot. I tried to find a mistake, but I couldn't. I also tried to browse Stack Overflow, but didn't find the answer I was looking for.
Here's the code:
import pygame
pygame.init()
run = True
screen = pygame.display.set_mode((600, 500))
pygame.display.set_caption('Podmornca')
desno = pygame.image.load('podmornicaD.png')
levo = pygame.image.load('podmornica.png')
ozadje = pygame.image.load('ozadje.png')
torpedoD = pygame.image.load('torpedo.png')
torpedoL = pygame.image.load('torpedoL.png')
class podmornica():
def __init__(self, x, y, v):
self.x = x
self.y = y
self.v = v
self.ziv = 100
self.levo = False
self.desno = True
def naris(self):
if self.levo:
screen.blit(levo, (self.x, self.y))
elif self.desno:
screen.blit(desno, (self.x, self.y))
class torpedo():
def __init__(self, x, y, smer):
self.x = x
self.y = y
self.smer = smer
self.v = 5 * smer
def naris(self, screen):
if self.smer < 0:
screen.blit(torpedoD, (self.x, self.y))
else:
screen.blit(torpedoL, (self.x, self.y))
igralec = podmornica(150, 300, 10)
#the list of bullets:
metki = []
def grafika():
screen.blit(ozadje, (0,0))
igralec.naris()
#Here is code for displaying the bullets
for metek in metki:
metek.naris(screen)
pygame.display.flip()
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
#This piece of code is for moving of bullets:
for metek in metki:
if metek.x < 600 and metek.x > 0:
metek.x += metek.v
else:
metki.pop(metki.index(metek))
if event.type == pygame.KEYDOWN and event.key == pygame.K_UP and igralec.y > 10:
igralec.y -= 3
if event.type == pygame.KEYDOWN and event.key == pygame.K_DOWN and igralec.y < 350:
igralec.y += 3
if event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT:
igralec.levo = True
igralec.desno = False
if event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
igralec.levo = False
igralec.desno = True
#the trigger for bullet:
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
if igralec.levo:
smer = -1
else:
smer = 1
if len(metki) < 5:
metki.append(torpedo(igralec.x, igralec.y, smer))
grafika()
pygame.quit()
The events have to be handled in the event loop. If you want to achieve a smooth movement, then you have get the key states by pygame.key.get_pressed().
Furthermore the bullets move much to fast. Control the frames by pygame.time.Clock() respectively .tick(). e.g:
FPS = 60
clock = pygame.time.Clock()
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.KEYDOWN:
#the trigger for bullet:
if event.key == pygame.K_SPACE:
if igralec.levo:
smer = -1
else:
smer = 1
if len(metki) < 5:
metki.append(torpedo(igralec.x, igralec.y, smer))
# This piece of code is for moving of bullets:
for metek in metki[:]:
if metek.x < 600 and metek.x > 0:
metek.x += metek.v
else:
metki.remove(metek)
keys = pygame.key.get_pressed()
if keys[pygame.K_UP] and igralec.y > 10:
igralec.y -= 3
if keys[pygame.K_DOWN] and igralec.y < 350:
igralec.y += 3
if keys[pygame.K_LEFT]:
igralec.levo = True
igralec.desno = False
if keys[pygame.K_RIGHT]:
igralec.levo = False
igralec.desno = True
grafika()

Pygame sprite crossing s creen

The issue is when i press the left or right key while i press it, the sprite crosses the left and right boundaries of the screen. But when i tap it, it will not cross only when i hold the key continuosly
this is the class for the humanship
class Human:
y = display_height * 0.8
x = display_width * 0.45
width = 120
image = pygame.image.load('yasin/alien1.png')
def run(self):
gameDisplay.blit(Human.image, (Human.x, Human.y))
This is the main loop which iterates throughout the game
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
if human.x > 0:
x_change = -8
else:
x_change = 0
elif event.key == pygame.K_RIGHT:
if human.x < display_width - human.width:
x_change = 8
else:
x_change = 0
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
human.x += x_change
human.run()
Move the if human.x > 0: and if human.x < display_width - human.width: out of the event loop because they'll only be executed once per event in the event queue. Rather check in the main while loop if the player is still inside of the game area, otherwise stop it.
I've also changed a few more things: The attributes should be defined in the __init__ method to make them instance attributes instead of class attributes. Use self.x instead of Human.x in the class. The x_change and y_change variables belong to the human object, so they should be attributes as well. Then you can add an update method to the Human in which you do the bounds checking and the movement.
import pygame
display_width, display_height = 640, 480
class Human:
def __init__(self):
self.image = pygame.image.load('yasin/alien1.png')
self.y = display_height * 0.8
self.x = display_width * 0.45
self.x_change = 0
self.y_change = 0
self.width = 120
def run(self, gameDisplay):
gameDisplay.blit(self.image, (self.x, self.y))
def update(self):
self.x += self.x_change
# Check if the human is outside of the game area.
if self.x < 0:
self.x_change = 0 # Stop it.
self.x = 0 # Reset the position, so that we can move again.
elif self.x > display_width - self.width:
self.x_change = 0
self.x = display_width - self.width
def main():
pygame.init()
gameDisplay = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
human = Human()
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
human.x_change = -8
elif event.key == pygame.K_RIGHT:
human.x_change = 8
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
human.x_change = 0
human.update()
gameDisplay.fill((30, 30, 30))
human.run(gameDisplay)
pygame.display.flip()
clock.tick(30)
if __name__ == '__main__':
main()
pygame.quit()

Pygame player movement stops when too many keys are pressed at the same time

When I try to move my character and press any other key at the same time, the movement suddenly stops. For example, the space key in my code is used to shoot a tiny orb out of the spaceship. Every time I press space and I am moving left and right quickly, the orb will shoot out but the player movement will be frozen for a second or two.
I have tried to switch to different ways of handling the way keys are input, but all of them seem to lead to this same problem. pygame.key.get_pressed() also has this problem when in my code.
I am not quite sure if this is a problem with my laptop keyboard or something in the code, so the code for the entire file is below.
import pygame, sys, decimal
# Screen Size
SCREEN_X = 400
SCREEN_Y = 400
# Loading Images
backgroundImg = pygame.image.load('StarBackground.png')
menuBar = pygame.image.load('Menu_Bar.png')
shipImg = pygame.image.load('PowerShip.png')
orb = pygame.image.load('Orb00.png')
class Ship(pygame.sprite.Sprite):
# Movement rate of change
change_x = 0
# Methods
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = shipImg.convert_alpha()
self.rect = self.image.get_rect()
self.rect.x = SCREEN_X / 2 - 8
self.rect.y = SCREEN_Y - 40
def move(self, speed):
self.change_x = speed
def stop(self):
self.change_x = 0
def update(self, screen):
self.rect.x += self.change_x
if self.rect.x < 0:
self.rect.x = 0
elif self.rect.right > SCREEN_X:
self.rect.x -= 1
screen.blit(self.image, self.rect)
class MenuBar(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = menuBar.convert_alpha()
self.rect = self.image.get_rect()
self.rect.x = 10
self.rect.y = 0
def update(self, screen):
screen.blit(self.image,self.rect)
class Bullet1(pygame.sprite.Sprite):
def __init__(self,x,y):
pygame.sprite.Sprite.__init__(self)
self.image = orb.convert_alpha()
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.alive = True
def update(self):
if self.alive == True:
self.rect.y -= 1
if self.alive == False:
self.rect.y = -10000
class HealthBar(pygame.sprite.Sprite):
pass
class EnergyBar(pygame.sprite.Sprite):
pass
class PointsBar(pygame.sprite.Sprite):
pass
class Background(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = backgroundImg.convert_alpha()
self.rect = self.image.get_rect()
self.rect.x = 0
self.rect.y = 0
def update(self, screen):
if self.rect.top > 0:
self.rect.y = SCREEN_Y * -1
self.rect.y += 1
screen.blit(self.image, self.rect)
def main():
pygame.init()
size = [SCREEN_X, SCREEN_Y]
screen = pygame.display.set_mode(size, pygame.DOUBLEBUF) # Set the height and width of the screen
pygame.display.set_caption("Space Adventure") # Setting the game name in the title bar
background = Background() # Creating the game objects
menubar = MenuBar()
ship = Ship()
finished = False # Close button exit code
bullet1Enabled = True
bullet1Count = 1
spacePressed = False
clock = pygame.time.Clock() # Manages the frames per second
lastkey = None # Variable that stores the last key pressed
bulletlist = []
# Game loop
while not finished:
for event in pygame.event.get():
print(lastkey)
if event.type == pygame.QUIT:
finished = True
pygame.event.set_blocked(pygame.MOUSEMOTION)
if event.type == pygame.KEYDOWN:
if lastkey != pygame.K_SPACE:
lastkey = event.key
if event.key == pygame.K_SPACE:
spacePressed = True
if bullet1Enabled == True:
bullet1 = Bullet1(ship.rect.x, ship.rect.y)
bulletlist.append(bullet1)
bullet1Count = 1
else:
spacePressed = False
if event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT and lastkey != pygame.K_LEFT:
lastkey = None
ship.move(0)
if event.key == pygame.K_LEFT and lastkey != pygame.K_RIGHT:
lastkey = None
ship.move(0)
if event.key == pygame.K_RIGHT or lastkey == pygame.K_LEFT:
spacePressed = False
if event.key == pygame.K_LEFT or lastkey == pygame.K_RIGHT:
spacePressed = False
#Bullet Delay
if spacePressed == True:
bullet1Count = True
if spacePressed == False:
bullet1Count = False
if lastkey == pygame.K_RIGHT:
ship.move(1)
if lastkey == pygame.K_LEFT:
ship.move(-1)
clock.tick(240) # Frames per second
background.update(screen) # Background update
# Menu Bar update
ship.update(screen) # Ship update
for b in bulletlist:
if b.rect.bottom <= 0:
b.alive = False
b.update()
screen.blit(b.image, b.rect)
menubar.update(screen)
pygame.display.flip() # Updates the display for everything
pygame.quit() # Clean shutdown on IDLE
if __name__ == "__main__":
main()
The problem occurs because you don't reset lastkey to None after you release the space bar, so you have to press left or right twice.
if event.type == pygame.KEYUP:
if event.key == pygame.K_SPACE:
lastkey = None
I don't see why you need the lastkey variable at all. I'd remove these lines from the main loop,
if lastkey == pygame.K_RIGHT:
ship.move(1)
if lastkey == pygame.K_LEFT:
ship.move(-1)
insert them in the event loop and change lastkey to event.key:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
ship.move(1)
if event.key == pygame.K_LEFT:
ship.move(-1)
Now you should be able to remove the lastkey completely.

I am trying to shoot multiple of bullets using pygame group module but I don't know how to do it properly

Problem 1: I am trying to shoot maximum of 5 bullets using pygame group class module but I can only shoot maximum of 1 bullet...
This is the bullet class:
class Bullets(pygame.sprite.Sprite):
def __init__(self,image,location):
pygame.sprite.Sprite.__init__(self)
self.image = image
self.rect=self.image.get_rect()
self.location =location
self.rect.left,self.rect.top = self.location
Down below: I have set 'bullet' as a sprite
def bullet_group(group):
for bullet in group:
print(group.sprites)
group.remove(bullet)
# After shooting a bullet, I want to remove the bullet from the group
# in order to change the 'shoot_point'(which is the location of the bullet)
# back to where it starts
shoot_point_x = fixed_shoot_point_x #fixed_shoot_point is the start location
shoot_point_y = fixed_shoot_point_y #of the bullet
group.add(bullet)
Just before the main while loop:
group=pygame.sprite.Group()
for i in range(0,5):
group.add(bullet)
I made 5 bullet sprites
In the main code down below:
if event.type == pygame.KEYDOWN:
if #some code
elif event.key == pygame.K_SPACE:
fixed_bullet_speed_change = [round(-(math.cos(math.atan2(RealTank.Trect.centery-shoot_point_y,RealTank.Trect.centerx-shoot_point_x))),1)*10,round(-(math.sin(math.atan2(RealTank.Trect.centery-shoot_point_y,RealTank.Trect.centerx-shoot_point_x))),1)*10]
# the line of code above is just some calculations that is not related to the question
group.remove(bullet)
# I removed the sprite from the group after shooting some bullets, in order to
# shoot another one
if event.type == pygame.KEYUP:
if #some code
elif event.key == pygame.K_SPACE:
group.add(bullet)
# adding back another one
Does anyone know what I am doing wrong????
Problem 2:
When I do 'print(group.sprites)' and press 'SPACEBAR', I get more sprites every time I press it...
==================================================================
Here's all of my code down below:(you don't need to see it...it isn't necessary)
Try the code down below, to visualize my problem
pictures:
import pygame,math
pygame.init()
red = (155,0,0)
class Tanks(pygame.sprite.Sprite):
def __init__(self,image,location,angle,speed,x_change,y_change,
turret_image,turret_angle,bullet_image):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image)
self.turret_image = pygame.image.load(turret_image)
self.bullet_image = pygame.image.load(bullet_image)
self.Brect = self.bullet_image.get_rect()
self.Trect = self.turret_image.get_rect()
self.rect = self.image.get_rect()
self.rect.left,self.rect.top=location
self.Trect.centerx,self.Trect.bottom = self.rect.centerx,self.rect.centery
self.angle = angle
self.turret_angle = turret_angle
self.speed = speed
self.x_change = x_change
self.y_change = y_change
print(self.angle)
def rotate(self):
rot_image = pygame.transform.rotate(self.image,self.angle)
rot_rect = rot_image.get_rect(center = self.rect.center)
return rot_image,rot_rect
def turret_rotate(self):
turret_rot_image = pygame.transform.rotate(self.turret_image,self.turret_angle)
turret_rot_rect = turret_rot_image.get_rect(center = self.Trect.midbottom)
return turret_rot_image,turret_rot_rect
## def bullet_rotate(self):
## bullet_rot_image = pygame.transform.rotate(self.bullet_image,self.turret_angle)
## bullet_rot_rect = bullet_rot_image.get_rect(center = )
def moving_after_angle_change(self):
x=round(math.cos(math.radians(self.angle+90)),1)*self.speed
y=round(math.sin(math.radians(self.angle-90)),1)*self.speed
return x,y
def shoot_point(self):
#print(self.turret_angle)
shoot_point_x = RealTank.Trect.centerx + math.cos(math.radians(RealTank.turret_angle+90))*55
shoot_point_y = RealTank.Trect.centery + math.sin(math.radians(RealTank.turret_angle-90))*55
return shoot_point_x,shoot_point_y
class Bullets(pygame.sprite.Sprite):
def __init__(self,image,location):
pygame.sprite.Sprite.__init__(self)
self.image = image
self.rect=self.image.get_rect()
self.location =location
self.rect.left,self.rect.top = self.location
def bullet_group(group):
for bullet in group:
print(group.sprites)
group.remove(bullet)
shoot_point_x = fixed_shoot_point_x
shoot_point_y = fixed_shoot_point_y
group.add(bullet)
#initial
player_image_str = 'Tank.png'
player_turret_str = 'turret - Copy.png'
player_gold_bullet_str = 'bullet.png'
clock = pygame.time.Clock()
FPS = 30
display_width,display_height = 900,600
screen = pygame.display.set_mode([display_width,display_height])
player_location = [600,300]
player_angle = 0
player_angle_change = 0
player_speed = 0
player_x_change=0
player_y_change=0
RealTank_x_change_store=0
RealTank_y_change_store=0
turret_angle = 0
turret_angle_change = 0
bullet_speed_change = [0,0]
fixed_bullet_speed = [0,0]
fixed_bullet_speed_change = [0,0]
shoot_point_x = 0
shoot_point_y=0
fixed_shoot_point_x=0
fixed_shoot_point_y=0
#main
RealTank = Tanks(player_image_str,player_location,player_angle,player_speed,
player_x_change,player_y_change,player_turret_str,turret_angle,player_gold_bullet_str)
bullet=Bullets(RealTank.bullet_image,[shoot_point_x,shoot_point_y])
group=pygame.sprite.Group()
for i in range(0,5):
group.add(bullet)
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_a:
turret_angle_change = 5
elif event.key == pygame.K_d:
turret_angle_change = -5
elif event.key == pygame.K_UP:
player_speed=2
elif event.key == pygame.K_DOWN:
player_speed=-2
elif event.key == pygame.K_LEFT:
player_angle_change = 2
elif event.key == pygame.K_RIGHT:
player_angle_change = -2
elif event.key == pygame.K_SPACE:
fixed_bullet_speed_change = [round(-(math.cos(math.atan2(RealTank.Trect.centery-shoot_point_y,RealTank.Trect.centerx-shoot_point_x))),1)*10,round(-(math.sin(math.atan2(RealTank.Trect.centery-shoot_point_y,RealTank.Trect.centerx-shoot_point_x))),1)*10]
group.remove(bullet)
if event.type == pygame.KEYUP:
if event.key == pygame.K_a or event.key == pygame.K_d:
turret_angle_change = 0
elif event.key == pygame.K_UP:
player_speed = 0
elif event.key == pygame.K_DOWN:
player_speed = 0
elif event.key == pygame.K_LEFT:
player_angle_change = 0
elif event.key == pygame.K_RIGHT:
player_angle_change = 0
elif event.key == pygame.K_SPACE:
group.add(bullet)
player_angle+=player_angle_change
turret_angle+=turret_angle_change
RealTank = Tanks(player_image_str,player_location,player_angle,player_speed,
player_x_change,player_y_change,player_turret_str,turret_angle,player_gold_bullet_str)
RealTank.image,RealTank.rect=RealTank.rotate()
RealTank.turret_image,RealTank.Trect = RealTank.turret_rotate()
RealTank.x_change,RealTank.y_change=RealTank.moving_after_angle_change()
RealTank_x_change_store += RealTank.x_change
RealTank_y_change_store += RealTank.y_change
RealTank.Trect.centerx +=RealTank_x_change_store
RealTank.Trect.centery +=RealTank_y_change_store
RealTank.rect.centerx += RealTank_x_change_store
RealTank.rect.centery += RealTank_y_change_store
shoot_point_x,shoot_point_y=RealTank.shoot_point()
fixed_shoot_point_x,fixed_shoot_point_y = RealTank.shoot_point()
screen.fill([0,0,0])
screen.blit(RealTank.image,RealTank.rect)
#bullet
print(fixed_bullet_speed_change)
fixed_bullet_speed[0]+=fixed_bullet_speed_change[0]
fixed_bullet_speed[1]+=fixed_bullet_speed_change[1]
shoot_point_x+=fixed_bullet_speed[0]
shoot_point_y+=fixed_bullet_speed[1]
#bullet end
bullet=Bullets(RealTank.bullet_image,[shoot_point_x,shoot_point_y])
#bullet group
bullet_group(group)
#bullet group end
screen.blit(bullet.image,bullet.location)
screen.blit(RealTank.turret_image,RealTank.Trect)
pygame.display.update()
clock.tick(FPS)
pygame.quit()
You create only one instance of bullet - you need 5 instances
group = pygame.sprite.Group()
for i in range(5):
bullet = Bullets(RealTank.bullet_image, [shoot_point_x, shoot_point_y])
group.add(bullet)
Doc: pygame.sprite.Group.add():
Add any number of Sprites to this Group. This will only add Sprites
that are not already members of the Group.
Inside while loop you create new bullet bullet = Bullets() (variable name bullet doesn't matter, id(bullet) do matter) and you try to remove it (remove(bullet)) but this instance is not in group so it removes nothing. And later you add bullet (add(bullet)) and it adds it because this instance is not in group yet.

Categories