I have the game very close to fully working, however, when I run the program, the program complains with this error
\Dodger.py", line 180, in bullets.remove(b) ValueError: list.remove(x): x not in list
Here's the code:
import pygame, random, sys
from pygame.locals import *
TEXTCOLOR = (0, 0, 0)
FPS = 60
BADDIEMINSIZE = 8
BADDIEMAXSIZE = 70
BADDIEMINSPEED = 1
BADDIEMAXSPEED = 12
ADDNEWBADDIERATE = 1
PLAYERMOVERATE = 3
WINDOWWIDTH = 1280
WINDOWHEIGHT = 780
screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
background = pygame.image.load("background.png")
backgroundRect = background.get_rect
background_position = [0, 0]
bulletpicture = pygame.image.load("bullet.png")
bullets = []
def terminate():
pygame.quit()
sys.exit()
def waitForPlayerToPressKey():
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE: # pressing escape quits
terminate()
return
def playerHasHitBaddie(playerRect, baddies):
for b in baddies:
if playerRect.colliderect(b['rect']):
return True
return False
def drawText(text, font, surface, x, y):
textobj = font.render(text, 1, TEXTCOLOR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
# set up pygame, the window, and the mouse cursor
pygame.init()
mainClock = pygame.time.Clock()
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('Dodger')
pygame.mouse.set_visible(False)
# set up fonts
font = pygame.font.SysFont(None, 48)
# set up sounds
gameOverSound = pygame.mixer.Sound('gameover.wav')
click_sound = pygame.mixer.Sound("pistol.wav")
# set up images
playerImage = pygame.image.load('ship.png')
playerRect = playerImage.get_rect()
baddieImage = pygame.image.load('baddie.png')
background_image = pygame.image.load("background.png") .convert()
# Copy image to screen
screen.blit(background_image, background_position)
# Set positions of graphics
background_position = [0, 0]
# show the "Start" screen
drawText('Dodger', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press a key to start.', font, windowSurface, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
topScore = 0
while True:
# set up the start of the game
baddies = []
score = 0
playerRect.topleft = (WINDOWWIDTH / 2, WINDOWHEIGHT - 50)
moveLeft = moveRight = moveUp = moveDown = False
reverseCheat = slowCheat = False
baddieAddCounter = 0
while True: # the game loop runs while the game part is playing
score += 1 # increase score
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == ord('z'):
reverseCheat = True
if event.key == ord('x'):
slowCheat = True
if event.key == K_LEFT or event.key == ord('a'):
moveRight = False
moveLeft = True
if event.key == K_RIGHT or event.key == ord('d'):
moveLeft = False
moveRight = True
if event.key == K_UP or event.key == ord('w'):
moveDown = False
moveUp = True
if event.key == K_DOWN or event.key == ord('s'):
moveUp = False
moveDown = True
if event.type == KEYUP:
if event.key == ord('z'):
reverseCheat = False
score = 0
if event.key == ord('x'):
slowCheat = False
score = 0
if event.key == K_ESCAPE:
terminate()
if event.key == K_LEFT or event.key == ord('a'):
moveLeft = False
if event.key == K_RIGHT or event.key == ord('d'):
moveRight = False
if event.key == K_UP or event.key == ord('w'):
moveUp = False
if event.key == K_DOWN or event.key == ord('s'):
moveDown = False
if event.key == ord('p'):
click_sound.play()
bullets.append([event.key-32, 500])
if event.type == MOUSEMOTION:
# If the mouse moves, move the player where the cursor is.
playerRect.move_ip(event.pos[0] - playerRect.centerx, event.pos[1] - playerRect.centery)
# Add new baddies at the top of the screen, if needed.
if not reverseCheat and not slowCheat:
baddieAddCounter += 1
if baddieAddCounter == ADDNEWBADDIERATE:
baddieAddCounter = 0
baddieSize = random.randint(BADDIEMINSIZE, BADDIEMAXSIZE)
newBaddie = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-baddieSize), 0 - baddieSize, baddieSize, baddieSize),
'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED),
'surface':pygame.transform.scale(baddieImage, (baddieSize, baddieSize)),
}
baddies.append(newBaddie)
# Move the player around.
if moveLeft and playerRect.left > 0:
playerRect.move_ip(-1 * PLAYERMOVERATE, 0)
if moveRight and playerRect.right < WINDOWWIDTH:
playerRect.move_ip(PLAYERMOVERATE, 0)
if moveUp and playerRect.top > 0:
playerRect.move_ip(0, -1 * PLAYERMOVERATE)
if moveDown and playerRect.bottom < WINDOWHEIGHT:
playerRect.move_ip(0, PLAYERMOVERATE)
# Move the mouse cursor to match the player.
pygame.mouse.set_pos(playerRect.centerx, playerRect.centery)
for b in range(len(bullets)):
bullets.remove(b)
# Move the baddies down.
for b in baddies:
if not reverseCheat and not slowCheat:
b['rect'].move_ip(0, b['speed'])
elif reverseCheat:
b['rect'].move_ip(0, -5)
elif slowCheat:
b['rect'].move_ip(0, 1)
# Delete baddies that have fallen past the bottom.
for b in baddies[:]:
if b['rect'].top > WINDOWHEIGHT:
baddies.remove(b)
# Draw the game world on the window.
for bullet in bullets:
if bullet[0]<0:
bullets.remove(bullet)
screen.blit(background_image, background_position)
for bullet in bullets:
screen.blit(bulletpicture, pygame.Rect(bullet[0], bullet[1], 0, 0,))
# Draw the score and top score.
drawText('Score: %s' % (score), font, windowSurface, 10, 0)
drawText('Top Score: %s' % (topScore), font, windowSurface, 10, 40)
# Draw the player's rectangle
windowSurface.blit(playerImage, playerRect)
# Draw each baddie
for b in baddies:
windowSurface.blit(b['surface'], b['rect'])
pygame.display.update()
# Check if any of the baddies have hit the player.
if playerHasHitBaddie(playerRect, baddies):
if score > topScore:
topScore = score # set new top score
break
mainClock.tick(FPS)
# Stop the game and show the "Game Over" screen.
gameOverSound.play()
drawText('You lose', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press a key to play again.', font, windowSurface, (WINDOWWIDTH / 3) - 80, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
gameOverSound.stop()
Just change:
for b in range(len(bullets)):
bullets.remove(b)
To:
bullets = []
Related
This is a game for teens.
The main guy is displayed well, the time, sound and the background are showing too.
But the bad guys and the key to press to move the bad guy are not working.
# 1 - Importing library
import pygame
from pygame.locals import *
import math
import random
# 2 - Initializing the game
pygame.init()
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
keys = {True, False, False, False}
playerpos =[100,100]
acc = [0,0]
arrows = []
badtimer = 100
badtimer1 = 0
badguys = [[300,100]]
healthvalue = 194
pygame.mixer.init()
# 3 - Loading images
player = pygame.image.load("resources/images/dude.png")
grass = pygame.image.load("resources/images/grass.png")
castle = pygame.image.load("resources/images/castle.png")
arrow = pygame.image.load("resources/images/bullet.png")
badguyimg1 = pygame.image.load("resources/images/badguy.png")
badguyimg = badguyimg1
healthbar = pygame.image.load("resources/images/healthbar.png")
health = pygame.image.load("resources/images/health.png")
gameover = pygame.image.load("resources/images/gameover.png")
youwin = pygame.image.load("resources/images/youwin.png")
# 3.1 - Load audio
hit = pygame.mixer.Sound("resources/audio/explode.wav")
enemy = pygame.mixer.Sound("resources/audio/enemy.wav")
shoot = pygame.mixer.Sound("resources/audio/shoot.wav")
hit.set_volume(0.05)
enemy.set_volume(0.05)
shoot.set_volume(0.05)
pygame.mixer.music.load('resources/audio/moonlight.wav')
pygame.mixer.music.play(-1, 0.0)
pygame.mixer.music.set_volume(0.25)
# 4 - keep looping through
# 4 - keep looping through
running = 1
exitcode = 0
# 5 - clearing the screen before drawing it again
screen.fill(0)
while running:
badtimer -= 1
for x in range(int(width / grass.get_width() + 1)):
for y in range(int(height / grass.get_height() + 1)):
screen.blit(grass, (x * 100, y * 100))
screen.blit(castle, (0, 30))
screen.blit(castle, (0, 135))
screen.blit(castle, (0, 240))
screen.blit(castle, (0, 345))
# 6.1 - Seting player position and rotation
position = pygame.mouse.get_pos()
angle = math.atan2(position[1] - (playerpos[1] + 32), position[0] - (playerpos[0] + 26))
playerrot = pygame.transform.rotate(player, 360 - angle * 57.29)
playerpos1 = (playerpos[0] - playerrot.get_rect().width / 10, playerpos[1] - playerrot.get_rect().height / 2)
screen.blit(playerrot, playerpos1)
# 6.2 - Draw arrows
for bullet in arrows:
index = 0
velx = math.cos(bullet[0]) * 10
vely = math.sin(bullet[0]) * 10
bullet[1] += velx
bullet[2] += vely
if bullet[1] < -64 or bullet[1] > 640 or bullet[2] < -64 or bullet[2] > 480:
arrows.pop(index)
# 6.3.1 - Attack castle
for bullet in arrows:
bullrect = pygame.Rect(arrow.get_rect())
bullrect.left = bullet[1]
bullrect.top = bullet[2]
if badrect.colliderect(bullrect):
acc[0] += 1
badguys.pop(index)
arrows.pop(index1)
index1 += 1
badrect = pygame.Rect(badguyimg.get_rect())
badrect.top = badguy[1]
badrect.left = badguy[0]
if badrect.left < 64:
healthvalue -= random.randint(5, 20)
badguys.pop(index)
# section 6.3.1 after if badrect.left<64:
hit.play()
# section 6.3.2 after if badrect.colliderect(bullrect):
enemy.play()
# 6.3.2 - Check for collisions
index1 = 0
# section 8, after if event.type==pygame.MOUSEBUTTONDOWN:
shoot.play()
# 6.3.3 - Next bad guy
index += 1
for projectile in arrows:
arrow1 = pygame.transform.rotate(arrow, 360 - projectile[0] * 57.29)
screen.blit(arrow1, (projectile[1], projectile[2]))
# 6.3 - Draw badgers
if badtimer == 0:
badguys.append([640, random.randint(50, 430)])
badtimer = 100 - (badtimer1 * 2)
if badtimer1 >= 35:
badtimer1 = 35
else:
badtimer1 += 5
index = 0
for badguy in badguys:
if badguy[0] < -64:
badguys.pop(index)
badguy[0] -= 7
index += 1
for badguy in badguys:
screen.blit(badguyimg, badguy)
# 6.4 - Draw clock
font = pygame.font.Font(None, 24)
survivedtext = font.render(str((90000-pygame.time.get_ticks()))+":"+str((pygame.time.get_ticks())/1000%60).zfill(2), True, (0,0,0))
textRect = survivedtext.get_rect()
textRect.topright=[635,5]
screen.blit(survivedtext, textRect)
# 6.5 - Draw health bar
screen.blit(healthbar, (5,5))
for health1 in range(healthvalue):
screen.blit(health, (health1+8,8))
# 7 - updating the screen
pygame.display.flip()
# 8 - loop through the events
for event in pygame.event.get():
# check if the event is the X button
if event.type == pygame.QUIT:
# if it is quit the game
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == K_w:
keys[0] = True
elif event.key == K_a:
keys[1] = True
elif event.key == K_s:
keys[2] = True
elif event.key == K_d:
keys[3] = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_w:
keys[0] = False
elif event.key == pygame.K_a:
keys[1] = False
elif event.key == pygame.K_s:
keys[2] = False
elif event.key == pygame.K_d:
keys[3] = False
if event.type == pygame.MOUSEBUTTONDOWN:
position = pygame.mouse.get_pos()
acc[1] += 1
arrows.append(
[math.atan2(position[1] - (playerpos1[1] + 32), position[0] - (playerpos1[0] + 26)),
playerpos1[0] + 32, playerpos1[1] + 32])
# 9 - Move player
if keys[0]:
playerpos[1] -= 5
elif keys[2]:
playerpos[1] += 5
if keys[1]:
playerpos[0] -= 5
elif keys[3]:
playerpos[0] += 5
exit(0)
#10 - Win/Lose check
if pygame.time.get_ticks()>=90000:
running=0
exitcode=1
if healthvalue<=0:
running=0
exitcode=0
if acc[1]!=0:
accuracy=acc[0]*1.0/acc[1]*100
else:
accuracy=0
# 11 - Win/lose display
if exitcode==0:
pygame.font.init()
font = pygame.font.Font(None, 24)
text = font.render("Accuracy: "+str(accuracy)+"%", True, (255,0,0))
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery+24
screen.blit(gameover, (0,0))
screen.blit(text, textRect)
else:
pygame.font.init()
font = pygame.font.Font(None, 24)
text = font.render("Accuracy: "+str(accuracy)+"%", True, (0,255,0))
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx
textRect.centery = screen.get_rect().centery+24
screen.blit(youwin, (0,0))
screen.blit(text, textRect)
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit(0)
pygame.display.flip()
You have wrong indentations.
You check keys inside if event.type == pygame.QUIT: so they are checked only when you close window.
for event in pygame.event.get():
# check if the event is the X button
if event.type == pygame.QUIT:
# if it is quit the game
pygame.quit()
# the same indentation like for other event.type
if event.type == pygame.KEYDOWN:
if event.key == K_w:
keys[0] = True
elif event.key == K_a:
keys[1] = True
elif event.key == K_s:
keys[2] = True
elif event.key == K_d:
keys[3] = True
# the same indentation like for other event.type
if event.type == pygame.KEYUP:
if event.key == pygame.K_w:
keys[0] = False
elif event.key == pygame.K_a:
keys[1] = False
elif event.key == pygame.K_s:
keys[2] = False
elif event.key == pygame.K_d:
keys[3] = False
# the same indentation like for other event.type
if event.type == pygame.MOUSEBUTTONDOWN:
position = pygame.mouse.get_pos()
acc[1] += 1
arrows.append(
[math.atan2(position[1] - (playerpos1[1] + 32), position[0] - (playerpos1[0] + 26)),
playerpos1[0] + 32, playerpos1[1] + 32])
# it should be outside `for event` loop
# 9 - Move player
if keys[0]:
playerpos[1] -= 5
elif keys[2]:
playerpos[1] += 5
if keys[1]:
playerpos[0] -= 5
elif keys[3]:
playerpos[0] += 5
Similar problem is with drawing badguy.
BTW: instead of all thess settings and checkings of keys you could use pygame.key.get_pressed
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
playerpos[1] -= 5
elif keys[pygame.K_a]:
playerpos[1] += 5
if keys[pygame.K_s]:
playerpos[0] -= 5
elif keys[pygame.K_d]:
playerpos[0] += 5
I have to complete this project for tomorrow so if anyone could please help me, I would appreciate it. When I take out the code for making the game harder (see comment in the code) the game over works. But when I add that part, even when you hit the obstacle the game keeps running. Please let me know how I can fix this problem. Thank you.
import pygame, random, sys
from pygame.locals import *
pygame.font.init
WINDOWWIDTH = 600
WINDOWHEIGHT = 600
TEXTCOLOR = (255, 255, 255)
BACKGROUNDCOLOR = (0, 0, 0)
FPS = 40
BADDIEMINSIZE = 100
BADDIEMAXSIZE = 100
BADDIEMINSPEED = 8
BADDIEMAXSPEED = 8
ADDNEWBADDIERATE = 60
PLAYERMOVERATE = 10
def terminate():
pygame.quit()
sys.exit()
def waitForPlayerToPressKey():
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE: # pressing escape quits
terminate()
return
def playerHasHitBaddie(playerRect, baddies):
for b in baddies:
if playerRect.colliderect(b['rect']):
return True
return False
def drawText(text, font, surface, x, y):
textobj = font.render(text, 1, TEXTCOLOR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
# set up pygame, the window, and the mouse cursor
pygame.init()
mainClock = pygame.time.Clock()
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('Dodger')
pygame.mouse.set_visible(False)
# set up fonts
font = pygame.font.SysFont(None, 48)
# set up sounds
gameOverSound = pygame.mixer.Sound('crash.wav')
pygame.mixer.music.load('background.wav')
# set up images
screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
bg = pygame.image.load('mud.jpg')
playerImage = pygame.image.load('Picture1.png')
playerRect = playerImage.get_rect()
baddieImage = pygame.image.load('Picture2.png')
# show the "Start" screen
drawText('Dodger', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press a key to start.', font, windowSurface, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
topScore = 0
while True:
# set up the start of the game
baddies = []
score = 0
level = 1
playerRect.topleft = (WINDOWWIDTH / 2, WINDOWHEIGHT - 50)
moveLeft = moveRight = moveUp = moveDown = False
reverseCheat = slowCheat = False
baddieAddCounter = 0
pygame.mixer.music.play(-1, 0.0)
while True: # the game loop runs while the game part is playing
score += 1 # increase score
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == ord('z'):
reverseCheat = True
if event.key == ord('x'):
slowCheat = True
if event.key == K_LEFT or event.key == ord('a'):
moveRight = False
moveLeft = True
if event.key == K_RIGHT or event.key == ord('d'):
moveLeft = False
moveRight = True
if event.key == K_UP or event.key == ord('w'):
moveDown = False
moveUp = True
if event.key == K_DOWN or event.key == ord('s'):
moveUp = False
moveDown = True
if event.type == KEYUP:
if event.key == ord('z'):
reverseCheat = False
score = 0
if event.key == ord('x'):
slowCheat = False
score = 0
if event.key == K_ESCAPE:
terminate()
if event.key == K_LEFT or event.key == ord('a'):
moveLeft = False
if event.key == K_RIGHT or event.key == ord('d'):
moveRight = False
if event.key == K_UP or event.key == ord('w'):
moveUp = False
if event.key == K_DOWN or event.key == ord('s'):
moveDown = False
if event.type == MOUSEMOTION:
# If the mouse moves, move the player where the cursor is.
playerRect.move_ip(event.pos[0] - playerRect.centerx, event.pos[1] - playerRect.centery)
# Add new baddies at the top of the screen, if needed.
if not reverseCheat and not slowCheat:
baddieAddCounter += 1
if baddieAddCounter == ADDNEWBADDIERATE:
baddieAddCounter = 0
baddieSize = random.randint(BADDIEMINSIZE, BADDIEMAXSIZE)
newBaddie = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-baddieSize), 0 - baddieSize, baddieSize, baddieSize),
'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED),
'surface':pygame.transform.scale(baddieImage, (baddieSize, baddieSize)),
}
baddies.append(newBaddie)
# Move the player around.
if moveLeft and playerRect.left > 0:
playerRect.move_ip(-1 * PLAYERMOVERATE, 0)
if moveRight and playerRect.right < WINDOWWIDTH:
playerRect.move_ip(PLAYERMOVERATE, 0)
if moveUp and playerRect.top > 0:
playerRect.move_ip(0, -1 * PLAYERMOVERATE)
if moveDown and playerRect.bottom < WINDOWHEIGHT:
playerRect.move_ip(0, PLAYERMOVERATE)
# Move the mouse cursor to match the player.
pygame.mouse.set_pos(playerRect.centerx, playerRect.centery)
# Move the baddies down.
for b in baddies:
if not reverseCheat and not slowCheat:
b['rect'].move_ip(0, b['speed'])
elif reverseCheat:
b['rect'].move_ip(0, -5)
elif slowCheat:
b['rect'].move_ip(0, 1)
# Delete baddies that have fallen past the bottom.
for b in baddies[:]:
if b['rect'].top > WINDOWHEIGHT:
baddies.remove(b)
# Draw the game world on the window.
screen.blit(bg, (0,0))
# Draw the score and top score.
drawText('Score: %s' % (score), font, windowSurface, 10, 0)
drawText('Top Score: %s' % (topScore), font, windowSurface, 10, 40)
drawText('Level: %s' % (level), font, windowSurface, 10, 80)
# Draw the player's rectangle
windowSurface.blit(playerImage, playerRect)
# Draw each baddie
for b in baddies:
windowSurface.blit(b['surface'], b['rect'])
pygame.display.update()
#Make game harder if player is doing well
if score>=500 and score<1000:
BADDIEMINSPEED = 10
BADDIEMAXSPEED = 10
drawText('LEVEL 2', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
pygame.display.update()
elif score>=1000 and score <1500:
BADDIEMINSPEED = 20
BADDIEMAXSPEED = 20
drawText('LEVEL 3', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
pygame.display.update()
elif score>=1500 and score<2000:
BADDIEMINSPEED = 30
BADDIEMAXSPEED = 30
drawText('LEVEL 4', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
pygame.display.update()
elif score>=2000 and score<3000:
BADDIEMINSPEED = 40
BADDIEMAXSPEED = 40
drawText('LEVEL 5', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
pygame.display.update()
elif score>=3000:
BADDIEMINSPEED = 50
BADDIEMAXSPEED = 50
drawText('LEVEL 6', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
pygame.display.update()
mainClock.tick(int(FPS))
# Check if any of the baddies have hit the player.
if playerHasHitBaddie(playerRect, baddies):
if score > topScore:
topScore = score # set new top score
# Stop the game and show the "Game Over" screen.
pygame.mixer.music.stop()
gameOverSound.play()
drawText('You have Crashed!', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press any key to play again', font, windowSurface, (WINDOWWIDTH / 3) - 80, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
gameOverSound.stop()
if playerHasHitBaddie(playerRect, baddies):
if score > topScore:
topScore = score # set new top score
# Stop the game and show the "Game Over" screen.
pygame.mixer.music.stop()
gameOverSound.play()
drawText('You have Crashed!', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press any key to play again', font, windowSurface, (WINDOWWIDTH / 3) - 80, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
gameOverSound.stop()
For the above, you can call terminate() at the very end of the if statement to force the game to quit and stop... permanently.
This question already has an answer here:
why won't this game start, it's looping [closed]
(1 answer)
Closed 8 years ago.
my background wont refresh and it keeps on saying game over.
i am trying to get one sprite on one side to move up and down and fire periodically and have a player sprite only be able move up and down and trys to fire a 'shoot' sprite at the enemy sprite
import pygame, random, sys
from pygame.locals import *
WINDOWWIDTH = 600
WINDOWHEIGHT = 600
TEXTCOLOR = (255, 255, 255)
BGC = (0, 0, 0)
FPS = 80
PLAYERMOVERATE = 5
countBy = 10
def terminate():
pygame.quit()
sys.exit()
def waitForPlayerToPressKey():
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
terminate()
return
def playerHasHitShoot(playerRect, shoot):
if playerRect.colliderect(shoot):
return True
return False
def baddieHasHitShoot(baddieRect, shoot):
if baddieRect.colliderect(shoot):
return True
return False
def drawText(text, font, surface, x, y):
textobj = font.render(text, 1, TEXTCOLOR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
pygame.init()
pygame.font.init()
font = pygame.font.SysFont(None,48)
mainClock = pygame.time.Clock()
screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('Mothers Day')
pygame.mouse.set_visible(True)
pygame.display.set_icon(pygame.image.load('gameicon.gif'))
gameStartSound = pygame.mixer.Sound('gamestart.wav')
gameOverSound = pygame.mixer.Sound('gameend.wav')
pygame.mixer.music.load('background.wav')
playerImage = pygame.image.load('starship.bmp')
playerRect = playerImage.get_rect()
baddieImage = pygame.image.load('enemy.bmp')
baddieRect = baddieImage.get_rect()
shootImage = pygame.image.load('shoot.bmp')
shootRect = shootImage.get_rect()
drawText('Star Trek', font, screen, (WINDOWWIDTH / 2.5), (WINDOWHEIGHT / 3))
drawText('Press a key to start.', font, screen, (WINDOWWIDTH / 3.75) - 30, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
def fire(shoot):
shootRect.topleft = ((playerRect / 2), 101)
shootRect.move_ip(5, 1)
topScore = 10000
while True:
SS = []
score = 10000
playerRect.topleft = (0, 100)
moveUp = moveDown = False
pygame.mixer.music.play(-1, 0.0)
while True:
score -= countBy
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_UP:
moveDown = False
moveUp = True
if event.key == ord(' '):
fire
if event.key == K_DOWN:
moveUp = False
moveDown = True
if event.type == KEYUP:
if event.key == ord(' '):
fire
if event.key == K_ESCAPE:
terminate()
if event.key == K_LEFT or event.key == ord('a'):
moveLeft = False
if event.key == K_RIGHT or event.key == ord('d'):
moveRight = False
if event.key == K_UP or event.key == ord('w'):
moveUp = False
if event.key == K_DOWN or event.key == ord('s'):
moveDown = False
if moveUp and playerRect.top > 0:
playerRect.move_ip(0, -1 * PLAYERMOVERATE)
if moveDown and playerRect.bottom < WINDOWHEIGHT:
playerRect.move_ip(0, PLAYERMOVERATE)
drawText('Score: %s' % (score), font, screen, 10, 0)
drawText('Top Score: %s' % (topScore), font, screen, 10, 40)
screen.blit(playerImage, playerRect)
screen.blit(shootImage, shootRect)
screen.blit(baddieImage, baddieRect)
pygame.display.update()
if playerHasHitShoot(playerRect, baddieRect):
score = 0
break
if baddieHasHitShoot(baddieRect, shoot):
if score > topScore:
score = topscore
break
mainClock.tick(FPS)
pygame.mixer.music.stop()
gameOverSound.play()
drawText('GAME OVER', font, screen, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press a key to play again.', font, screen, (WINDOWWIDTH / 3) - 80, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
gameOverSound.stop()
the answer to why my screen won't refresh is i didn't call the screen.blit function
in my python program a c++ error pops up. i know that my program is glitchy and has bugs but why is there a error with c++
Assertion failed!
Program: C:\Python33\pythonw.exe
File: .-\--\audio\mpegtoraw.cpp
Line: 505
Expression: audio->rawdatawriteoffset > len
For information on how your program can cause an assertion
failure, see the Visual C++ documentation on asserts
(Press Retry to debug the application - JIT must be enabled)
import pygame, random, sys
from pygame.locals import *
WINDOWWIDTH = 600
WINDOWHEIGHT = 600
TEXTCOLOR = (255, 255, 255)
BGC = (0, 0, 0)
FPS = 80
PLAYERMOVERATE = 5
countBy = 10
def terminate():
pygame.quit()
sys.exit()
def waitForPlayerToPressKey():
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
terminate()
return
def playerHasHitShoot(playerRect, shoot):
if playerRect.colliderect(shoot):
return True
return False
def baddieHasHitShoot(baddieRect, shoot):
if baddieRect.colliderect(shoot):
return True
return False
def drawText(text, font, surface, x, y):
textobj = font.render(text, 1, TEXTCOLOR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
pygame.init()
pygame.font.init()
font = pygame.font.SysFont(None,48)
mainClock = pygame.time.Clock()
screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('Mothers Day')
pygame.mouse.set_visible(True)
pygame.display.set_icon(pygame.image.load('gameicon.gif'))
gameStartSound = pygame.mixer.Sound('gamestart.wav')
gameOverSound = pygame.mixer.Sound('gameend.wav')
pygame.mixer.music.load('background.mp3')
playerImage = pygame.image.load('starship.bmp')
playerRect = playerImage.get_rect()
baddieImage = pygame.image.load('enemy.bmp')
baddieRect = baddieImage.get_rect()
shootImage = pygame.image.load('shoot.bmp')
shootRect = shootImage.get_rect()
drawText('Star Trek', font, screen, (WINDOWWIDTH / 2.5), (WINDOWHEIGHT / 3))
drawText('Press a key to start.', font, screen, (WINDOWWIDTH / 3.75) - 30, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
def fire(shoot):
shootRect.topleft = ((playerRect / 2), 101)
shootRect.move_ip(5, 1)
topScore = 10000
while True:
SS = []
score = 10000
playerRect.topleft = (0, 100)
moveUp = moveDown = False
pygame.mixer.music.play(-1, 0.0)
while True:
score -= countBy
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_UP:
moveDown = False
moveUp = True
if event.key == ord(' '):
fire
if event.key == K_DOWN:
moveUp = False
moveDown = True
if event.type == KEYUP:
if event.key == ord(' '):
fire
if event.key == K_ESCAPE:
terminate()
if event.key == K_LEFT or event.key == ord('a'):
moveLeft = False
if event.key == K_RIGHT or event.key == ord('d'):
moveRight = False
if event.key == K_UP or event.key == ord('w'):
moveUp = False
if event.key == K_DOWN or event.key == ord('s'):
moveDown = False
if moveUp and playerRect.top > 0:
playerRect.move_ip(0, -1 * PLAYERMOVERATE)
if moveDown and playerRect.bottom < WINDOWHEIGHT:
playerRect.move_ip(0, PLAYERMOVERATE)
drawText('Score: %s' % (score), font, screen, 10, 0)
drawText('Top Score: %s' % (topScore), font, screen, 10, 40)
screen.blit(playerImage, playerRect)
screen.blit(shootImage, shootRect)
screen.blit(baddieImage, baddieRect)
pygame.display.update()
if playerHasHitShoot(playerRect, baddieRect):
score = 0
break
if baddieHasHitShoot(baddieRect, shoot):
if score > topScore:
score = topscore
break
mainClock.tick(FPS)
pygame.mixer.music.stop()
gameOverSound.play()
drawText('GAME OVER', font, screen, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press a key to play again.', font, screen, (WINDOWWIDTH / 3) - 80, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
gameOverSound.stop()
This appears to be a bug in the Python music player, it has trouble converting some MP3 files. The only solution appears to be to try a different file.
I made a script in python 2.6. When I tried running it on the computer(Windows Vista Home Basic) it worked perfectly fine but when I tried making it in an .exe the problems started. The problems were that when I clicked on the executable on other computers(windows 7 and I think the new version of windows vista) it came up with an error box and disappears really quickly. It disappears so quickly that I can't read all of the error messages. But I saw part of the message saying that there was an error on line 70 and line 54 and that there is an 'importError: DLL load failed; The specified module could not be found'. For some reason it looks perfectly fine to me. In case I made the script into an executable with py2exe(latest one). The lines are highlighted in the script below.
import pygame, random, sys
from pygame.locals import *
WINDOWWIDTH = 600
WINDOWHEIGHT = 600
RED = (255, 0, 0)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
TEXTCOLOR = WHITE
BACKGROUNDCOLOR = BLACK
FPS = 40
ASTEROIDMINSIZE = 10
ASTEROIDMAXSIZE = 40
ASTEROIDMINSPEED = 1
ASTEROIDMAXSPEED = 8
ADDNEWASTEROIDRATE = 6
PLAYERMOVERATE = 5
MAXHEALTH = 3
def terminate():
pygame.quit()
sys.exit()
def waitForPlayerToPressKey():
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE: # pressing escape quits
terminate()
return
def playerHasHitBaddie(playerRect, asteroids):
for a in asteroids:
if playerRect.colliderect(a['rect']):
return True
return False
def drawText(text, font, surface, x, y):
textobj = font.render(text, 1, TEXTCOLOR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
# set up pygame, the window, and the mouse cursor
pygame.init()
mainClock = pygame.time.Clock()
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('Dodger')
pygame.mouse.set_visible(False)
# set up fonts
(LINE 54)font = pygame.font.SysFont(None, 48)
# set up sounds
gameOverSound = pygame.mixer.Sound('gameover.wav')
pygame.mixer.music.load('background.mid')
# set up images
playerImage = pygame.image.load('player.png')
playerRect = playerImage.get_rect()
baddieImage = pygame.image.load('asteroid.png')
tokenImage = pygame.image.load('tokens.png')
# show the "Start" screen
drawText('Asteroid Shower', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press a key to start.', font, windowSurface, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 3) + 50)
drawText('By Sandy Goetjens', font, windowSurface, (WINDOWWIDTH / 3) - 100, (WINDOWHEIGHT / 3) + 100)
(LINE 70)pygame.display.update()
waitForPlayerToPressKey()
topScore = 0
while True:
# set up the start of the game
asteroids = []
score = 0
playerRect.topleft = (WINDOWWIDTH / 2, WINDOWHEIGHT - 50)
moveLeft = moveRight = moveUp = moveDown = False
reverseCheat = slowCheat = False
asteroidAddCounter = 0
pygame.mixer.music.play(-1, 0.0)
while True: # the game loop runs while the game part is playing
score += 1 # increase score
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == ord('z'):
reverseCheat = True
if event.key == ord('x'):
slowCheat = True
if event.key == K_LEFT or event.key == ord('a'):
moveRight = False
moveLeft = True
if event.key == K_RIGHT or event.key == ord('d'):
moveLeft = False
moveRight = True
if event.key == K_UP or event.key == ord('w'):
moveDown = False
moveUp = True
if event.key == K_DOWN or event.key == ord('s'):
moveUp = False
moveDown = True
if event.type == KEYUP:
if event.key == ord('z'):
reverseCheat = False
score = 0
if event.key == ord('x'):
slowCheat = False
score = 0
if event.key == K_ESCAPE:
terminate()
if event.key == K_LEFT or event.key == ord('a'):
moveLeft = False
if event.key == K_RIGHT or event.key == ord('d'):
moveRight = False
if event.key == K_UP or event.key == ord('w'):
moveUp = False
if event.key == K_DOWN or event.key == ord('s'):
moveDown = False
if event.type == MOUSEMOTION:
# If the mouse moves, move the player where the cursor is.
playerRect.move_ip(event.pos[0] - playerRect.centerx, event.pos[1] - playerRect.centery)
# Add new baddies at the top of the screen, if needed.
if not reverseCheat and not slowCheat:
asteroidAddCounter += 1
if asteroidAddCounter == ADDNEWASTEROIDRATE:
asteroidAddCounter = 0
asteroidSize = random.randint(ASTEROIDMINSIZE, ASTEROIDMAXSIZE)
newAsteroid = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-asteroidSize), 0 - asteroidSize, asteroidSize, asteroidSize),
'speed': random.randint(ASTEROIDMINSPEED, ASTEROIDMAXSPEED),
'surface':pygame.transform.scale(baddieImage, (asteroidSize, asteroidSize)),
}
asteroids.append(newAsteroid)
# Move the player around.
if moveLeft and playerRect.left > 0:
playerRect.move_ip(-1 * PLAYERMOVERATE, 0)
if moveRight and playerRect.right < WINDOWWIDTH:
playerRect.move_ip(PLAYERMOVERATE, 0)
if moveUp and playerRect.top > 0:
playerRect.move_ip(0, -1 * PLAYERMOVERATE)
if moveDown and playerRect.bottom < WINDOWHEIGHT:
playerRect.move_ip(0, PLAYERMOVERATE)
# Move the mouse cursor to match the player.
pygame.mouse.set_pos(playerRect.centerx, playerRect.centery)
# Move the baddies down.
for a in asteroids:
if not reverseCheat and not slowCheat:
a['rect'].move_ip(0, a['speed'])
elif reverseCheat:
a['rect'].move_ip(0, -5)
elif slowCheat:
a['rect'].move_ip(0, 1)
# Delete baddies that have fallen past the bottom.
for a in asteroids[:]:
if a['rect'].top > WINDOWHEIGHT:
asteroids.remove(a)
# Draw the game world on the window.
windowSurface.fill(BACKGROUNDCOLOR)
# Draw the score and top score.
drawText('Score: %s' % (score), font, windowSurface, 10, 0)
drawText('Top Score: %s' % (topScore), font, windowSurface, 10, 40)
# Draw the player's rectangle
windowSurface.blit(playerImage, playerRect)
# Draw each baddie
for a in asteroids:
windowSurface.blit(a['surface'], a['rect'])
pygame.display.update()
# Check if any of the baddies have hit the player.
if playerHasHitBaddie(playerRect, asteroids):
if score > topScore:
topScore = score # set new top score
break
mainClock.tick(FPS)
# Stop the game and show the "Game Over" screen.
pygame.mixer.music.stop()
gameOverSound.play()
drawText('GAME OVER', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press a key to play again.', font, windowSurface, (WINDOWWIDTH / 3) - 80, (WINDOWHEIGHT / 3) + 50)
pygame.display.update()
waitForPlayerToPressKey()
gameOverSound.stop()
To get the full Error you can do this in your program:
try:
something_with_error
except:
import traceback
traceback.print_exc()
input()
Then you can see the full error.