I am making a game, and I've set the game to generate two enemies at a random y position and once they are shot, regenerate them but in a different y position, but my code sometimes generates a third enemy, and after that a fourth, and it continues, but there is no specific pattern I can notice that might be causing that issue. I will show you my code, please point out any issues / improvements that could fix this issue.
import pygame
pygame.init()
pygame.mixer.init()
import random
gunshot = pygame.mixer.Sound("audio/gunshot.wav")
music = pygame.mixer.music.load("audio/music.mp3")
click = pygame.mixer.Sound("audio/click.wav")
hit = pygame.mixer.Sound("audio/hit.wav")
deathsound = pygame.mixer.Sound("audio/deathsound.wav")
pygame.mixer.music.set_volume(0.05)
gunshot.set_volume(0.07)
click.set_volume(0.3)
hit.set_volume(0.1)
deathsound.set_volume(0.3)
pygame.mixer.music.play(-1)
sw = 400
sh = 400
screen = pygame.display.set_mode((sw,sh))
pygame.display.set_caption("gonnagiveanamelater")
running = True
bg = pygame.image.load("graphics/bg.png")
player = pygame.image.load("graphics/player.png")
clock = pygame.time.Clock()
bullets = []
enemies = []
enemyy = 50
enemy2y = 350
pygame.display.set_icon(player)
score = 0
class enemy():
def __init__(self, x, y, sid):
self.x = x
self.y = y
self.id = sid
self.enemysurf = pygame.image.load("graphics/enemy.png")
self.enemyrect = self.enemysurf.get_rect(center=(self.x, self.y))
def draw(self):
screen.blit(self.enemysurf, self.enemyrect)
class bullet():
def __init__(self, sp):
self.x = 30
self.y = sp
self.bulletsurf = pygame.image.load("graphics/bullet.png")
self.bulletrect = self.bulletsurf.get_rect(center=(self.x, self.y))
def draw(self):
screen.blit(self.bulletsurf, self.bulletrect)
while running:
clock.tick(60)
pos = pygame.mouse.get_pos()
screen.blit(bg, (0,0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if len(bullets) <= 4:
bullets.append(bullet(event.pos[1]))
gunshot.play()
else:
click.play()
for bulllet in bullets:
bulllet.bulletrect.x += 3
bulllet.draw()
if bulllet.bulletrect.midright[0] >= 365:
bullets.remove(bulllet)
if len(enemies) <= 2:
if enemyy - enemy2y <= 100:
enemyy = random.randint(50,350)
else:
enemies.append(enemy(370, enemyy, 1))
enemies.append(enemy(370, enemy2y, 2))
else:
pass
for bllet in bullets:
for enmy in enemies:
if bllet.bulletrect.colliderect(enmy.enemyrect):
hit.play()
score += 1
enemies.remove(enmy)
if enmy.id == 1:
enemyy = random.randint(50, 350)
if enmy.id == 2:
enemy2y = random.randint(50, 350)
playerrect = player.get_rect(center=(30, pos[1]))
screen.blit(player, playerrect)
for enmy in enemies:
enmy.draw()
pygame.display.update()
Aucun commentaire:
Enregistrer un commentaire