Variables and Surface won't Update in Python/Pygame - python

I am trying to make my game have special abilities for the player, but am having some issues. For some reason user_health_active and user_health_display_active do not update after reaching round 10. I can't figure out why this is and have been attempting to for about two hours. By the seems of it, not only does the surface not update, but the actual background function doesn't either. If anyone can provide me some insight on why this isn't working, please let me know. Here is my code.
"""
Game Developer: Austin H.
Game Owner: Austin H.
Licensed Through: theoiestinapps
Build: 2
Version: 1.0.1
"""
import os
import pygame as pygame
import random
import sys
import time
pygame.init()
left = False
right = False
playerDead = False
devMode = False
game_completed = False
game_level_score = (0)
game_display_score = (0)
enemy_speed = (5)
user_teleport_active = False
user_health_active = False
user_teleport_display_active = ("False")
user_health_display_active = ("False")
display_width = 800
display_height = 600
customBlue = (17, 126, 194)
black = (0, 0, 0)
blue = (0, 0, 255)
green = (0, 255, 0)
red = (255, 0, 0)
white = (255, 255, 255)
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption("Space Dodge")
clock = pygame.time.Clock()
backgroundMusic = pygame.mixer.music.load('C:/Program Files/Space Dodge/game_background_music.mp3')
enemyImg = pygame.image.load('C:/Program Files/Space Dodge/enemy_image.png')
backgroundImg = pygame.image.load('C:/Program Files/Space Dodge/background_image.png')
rocketImg = pygame.image.load('C:/Program Files/Space Dodge/player_image.png')
injuredSound = pygame.mixer.Sound('C:/Program Files/Space Dodge/player_hurt_sound.wav')
def teleport_powerup(user_teleport_display_active):
font = pygame.font.SysFont(None, 25)
text = font.render("Teleport Powerup: " + str(user_teleport_display_active), True, red)
gameDisplay.blit(text, (display_width - 205, 5))
def ehealth_powerup(user_health_display_active):
font = pygame.font.SysFont(None, 25)
text = font.render("Ehealth Powerup: " + str(user_health_display_active), True, red)
gameDisplay.blit(text, (display_width - 205, 25))
def enemies_dodged(enemy_objects_dodged):
font = pygame.font.SysFont(None, 25)
text = font.render("Dodge Asteroids: " + str(enemy_objects_dodged), True, green)
gameDisplay.blit(text, (5, 5))
def game_level(game_display_score):
font = pygame.font.SysFont(None, 25)
game_display_score = game_level_score + 1
text = font.render("Game Level: " + str(game_display_score), True, green)
gameDisplay.blit(text, (5, 25))
def enemies(enemyx, enemyy, enemyw, enemyh, color):
pygame.draw.rect(gameDisplay, color, [enemyx, enemyy, enemyw, enemyh])
def rocket(x, y):
gameDisplay.blit(rocketImg, (x, y))
def background(cen1, cen2):
gameDisplay.blit(backgroundImg, (cen1, cen2))
def text_objects(text, font):
textSurface = font.render(text, True, blue)
return textSurface, textSurface.get_rect()
def message_display(text):
global game_completed
largeText = pygame.font.Font('freesansbold.ttf', 70)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width / 2), (display_height / 2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
if game_completed == True:
time.sleep(300)
else:
time.sleep(5)
if game_level_score > 0:
pass
else:
pygame.mixer.music.play()
game_loop()
def crash():
injuredSound.play()
message_display("You Died. Game Over!")
def game_loop():
global left
global right
global playerDead
global game_level_score
global enemy_speed
global game_completed
global user_teleport_active
global user_teleport_display_active
global user_health_active
global user_health_display_active
x = (display_width * 0.43)
y = (display_height * 0.74)
cen1 = (0)
cen2 = (0)
x_change = 0
rocket_width = (86)
game_score = (0)
enemy_objects_dodged = (0)
enemy_startx = random.randrange(0, display_width)
enemy_starty = -600
enemy_width = 100
enemy_height = 100
while not playerDead:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.mixer.music.stop()
playerDead = True
if devMode == True:
print(event)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
left = True
if event.key == pygame.K_d:
right = True
if event.key == pygame.K_LEFT:
left = True
if event.key == pygame.K_RIGHT:
right = True
if event.key == pygame.K_KP4:
left = True
if event.key == pygame.K_KP6:
right = True
if event.key == pygame.K_ESCAPE:
playerDead = True
if event.key == pygame.K_SPACE:
game_level_score += 1
if event.type == pygame.KEYUP:
if event.key == pygame.K_a or pygame.K_d:
left = False
if event.key == pygame.K_d:
right = False
if event.key == pygame.K_LEFT:
left = False
if event.key == pygame.K_RIGHT:
right = False
if event.key == pygame.K_KP4:
left = False
if event.key == pygame.K_KP6:
right = False
if event.key == pygame.K_SPACE:
pass
if left and right:
x_change *= 1
elif left and x > -86:
x_change = -5
elif right and x < (display_width - 89):
x_change = 5
else:
x_change = 0
if game_score == 10:
enemy_speed += 0.5
game_level_score += 1
if game_level_score == 49:
game_completed = True
message_display('Game Complete!')
else:
message_display('Levels Completed: %s' % game_level_score)
if game_level_score > 4:
user_teleport_active = True
user_teleport_display_active = ("True")
elif game_level_score > 9:
user_health_active = True
user_health_display_active = ("True")
if user_teleport_active == True:
if x < -0:
x = 850
if enemy_starty > display_height:
enemy_starty = 0 - enemy_height
enemy_startx = random.randrange(0, display_width)
game_score += 1
enemy_objects_dodged += 1
if y < enemy_starty + enemy_height:
if x > enemy_startx and x < enemy_startx + enemy_width or x + rocket_width > enemy_startx and x + rocket_width < enemy_startx + enemy_width:
pygame.mixer.music.stop()
game_level_score = (0)
user_teleport_active = False
user_teleport_display_active = ("False")
crash()
x += x_change
background(cen1, cen2)
enemies(enemy_startx, enemy_starty, enemy_width, enemy_height, customBlue)
enemy_starty += enemy_speed
rocket(x, y)
enemies_dodged(enemy_objects_dodged)
game_level(game_display_score)
teleport_powerup(user_teleport_display_active)
ehealth_powerup(user_health_display_active)
pygame.display.update()
clock.tick(90)
pygame.mixer.music.set_volume(0.20)
pygame.mixer.music.play(-1)
game_loop()
pygame.quit()
quit()

The code that modifies the variables you mention will never be run. Here's the relevant bit:
if game_level_score > 4:
user_teleport_active = True
user_teleport_display_active = ("True")
elif game_level_score > 9:
user_health_active = True
user_health_display_active = ("True")
Because you're using an if and an elif, the condition for the second block is only ever tested if the first block's condition was false. Since any value greater than 9 is also going to be greater than 4, the second block will never run.
If you want the two conditions to be tested independently, you need to just use plain if statements for both conditions. If you only want one block to run , you either need to extend the first condition to 4 < game_level_score <= 9 or you need to change the order so that the > 9 test comes before the > 4 test.

Related

Python file .exe just appear in a moment and close immediately after that

I'm new to pygame. I have made a code about the game similar to dinosaur game when the internet is interupt. But when I convert from .py to .exe it just open in a moment and close immediately although main script runs fine. The command I've been using was pyinstaller file.py --onefile which make a executable that keeps closing immediately when i run it. I have checked wheather there is a error but it doesn't( i dont you any image.png outside)
import pygame
import time
import random
import sys
pygame.init()
white = (255,255,255)
yellow = (255,255,102)
black = (0,0,0)
red = (235, 64, 52)
width = 1000
height = 600
clock = pygame.time.Clock()
font_style = pygame.font.SysFont(None, 30)
score_font = pygame.font.SysFont('monospace', 35)
screen = pygame.display.set_mode((width,height))
def message(msg, color):
mesg = font_style.render(msg, True, color)
screen.blit(mesg, (round(width/3), round(height/3)))
bush_speed = 1
def your_score(score1):
value = score_font.render("Your Score: " + str(score1), True, yellow)
screen.blit(value, [0, 0])
game_over = False
def collision(player_pos,bush_pos):
p_x = player_pos[0]
p_y = player_pos[1]
b_x = bush_pos[0]
b_y = bush_pos[1]
if (b_x >= p_x and b_x < p_x + 50 ) or (b_x == p_x) or (p_x >= b_x and p_x < b_x + 50) :
if (b_y >= p_y and b_y < p_y + 100) or (b_y == p_y) :
return True
return False
def bush(bush_height,bush_pos):
pygame.draw.rect(screen,red, [bush_pos[0],bush_pos[1],50,bush_height])
def speed(bush_speed,score1):
if score1 < 3:
bush_speed = 50
elif score1 < 20:
bush_speed = 4
elif score1 < 30:
bush_speed = 5
else:
bush_speed = 15
def game_loop():
game_close = False
player_pos = [200,500]
player_jump =[0,0]
player_height = 100
player_size = 50
score1 = 0
game_over = False
bush_size = 50
bush_height = (round(random.randint(50,100)/10) *10)
bush_pos = [width - bush_size, height - bush_height]
while not game_over:
while game_close:
screen.fill(white)
message("You Lost! Press C-Play Again or Q-Quit", red)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
game_loop()
if event.key == pygame.K_q:
game_over = True
game_close = False
screen.fill(black)
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if player_pos[0] > 0:
if event.key == pygame.K_LEFT:
player_pos[0] -= 50
if player_pos[0] < width - player_size:
if event.key == pygame.K_RIGHT:
player_pos[0] +=50
if player_pos[1] == height -100:
if event.key == pygame.K_SPACE:
player_pos[1] -=200
player_jump[0] = 1
if player_pos[1] < height - player_height :
player_pos[1] += player_jump[0]
bush_pos[0] -= bush_speed*2
clock.tick(200)
if bush_pos[0] < 0 :
bush_height = (round(random.randint(50,100)/10) *10)
bush_pos = [width - bush_size, height - bush_height]
score1 +=1
speed(bush_speed,score1)
if collision(player_pos,bush_pos):
game_close = True
bush(bush_height,bush_pos)
your_score(score1)
pygame.draw.rect(screen, red, (player_pos[0],player_pos[1],player_size,player_height))
pygame.display.update()
pygame.display.flip()
game_loop()
sorry if my english is bad and my knowledge of code is too limited
Fonts are often the issue here, same goes for audio files. Try replacing:
font_style = pygame.font.SysFont(None, 30)
with
font_style = pygame.font.SysFont("Arial", 30)
Arial is pretty much always a "safe bet" in these cases. Also before converting with pyinstaller change your file name to main.py. Also do not forget to update pygame to 2.0.0.dev6 or newer.
It should work now.

Game Wont Restart after Game Over

I made a game on python pygame similar to space invaders but instead the aliens shoot at you. So if I manage to get hit by an alien. The game is over, I have two options, Menu, and quit. If I quit and try to play again it says game over AGAIN right after I click play. Any help would be appreciated.
I know its because when the game is over, and I restart my game again, the spaceship spawns again back where it was when it died. And I don't know how to fix that.
import sys
from pygame import *
from math import *
from random import *
import random
import math
init()
display_width = 1000
display_height = 700
shipx = 350
shipy = 550
asteroids=[]
astroidX=randint(0,800)
astroidY=randint(50,500)
astroidY_change=0
alien=[]
aliencounter=0
enemy_y =0
enemy_x=0
alienbullets=[]
w=[0,5]
gameDisplay = display.set_mode((display_width,display_height))
screen=display.set_mode((1000,700))
white = (255,255,255)
black = (0,0,0)
red = (200,0,0)
light_red = (255,0,0)
yellow = (200,200,0)
light_yellow = (255,255,0)
green = (34,177,76)
light_green = (0,255,0)
blue = (0,0,255)
clock = time.Clock()
explosion_sound = mixer.Sound('./sounds/boom.wav')
bullet_sound = mixer.Sound('./sounds/shot1.wav')
bg_sound = mixer.Sound('./sounds/bgmusic1.ogg')
smallfont = font.SysFont("comicsansms", 25)
medfont = font.SysFont("comicsansms", 50)
largefont = font.SysFont("comicsansms", 85)
xlargefont = font.SysFont("Girassol", 100)
textx = 10
texty = 10
bg_imgs = ['./image/bg_big.png',
'./image/seamless_space.png',
'./image/space3.jpg']
bg_move_dis = 0
bg_1 = image.load(bg_imgs[0]).convert()
bg_2 = image.load(bg_imgs[1]).convert()
bg_3 = image.load(bg_imgs[2]).convert()
Score_1 = 200
Score_2 = 200
if (Score_1 + Score_2) < 500:
background = bg_1
elif (Score_1 + Score_2) < 1500:
background = bg_2
else:
background = bg_3
v=[0,-5]#horiz and vertical speed of the bullet
#print(ets)
bullets=[]#empty list for bullets
astroid=image.load("image/meteorBrown_med1.png").convert_alpha()
alienspaceship=image.load("image/ufo.png").convert_alpha()
def show_score(x,y):
score = smallfont.render("Score : " + str(score_value), True, light_yellow)
screen.blit(score,(x,y))
def show_lives(x,y):
lives = smallfont.render("Lives : " + str(livesr), True, light_yellow)
screen.blit(lives,(x,y))
def text_objects(text, color,size = "small"):
if size == "small":
textSurface = smallfont.render(text, True, color)
if size == "medium":
textSurface = medfont.render(text, True, color)
if size == "large":
textSurface = largefont.render(text, True, color)
if size == "xlarge":
textSurface = xlargefont.render(text, True, color)
return textSurface, textSurface.get_rect()
def text_to_button(msg, color, buttonx, buttony, buttonwidth, buttonheight, size = "small"):
textSurf, textRect = text_objects(msg,color,size)
textRect.center = ((buttonx+(buttonwidth/2)), buttony+(buttonheight/2))
gameDisplay.blit(textSurf, textRect)
def message_to_screen(msg,color, y_displace = 0, size = "small"):
textSurf, textRect = text_objects(msg,color,size)
textRect.center = (int(display_width / 2), int(display_height / 2)+y_displace)
gameDisplay.blit(textSurf, textRect)
def button(text, x, y, width, height, inactive_color, active_color, action = None):
cur = mouse.get_pos()
click = mouse.get_pressed()
#print(click)
if x + width > cur[0] > x and y + height > cur[1] > y:
draw.rect(gameDisplay, active_color, (x,y,width,height))
if click[0] == 1 and action != None:
if action == "Quit":
quit()
if action == "Play":
play()
if action == "Controls":
control_menu()
if action == "Back":
game_intro()
else:
draw.rect(gameDisplay, inactive_color, (x,y,width,height))
text_to_button(text,black,x,y,width,height)
def game_intro():
menu_1 = image.load('./image/menubackground.jpg')
gameDisplay.blit(menu_1,(0,0))
intro = True
while intro:
for evt in event.get():
#print(event)
if evt.type == QUIT:
quit()
if evt.type == KEYDOWN:
if evt.key == K_c:
intro = False
elif evt.key == K_q:
quit()
message_to_screen("Space Heroes!",green,-210,size="xlarge")
message_to_screen("The objective is to shoot and destroy",white,-30)
message_to_screen("the enemy ships before they destroy you.",white,10)
message_to_screen("Defeat all of them to advance to next level!.",white,50)
message_to_screen("By Wafi Hassan",blue, 110)
button("Play", 230,500,100,50, green, light_green, action="Play")
button("Controls", 430,500,100,50, yellow, light_yellow, action="Controls")
button("Quit", 630,500,100,50, red, light_red, action ="Quit")
display.update()
clock.tick(15)
def control_menu():
menu_1 = image.load('./image/menubackground.jpg')
gameDisplay.blit(menu_1,(0,0))
intro = True
while intro:
for evt in event.get():
#print(event)
if evt.type == QUIT:
quit()
if evt.type == KEYDOWN:
if evt.key == K_c:
intro = False
elif evt.key == K_q:
quit()
message_to_screen("Controls",blue,-210,size="large")
message_to_screen("SPACE - SHOOT",white,-30)
message_to_screen("W-A-S-D - up, down, left, right movement",white,10)
button("Back", 550,500,100,50, red, light_red, action ="Back")
display.update()
clock.tick(15)
def game_over():
bg_sound.stop()
menu_1 = image.load('./image/gameover.jpg').convert()
gameDisplay.blit(menu_1,(0,0))
gameover = True
while gameover:
for evt in event.get():
if evt.type == QUIT:
quit()
button("QUIT", 550,500,100,50, red, light_red, action ="Quit")
button("MENU", 310,500,100,50, red, light_red, action ="Back")
display.update()
clock.tick(15)
def play():
display_width = 1000
display_height = 700
screen=display.set_mode((display_width,display_height))
running=True
y=0
while running:
for evt in event.get():
#print(event)
if evt.type == QUIT:
quit()
exit()
if evt.type == KEYDOWN:
if evt.key == K_e:
gameLoop()
rel_y = y % bg_3.get_rect().width
screen.blit(bg_3,(0,rel_y - bg_3.get_rect().width))
if rel_y < 600:
screen.blit(bg_3,(0,rel_y))
y +=1
message_to_screen("Attention, Fighter! ",blue,-300,size="medium")
message_to_screen("You have been summoned by our government to protect our planet Kiblar.",white,-210)
message_to_screen("We are being attacked by incoming enemies from the planet Noxus.",white,-170)
message_to_screen("You are our only defender left, protect us at all costs!",white,-130)
message_to_screen("Intelligence reports that there are 2 waves of enemies.",white,-90)
message_to_screen("After you eliminate them all, they will send their mothership Dengrau.",white,-50)
message_to_screen("Killing Dengrau will save our existence on galaxy 1029 from the rival planet Noxus.",white,-10)
message_to_screen("ARE YOU READY TO TAKE THIS CHALLENGE?!",white,130)
message_to_screen("CLICK [E] TO START!",red,190)
display.update()
myclock.tick(120)
quit()
##def enemy_generate():
##
## for i in range(5):
## asteroids.append((randint(50 ,800),randint(0,100)))
##
def drawScene(screen,sx,sy,bull,alienbull,alien,asteroids):
lee=image.load("image/laserRed16.png").convert_alpha()
bt=image.load("image/missile.png").convert_alpha()
spaceship=image.load("image/ship.png").convert_alpha()
screen.blit(spaceship,[sx,sy])
for b in bull:
screen.blit(bt,(b[0],b[1]))#drawing the bullets
for en in alien:
screen.blit(alienspaceship,(en[0],en[1]))
for a in asteroids:
screen.blit(astroid,(a[0] ,(a[1] + astroidY_change)))
for eb in alienbull:
screen.blit(lee,(eb[0],eb[1]))#drawing the bullets
display.update()
score_value=0
lives=3
def checkHits(bull,targ):
global score_value
for b in bull:# go through each bullet
## for a in astero:
## aliendistance = math.sqrt((math.pow(b[0]-a[0],2)) + (math.pow(b[1]-a[1],2)))
## if aliendistance < 50:
## asteroids.remove(a)
## bull.remove(b)
## explosion_sound.play()
## score_value+=1
## break
for t in targ: #go through each target
distance = math.sqrt((math.pow(b[0]-t[0],2)) + (math.pow(b[1]-t[1],2)))
if distance < 30:
targ.remove(t)#removes the target
bull.remove(b)#removes the bullet
explosion_sound.play()
score_value += 1
if score_value==10:
next_level()
break
livesr=3
def checkalienbullets(alienbull):
global livesr
global score_value
for a in alienbull:
alienbdistance=math.sqrt((math.pow(a[0]-shipx,2)) + (math.pow(a[1]-shipy,2)))
if alienbdistance<40:
livesr-=3
print(livesr)
if livesr<=0:
game_over()
def moveBullets(bull):
for b in bull:
b[0]+=b[2]
b[1]+=b[3]
if b[1]>700:#off-screen
bull.remove(b)
def move_alien_bull(ebull):
for e in ebull:
e[0]+=e[2]
e[1]+=e[3]
if e[1]>700:#off-screen
ebull.remove(e)
def next_level():
if random.randrange(0,6*40) == 1:
aliencounter+=1
x= randint(50,700)
y= randint(0,100)
alien.append([x,y])
alienbullets.append([x,y,w[0],w[1]])
myclock=time.Clock()
##y=0
##enemy_generate()
def gameLoop():
livesr=3
bg_sound.play(-1)
rapidbullet=20
y=0
score=0
ship_x =0
ship_y=0
global shipx
global shipy
global aliencounter
global astroidY
global astroidY_change
global enemy_y
global alien
## global livesr
direction= None
running=True
function=True
while running:
astroidY_change += .5
#enemy_y += 0
#global alienbullets
for evt in event.get():
if evt.type==QUIT:
running=False
quit()
if evt.type==KEYDOWN:
if evt.key == K_LEFT:
ship_x = -2.5
if evt.key == K_RIGHT:
ship_x = 2.5
## if evt.key == K_UP:
## ship_y = -2
## if evt.key == K_DOWN:
## ship_y = 2
if evt.type==KEYUP:
if evt.key == K_LEFT or evt.key == K_RIGHT:
ship_x = 0
## ship_y = 0
shipx += ship_x
## shipy += ship_y
if shipx <= 0:
shipx = 0
elif shipx >= 900:
shipx = 900
## if shipy <= 0:
## shipy = 0
## elif shipy >= 650:
## shipy = 650
# astroid Movement
astroidY += astroidY_change
if astroidY_change >=650:
astroidY_change =0
if rapidbullet<20:
rapidbullet+=1
keys=key.get_pressed()
if keys[32] and rapidbullet==20:#32 is the space key
bullet_sound.play()
bullets.append([shipx,shipy,v[0],v[1]])
rapidbullet=0
while function:
if random.randrange(0,6*40) == 1:
aliencounter+=1
x= randint(50,700)
y= randint(0,100)
alien.append([x,y])
alienbullets.append([x,y,w[0],w[1]])
if aliencounter==10:
function=False
rel_y = y % bg_3.get_rect().width
screen.blit(bg_3,(0,rel_y - bg_3.get_rect().width))
if rel_y < 700:
screen.blit(bg_3,(0,rel_y))
y +=1
if enemy_y >= 600:
enemy_y = 0
show_score(textx,texty)
show_lives(10,40)
moveBullets(bullets)
move_alien_bull(alienbullets)
checkHits(bullets,alien)
checkalienbullets(alienbullets)
drawScene(screen,shipx,shipy,bullets,alienbullets,alien,asteroids)
display.update()
myclock.tick(120)
quit()
game_intro()
You can call your introductory position setup for the spaceship when you start the game, like this:
import sys
from pygame import *
from math import *
from random import *
import random
import math
init()
display_width = 1000
display_height = 700
shipx = 350
shipy = 550
asteroids=[]
astroidX=randint(0,800)
astroidY=randint(50,500)
astroidY_change=0
alien=[]
aliencounter=0
enemy_y =0
enemy_x=0
alienbullets=[]
w=[0,5]
gameDisplay = display.set_mode((display_width,display_height))
screen=display.set_mode((1000,700))
white = (255,255,255)
black = (0,0,0)
red = (200,0,0)
light_red = (255,0,0)
yellow = (200,200,0)
light_yellow = (255,255,0)
green = (34,177,76)
light_green = (0,255,0)
blue = (0,0,255)
clock = time.Clock()
explosion_sound = mixer.Sound('./sounds/boom.wav')
bullet_sound = mixer.Sound('./sounds/shot1.wav')
bg_sound = mixer.Sound('./sounds/bgmusic1.ogg')
smallfont = font.SysFont("comicsansms", 25)
medfont = font.SysFont("comicsansms", 50)
largefont = font.SysFont("comicsansms", 85)
xlargefont = font.SysFont("Girassol", 100)
textx = 10
texty = 10
bg_imgs = ['./image/bg_big.png',
'./image/seamless_space.png',
'./image/space3.jpg']
bg_move_dis = 0
bg_1 = image.load(bg_imgs[0]).convert()
bg_2 = image.load(bg_imgs[1]).convert()
bg_3 = image.load(bg_imgs[2]).convert()
Score_1 = 200
Score_2 = 200
if (Score_1 + Score_2) < 500:
background = bg_1
elif (Score_1 + Score_2) < 1500:
background = bg_2
else:
background = bg_3
v=[0,-5]#horiz and vertical speed of the bullet
#print(ets)
bullets=[]#empty list for bullets
astroid=image.load("image/meteorBrown_med1.png").convert_alpha()
alienspaceship=image.load("image/ufo.png").convert_alpha()
def show_score(x,y):
score = smallfont.render("Score : " + str(score_value), True, light_yellow)
screen.blit(score,(x,y))
def show_lives(x,y):
lives = smallfont.render("Lives : " + str(livesr), True, light_yellow)
screen.blit(lives,(x,y))
def text_objects(text, color,size = "small"):
if size == "small":
textSurface = smallfont.render(text, True, color)
if size == "medium":
textSurface = medfont.render(text, True, color)
if size == "large":
textSurface = largefont.render(text, True, color)
if size == "xlarge":
textSurface = xlargefont.render(text, True, color)
return textSurface, textSurface.get_rect()
def text_to_button(msg, color, buttonx, buttony, buttonwidth, buttonheight, size = "small"):
textSurf, textRect = text_objects(msg,color,size)
textRect.center = ((buttonx+(buttonwidth/2)), buttony+(buttonheight/2))
gameDisplay.blit(textSurf, textRect)
def message_to_screen(msg,color, y_displace = 0, size = "small"):
textSurf, textRect = text_objects(msg,color,size)
textRect.center = (int(display_width / 2), int(display_height / 2)+y_displace)
gameDisplay.blit(textSurf, textRect)
def button(text, x, y, width, height, inactive_color, active_color, action = None):
cur = mouse.get_pos()
click = mouse.get_pressed()
#print(click)
if x + width > cur[0] > x and y + height > cur[1] > y:
draw.rect(gameDisplay, active_color, (x,y,width,height))
if click[0] == 1 and action != None:
if action == "Quit":
quit()
if action == "Play":
play()
if action == "Controls":
control_menu()
if action == "Back":
game_intro()
else:
draw.rect(gameDisplay, inactive_color, (x,y,width,height))
text_to_button(text,black,x,y,width,height)
def game_intro():
shipx = 350
shipy = 550
menu_1 = image.load('./image/menubackground.jpg')
gameDisplay.blit(menu_1,(0,0))
intro = True
while intro:
for evt in event.get():
#print(event)
if evt.type == QUIT:
quit()
if evt.type == KEYDOWN:
if evt.key == K_c:
intro = False
elif evt.key == K_q:
quit()
message_to_screen("Space Heroes!",green,-210,size="xlarge")
message_to_screen("The objective is to shoot and destroy",white,-30)
message_to_screen("the enemy ships before they destroy you.",white,10)
message_to_screen("Defeat all of them to advance to next level!.",white,50)
message_to_screen("By Wafi Hassan",blue, 110)
button("Play", 230,500,100,50, green, light_green, action="Play")
button("Controls", 430,500,100,50, yellow, light_yellow, action="Controls")
button("Quit", 630,500,100,50, red, light_red, action ="Quit")
display.update()
clock.tick(15)
def control_menu():
menu_1 = image.load('./image/menubackground.jpg')
gameDisplay.blit(menu_1,(0,0))
intro = True
while intro:
for evt in event.get():
#print(event)
if evt.type == QUIT:
quit()
if evt.type == KEYDOWN:
if evt.key == K_c:
intro = False
elif evt.key == K_q:
quit()
message_to_screen("Controls",blue,-210,size="large")
message_to_screen("SPACE - SHOOT",white,-30)
message_to_screen("W-A-S-D - up, down, left, right movement",white,10)
button("Back", 550,500,100,50, red, light_red, action ="Back")
display.update()
clock.tick(15)
def game_over():
bg_sound.stop()
menu_1 = image.load('./image/gameover.jpg').convert()
gameDisplay.blit(menu_1,(0,0))
gameover = True
while gameover:
for evt in event.get():
if evt.type == QUIT:
quit()
button("QUIT", 550,500,100,50, red, light_red, action ="Quit")
button("MENU", 310,500,100,50, red, light_red, action ="Back")
display.update()
clock.tick(15)
def play():
display_width = 1000
display_height = 700
screen=display.set_mode((display_width,display_height))
running=True
y=0
while running:
for evt in event.get():
#print(event)
if evt.type == QUIT:
quit()
exit()
if evt.type == KEYDOWN:
if evt.key == K_e:
gameLoop()
rel_y = y % bg_3.get_rect().width
screen.blit(bg_3,(0,rel_y - bg_3.get_rect().width))
if rel_y < 600:
screen.blit(bg_3,(0,rel_y))
y +=1
message_to_screen("Attention, Fighter! ",blue,-300,size="medium")
message_to_screen("You have been summoned by our government to protect our planet Kiblar.",white,-210)
message_to_screen("We are being attacked by incoming enemies from the planet Noxus.",white,-170)
message_to_screen("You are our only defender left, protect us at all costs!",white,-130)
message_to_screen("Intelligence reports that there are 2 waves of enemies.",white,-90)
message_to_screen("After you eliminate them all, they will send their mothership Dengrau.",white,-50)
message_to_screen("Killing Dengrau will save our existence on galaxy 1029 from the rival planet Noxus.",white,-10)
message_to_screen("ARE YOU READY TO TAKE THIS CHALLENGE?!",white,130)
message_to_screen("CLICK [E] TO START!",red,190)
display.update()
myclock.tick(120)
quit()
##def enemy_generate():
##
## for i in range(5):
## asteroids.append((randint(50 ,800),randint(0,100)))
##
def drawScene(screen,sx,sy,bull,alienbull,alien,asteroids):
lee=image.load("image/laserRed16.png").convert_alpha()
bt=image.load("image/missile.png").convert_alpha()
spaceship=image.load("image/ship.png").convert_alpha()
screen.blit(spaceship,[sx,sy])
for b in bull:
screen.blit(bt,(b[0],b[1]))#drawing the bullets
for en in alien:
screen.blit(alienspaceship,(en[0],en[1]))
for a in asteroids:
screen.blit(astroid,(a[0] ,(a[1] + astroidY_change)))
for eb in alienbull:
screen.blit(lee,(eb[0],eb[1]))#drawing the bullets
display.update()
score_value=0
lives=3
def checkHits(bull,targ):
global score_value
for b in bull:# go through each bullet
## for a in astero:
## aliendistance = math.sqrt((math.pow(b[0]-a[0],2)) + (math.pow(b[1]-a[1],2)))
## if aliendistance < 50:
## asteroids.remove(a)
## bull.remove(b)
## explosion_sound.play()
## score_value+=1
## break
for t in targ: #go through each target
distance = math.sqrt((math.pow(b[0]-t[0],2)) + (math.pow(b[1]-t[1],2)))
if distance < 30:
targ.remove(t)#removes the target
bull.remove(b)#removes the bullet
explosion_sound.play()
score_value += 1
if score_value==10:
next_level()
break
livesr=3
def checkalienbullets(alienbull):
global livesr
global score_value
for a in alienbull:
alienbdistance=math.sqrt((math.pow(a[0]-shipx,2)) + (math.pow(a[1]-shipy,2)))
if alienbdistance<40:
livesr-=3
print(livesr)
if livesr<=0:
game_over()
def moveBullets(bull):
for b in bull:
b[0]+=b[2]
b[1]+=b[3]
if b[1]>700:#off-screen
bull.remove(b)
def move_alien_bull(ebull):
for e in ebull:
e[0]+=e[2]
e[1]+=e[3]
if e[1]>700:#off-screen
ebull.remove(e)
def next_level():
if random.randrange(0,6*40) == 1:
aliencounter+=1
x= randint(50,700)
y= randint(0,100)
alien.append([x,y])
alienbullets.append([x,y,w[0],w[1]])
myclock=time.Clock()
##y=0
##enemy_generate()
def gameLoop():
livesr=3
bg_sound.play(-1)
rapidbullet=20
y=0
score=0
ship_x =0
ship_y=0
global shipx
global shipy
global aliencounter
global astroidY
global astroidY_change
global enemy_y
global alien
## global livesr
direction= None
running=True
function=True
while running:
astroidY_change += .5
#enemy_y += 0
#global alienbullets
for evt in event.get():
if evt.type==QUIT:
running=False
quit()
if evt.type==KEYDOWN:
if evt.key == K_LEFT:
ship_x = -2.5
if evt.key == K_RIGHT:
ship_x = 2.5
## if evt.key == K_UP:
## ship_y = -2
## if evt.key == K_DOWN:
## ship_y = 2
if evt.type==KEYUP:
if evt.key == K_LEFT or evt.key == K_RIGHT:
ship_x = 0
## ship_y = 0
shipx += ship_x
## shipy += ship_y
if shipx <= 0:
shipx = 0
elif shipx >= 900:
shipx = 900
## if shipy <= 0:
## shipy = 0
## elif shipy >= 650:
## shipy = 650
# astroid Movement
astroidY += astroidY_change
if astroidY_change >=650:
astroidY_change =0
if rapidbullet<20:
rapidbullet+=1
keys=key.get_pressed()
if keys[32] and rapidbullet==20:#32 is the space key
bullet_sound.play()
bullets.append([shipx,shipy,v[0],v[1]])
rapidbullet=0
while function:
if random.randrange(0,6*40) == 1:
aliencounter+=1
x= randint(50,700)
y= randint(0,100)
alien.append([x,y])
alienbullets.append([x,y,w[0],w[1]])
if aliencounter==10:
function=False
rel_y = y % bg_3.get_rect().width
screen.blit(bg_3,(0,rel_y - bg_3.get_rect().width))
if rel_y < 700:
screen.blit(bg_3,(0,rel_y))
y +=1
if enemy_y >= 600:
enemy_y = 0
show_score(textx,texty)
show_lives(10,40)
moveBullets(bullets)
move_alien_bull(alienbullets)
checkHits(bullets,alien)
checkalienbullets(alienbullets)
drawScene(screen,shipx,shipy,bullets,alienbullets,alien,asteroids)
display.update()
myclock.tick(120)
quit()
game_intro()
I just copied shipx = 350 and shipy = 550 from the start to game_intro(). Hope this helps!
Found where the problem lies.
livesr=3
def checkalienbullets(alienbull):
global livesr
global score_value
for a in alienbull:
alienbdistance=math.sqrt((math.pow(a[0]-shipx,2)) + (math.pow(a[1]-shipy,2)))
if alienbdistance<40:
livesr-=3
print(livesr)
if livesr<=0:
game_over()
The problem is in the alienbdistance value. I printed out these values while the program ran and got this:
alienbdistance 281.1440911703463
alienbdistance 81.04936767180853
alienbdistance 170.03823099526764
alienbdistance 205.36065835500236
alienbdistance 162.5207679036744
alienbdistance 46.17358552246078
alienbdistance 134.1044369139217
alienbdistance 272.7673000929547
alienbdistance 128.37834708392222
alienbdistance 39.96248240537617
0 <--this is livesr value
alienbdistance 35.805027579936315 <--first alienbdistance value after restarting the game
-3 <--this is livesr value
If the alienbdistance value is below 40, you execute these lines of code:
if alienbdistance<40:
livesr-=3
print(livesr)
if livesr<=0:
game_over()
So now that livesr=0 after the first game over, livesr will immediately be set to -3 since the first or one of the initial values for alienbdistance is below 40. After that statement, you execute the livesr<=0 statement, which will be executed since livesr = -3 at this point, initiating the gameover.
I would recommend fine tuning your alienbdistance value. Somehow between the first run and second run, alienbdistance is being calculated differently. I tried resetting
shipx = 350
shipy = 550
alienbullets=[]
after each game over, but that did not help.

Starting a game when countdown is over pygame

So I have this code that's my main game:
def game():
running = True
import pygame, sys
import random
import math as m
mainClock = pygame.time.Clock()
pygame.init()
pygame.font.init
pygame.display.set_caption('Ping Pong')
SCREEN = width, height = 900,600
white = (255, 255, 255)
green = (0, 255, 0)
blue = (0, 0, 128)
black = (0,0,0)
speed = [4,4]
font = pygame.font.Font('freesansbold.ttf', 32)
score = 0
score = str(score)
font.size(score)
font.set_bold(True)
text = font.render(score, True, white)
textRect = text.get_rect()
textRect.center = ((width/2 - width / 20), (height/60 + height/20))
screen = pygame.display.set_mode(SCREEN, 0,32)
height1 = height/4
score = int(score)
ball = pygame.Rect(width/2, height/2, 50,50)
player = pygame.Rect(0,(height/2),25,height1)
player_1 = pygame.Rect(width - 25,(height/2),25,height1)
font1 = pygame.font.Font('freesansbold.ttf', 32)
score1 = 0
score1 = str(score)
font1.size(score1)
font1.set_bold(True)
text1 = font1.render(score1, True, white)
score1 = int(score1)
textRect1 = text1.get_rect()
textRect1.center = ((width/2 + width / 15), (height/60 + height/20))
up = False
down = False
up_1 = False
down_1 = False
RED = (255,0,0)
particles = []
while running:
color = (192,192,192)
# clear display #
screen.fill((0,0,0))
screen.blit(text, textRect)
screen.blit(text1, textRect1)
bx = ball.centerx
by = ball.centery
particles.append([[bx, by],[random.randint(0,20) / 10 - 1, -1], random.randint(4,6)])
for particle in particles:
particle[0][0] += particle[1][0]
particle[0][1] += particle[1][1]
particle[2] -= 0.1
particle[1][1] += 0.1
pygame.draw.circle(screen, color, [int(particle[0][0]), int(particle[0][1])], int(particle[2]))
if particle[2] <= 0:
particles.remove(particle)
if up == True:
player.y -= 5
if down == True:
player.y += 5
if up_1 == True:
player_1.y -= 5
if down_1 == True:
player_1.y += 5
if player.top < 0 :
player.y = 0
if player.bottom > height:
player.bottom = height
if player_1.top < 0 :
player_1.y = 0
if player_1.bottom > height :
player_1.bottom = height
for i in range(-90,(height + 130), 120):
rectangle = pygame.Rect((width/2), i, 13, 60)
pygame.draw.rect(screen, (255,255,255), rectangle)
pygame.draw.rect(screen,(191, 224, 255),player)
pygame.draw.rect(screen,(191, 224, 255),player_1)
color = (192,192,192)
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
pygame.draw.rect(screen,color,ball, 3)
import time
ball.x += speed[0]
ball.y += speed[1]
if ball.top < 0 or ball.bottom > height:
speed[1] = -speed[1]
r = random.randint(0,255)
g = random.randint(0,255)
b = random.randint(0,255)
pygame.draw.rect(screen,(r,b,g),ball, 3)
pygame.draw.circle(screen, (r,b,g), [int(particle[0][0]), int(particle[0][1])], int(particle[2]))
dab = random.randint(0,1)
if ball.left < 0 :
font = pygame.font.Font('freesansbold.ttf', 32)
score1 = int(score1)
score1 += 1
score1 = str(score1)
font.set_bold(True)
text1 = font.render(score1, True, white)
textRect1 = text.get_rect()
textRect1.center = ((width/2 + width / 15), (height/60 + height/20))
screen.blit(text1, textRect1)
ball.x = width/2
ball.y = height/2
if dab == 1:
ball.x += -speed[0]
ball.y += -speed[1]
elif dab == 0:
ball.x += speed[0]
ball.y += speed[1]
if ball.right > width:
font = pygame.font.Font('freesansbold.ttf', 32)
score = int(score)
score += 1
score = str(score)
font.set_bold(True)
text = font.render(score, True, white)
textRect = text.get_rect()
textRect.center = ((width/2 - width / 20), (height/60 + height/20))
screen.blit(text, textRect)
ball.x = width/2
ball.y = height/2
if dab == 1:
ball.x += -speed[0]
ball.y += -speed[1]
elif dab == 0:
ball.x += speed[0]
ball.y += speed[1]
# event handling #
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_s:
down = True
if event.key == K_w:
up = True
if event.key == K_UP:
up_1 =True
if event.key == K_ESCAPE:
running = False
if event.key == K_DOWN:
down_1 = True
if event.type == KEYUP:
if event.key == K_s:
down = False
if event.key == K_w:
up = False
if event.key == K_UP:
up_1 = False
if event.key == K_DOWN:
down_1 = False
if ball.colliderect(player_1):
dab = random.randint(0,1)
if dab == 1:
speed[1] = -speed[1]
speed[0] = -speed[0]
r = random.randint(0,255)
g = random.randint(0,255)
b = random.randint(0,255)
pygame.draw.rect(screen,(r,b,g),ball, 3)
if ball.colliderect(player):
speed[0] = -speed[0]
speed[0] = random.randint(4,6)
r = random.randint(0,255)
g = random.randint(0,255)
b = random.randint(0,255)
pygame.draw.rect(screen,(r,b,g),ball, 3)
# update display #
pygame.display.update()
mainClock.tick(60)
and I have a menu screen that displays some options. Only button_1 works.:
def main_menu():
while True:
white = (255,255,255)
font = pygame.font.Font('freesansbold.ttf', 32)
font.set_bold(True)
screen.fill((0,0,0))
button_1 = pygame.Rect(width/2, (height/2), width/2, 50)
button_1.centerx = width/2
button_2 = pygame.Rect(width/2, height/1.5, width/2, 50)
button_2.centerx = width/2
pygame.draw.rect(screen, (255, 0, 0), button_1)
pygame.draw.rect(screen, (255, 0, 0), button_2)
#draw_text('Start!', font, (255, 255, 255), screen, button_1.centerx, button_1.centery)
font = pygame.font.Font('freesansbold.ttf', 32)
font.set_bold(True)
text1 = font.render('Start!', True, white)
textRect1 = text1.get_rect()
textRect1.center = (button_1.centerx, button_1.centery)
screen.blit(text1, textRect1)
mx, my = pygame.mouse.get_pos()
if button_1.collidepoint((mx, my)):
if click:
game()
if button_2.collidepoint((mx, my)):
if click:
options()
click = False
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
if event.type == MOUSEBUTTONDOWN:
if event.button == 1:
click = True
pygame.display.update()
clock.tick(60)
How do I make it so that after button_1 is pressed, there's a 3,2,1 countdown on the screen, and then the game starts?
In order to do the countdown, you import the time module:
import time
...then you need a for loop, with a step -1, counting down from 3 to 1. Inside the for loop, print the numbers and sleep one second, using the time module:
for a in range(3,0,-1):
print(a)
time.sleep(1)
After this for loop, you put the rest of your code.

Using an image as an object in pygame, but it wont appear in the game frame

The image im trying to use is the drakeImg, which is supposed to drop from the top of the game frame, the game is working fine but i cannot see the drakeImg dropping from the top of the screen, all i can see is the boatImg and the background, but the dodged count and crash() still work. Here is my code:
import pygame
import time
import random
pygame.init()
display_width = 800
display_height = 700
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
blue = (3,30,104)
boat_width = 110
drake_width = 110
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Gotta Go Fast')
clock = pygame.time.Clock()
drakeImg = pygame.image.load('drake.png')
drakeImg = pygame.transform.scale(drakeImg, (100, 100))
boatImg = pygame.image.load('boat.png')
boatImg = pygame.transform.scale(boatImg, (100, 150))
bg = pygame.image.load("bg.png")
def drakes_dodged(count):
font = pygame.font.SysFont(None, 25)
text = font.render("Drakes Dodged: " + str(count), True, green)
gameDisplay.blit(text,(0,0))
def drake(drakex, drakey):
gameDisplay.blit(drakeImg, (drakex, drakey))
def boat(x,y):
gameDisplay.blit(boatImg, (x,y))
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf',115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2),(display_height/3))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
game_loop()
def crash():
message_display('You Lost!')
def game_loop():
x = (display_width * 0.45)
y = (display_height * 0.75)
drake_startx = random.randrange(0, display_width)
drake_starty = -550
drake_speed = 4
drake_height = 100
drakesDodged = 0
gameExit = False
key_right = False
key_left = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
key_left = True
if event.key == pygame.K_RIGHT:
key_right = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
key_left = False
if event.key == pygame.K_RIGHT:
key_right = False
gameDisplay.blit(bg, (0, 0))
drake_starty += drake_speed
boat(x,y)
drakes_dodged(drakesDodged)
if key_left == True and x > 0:
x += -5
if key_right == True and x < (display_width - boat_width):
x += 5
if drake_starty > display_height:
drake_starty = 0 - drake_height
drake_startx = random.randrange(0,display_width)
drakesDodged += 1
if drakesDodged % 10 == 0:
drake_speed += 2
if y < drake_starty + drake_height:
if x + boat_width > drake_startx and x < drake_startx + drake_width:
crash()
pygame.display.update()
clock.tick(60)
game_loop()
pygame.quit()
quit()
You missed to call the drake method:
def game_loop():
# [...]
while not gameExit:
# [...]
drake(drake_startx, drake_starty) # <---
pygame.display.update()
clock.tick(60)

ValueError: list.remove(x): x not in list ~ Pygame (Python)

I am trying to write a rip off 'Brick Breaker' game in Pygame. But I am currently stuck and do not know what to do know.
(blah blah blah, explain scenario much more clearly, blah blah blah, clear, clear scenario)
(I need more random text so I can post all this code)
Here is all of the code, (yes all of it):
import pygame, sys, time, random
from pygame.locals import *
pygame.init()
fpsclock = pygame.time.Clock()
WINDOWWIDTH = 450
WINDOWHEIGHT = 650
mainwindow = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption('Luzion - Brick Breaker')
paddle = pygame.image.load('Brick Breaker - Paddle.png')
paddlerect = paddle.get_rect()
paddlerect.topleft = (190, 575)
ball = pygame.image.load ('ball.png')
ballrect = ball.get_rect()
ballrect.topleft = (195, 565)
cooltext = pygame.image.load('cooltext1.png')
cooltextrect = cooltext.get_rect()
cooltextrect.topleft = (0, 0)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 128, 0)
BLUE = (0, 0, 255)
LIME = (0, 255, 0)
TEXTCOLOR = WHITE
font = pygame.font.SysFont(None, 48)
def displaytext(text, font, surface, x, y):
text = font.render(text, 1, TEXTCOLOR)
textrect = text.get_rect()
textrect.topleft = (x, y)
surface.blit(text, textrect)
def waitforplayer():
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
return
moveleft = False
moveright = False
SPEED = 7
bmoveup = bmovedown = bmoveleft = bmoveright = False
BALLSPEED = 8
mainwindow.blit(cooltext, cooltextrect)
pygame.display.update()
time.sleep(1)
displaytext('Level 1', font, mainwindow, 150, 100)
pygame.display.update()
time.sleep(1)
displaytext('Press any key to begin...', font, mainwindow, 22, 200)
pygame.display.update()
waitforplayer()
while True:
rb = pygame.image.load('redblock.png')
rbrect = rb.get_rect()
rbrect.topleft = (0, 0)
rb1 = rb
rb1rect = rb1.get_rect()
rb1rect.topleft = (40, 0)
level1blocks = [rb, rb1]
level1rects = [rbrect, rb1rect]
number = random.randint(0, 1)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == ord('a') or event.key == K_LEFT:
moveleft = True
moveright = False
if event.key == ord('d') or event.key == K_RIGHT:
moveleft = False
moveright = True
if event.key == ord('g'):
bmoveup = True
if number == 1:
bmoveleft = True
else:
bmoveright = True
if event.type == KEYUP:
if event.key == ord('a') or event.key == K_LEFT:
moveleft = False
if event.key == ord('d') or event.key == K_RIGHT:
moveright = False
if moveleft and paddlerect.left > 0:
paddlerect.left -= SPEED
if moveright and paddlerect.right < WINDOWWIDTH:
paddlerect.right += SPEED
if bmovedown and ballrect.bottom < WINDOWHEIGHT:
ballrect.top += BALLSPEED
if bmoveup and ballrect.top > 0:
ballrect.top -= BALLSPEED
if bmoveleft and ballrect.left > 0:
ballrect.left -= BALLSPEED
if bmoveright and ballrect.right < WINDOWWIDTH:
ballrect.right += BALLSPEED
if ballrect.top <= 0:
bmovedown = not bmovedown
bmoveup = not bmoveup
if ballrect.left <= 0:
bmoveleft = not bmoveleft
bmoveright = not bmoveright
if ballrect.right >= WINDOWWIDTH:
bmoveleft = not bmoveleft
bmoveright = not bmoveright
if ballrect.bottom >= WINDOWHEIGHT:
bmovedown = not bmovedown
bmoveup = not bmoveup
mainwindow.fill(WHITE)
mainwindow.blit(paddle, paddlerect)
mainwindow.blit(ball, ballrect)
for x in range(len(level1blocks)):
mainwindow.blit(level1blocks[x], level1rects[x])
for x in level1rects:
if ballrect.colliderect(x):
level1rects.remove([x])
level1blocks.remove([x])
if ballrect.colliderect(paddlerect):
bmovedown = not bmovedown
bmoveup = not bmoveup
bmoveleft = not bmoveleft
bmoveright = not bmoveright
pygame.display.update()
fpsclock.tick(35)
And here is my error:
Traceback (most recent call last):
File "C:/Python32/Luzion - Brick Breaker", line 144, in <module>
level1rects.remove([x])
ValueError: list.remove(x): x not in list
Please help.
As you mention in the comments, both for loops are inside a larger while loop. That means that when the line
level1rects.remove(x)
happens, it will decrease the size of level1rects and cause level1rects[x] (when x is 1) to raise an exception.
The best way to fix this is to change your for loops to the following:
for b in level1blocks:
mainwindow.blit(b, b.get_rect())
for x in level1blocks[:]:
if ballrect.colliderect(x.get_rect()):
level1blocks.remove(x)
This obliviates the need for level1rects- it caused too many problems, because you were removing items from the list of rectangles without removing the corresponding block from the list of blocks. Changing the first loop to for b in level1blocks: allows the code to work even as blocks disappear.
Do a print or pprint on the level1blocks and level1rects lists, one of them doesn't have enough members for the range(2) iterator, which will try accessing the first (index 0) and second (index 1) members of each list.

Categories