I did some research to see if I could fix my problem on my own but it has been fruitless so far. I've checked to see if I ran the .display command too much but I haven't, the program will run without error but the screen appears black except when I close the window out, you can catch a glimpse of what it is supposed to display. Any insight into what is wrong? Help is greatly appreciated!
import math
import random
import pygame
from pygame import mixer
# Initialize the pygame
pygame.init()
# create the screen
screen = pygame.display.set_mode((800, 600))
# Background
background = pygame.image.load('space background.png')
# Background Sound
# come back to this from bg music 'mixer.music.load('insert file name')'
# mixer.music.play(-1)
# Title and Icon
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load('ufo.png')
pygame.display.set_icon(icon)
# Player
playerImg = pygame.image.load('ship.png')
playerX = 370
playerY = 480
playerX_change = 0
# Enemy
enemyImg = []
enemyX = []
enemyY = []
enemyX_change = []
enemyY_change = []
num_of_enemies = 6
for i in range(num_of_enemies):
enemyImg.append(pygame.image.load('enemy.png'))
enemyX.append(random.randint(0, 735))
enemyY.append(random.randint(50, 150))
enemyX_change.append(0.3)
enemyY_change.append(40)
# Bullet
# Ready - you cat see the bullet on the screen
# Fire - The bullet is currently moving
bulletImg = pygame.image.load('bullet.png')
bulletX = 0
bulletY = 480
bulletX_change = 0
bulletY_change = 1 # Bullet speed
bullet_state = "ready"
# Score
score_value = 0
font = pygame.font.Font('Minecraft.ttf', 24)
textX = 10
testY = 10 # might have to change back to 'text'
# Game Over text
over_font = pygame.font.Font('Minecraft.ttf', 64)
def show_score(x, y):
score = font.render("Score : " + str(score_value), True, (225, 225, 255))
screen.blit(score, (x, y))
def game_over_text(x, y):
over_text = over_font.render("GAME OVER", True, (225, 225, 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
# Game Loop
running = True
while running:
# RGB
screen.fill((0, 0, 0))
# background image
screen.blit(background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# if keystroke is pressed check whether its right or left
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -0.7 # player speed
if event.key == pygame.K_RIGHT:
playerX_change = 0.7
if event.key == pygame.K_SPACE:
if bullet_state == "ready":
bullet_Sound = mixer.Sound('laser.wav')
bullet_Sound.play()
# Get the current X corrdinate of te spaceship
bulletX = playerX
fire_bullet(playerX, bulletY)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
# 5 = 5 + -0.1 -> 5 = 5 - 0.1
# 5 = 5 + 0.1
# Checking for boundries of spaceship
playerX += playerX_change
if playerX <= 0:
playerX = 0
elif playerX >= 736:
playerX = 736
# Enemy Movement
for i in range(num_of_enemies):
# Game over
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.3 # enemy speed
enemyY[i] += enemyY_change[i]
elif enemyX[i] >= 736:
enemyX_change[i] = -0.3
enemyY[i] += enemyY_change[i]
# Collision
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 += 100
enemyX[i] = random.randint(0, 736)
enemyY[i] = random.randint(50, 150)
enemy(enemyX[i], enemyY[i], i)
# Bullet Movement
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, testY)
pygame.display.update()
All you have to do is indent the last bit of code (the 11 lines under the comment Bullet Movement) one level in. Right now, it's not under the while loop, which explains why the screen is black and why it only appears after you click the close button (which exits the loop and executes the drawing code). Hope this helps!
Related
This question already has answers here:
how restarting game on pygame works
(1 answer)
Pygame restart function
(2 answers)
In game loop, how do I restart game properly using nested class or loop?
(1 answer)
Reset and restart pygame program doesn't work
(1 answer)
Closed 3 months ago.
I followed a tutorial guide on how to make this game but they never said how to put in a restart. I'm not quite sure how to do it, would anyone here know off the top of their head? Here's the code.
import pygame
import math
import random
from pygame import mixer
# Start the Program
pygame.init()
# Create the Screen
screen = pygame.display.set_mode((800, 600))
running = True
# Background
background = pygame.image.load('background.png')
# Background Sound
mixer.music.load('theme.mp3')
mixer.music.play(-1)
# Title and Icon
pygame.display.set_caption("Boot Craft")
icon = pygame.image.load('Starcraft.png')
pygame.display.set_icon(icon)
# Player
player_image = pygame.image.load('BC.png')
playerX = 370
playerY = 480
playerX_change = 0
playerY_change = 0
# Enemy
enemy_image = []
enemyX = []
enemyY = []
enemyX_change = []
enemyY_change = []
num_of_enemies = 6
for i in range(num_of_enemies):
enemy_image.append(pygame.image.load('Zergling.png'))
enemyX.append(random.randint(0, 768))
enemyY.append(random.randint(50, 150))
enemyX_change.append(0.2)
enemyY_change.append(40)
# Bullet
# Ready - You can't see the bullet on the screen
# Fire - The bullet is currently moving
bullet_image = pygame.image.load('Bullet.png')
bulletX = 0
bulletY = 480
bulletX_change = 0
bulletY_change = .5
bullet_state = "ready"
# Score
score_value = 0
font = pygame.font.Font('freesansbold.ttf', 32)
textX = 10
textY = 10
# Game Over
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))
continue_text = over_font.render('CONTINUE? Y/N', True, (255, 255, 255))
screen.blit(over_text, (200, 250))
screen.blit(continue_text, (160, 350))
def player(x, y):
screen.blit(player_image, (x, y))
def enemy(x, y, i):
screen.blit(enemy_image[i], (x, y))
def fire_bullet(x, y):
global bullet_state
bullet_state = "fire"
screen.blit(bullet_image, (x + 8, 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
# Game Loop - Runs Game
while running:
# RGB Color Values 0-255
screen.fill((0, 0, 0))
# Background Image
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_y:
running = True
# Check Key pressed.
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT or event.key == pygame.K_a:
playerX_change = -0.2
if event.key == pygame.K_RIGHT or event.key == pygame.K_d:
playerX_change = 0.2
if event.key == pygame.K_SPACE:
if bullet_state == "ready":
bullet_sound = mixer.Sound('laser.wav')
bullet_sound.play()
# Get the current X coordinate of the spaceship
bulletX = playerX
fire_bullet(bulletX, bulletY)
# Check Key released.
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == pygame.K_a or event.key == pygame.K_d:
playerX_change = 0
playerX += playerX_change
# Adds Boundary
if playerX <= 0:
playerX = 0
elif playerX >= 721:
playerX = 721
# Enemy Movement
for i in range(num_of_enemies):
# Game Over
if enemyY[i] > 440:
for j in range(num_of_enemies):
enemyY[j] = 2000
game_over_text()
enemyX[i] += enemyX_change[i]
if enemyX[i] <= 0:
enemyX_change[i] = 0.2
enemyY[i] += enemyY_change[i]
elif enemyX[i] >= 768:
enemyX_change[i] = -0.2
enemyY[i] += enemyY_change[i]
# Collision
collision = isCollision(enemyX[i],enemyY[i],bulletX,bulletY)
if collision:
explosion_sound = mixer.Sound('explode.wav')
explosion_sound.play()
bulletY = 480
bullet_state = "ready"
score_value += 1
enemyX[i] = random.randint(0, 768)
enemyY[i] = random.randint(50, 150)
enemy(enemyX[i], enemyY[i], i)
# Bullet Movement
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()
I'm not sure what to try, as what I googled used different ways of running the game. New to this, so genuinely confused.
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()```
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)
I've completed a PyGame lesson and written all of the tutorial's code. And I'm presently working on a Restart button for the game, which basically allows you to re-play the game without having to re-run the code. I've created the button's class and made the button itself clickable; the only thing I'm lacking is a mechanism to restart the game by hitting the button.
import pygame
import random
import math
from pygame import mixer
# Initialize PyGame
pygame.init()
# Create the screen
screen = pygame.display.set_mode((800, 600))
# Background
background = pygame.image.load('background.png')
# Background Music
mixer.music.load('background.wav')
mixer.music.play(-1)
# Title and Icon
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load('ufo.png')
pygame.display.set_icon(icon)
# Player
PlayerImg = pygame.image.load('player.png')
PlayerX = 370
PlayerY = 480
PlayerX_change = 0
# Enemy
enemyImg = []
enemyX = []
enemyY = []
enemyX_change = []
enemyY_change = []
num_of_enemies = 6
for i in range(num_of_enemies):
enemyImg.append(pygame.image.load('enemy.png'))
enemyX.append(random.randint(100, 736))
enemyY.append(random.randint(50, 150))
enemyX_change.append(4)
enemyY_change.append(40)
# Bullet
# Ready - You can't see the bullet on the screen
# Fire - The bullet is currently moving
bulletImg = pygame.image.load('bullet.png')
bulletX = 0
bulletY = 480
bulletX_change = 0
bulletY_change = 2.5
bullet_state = "ready"
# Score
score_value = 0
font = pygame.font.Font('freesansbold.ttf', 32)
textX = 10
textY = 10
# Game Over
over_font = pygame.font.Font('freesansbold.ttf', 64)
# Final Score
final_font = pygame.font.Font('freesansbold.ttf', 40)
# Restart Button
button_img = pygame.image.load('restart.png')
buttonX = 350
buttonY = 375
GameOver = False
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 final_score_text():
final_text = final_font.render("Final Score: " + str(score_value), True, (255, 255, 255))
screen.blit(final_text, (260, 325))
def player(x, y):
screen.blit(PlayerImg, (x, y))
def enemy(x, y):
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
class Button():
def __init__(self, x, y, image):
self.image = image
self.rect = self.image.get_rect()
self.rect.topleft = (x, y)
def draw(self):
action = False
# get mouse position
pos = pygame.mouse.get_pos()
# check if mouse is over the button
if self.rect.collidepoint(pos):
if pygame.mouse.get_pressed()[0] == 1:
action = True
# draw button
screen.blit(self.image, (self.rect.x, self.rect.y))
return action
# create restart button instance
button = Button(buttonX, buttonY, button_img)
# Game loop
running = True
while running:
# RGB - Red, Green, Blue
screen.fill((0, 0, 0))
# Background Image
screen.blit(background, (0, 0))
if GameOver is False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# If keystroke is pressed, check whether it's Right or Left
if event.type == pygame.KEYDOWN:
if event.key == ord(','):
PlayerX_change = -7
if event.key == ord('.'):
PlayerX_change = 7
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)
if event.type == pygame.KEYUP:
if event.key == ord(',') or event.key == ord('.'):
PlayerX_change = 0
# Blits
player(PlayerX, PlayerY)
show_score(textX, textY)
# Player Boundaries
PlayerX += PlayerX_change
if PlayerX <= 0:
PlayerX = 0
elif PlayerX >= 736:
PlayerX = 736
# Enemy Movement
for i in range(num_of_enemies):
enemyX[i] += enemyX_change[i]
if enemyX[i] <= 0:
enemyX_change[i] = 3
enemyY[i] += enemyY_change[i]
elif enemyX[i] >= 736:
enemyX_change[i] = -3
enemyY[i] += enemyY_change[i]
# Collision
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 += 100
enemyX[i] = random.randint(0, 736)
enemyY[i] = random.randint(50, 150)
enemy(enemyX[i], enemyY[i])
# Bullet Movement
if bulletY <= 0:
bulletY = 480
bullet_state = "ready"
if bullet_state == "fire":
fire_bullet(bulletX, bulletY)
bulletY -= bulletY_change
# Game Over
if enemyY[i] > 420:
GameOver = True
if GameOver is True:
for j in range(num_of_enemies):
enemyY[j] = 2000
game_over_text()
textY = 2000
final_score_text()
if button.draw() is True:
print("Clicked")
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.update()
Write a function that initializes all game states. The function must set all the relevant variables in global name space (Use the global statement):
def init_game():
global PlayerX, PlayerY, PlayerX_change
global bulletX, bulletY, bulletX_change, bulletY_change, bullet_state
global enemyImg, enemyX, enemyX, enemyX_change, enemyY_change, num_of_enemies
PlayerX = 370
PlayerY = 480
PlayerX_change = 0
bulletX = 0
bulletY = 480
bulletX_change = 0
bulletY_change = 2.5
bullet_state = "ready"
enemyImg = []
enemyX = []
enemyY = []
enemyX_change = []
enemyY_change = []
num_of_enemies = 6
for i in range(num_of_enemies):
enemyImg.append(pygame.image.load('enemy.png'))
enemyX.append(random.randint(100, 736))
enemyY.append(random.randint(50, 150))
enemyX_change.append(4)
enemyY_change.append(40)
Call the function before the application loop. Call it again when you click the button:
button = Button(buttonX, buttonY, button_img)
init_game()
# Game loop
running = True
while running:
# [...]
if GameOver is True:
# [...]
if button.draw() is True:
print("Clicked")
GameOver = False
init_game()
# [...]
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Im following a tutorial to code a game, as far as i can tell, my code is the same as the one in the tutorial, ive been working at this for about 45mins, and checked over the code twice, but here is the code
import pygame
import math
import random
# Intialize the Pygame
pygame.init()
# Create the Screen
screen = pygame.display.set_mode((800, 600))
# Background
background = pygame.image.load("space.png")
# Title and Icon
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load("alien.png")
pygame.display.set_icon(icon)
# Player
playerImg = pygame.image.load("player.png")
playerX = 370
playerY = 480
playerX_change = 0
# Enemy
enemyImg = []
enemyX = []
enemyY = []
enemyX_change = []
enemyY_change = []
num_of_enemies = 6
for i in range(num_of_enemies):
enemyImg.append(pygame.image.load("enemy.png"))
enemyX.append(random.randint(0, 736))
enemyY.append(random.randint(50, 150))
enemyX_change.append(4)
enemyY_change.append(30)
# Bullet
# Ready - You can't see the bullet on the screen
# Fire_ The bullet is currently moving
bulletImg = pygame.image.load("bullet.png")
bulletX = 0
bulletY = 480
bulletX_change = 0
bulletY_change = 15
bullet_state = "ready"
score = 0
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
# Game Loop
running = True
while running:
# RGB - Red, Green, Blue
screen.fill((0, 0, 0))
# Background image
screen.blit(background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# If keystroke is pressed check whether its right or left
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -5
if event.key == pygame.K_RIGHT:
playerX_change = 5
if event.key == pygame.K_SPACE:
if bullet_state is "ready":
bulletX = playerX
fire_bullet(bulletX, bulletY)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
# Checking for boundaries for space ship
playerX += playerX_change
if playerX <= 0:
playerX = 0
elif playerX >= 736:
playerX = 736
# Enemy movement
for i in range(num_of_enemies):
enemyX[i] += enemyX_change[i]
if enemyX[i] <= 0:
enemyX_change[i] = 4
enemyY[i] += enemyY_change[i]
elif enemyX[i] >= 736:
enemyX_change[i] = -4
enemyY[i] += enemyY_change[i]
# Collision
collision = isCollision(enemyX[i], enemyY[i], bulletX, bulletY)
if collision:
bulletY = 480
bullet_state = "ready"
score += 1
print(score)
enemyX[i] = random.randint(0, 736)
enemyY[i] = random.randint(50, 150)
enemy(enemyX[i], enemyY[i], i)
# Bullet Movement
if bulletY <= 0:
bulletY = 480
bullet_state = "ready"
if bullet_state is "fire":
fire_bullet(bulletX, bulletY)
bulletY -= bulletY_change
player(playerX, playerY)
pygame.display.update()
Here is the error im getting:
line 70
if distance < 27:
^
SyntaxError: invalid syntax
Process finished with exit code 1
Im new to python, so it might be something stupid that i forgot, but i cannot figure this out.
You miss a close bracket:
distance = math.sqrt(math.pow(enemyX - bulletX, 2) + (math.pow(enemyY - bulletY, 2)))
I am making a space invader like game, everything works fine, but ever since I added multiple enemies using a list, their images/sprites disappeared and only reappear once hit for a second and than disappear once more.
I've checked, the image file is fine, and as far as I can see nothing unusual is happening behind the since as well, and the score adds up fine whenever an enemy is hit.
What might be the issue?
import pygame
import random
import math
# Initializing pygame
pygame.init()
# Screen creation and config
screen = pygame.display.set_mode((1024, 600))
# Background
background = pygame.image.load('court_level_bg.jpg')
# Title and Icon
pygame.display.set_caption("Space Invaders")
# Player config
player_img = pygame.image.load('Mini_Bibi.png')
playerX = 430
playerY = 480
playerX_change = 0
# Enemy config
enemy_img = []
enemyX = []
enemyY = []
enemyX_change = []
enemyY_change = []
num_enemies = 5
for i in range(num_enemies):
enemy_img.append(pygame.image.load('Enemy1.png'))
enemyX.append(random.randint(0, 1024))
enemyY.append(random.randint(5, 150))
enemyX_change.append(1.5)
enemyY_change.append(40)
# Bullet config
bullet_img = pygame.image.load('Weapon.png')
bulletX = 0
bulletY = 480
bulletX_change = 0
bulletY_change = 6
bullet_state = "ready"
score = 0
# Create player
def player(x, y):
screen.blit(player_img, (x, y))
# Create enemy
def enemy(x, y, i):
screen.blit(enemy_img[i], (x, y))
def fire_bullet(x, y):
global bullet_state
bullet_state = "fire"
screen.blit(bullet_img, (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
# Game Loop
scrn_stat = True
while scrn_stat:
# Screen RGB color config
screen.fill((0, 0, 0))
# Background image
screen.blit(background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
scrn_stat = False
# X axis Keystroke listening
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -4
if event.key == pygame.K_RIGHT:
playerX_change = 4
if event.key == pygame.K_SPACE:
if bullet_state is "ready":
bulletX = playerX
fire_bullet(bulletX, bulletY)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
playerX += playerX_change
# Player boundaries
if playerX <= 0:
playerX_change = 0;
elif playerX >= 945:
playerX_change = 0;
# Enemy movement
for i in range(num_enemies):
enemyX[i] += enemyX_change[i]
if enemyX[i] <= 0:
enemyX_change[i] = 3
enemyY[i] += enemyY_change[i]
elif enemyX[i] >= 945:
enemyX_change[i] = -3
enemyY[i] += enemyY_change[i]
# Collision
collision = isCollision(enemyX[i], enemyY[i], bulletX, bulletY)
if collision:
bulletY = 480
bullet_state = "ready"
score += 1
print(score)
enemyX[i] = random.randint(0, 945)
enemyY[i] = random.randint(50, 150)
enemy(enemyX[i], enemyY[i], i)
# Bullet Movement
if bulletY <= 0:
bulletY = 480
bullet_state = "ready"
if bullet_state is "fire":
fire_bullet(bulletX, bulletY)
bulletY -= bulletY_change
player(playerX, playerY)
pygame.display.update()
enemy() has to be called for each enemy in every frame, rather than in case of a collision only. It is an Indentation issue:
for i in range(num_enemies):
enemyX[i] += enemyX_change[i]
if enemyX[i] <= 0:
enemyX_change[i] = 3
enemyY[i] += enemyY_change[i]
elif enemyX[i] >= 945:
enemyX_change[i] = -3
enemyY[i] += enemyY_change[i]
# Collision
collision = isCollision(enemyX[i], enemyY[i], bulletX, bulletY)
if collision:
bulletY = 480
bullet_state = "ready"
score += 1
print(score)
enemyX[i] = random.randint(0, 945)
enemyY[i] = random.randint(50, 150)
#<--|
enemy(enemyX[i], enemyY[i], i)