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.
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.