My pygame programm has an issue. My bullet doesnt appear. But I know, that it exist. I tried many thing but nothing helped. I can let it appear but then my player and the bulle start flickering. Pls help. My character also has an moving animation. Pls read at first my code, then answer. Stackoverflow dont delete my message. Ihr Hurensöhne :)
import random
import pygame
# Intialize the pygame
pygame.init()
# create the screen
screen = pygame.display.set_mode((640, 360))
# Background
background = pygame.image.load('SSF2_Final_Valley.png')
walkRight = [pygame.image.load('R1a.png'), pygame.image.load('R2a.png'), pygame.image.load('R3a.png'), pygame.image.load('R4a.png'), pygame.image.load('R5a.png'), pygame.image.load('R6a.png'), pygame.image.load('R7a.png'), pygame.image.load('R8a.png'), pygame.image.load('R9a.png')]
walkLeft = [pygame.image.load('L1a.png'), pygame.image.load('L2a.png'), pygame.image.load('L3a.png'), pygame.image.load('L4a.png'), pygame.image.load('L5a.png'), pygame.image.load('L6a.png'), pygame.image.load('L7a.png'), pygame.image.load('L8a.png'), pygame.image.load('L9a.png')]
char = pygame.image.load('stand.png')
vel = 5
width = 64
screen_width = 640
left = False
right = False
clockobject = pygame.time.Clock()
#player
playerImg = pygame.image.load('stand.png')
playerX = 15
playerY = 290
playerX_change = 0
# Bullet
# Ready - You can't see the bullet on the screen
# Fire - The bullet is currently moving
bulletImg = pygame.image.load('kunai.png')
bulletX = 15
bulletY = 290 - 32
bulletX_change = 3
bulletY_change = 0
bullet_state = "ready"
def redrawGameWindow():
global player
def player(x, y):
global walkCount
screen.blit(background, (0,0))
#chracter wird gezecihnet
if walkCount + 1 >= 20:
walkCount = 0
if left:
screen.blit(walkLeft[walkCount//3], (x, y))
walkCount += 1
elif right:
screen.blit(walkRight[walkCount//3], (x, y))
walkCount += 1
global fire_bullet
def fire_bullet(x, y):
global bullet_state
bullet_state = "fire"
screen.blit(bulletImg, (x + 32, y + 32))
screen.blit(char, (x, y))
"""def fire_bullet(x, y):
global bullet_state
bullet_state = "fire"
screen.blit(bulletImg, (x + 32, y + 32))
pygame.display.update()"""
running = True
while running:
# RGB = Red, Green, Blue
#screen.fill((0, 0, 0))
# Background Image
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
exit()
# if keystroke is pressed check whether its right or left
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
if bullet_state is "ready":
# Get the current x cordinate of the spaceship
bulletX = playerX
fire_bullet(bulletX, bulletY)
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and playerX > vel:
playerX -= vel
left = True
right = False
elif keys[pygame.K_RIGHT] and playerX < screen_width- width :
playerX += vel
right = True
left = False
else:
right = False
left = False
walkCount = 0
# 5 = 5 + -0.1 -> 5 = 5 - 0.1
# 5 = 5 + 0.1
playerX += playerX_change
"""if playerX <= 0:
playerX = 0
elif playerX >= 640 - 64:
playerX = 608 - 64"""
screen.blit(background, (0,0))
redrawGameWindow()
if bulletX <= 0:
bulletX = 15
bullet_state = "ready"
if bullet_state is "fire":
fire_bullet(bulletX, bulletY)
bulletX += bulletX_change
if (bulletX > screen_width-width):
bullet_state = "ready"
if keys[pygame.K_f]:
playerX = bulletX
player(playerX, playerY)
pygame.display.update()
Remove the functions player and fire_bullet from the function redrawGameWindow. player and fire_bullet have to be functions in global namespace. However redrawGameWindow has to invoke the functions player and fire_bullet. Draw the background and update the display in redrawGameWindow:
def player(x, y):
global walkCount
if walkCount + 1 >= 20:
walkCount = 0
if left:
screen.blit(walkLeft[walkCount//3], (x, y))
walkCount += 1
elif right:
screen.blit(walkRight[walkCount//3], (x, y))
walkCount += 1
else:
screen.blit(char, (x, y))
def fire_bullet(x, y):
global bullet_state
bullet_state = "fire"
screen.blit(bulletImg, (x + 32, y + 32))
def redrawGameWindow():
screen.blit(background, (0,0))
player(playerX, playerY)
if bullet_state is "fire":
fire_bullet(bulletX, bulletY)
pygame.display.update()
Call redrawGameWindow at the end of the application loop:
clock = pygame.time.Clock()
running = True
while running:
clock.tick(60)
# [...]
if bulletX <= 0:
bulletX = 15
bullet_state = "ready"
if bullet_state is "fire":
bulletX += bulletX_change
if (bulletX > screen_width-width):
bullet_state = "ready"
if keys[pygame.K_f]:
playerX = bulletX
redrawGameWindow()
Related
So I was trying to build this game using a free course on Youtube by Freecodeacademy(feel free to check them out) and after I finished I tried to add my own restart key log to the game. In the sense that I wanted that if people press R the game restarts.
I have tried the following methods
Put the game loop in a separate function and try to use recursion to replay the function over and over again but while the game does work, the images such as the bullet image or background does not load and hence it does not work properly
I have also tried creating a new python file in the same project and tried to import the main file over and over again using importlib.reload(main) but I can't seem to do that either.
I was wondering what else could the solution be and if there is a more efficient solution. I will leave my code down below and would appreciate any help.
Ps: I am only a armature in coding right now so I understand this problem might be small and stupid but I do want to learn from my failures and mistakes. Also I apologize if there is something wrong with anything in my question. This is my first question on stack overflow.
import pygame
import random
import math
from pygame import mixer
pygame.init() # This is to Initialise the game
screen = pygame.display.set_mode((800, 600)) # create screen and set height
# Background
background = pygame.image.load('background.png')
# 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
playerX_change = 0
def player(x, y): # This function is used to display the value on the screen
screen.blit(playerImg, (x, y)) # Blit is used to display stuff on the screen
# Enemy
enemyImg = []
enemyX = []
enemyY = []
enemyX_change = []
enemyY_change = []
num_of_enemies = 6
for i in range(num_of_enemies):
enemyImg.append(pygame.image.load("invader.png"))
enemyX.append(random.randint(0, 736))
enemyY.append(random.randint(50, 150))
enemyX_change.append(4)
enemyY_change.append(40)
def enemy(x, y, i): # This function is used to display the value on the screen
screen.blit(enemyImg[i], (x, y)) # Blit is used to display stuff on the screen
# Bullet
bulletImg = pygame.image.load('bullet.png')
bulletX = 0
bulletY = 480
bulletX_change = 0
bulletY_change = 10
bullet_state = "ready" # Ready state means bullet has not yet been fired, we use this as a bool
# Score
score_value = 0
font = pygame.font.Font('freesansbold.ttf', 16)
textX = 10
textY = 10
# Game Over Text
over_font = pygame.font.Font("freesansbold.ttf", 64)
def show_score(x, y):
over_text = font.render("Score: " + str(score_value), True, (255, 255, 255))
screen.blit(over_text, (x, y))
def game_over_text():
over_text = over_font.render("GAME OVER ", True, (255, 255, 255))
screen.blit(over_text, (200, 250))
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:
# Background color
screen.fill((0, 0, 0))
# Background image
screen.blit(background, (0, 0))
for event in pygame.event.get(): # pygame.event.get() function is used to create a container of every action done
if event.type == pygame.QUIT: # Close game when cross is clicked
running = False
# Recording Keystrokes
if event.type == pygame.KEYDOWN: # KEYDOWN is used to check if key is pressed
if event.key == pygame.K_LEFT:
playerX_change -= 5
if event.key == pygame.K_RIGHT:
playerX_change += 5
if event.key == pygame.K_SPACE: # Bullet Shot
if bullet_state == "ready":
bullet_sound = mixer.Sound("laser.wav")
bullet_sound.play()
bulletX = playerX
fire_bullet(bulletX, playerY)
if event.key == pygame.K_r:
restart = True
if event.type == pygame.KEYUP: # KEYUP is used to know if the key is released
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
# Player Call
playerX += playerX_change
# Setting Boundaries
if playerX <= 0:
playerX = 0
if playerX >= 736:
playerX = 736
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] = 4
enemyY[i] += enemyY_change[i]
elif enemyX[i] >= 736:
enemyX_change[i] = -4
enemyY += enemyY_change
# Collision
collision = isCollision(enemyX[i], enemyY[i], bulletX, bulletY)
if collision:
explosion_sound = mixer.Sound("explosion.wav")
explosion_sound.play()
bulletY = 480
score_value += 1
bullet_state = "ready"
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, textY)
# Constantly updates the changes
pygame.display.update()
Write a function that will reset any variables that change when the game is running:
enemy_image = pygame.image.load("invader.png")
def resetGame():
global playerX, playerY, playerX_change
global enemyImg, enemyX, enemyY, enemyX_change, enemyY_change
global score_value
global bulletX, bulletY, bulletX_change, bulletY_change, bullet_state
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(enemy_image)
enemyX.append(random.randint(0, 736))
enemyY.append(random.randint(50, 150))
enemyX_change.append(4)
enemyY_change.append(40)
bulletX = 0
bulletY = 480
bulletX_change = 0
bulletY_change = 10
bullet_state = "ready"
score_value = 0
Call the function once if the game needs to be restarted. You can even call the function before the application loop instead of setting all the variables.
This question already has answers here:
How can you rotate the sprite and shoot the bullets towards the mouse position?
(1 answer)
calculating direction of the player to shoot pygame
(1 answer)
Shooting a bullet in pygame in the direction of mouse
(2 answers)
Closed 2 years ago.
import pygame
import random
import math
from pygame import mixer
pygame.init()
screen = pygame.display.set_mode((1280, 720))
background = pygame.image.load('1264.jpg')
background = pygame.transform.scale(background, (1290, 720))
pygame.display.set_caption("FlySwapper")
icon = pygame.image.load('logo.png')
pygame.display.set_icon(icon)
playerImg = pygame.image.load('Frosk.png')
playerX = 580
playerY = 550
playerX_change = 0
playerY_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('flue.png'))
enemyX.append(random.randint(0, 1290))
enemyY.append(random.randint(0, 310))
enemyX_change.append(0.5)
enemyY_change.append(0.5)
bulletImg = pygame.image.load('skudd.png')
bulletX = 0
bulletY = 0
bulletX_change = 2
bulletY_change = 2
bullet_state = "ready"
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 + 35, y + 10))
running = True
while running:
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_a:
playerX_change = -1
if event.key == pygame.K_d:
playerX_change = 1
if event.key == pygame.K_w:
playerY_change = -1
if event.key == pygame.K_s:
playerY_change = 1
if event.type == pygame.KEYUP:
if event.key == pygame.K_a or event.key == pygame.K_d:
playerX_change = 0
if event.type == pygame.KEYUP:
if event.key == pygame.K_w or event.key == pygame.K_s:
playerY_change = 0
LEFT = 1
RIGHT = 3
if event.type == pygame.MOUSEBUTTONUP and event.button == LEFT:
if bullet_state == "ready":
#bullet_Sound = mixer.Sound('.wav')
#bullet_Sound.play()
bulletX = playerX
bulletY = playerY
fire_bullet(bulletX, bulletY)
playerX += playerX_change
playerY += playerY_change
if playerX <= 0:
playerX = 0
elif playerX >= 1150:
playerX = 1150
if playerY <= 310:
playerY = 310
elif playerY >= 590:
playerY = 590
player(playerX, playerY)
for i in range(num_of_enemies):
enemyX[i] += enemyX_change[i]
enemyY[i] += enemyY_change[i]
if enemyX[i] <= 0:
enemyX_change[i] = 0.5
elif enemyX[i] >= 1150:
enemyX_change[i] = -0.5
if enemyY[i] <= 0:
enemyY_change[i] = 0.5
elif enemyY[i] >= 590:
enemyY_change[i] = -0.5
enemy(enemyX[i], enemyY[i], i)
if bulletY <= 0:
bullet_state = "ready"
if bullet_state == "fire":
fire_bullet(bulletX, bulletY)
bulletY -= bulletY_change
pygame.display.update()
I have been trying to make the bullet go towards my mouse on left click for weeks, my teacher can't help me apparantly and I am pretty new to python.
I know that I have made the bullet to only go forward in this code, but I was planning on changing it to go towards the mouse click later.
I'm sorry if this was a bad explanation of my problem.
When you click the mouse, you need to calculate the normalized direction vector (Unit vector) from the start position of the bullet to the mouse position. Define the speed of the bullet and multiply the direction vector by the speed:
dx = event.pos[0] - bulletX
dy = event.pos[1] - bulletY
dist = math.sqrt(dx*dx + dy*dy)
bulletX_change = bullet_speed * dx/dist
bulletY_change = bullet_speed * dy/dist
relevant changes:
def fire_bullet(x, y):
screen.blit(bulletImg, (x + 35, y + 10))
running = True
while running:
# [...]
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# [...]
if event.type == pygame.MOUSEBUTTONUP and event.button == LEFT:
if bullet_state == "ready":
#bullet_Sound = mixer.Sound('.wav')
#bullet_Sound.play()
bulletX = playerX
bulletY = playerY
bullet_state = "fire"
dx = event.pos[0] - bulletX
dy = event.pos[1] - bulletY
dist = math.sqrt(dx*dx + dy*dy)
bulletX_change = bullet_speed * dx/dist
bulletY_change = bullet_speed * dy/dist
# [...]
if playerX < 0 or bulletY < 0 or playerX > 1280 or bulletY > 720:
bullet_state = "ready"
if bullet_state == "fire":
bulletX += bulletX_change
bulletY += bulletY_change
fire_bullet(bulletX, bulletY)
pygame.display.update()
so i was learning python and i finished the game and everything is working but now i have no idea about how to restart the game i mean when it ends what is next? how to start again
i will put a link for my full code and here is what have done so far.
Thank you so much!
if Bullet_state is "fire":
fire(BulletX, BulletY)
BulletY -= Bullet_MovementY
player(playerX, playerY)
score(textX, textY)
pygame.display.update()
For the restart logic, keep the current game loop but add a flag to indicate that the game has ended. In the loop, check for this flag and display the restart prompt if the flag is set. Also encapsulate the initialization process in a function so it can be called at each restart.
Note that I tested this in Python 3.8.
Try this code. When the score reaches 3, the game ends and the restart prompt is displayed.
import pygame
import random
import math
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Space Invadors')
icon = pygame.image.load('1.png')
pygame.display.set_icon(icon)
#Background
Background = pygame.image.load('background.png')
def SetGameStart(): # initialize variables
global Player_Image,playerX,playerY,Key_Movement,Enemy_Image,EnemyX,EnemyY,Enemy_MovementX,Enemy_MovementY
global Bullet_Image,BulletX,BulletY,Bullet_MovementX,Bullet_MovementY,Bullet_state,Score
# Player
Player_Image = pygame.image.load('player.png')
playerX = 370
playerY = 480
Key_Movement = 0
# Enemy
Enemy_Image = pygame.image.load('monster2.png')
EnemyX = random.randint(0, 735)
EnemyY = random.randint(50, 150)
Enemy_MovementX = 1.5
Enemy_MovementY = 40
# Bullet
Bullet_Image = pygame.image.load('bullet.png')
BulletX = 0
BulletY = 480
Bullet_MovementX = 0
Bullet_MovementY = 10
Bullet_state = "Ready"
Score = 0
def Fire(x, y):
global Bullet_state
Bullet_state = "Fire"
screen.blit(Bullet_Image, (x + 16, y + 10))
def player(x, y):
# blit is draw! draw an image on the screen
screen.blit(Player_Image, (x, y))
def Enemy(x, y):
screen.blit(Enemy_Image, (x, y))
def is_Collided(BulletX, BulletY, EnemyX, EnemyY):
distance = math.sqrt(math.pow(BulletX - EnemyX, 2) + math.pow(BulletY - EnemyY, 2))
if distance < 27:
return True
else:
return False
SetGameStart() # initialize variables
GameDone = False
def text_objects(text, font):
textSurface = font.render(text, True, (0,200,0))
return textSurface, textSurface.get_rect()
Close = True
while Close:
screen.fill((0, 0, 0))
screen.blit(Background, (0, 0))
if GameDone: # pause game loop, show restart prompt
largeText = pygame.font.SysFont("comicsansms",20)
TextSurf, TextRect = text_objects("Game Over. Press Space to restart.", largeText)
TextRect.center = ((800/2),(600/2))
screen.blit(TextSurf, TextRect)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
Close = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q: # press Q to quit
Close = False
break
if event.key == pygame.K_SPACE: # press space to restart
GameDone = False
SetGameStart() # initialize variables
continue # skip game process
for event in pygame.event.get():
if event.type == pygame.QUIT:
Close = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
Key_Movement = -4
if event.key == pygame.K_RIGHT:
Key_Movement = 4
if event.key == pygame.K_SPACE:
# to fix the Pressing on space will reload the Bullet
if Bullet_state is "Ready":
BulletX = playerX
Fire(BulletX, playerY)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
Key_Movement = 0
playerX += Key_Movement
if playerX <= 0:
playerX = 0
elif playerX >= 736:
playerX = 736
# Enemy movement limit
EnemyX += Enemy_MovementX
if EnemyX <= 0:
Enemy_MovementX = 1.5
EnemyY += Enemy_MovementY
elif EnemyX >= 736:
Enemy_MovementX = -1.5
EnemyY += Enemy_MovementY
if BulletY <= 0:
BulletY = 480
Bullet_state = "Ready"
if Bullet_state is "Fire":
Fire(BulletX, BulletY)
BulletY -= Bullet_MovementY
Collision = is_Collided(EnemyX, EnemyY, BulletX, BulletY)
if Collision:
BulletY = 480
Bullet_state = "Ready"
Score += 1
print(Score)
EnemyX = random.randint(0, 735)
EnemyY = random.randint(50, 150)
Enemy(EnemyX, EnemyY)
player(playerX, playerY)
pygame.display.update()
if Score == 3:
GameDone = True
Prompt
I recently made a small game about some of my friends and when i try to convert it to an exe file, using the auto-py-to-exe project i get an error.When I open the exe file it says "Failed to execute script"
I have some pictures and audios, all the elements are in the same folder.
Here's the code:
import pygame
import random
import math
from pygame import mixer
# Initialize the pygame
pygame.init()
# rezolutia ecranului
screen = pygame.display.set_mode((800, 600))
#Background
background = pygame.image.load("background.png")
#Background sound
#mixer.music.load("Talent de tigan.mp3")
#mixer.music.play(-1)
# titlu si iconita
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load("icon.png")
pygame.display.set_icon(icon)
# Player
playerImg = pygame.image.load("vld1.png")
playerX = 370
playerY = 515
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("urs.png"))
enemyX.append(random.randint(0, 735))
enemyY.append(random.randint(50, 150))
enemyX_change.append(2)
enemyY_change.append(40)
# Bullet
bulletImg = pygame.image.load("bullet.png")
bulletX = 0
bulletY = 480
bulletX_change = 0
bulletY_change = 10
# ready - nu pot vedea glontu pe ecran
# fire - glontu se misca
bullet_state = "ready"
# Score
score_value = 0
font = pygame.font.Font("Fruity Stories.ttf", 32)
textX = 10
textY = 10
# Game over text
over_font = pygame.font.Font("Fruity Stories.ttf", 124)
def show_score(x,y):
score = font.render("Ursi ucisi :" + str(score_value),True, (255,255,255))
screen.blit(score, (x, y))
def game_over_text():
over_text = over_font.render("Te-a mancat ",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
# sa nu se inchida fereastra
running = True
while running:
#background 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
#player movement
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -3
if event.key == pygame.K_RIGHT:
playerX_change = 3
if event.key == pygame.K_SPACE:
if bullet_state is "ready":
bullet_sound = mixer.Sound("inreg.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:
playerX_change = 0
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] > 470:
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:
explx_sound = mixer.Sound("mustea4.wav")
explx_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()
Thank you for your time.
I am using Python 3 btw.
you need to add your data files:
If you use windows:
pyinstaller --onefile -w --add-data="background.png;." --add-data="icon.png;."\
#continue adding add-data for all your files
script.py
else replace ; with :.
This way pyinstaller knows which files are needed for your game to work and can add them
This question already has answers here:
Lag when win.blit() background pygame
(2 answers)
Closed 2 years ago.
I made a little space invaders game with pygame, I noticed that the game lags for a few seconds periodically. I do not know what the problem is. I am a beginner.
Can you tell me why this happens? Is there any fix to this?
Also, why does everything slow down once you add the background image in the main game loop?
import pygame
from pygame import mixer
import random
import math
# Starting pygame
pygame.init()
# window
screen = pygame.display.set_mode((800, 600))
background = pygame.image.load('background.png')
# title and icon
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load('icon.png')
pygame.display.set_icon(icon)
# background
mixer.music.load('galaxy.ogg')
mixer.music.play(-1)
# player
playerimg = pygame.image.load('rocket.png')
playerX = 370
playerY = 480
playerX_change = 0
# Enemy
enemy_img = []
enemyX = []
enemyY = []
enemyX_change = []
enemyY_change = []
num_of_enemies = 1
for i in range(num_of_enemies):
enemy_img.append(pygame.image.load('Enemy.png'))
enemyX.append(random.randint(0, 735))
enemyY.append(random.randint(50, 300))
enemyX_change.append(4)
enemyY_change.append(40)
# Bullet
bulletimg = pygame.image.load('bullet.png')
bulletX = 0
bulletY = 480
bulletX_change = 0
bulletY_change = 10
bullet_state = "ready"
# ready = you can't see the bullet on the screen
# fire = the bullet is currently moving
# score
score_value = 0
font = pygame.font.Font('freesansbold.ttf', 32)
textX = 10
textY = 10
# gameover text
over_font = pygame.font.Font('freesansbold.ttf', 70)
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, 0, 0))
screen.blit(over_text, (200, 250))
def player(x, y):
screen.blit(playerimg, (x, y))
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(bulletimg, (x + 25, y + 10))
def iscollision(enemyX, enemyY, bulletX, bulletY):
distance = math.sqrt(math.pow(enemyX - bulletX, 2) + math.pow(enemyY - bulletY, 2))
if distance < 30:
return True
else:
return False
# gameloop
running = True
while running:
# RGB screen
screen.fill((0, 0, 0))
screen.blit(background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Check keystroke left or right
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -10
if event.key == pygame.K_RIGHT:
playerX_change = 10
if event.key == pygame.K_SPACE:
if bullet_state is "ready":
bullet_sound = mixer.Sound('shoot.wav')
bullet_sound.play()
# gets the current x cor of the player
bulletX = playerX
fire_bullet(bulletX, bulletY)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
playerX_change = 0
if event.key == pygame.K_RIGHT:
playerX_change = 0
playerX += playerX_change
if playerX <= 0:
playerX = 0
elif playerX >= 736:
playerX = 736
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] *= -1
enemyY[i] += enemyY_change[i]
elif enemyX[i] >= 736:
enemyX_change[i] *= -1
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
# print(score)
enemyX[i] = random.randint(0, 735)
enemyY[i] = random.randint(50, 300)
enemy(enemyX[i], enemyY[i], i)
# if enemyY <= 50:
# enemyY_change *= -1
# elif enemyY >= 300:
# enemyY_change *= -1
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()
Call convert() on the background image. That ensures that the image has the same pixel format as the display Surface and will help blit to operate with optimal performance:
screen = pygame.display.set_mode((800, 600))
background = pygame.image.load('background.png').convert()
Note, if the surface has a different format than the display, then blit has to convert the format on the fly in every frame.