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.
Related
I have recently gotten into pygame and I am having trouble. My life counter is not working in my program.
import pygame, time, random
pygame.init() # Initializes Pygame
display_width = 1280
display_height = 720
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Cube Game')
black = (0,0,0)
white = (255,255,255)
clock = pygame.time.Clock()
def life(lives):
font = pygame.font.SysFont(None, 25);
text = font.render("Lives: " + str(lives), True, white)
gameDisplay.blit(text,(1200,5))
def score(count):
font = pygame.font.SysFont(None, 25);
text = font.render("Score: " + str(count), True, white)
gameDisplay.blit(text,(5,5))
def enemyBall(ballx, bally, ballr, color):
pygame.draw.circle(gameDisplay, color, [ballx, bally], ballr)
# Creates Location for the Cube
def cube(x,y,side):
pygame.draw.rect(gameDisplay, white, [x, y, side, side])
def text_objects(text, font):
textSurface = font.render(text, True, white)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf', 50)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
__init__()
def dead():
gameDisplay.fill(black)
message_display('You have fallen out of the castle and died!')
# Game Loop
def __init__():
x = ((display_width/2) - 30)
y = (display_height - 70)
side = 60
x_change = 0
ballx_change = 25
bally_change = 25
ball_radius = 50
ball_startx = random.randrange(26, (display_width-ball_radius-1))
ball_starty = random.randrange((ball_radius+1), 100)
death = False
goodbye = False
myLives = 3
myScore = 0
# If Player has not Died
while not death:
for event in pygame.event.get():
if event.type == pygame.QUIT:
death = True
pygame.display.quit()
pygame.quit()
quit()
# Key is still Pressed
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -10
if event.key == pygame.K_RIGHT:
x_change = 10
# Key is no longer Pressed
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
x += x_change
gameDisplay.fill(black)
# Defines the enemy ball
enemyBall(ball_startx, ball_starty, ball_radius, white)
ball_startx += ballx_change
ball_starty += bally_change
# Wall Collision
if ball_startx - ball_radius <= 0 or ball_startx + ball_radius >= display_width:
ballx_change = -ballx_change
myScore += 1
if ball_starty - ball_radius <= 0 or ball_starty + ball_radius >= display_height:
bally_change = -bally_change
myScore += 1
# Determines Player Position
cube(x,y,side)
# Score and Life Counter
score(myScore)
life(myLives)
# Death by Abyss
if x > display_width or x < -50:
myLives -= 1
dead()
# Death by Ball
if ball_startx + ball_radius >= x and ball_startx - ball_radius <= x + side:
if ball_starty + ball_radius >= y and ball_starty - ball_radius <= y + side:
myLives -= 1
dead()
pygame.display.update()
clock.tick(60)
time.sleep(2)
__init__()
pygame.display.quit()
pygame.quit()
quit()
I have a statement that decreases the life counter by one when the player dies. However, the life counter seems to reset to 3 (the original amount). What do I have to change to fix the life counter? Thanks!
dead() calls message_display() which calls your init() again. On every init() call, you set myLives = 3 again.
When the player dies, you call dead().
dead() calls message_display().
message_display() calls __init__() again (even though it was already running).
The beginning of __init__() says myLives = 3.
If you don't want the variable reset to 3 when the player dies, don't keep calling __init__ again, because the start of that function always resets myLives to 3.
I am creating a basic game. I have mainly two codes for :(i) Menu (ii) Basic Game. I want to run 'while game_over' loop after clicking 'start' button. But the code does not respond after I click 'start' button.
import pygame
import random
import sys
pygame.init()
w=800
h=600
yellow=(255,255,0)
player_size=25
player_pos=[w/2,h-(2*player_size)]
enemy_size=25
enemy_pos=[random.randint(0,w-enemy_size),0]
enemy_list=[ ]
Menu_bg_color=(34,139,34)
red=(255,0,0)
blue=(0,0,125)
bright_blue=(0,0,255)
font_size=35
b1_pos=[w/2-50,h/2]
b1_size=[105,50]
bg_color=(0,0,0)
screen=pygame.display.set_mode((w,h))
speed=10
score=0
clock=pygame.time.Clock()
myFont=pygame.font.SysFont("monospace",font_size)
Menu_myFont=pygame.font.SysFont("freesansbold.tff",font_size)
running=True
Menu_running=True
#GAME CODE
def GameCode():
global game_over
global score
global speed
global player_pos
def set_level(score,speed):
if score<10:
speed=5
elif score<20:
speed=6
elif score<30:
speed=8
elif score<40:
speed=10
elif score<50:
speed=13
elif score<200:
speed=15
else:
speed=20
return speed
def drop_enemies(enemy_list):
delay=random.random()
if len(enemy_list)<6 and delay<0.1:
x_pos=random.randint(0,w-enemy_size)
y_pos=0
enemy_list.append([x_pos,y_pos])
def draw_enemies(enemy_list):
for enemy_pos in enemy_list:
pygame.draw.rect(screen,blue, (enemy_pos[0],enemy_pos[1],enemy_size,enemy_size))
def update_enemy_pos(enemy_list,score):
for idx,enemy_pos in enumerate(enemy_list):
if enemy_pos[1]>=0 and enemy_pos[1]<h:
enemy_pos[1]+=speed
else:
enemy_list.pop(idx)
score+=1
return score
def detect_collision(player_pos,enemy_pos):
p_x=player_pos[0]
p_y=player_pos[1]
e_x=enemy_pos[0]
e_y=enemy_pos[1]
if (e_x>=p_x and e_x<(p_x+player_size)) or (p_x>=e_x and p_x<(e_x+enemy_size)):
if (e_y>=p_y and e_y<(p_y+player_size)) or (p_y>=e_y and p_y<(e_y+enemy_size)):
return True
return False
def collision_check(enemy_list,player_pos):
for enemy_pos in enemy_list:
if detect_collision(enemy_pos,player_pos):
return True
return False
while game_over==False:
for event in pygame.event.get():
if event.type==pygame.QUIT:
sys.exit()
if event.type==pygame.KEYDOWN:
x=player_pos[0]
y=player_pos[1]
if event.key==pygame.K_LEFT:
x-=player_size
elif event.key==pygame.K_UP:
y-=player_size
elif event.key==pygame.K_RIGHT:
x+=player_size
elif event.key==pygame.K_DOWN:
y+=player_size
player_pos=[x,y]
screen.fill(bg_color)
#screen.blit(road,(0,0))
drop_enemies(enemy_list)
score=update_enemy_pos(enemy_list,score)
speed=set_level(score,speed)
text='Your Score is:' + str(score)
label=myFont.render(text,1,yellow)
screen.blit(label,(w/2,h-40))
if collision_check(enemy_list,player_pos):
game_over=True
break
draw_enemies(enemy_list)
pygame.draw.rect(screen,red,(player_pos[0],player_pos[1],player_size,player_size))
clock.tick(30)
pygame.display.update()
pygame.display.flip()
#MENU CODE
def MenuCode():
global game_over
def button(b1_pos,b1_size):
mouse_pos=pygame.mouse.get_pos()
click=pygame.mouse.get_pressed()
if (b1_pos[0]<mouse_pos[0]<(b1_pos[0]+b1_size[0])) and (b1_pos[1]<mouse_pos[1]<(b1_pos[1]+b1_size[1])):
pygame.draw.rect(screen,bright_blue,(b1_pos[0],b1_pos[1],b1_size[0],b1_size[1]))
if click[0]==1:
game_over=False
else:
pygame.draw.rect(screen,blue,(b1_pos[0],b1_pos[1],b1_size[0],b1_size[1]))
text='START'
label=Menu_myFont.render(text,1,red)
screen.blit(label,(w/2-38,h/2+5))
Menu_running=True
while Menu_running:
for event in pygame.event.get():
if event.type==pygame.QUIT:
sys.exit()
screen.fill(Menu_bg_color)
button(b1_pos,b1_size)
#button(b1_pos,b1_size,'quit')
pygame.display.update()
clock.tick(30)
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
break;
screen.fill(bg_color)
if MenuCode():
if game_over==False:
GameCode()
clock.tick(30)
pygame.display.update()
Here's a substantially revised version of your code that doesn't have the problem. I have revised the code so it closely adheres to the PEP 8 - Style Guide for Python Code guidelines and also eliminated many of the global variables you had by making them local to the function that uses them.
One of the primary cosmetic things I did was determine which of the globals were unchanging constants and which were variables whose values actually changed. After doing that, I changed the names of the constant ones to all UPPERCASE (as per PEP 8) and moved those with varying values to inside whichever function was actually using them.
The most extensive changes were made to the menu handling function — now named menu_code() — which was probably the main source of your problems. To help facilitate the rewrite, I've added a MenuButton class to encapsulate their behavior to a large degree and reduce repetitious code.
Note that there may be problems with the game_code() function because because I didn't attempted to optimize, test, or debug it.
Hopefully this will provide you with a good base upon which to further develop the game. I strongly suggest you read and start following PEP 8.
import random
import pygame as pyg
W, H = 800, 600
RED = (255, 0, 0)
BLUE = (0, 0, 125)
BRIGHT_BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
PLAYER_SIZE = 25
ENEMY_SIZE = 25
FONT_SIZE = 35
BG_COLOR = BLACK
FPS = 30
START, QUIT = 0, 1 # Button selection codes returned by menu_code()
pyg.init()
screen = pyg.display.set_mode((W, H))
pyg.display.set_caption('Basic Game')
clock = pyg.time.Clock()
game_font = pyg.font.SysFont("monospace", FONT_SIZE)
menu_font = pyg.font.SysFont("freesansbold.ttf", FONT_SIZE)
def game_code():
enemy_pos = [random.randint(0, W-ENEMY_SIZE), 0]
enemy_list = []
game_over = False
player_pos = [W/2, H - 2*PLAYER_SIZE]
score = 0
speed = 10
def get_speed(score):
if score < 10:
speed = 5
elif score < 20:
speed = 6
elif score < 30:
speed = 8
elif score < 40:
speed = 10
elif score < 50:
speed = 13
elif score < 200:
speed = 15
else:
speed = 20
return speed
def drop_enemies(enemy_list):
delay = random.random()
if len(enemy_list) < 6 and delay < 0.1:
x_pos = random.randint(0, W-ENEMY_SIZE)
y_pos = 0
enemy_list.append([x_pos, y_pos])
def draw_enemies(enemy_list):
for enemy_pos in enemy_list:
pyg.draw.rect(screen, BLUE,
(enemy_pos[0], enemy_pos[1], ENEMY_SIZE, ENEMY_SIZE))
def update_enemy_pos(enemy_list, score):
for idx, enemy_pos in enumerate(enemy_list):
if enemy_pos[1] >= 0 and enemy_pos[1] < H:
enemy_pos[1] += speed
else:
enemy_list.pop(idx)
score += 1
return score
def detect_collision(player_pos, enemy_pos):
p_x, p_y = player_pos
e_x, e_y = enemy_pos
if ((e_x >= p_x and e_x < (p_x + PLAYER_SIZE))
or (p_x >= e_x and p_x < (e_x + ENEMY_SIZE))):
if ((e_y >= p_y and e_y < (p_y+PLAYER_SIZE))
or (p_y >= e_y and p_y < (e_y + ENEMY_SIZE))):
return True
return False
def collision_check(enemy_list, player_pos):
for enemy_pos in enemy_list:
if detect_collision(enemy_pos, player_pos):
return True
return False
while not game_over:
for event in pyg.event.get():
if event.type == pyg.QUIT:
game_over = True
break
if event.type == pyg.KEYDOWN:
x = player_pos[0]
y = player_pos[1]
if event.key == pyg.K_LEFT:
x -= PLAYER_SIZE
elif event.key == pyg.K_UP:
y -= PLAYER_SIZE
elif event.key == pyg.K_RIGHT:
x += PLAYER_SIZE
elif event.key == pyg.K_DOWN:
y += PLAYER_SIZE
player_pos = [x, y]
screen.fill(BG_COLOR)
drop_enemies(enemy_list)
score = update_enemy_pos(enemy_list, score)
speed = get_speed(score)
text = 'Your Score is:' + str(score)
label = game_font.render(text, 1, YELLOW)
screen.blit(label, (W/2, H-40))
if collision_check(enemy_list, player_pos):
game_over = True
break
draw_enemies(enemy_list)
pyg.draw.rect(screen, RED,
(player_pos[0], player_pos[1], PLAYER_SIZE, PLAYER_SIZE))
clock.tick(FPS)
pyg.display.update()
# pyg.display.flip() # Don't do both update() and flip().
class MenuButton:
def __init__(self, text, value, rect):
self.text = text
self.value = value
self.rect = rect
def draw(self):
# Background color determined by whether mouse is positioned over label.
mouse_pos = pyg.mouse.get_pos()
fg_color = RED
bg_color = BRIGHT_BLUE if self.rect.collidepoint(mouse_pos) else BLUE
pyg.draw.rect(screen, bg_color, self.rect)
pyg.draw.rect(screen, YELLOW, self.rect, 1) # Draw a border.
label = menu_font.render(self.text, 1, fg_color)
# Center lable text inside its rectangle.
txw, txh = menu_font.size(self.text)
screen.blit(label, (self.rect.left + txw/2, self.rect.top + txh/2))
def menu_code():
MENU_BG_COLOR = (34, 139, 34)
LABEL_SIZE = LABEL_WIDTH, LABEL_HEIGHT = (105, 50)
B1_RECT = pyg.Rect((W/2 - LABEL_WIDTH/2, H/2 - LABEL_HEIGHT/2), LABEL_SIZE)
B2_RECT = pyg.Rect((W/2 - LABEL_WIDTH/2, H/2 + LABEL_HEIGHT/2), LABEL_SIZE)
MENU_BUTTONS = [MenuButton('Start', START, B1_RECT),
MenuButton('Quit', QUIT, B2_RECT)]
choice = None
while choice is None:
screen.fill(MENU_BG_COLOR)
for button in MENU_BUTTONS:
button.draw()
for event in pyg.event.get():
if event.type == pyg.QUIT:
choice = QUIT
# Handle left mouse button clicks.
if event.type == pyg.MOUSEBUTTONDOWN and event.button == 1:
for button in MENU_BUTTONS:
if button.rect.collidepoint(event.pos):
choice = button.value
break
pyg.display.update()
clock.tick(FPS)
return choice
# Main loop.
running = True
while running:
for event in pyg.event.get():
if event.type == pyg.QUIT:
running = False
break;
screen.fill(BG_COLOR)
choice = menu_code()
if choice == START:
game_code()
if choice == QUIT:
running = False
pyg.display.update()
clock.tick(FPS)
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)
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.
This is my code for a maths program I am making for high school. I am struggling at the moment because I can't figure out what I've done wrong, it says that sum1 isn't defined. If someone could please take their time to go through my code and sort it out I would be very grateful.
my error is on this line: (line 130)
message_to_screen("What is: " + str(sum1) + " + " + str(sum2),
black,
-100,
"medium")
Do let me know if I need to clarify anything.
Thanks!
# Below I am importing the modules that I will need
import pygame
import random
import time
from pygame.locals import *
# This initiates pygame
pygame.init()
# These are my defined colours
white = (255,255,255)
lightGrey = (200,200,200)
black = (0,0,0)
grey = (100,100,100)
red = (255,0,0)
yellow = (200,200,0)
green = (34,177,76)
# This sets the display width and height
display_width = 800
display_height = 600
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Major League Mathematics')
clock = pygame.time.Clock()
FPS = 30
easyvalues = list(range(10, 100 + 1))
mediumvalues = list(range(100, 1000 + 1))
hardvalues = list(range(1000, 10000 + 1))
# These are my set sizes for my message_to_screen definition
smallfont = pygame.font.SysFont("Arial", 30)
medfont = pygame.font.SysFont("Arial", 50)
largefont = pygame.font.SysFont("Arial", 100)
menufont = pygame.font.SysFont("Arial", 80)
# The next 3 definitions define how text is displayed
def text_objects(text,color,size):
# This is an 'if' statement
if size == "small":
textSurface = smallfont.render(text, True, color)
elif size == "medium":
textSurface = medfont.render(text, True, color)
elif size == "large":
textSurface = largefont.render(text, True, color)
elif size == "menu":
textSurface = menufont.render(text, True, color)
return textSurface, textSurface.get_rect()
def text_to_button(msg, color, buttonx, buttony, buttonwidth, buttonheight, size = "medium"):
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 = (display_width / 2), (display_height / 2) + y_displace
gameDisplay.blit(textSurf, textRect)
def button(text, color, x, y, width, height, inactive_color, active_color, value = None):
cur = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x + width > cur[0] > x and y + height > cur[1] > y:
pygame.draw.rect(gameDisplay, active_color, (x, y, width, height))
if click[0] == 1 and value != None:
if value == "easy":
easyvalues = list(range(10, 100 + 1))
sum1 = random.choice(easyvalues)
sum2 = random.choice(easyvalues)
gameLoop()
if value == "medium":
mediumvalues = list(range(100, 1000 + 1))
sum1 = random.choice(mediumvalues)
sum2 = random.choice(mediumvalues)
gameLoop()
if value == "hard":
hardvalues = list(range(1000, 10000 + 1))
sum1 = random.choice(hardvalues)
sum2 = random.choice(hardvalues)
gameLoop()
else:
easyvalues = list(range(10, 100 + 1))
sum1 = random.choice(easyvalues)
sum2 = random.choice(easyvalues)
gameLoop()
else:
pygame.draw.rect(gameDisplay, inactive_color, (x, y, width, height))
text_to_button(text, black, x, y, width, height)
def question():
if value == "easy":
sum1 = random.choice(easyvalues)
sum2 = random.choice(easyvalues)
if value == "medium":
sum1 = random.choice(mediumvalues)
sum2 = random.choice(mediumvalues)
if value == "hard":
sum1 = random.choice(hardvalues)
sum2 = random.choice(hardvalues)
else:
sum1 = random.choice(easyvalues)
sum2 = random.choice(easyvalues)
print sum1
print sum2
print sum1 + sum2
print value
#Here I am trying to enable raw input from the user
def answer():
answer = ""
font = pygame.font.SysFont("Arial", 50)
pygame.draw.rect(gameDisplay, white, [200,250,400,100])
message_to_screen("What is: " + str(sum1) + " + " + str(sum2),
black,
-100,
"medium")
input = True
while input:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.unicode.isdigit():
answer += event.unicode
if event.key == K_BACKSPACE:
answer = answer[:-1]
# This is temporary, while I program the rest
elif event.key == K_RETURN:
if answer == sum1 + sum2:
message_to_screen("Correct!", green, 0, "large")
else:
message_to_screen("Wrong!", red, 0, "large")
elif event.key == pygame.K_KP_ENTER:
if answer == sum1 + sum2:
message_to_screen("Correct!", green, 0, "large")
else:
message_to_screen("Wrong!", red, 0, "large")
elif event.key == K_ESCAPE:
pygame.quit()
quit()
elif event.type == pygame.QUIT:
pygame.quit()
quit()
block = font.render("Answer: " + answer, True, black)
rect = 210,280
gameDisplay.blit(block, rect)
pygame.display.flip()
## This is a reference so that I can get my code working
##def name():
## pygame.init()
## screen = pygame.display.set_mode((480, 360))
## name = ""
## font = pygame.font.Font(None, 50)
## while True:
## for evt in pygame.event.get():
## if evt.type == KEYDOWN:
## if evt.unicode.isalpha():
## name += evt.unicode
## elif evt.key == K_BACKSPACE:
## name = name[:-1]
## elif evt.key == K_RETURN:
## name = ""
## elif evt.type == QUIT:
## return
## screen.fill((0, 0, 0))
## block = font.render(name, True, (255, 255, 255))
## rect = block.get_rect()
## rect.center = screen.get_rect().center
## screen.blit(block, rect)
## pygame.display.flip()
##def input_box():
##
## pygame.draw.rect(gameDisplay, grey, [(display_width / 2) - 150,(display_height / 2) + 160,300,80])
##
##
## for event in pygame.get():
## if event.type == pygame.KEYDOWN:
# This definition defines a start screen so that my game doesnt play straight away
def startScreen():
menu = True
while menu:
# This allows me to quit the game without any problems
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
quit()
# This takes away the menu screen and starts the game once you've pressed 'Enter'
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
menu = False
gameDisplay.fill(grey)
message_to_screen("Major League Mathematics", black, -200, "menu")
#button building
button("Easy", black, 100, 220, 150, 100, lightGrey, white, value = "easy")
button("Medium", black, 325, 220, 150, 100, lightGrey, white, value = "medium")
button("Hard", black, 550, 220, 150, 100, lightGrey, white, value = "hard")
message_to_screen("Select a difficulty to start!", black, 250, "small")
pygame.display.update()
# This is my main loop that my game will run off
def gameLoop():
gameExit = False
gameOver = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
quit()
gameDisplay.fill(grey)
answer()
pygame.display.update()
clock.tick(FPS)
pygame.quit()
quit()
startScreen()
Inside you question() function, if value is not equal to "easy", "medium" or "hard", it'll bump into an undefined sum1 variable. As you didn't say exactly in which line the exception is raised, that would be my best bet.
EDIT:
OK, the reason I asked if you knew about some variable scope concepts is because I see you have some functions not being called and tries to access variables outside their scope. I strongly suggest you further readings about variable scoping, but as an immediate answer, the following changes in your code should work for you (can't test it from here):
- In your button function
if x + width > cur[0] > x and y + height > cur[1] > y:
pygame.draw.rect(gameDisplay, active_color, (x, y, width, height))
if click[0] == 1 and value != None:
if value == "easy":
easyvalues = list(range(10, 100 + 1))
sum1 = random.choice(easyvalues)
sum2 = random.choice(easyvalues)
gameLoop(sum1, sum2)
if value == "medium":
mediumvalues = list(range(100, 1000 + 1))
sum1 = random.choice(mediumvalues)
sum2 = random.choice(mediumvalues)
gameLoop(sum1, sum2)
if value == "hard":
hardvalues = list(range(1000, 10000 + 1))
sum1 = random.choice(hardvalues)
sum2 = random.choice(hardvalues)
gameLoop(sum1, sum2)
else:
easyvalues = list(range(10, 100 + 1))
sum1 = random.choice(easyvalues)
sum2 = random.choice(easyvalues)
gameLoop(sum1, sum2)
- In your gameLoop function
def gameLoop(sum1, sum2):
gameExit = False
gameOver = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
quit()
gameDisplay.fill(grey)
answer(sum1, sum2)
pygame.display.update()
clock.tick(FPS)
pygame.quit()
quit()
- In your answer function
def answer(sum1, sum2):