How do you restart a game on pygame by using a button? - python

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()
# [...]

Related

How to add game restart in this pgame code? [duplicate]

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.

Pygame displays a black screen

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!

Increasing variables that are in use in pygame

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)

Blitting an image directly on top of another image in pygame [duplicate]

This question already has answers here:
How to center an image in the middle of the window in pygame?
(1 answer)
How to Center Text in Pygame
(6 answers)
Closed 5 months ago.
So I am trying to make a space-invaders game, and decided to have a missile weapon that would have a trigger. If you didn't hit the trigger, whatever alien it hit died and nothing else. If you do trigger it, the code would teleport the missile away and replace it with an explosion image. anything within the image would die. However, while the detonation button works and only one alien dies when it doesn't detonate, the detonation does not summon the explosion image, or do anything to the aliens. The missile just disappears and plays the detonation noise.
This is my code:
import pygame
from pygame import mixer
import random
import math
import time
pygame.init()
screen = pygame.display.set_mode((800, 600))
explosion_Sound = mixer.Sound('explosion.wav')
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"
missileImg = pygame.image.load('missile.png')
missileX = 0
missileY = 0
missileX_change = 0
missileY_change = 0.7
missile_state = "ready"
explosionImg = pygame.image.load('explosion.png')
explosionX = missileX
explosionY = missileY
explosionX_change = 0
explosionY_change = 0
explosion_state = "ready"
score_value = 34
font = pygame.font.Font('freesansbold.ttf', 32)
textX = 10
textY = 10
over_font = pygame.font.Font('freesansbold.ttf', 64)
level_up_font = pygame.font.Font('freesansbold.ttf', 64)
instructions = pygame.font.Font('freesansbold.ttf', 32)
def missile_instructions():
instruction = instructions.render("Press the M key to shoot missile", True, (255, 255, 255))
screen.blit(instruction, (200, 350))
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 level_up():
levelup_text = level_up_font.render("LEVEL UP!", True, (255, 255, 255))
screen.blit(levelup_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 fire_missile(x,y):
global missile_state
missile_state = "fire"
screen.blit(missileImg, (x + 16, y + 10))
def explosion(x,y):
global explosion_state
explosion_state = "fire"
screen.blit(explosionImg, (x,y))
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)
num_of_enemies += new_enemies
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
def isCollision2(enemyX, enemyY, missileX, missileY):
distance2 = math.sqrt((math.pow(enemyX-missileX,2)) + (math.pow(enemyY-missileY,2)))
if distance2 < 27:
return True
else:
return False
def isCollision3(enemyX, enemyY, explosionX, explosionY):
distance3 = math.sqrt((math.pow(enemyX-explosionX,2)) + (math.pow(enemyY-explosionY, 2)))
if distance3 < 128:
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:
pygame.quit()
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)
if event.key == pygame.K_m:
if score_value >= 35:
if missile_state == "ready":
missile_sound = mixer.Sound('laser.wav')
missile_sound.play()
missileX = playerX
fire_missile(missileX,missileY)
if event.key == pygame.K_n:
if score_value >= 35:
if missile_state == "fire":
explosion_state = "fire"
explosion_Sound.play()
explosionX = missileX
explosionY = missileY
missile_state = "ready"
missileX = bulletX
missileY = 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.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)
collision2 = isCollision2(enemyX[i], enemyY[i], missileX, missileY)
if collision2:
explosion_Sound = mixer.Sound('explosion.wav')
explosion_Sound.play()
missileY = 480
missile_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
if missileY <= 0:
missileY = 480
missile_state = "ready"
if missile_state == "fire":
fire_missile(missileX, missileY)
missileY -= missileY_change
player(playerX, playerY)
show_score(textX, textY)
if score_value == 20:
create_enemies(4)
score_value += 1
if score_value == 21:
level_up()
if score_value == 35:
level_up()
missile_instructions()
if score_value == 50:
create_enemies(5)
score_value += 1
if score_value == 51:
level_up()
pygame.display.update()
I don't receive any error messages, and the game doesn't crash, it simply continues as if the missile was never there, and the missile is also available for use as soon as it has been detonated.

Pygame Character wont move left or right

In my below code using PyGame, the character won't move left or right and the bullet won't shoot. I'm not sure what's causing this. It works without the whole start menu with buttons concept so I was wondering if that is the issue?
import pygame
from pygame import mixer
import math
import random
import time
# Initialize pygame module
pygame.init()
# Create the screen
screen = pygame.display.set_mode((800, 600))
display_width = 800
display_height = 600
# Background
background = pygame.image.load('space1.jpg')
# Background Sound
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('space-invaders.png')
playerX = 370
playerY = 480
player_change = 0
playerX += player_change
# Enemy
enemyImg = []
enemyX = []
enemyY = []
enemyX_change = []
enemyY_change = []
num_of_enemies = 6
# Colours
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (150, 0, 0)
GREEN = (0, 150, 0)
BRIGHT_RED = (255, 0,0)
BRIGHT_GREEN = (0, 255, 0)
for i in range(num_of_enemies):
enemyImg.append(pygame.image.load('alien.png'))
enemyX.append(random.randint(0, 736))
enemyY.append(random.randint(50, 150))
enemyX_change.append(2)
enemyY_change.append(40)
# Bullet
# Ready - You cant see the bullet on the screen
# Fire - The bullet is current moving
bulletImg = pygame.image.load('bullet.png')
bulletX = 0
bulletY = 480
bulletY_change = 10
bullet_state = 'ready'
# Score
score_value = 0
font = pygame.font.Font('freesansbold.ttf', 32)
textX = 10
textY = 10
# Game Over Text
over_font = pygame.font.Font('freesansbold.ttf', 64)
# Clock
clock = pygame.time.Clock()
def show_score(x, y):
score = font.render('score : ' + str(score_value), True, (0, 255, 0))
screen.blit(score, (x, y))
def game_over_text():
over_text = over_font.render('GAME OVER', True, (0, 255, 0))
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
def text_objects(text, font):
textSurface = font.render(text, True, WHITE)
return textSurface, textSurface.get_rect()
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
screen.fill(BLACK)
largeText = pygame.font.Font('freesansbold.ttf', 105)
TextSurf, TextRect = text_objects('Space Invaders', largeText)
TextRect.center = ((display_width/2), 200)
screen.blit(TextSurf, TextRect)
button('Start Invasion', 325, 350, 150, 50, GREEN, BRIGHT_GREEN, 'play')
button('Quit Mission', 325, 450, 150, 50, RED, BRIGHT_RED, 'quit')
pygame.display.update()
clock.tick(15)
#Game Loop
def game_loop(playerX, playerY, player_change, bulletX, bulletY, bulletX_change, bulletY_change, bullet_state, bulletImg):
running = True
while running:
playerX = 370
playerY = 480
player_change = 0
playerX += player_change
# RGB R G B
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 left or right
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player_change = -5
if event.key == pygame.K_RIGHT:
player_change = 5
if event.key == pygame.K_SPACE:
if bullet_state is 'ready':
bullet_sound = mixer.Sound('laser.wav')
bullet_sound.play()
# Get the current x coordinate of the spaceship
bulletX = playerX
fire_bullet(bulletX, bulletY)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
player_change = 0
# boundary for spaceship
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] = 2
enemyY[i] += enemyY_change[i]
elif enemyX[i] >= 736:
enemyX_change[i] = -2
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 += 1
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)
show_score(textX, textY)
pygame.display.update()
def button(msg, x, y, w, h, inactivecolour, activecolour, action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x + w > mouse[0] > x and y + h > mouse[1] > y:
pygame.draw.rect(screen, activecolour, (x, y, w, h))
if click[0] == 1 and action != None:
if action == 'play':
game_loop(370, 480, 0, 0, 480, 0, 10, 'ready', pygame.image.load('bullet.png'))
if action == 'quit':
pygame.quit()
quit()
else:
pygame.draw.rect(screen, inactivecolour, (x, y, w, h))
smallText = pygame.font.Font('freesansbold.ttf', 20)
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ((x + (w / 2)), (y + (h / 2)))
screen.blit(textSurf, textRect)
game_intro()
the character won't move
The movement of the player player_change is continuously set 0, in the main application loop. Further more, the position of the player is continuously initialized:
def game_loop(playerX, playerY, player_change, bulletX, bulletY, bulletX_change, >bulletY_change, bullet_state, bulletImg):
running = True
while running:
playerX = 370
playerY = 480
player_change = 0
Initialize playerX, playerY and player_change before the loop:
def game_loop(playerX, playerY, player_change, bulletX, bulletY, bulletX_change, bulletY_change, bullet_state, bulletImg):
running = True
player_change = 0
playerX = 370
playerY = 480
while running:
playerX += player_change
# [...]
the bullet won't shoot
If you want to fire a bullet, then you have to set the initial position of the bullet bulletX, bulletY = playerX, playerY and set bullet_state = 'fire':
def game_loop(playerX, playerY, player_change, bulletX, bulletY, bulletX_change, bulletY_change, bullet_state, bulletImg):
# [...]
while running:
playerX += player_change
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# If keystroke is pressed check whether its left or right
if event.type == pygame.KEYDOWN:
# [...]
if event.key == pygame.K_SPACE:
if bullet_state is 'ready':
#bullet_sound = mixer.Sound('laser.wav')
#bullet_sound.play()
# Get the current x coordinate of the spaceship
bulletX, bulletY = playerX, playerY
bullet_state = 'fire'
Note, the global variable bullet_state
def fire_bullet(x, y):
global bullet_state
bullet_state = 'fire'
is different to the local variable bullet_state in game_loop, because bullet_state is an argument to game_loop and thus a completely different variable in a different scope, which has casually the same name:
def game_loop(playerX, playerY, player_change, bulletX, bulletY,
bulletX_change, bulletY_change,
bullet_state, # <--- that is a new variable in local scope
# and not the "global" bullet_state
bulletImg):
# [...]
player_change = 0
playerX += player_change
Try swapping the order of these two lines. Otherwise the change will always be zero when the X location is updated.

Categories

Resources