Increasing variables that are in use in pygame

Viewed 67

I am coding a space invaders game in pygame, and wanted to make it so that when the player reaches 50 points, the game increases the number of invaders from 6 to 10. In the game, the enemies respawn near the top half of the screen immediately after dying. The game functions perfectly normally until you reach 50 points, at which it immediately crashes. How do I make it so that the variable storing the number of enemies (num_of_enemies) increases, while the game is still running?

In the code I have put here, I removed my attempt to change the num_of_enemies variable, but fyi, I placed it just above "pygame.display.update()". my crappy attempt to resolve the issue boiled down to:

if score_value >= 50: num_of_enemies += 10

I have also tried this code while assigning num_of_enemies a global value, but it simply defects the game, and messes up again.

Code:

import pygame
from pygame import mixer
import random
import math


pygame.init()

screen = pygame.display.set_mode((800, 600))

background = pygame.image.load('Background.jpg')
background = pygame.transform.scale(background, (800, 600))

mixer.music.load('background.wav')
mixer.music.play(-1)

pygame.display.set_caption("Space Invaders")
icon = pygame.image.load('ufo.png')
pygame.display.set_icon(icon)

playerImg = pygame.image.load('spaceship.png')
playerX = 370
playerY = 480
playerX_change = 0

enemyImg = []
enemyX = []
enemyY = []
enemyX_change = []
enemyY_change = []
num_of_enemies = 6

for i in range(num_of_enemies):
    enemyImg.append(pygame.image.load('ufo.png'))
    enemyX.append(random.randint(0, 750))
    enemyY.append(random.randint(50, 200))
    enemyX_change.append(0.5)
    enemyY_change.append(40)

bulletImg = pygame.image.load('bullet.png')
bulletX = 0
bulletY = 480
bulletX_change = 0
bulletY_change = 1
bullet_state = "ready"

score_value = 0
font = pygame.font.Font('freesansbold.ttf', 32)

textX = 10
textY = 10

over_font = pygame.font.Font('freesansbold.ttf', 64)

def show_score(x,y):
    score = font.render("Score : " + str(score_value), True, (255, 255, 255))
    screen.blit(score, (x,y))
    
def game_over_text():
    over_text = over_font.render("GAME OVER", True, (255, 255, 255))
    screen.blit(over_text, (200, 250))
    
def player(x,y): 
    screen.blit(playerImg,(x, y))
    
def enemy(x,y, i):
    screen.blit(enemyImg[i],(x,y))
    
def fire_bullet(x,y):
    global bullet_state
    bullet_state = "fire"
    screen.blit(bulletImg,(x + 16, y + 10))
    
    
def isCollision(enemyX, enemyY, bulletX, bulletY):
    distance = math.sqrt((math.pow(enemyX-bulletX,2)) + (math.pow(enemyY-bulletY,2)))
    if distance < 27:
        return True
    else:
        return False
    
running = True
while running:
    
    screen.fill((0, 0, 0))
    
    screen.blit(background,(0,0))
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

            
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                playerX_change = -1
            if event.key == pygame.K_RIGHT:
                playerX_change = 1
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                playerX_change = 0
            if event.key == pygame.K_SPACE:
                if bullet_state == "ready":
                    bullet_sound = mixer.Sound('laser.wav')
                    bullet_sound.play()
                    bulletX = playerX
                    fire_bullet(bulletX,bulletY)
                

    
    playerX += playerX_change
    
    if playerX <= 0:
        playerX = 0
    elif playerX >= 768:
        playerX = 768

    
    for i in range(num_of_enemies):
        
        
        if enemyY[i] > 440:
            for j in range(num_of_enemies):
                enemyY[j] = 2000
                
            game_over_text()
            break
        
        
        enemyX[i] += enemyX_change[i]
        if enemyX[i] <= 0:
            enemyX_change[i] = 0.5
            enemyY[i] += enemyY_change[i]
        elif enemyX[i] >= 768:
            enemyX_change[i] = -0.5
            enemyY[i] += enemyY_change[i]
            
            
        collision = isCollision(enemyX[i], enemyY[i], bulletX, bulletY)
        if collision:
            explosion_Sound = mixer.Sound('explosion.wav')
            explosion_Sound.play()
            bulletY = 480
            bullet_state = "ready"
            score_value += 1
            print(f"score = {score_value}")
            enemyX[i] = random.randint(50, 768)
            enemyY[i] = random.randint(50, 200)
        
        enemy(enemyX[i], enemyY[i], i)
        
    
    
    if bulletY <= 0:
        bulletY = 480
        bullet_state = "ready"
    if bullet_state == "fire":
        fire_bullet(bulletX,bulletY)
        bulletY -= bulletY_change
    
    
    player(playerX, playerY)
    
    show_score(textX, textY)
    

    pygame.display.update()```

1 Answers

IT is not enough just to change num_of_enemies you also need to add new items in the lists.

Write a function that crates the enemies:

def create_enemies(new_enemies):
    global num_of_enemies
    
    enemy_image = pygame.image.load('ufo.png')
    for i in range(new_enemies):
        enemyImg.append(enemy_image)
        enemyX.append(random.randint(0, 750))
        enemyY.append(random.randint(50, 200))
        enemyX_change.append(0.5)
        enemyY_change.append(40)

    # now the number of enemies has changed
    num_of_enemies += new_enemies

Call the function at the begin of the application:

enemyImg = []
enemyX = []
enemyY = []
enemyX_change = []
enemyY_change = []

num_of_enemies = 0  # 0! actually you have 0 enemies
create_enemies(6)   # create 6 new enemies

Call the function again if you want to change the number of enemies:

# create 4 more enemies, now the number of enemies changes from 6 to 10
create_enemies(4)
Related