Python 什么是运行时错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19763756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is a runtime error?
提问by user2727932
I made a game with Python 2.6. I also made it into an executable with cx_Freeze 4.3. When I run the executable on my computer it came up with this:
我用 Python 2.6 制作了一个游戏。我还使用 cx_Freeze 4.3 将它变成了可执行文件。当我在我的计算机上运行可执行文件时,它想出了这个:
Microsoft Visual C++ Runtime Library
Program: C:\Users\smm\Desktop\asteroid shower 1.4.5\asteroid.exe
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
I don't understand what happened here. I tried solving the problem but with no luck. Then I searched the runtime error on google and it said it might be the compatibility. I wrote the original script on windows vista with the downloaded version of the windows 7 python 2.6. I did this because the windows vista had no internet so I downloaded the python, pygame and cx_freeze .msi files on my windows 7 laptop. Then I transferred the files to the desktop windows vista. Is this the problem? Or maybe the script? I don't think its the script as I can play the game when it is still a python script. Its a bit long though... I running windows 7 with python 2.6, pygame 2.6 and cx_freeze 4.3. Thanks if you can help me :).
我不明白这里发生了什么。我试图解决这个问题,但没有运气。然后我在谷歌上搜索了运行时错误,它说可能是兼容性。我在 windows vista 上用下载的 windows 7 python 2.6 版本编写了原始脚本。我这样做是因为 windows vista 没有互联网,所以我在 windows 7 笔记本电脑上下载了 python、pygame 和 cx_freeze .msi 文件。然后我将文件传输到桌面 windows vista。这是问题吗?或者可能是脚本?我不认为它是脚本,因为当它仍然是 python 脚本时我可以玩游戏。虽然它有点长......我使用python 2.6,pygame 2.6和cx_freeze 4.3运行Windows 7。谢谢你,如果你能帮助我:)。
# By Sandy Goetjens
# Asteroid Shower V1.4.5
import pygame, random, sys, time
from pygame.locals import *
WINDOWWIDTH = 600
WINDOWHEIGHT = 600
RED = (255, 0, 0)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
TEXTCOLOR = WHITE
BACKGROUNDCOLOR = BLACK
FPS = 40
ASTEROIDCIRCLESPEED = 1
ASTEROIDMINSIZE = 10
ASTEROIDMAXSIZE = 40
ASTEROIDMINSPEED = 1
ASTEROIDMAXSPEED = 8
ADDNEWASTEROIDRATE = 10
PLAYERMOVERATE = 5
TOKENSIZE = 20
TOKENSPEED = 8
ADDNEWTOKENRATE = 6
BULLETSPEED = 3
BULLETFIRETIME = 1000
BULLETSIZE = 20
GHOSTSIZE = 20
GHOSTSPEED = 5
ADDNEWGHOSTRATE = 8
HEALTHSIZE = 20
HEALTHSPEED = 10
ADDNEWHEALTHRATE = 9
EYEBALLSIZE = 20
EYEBALLSPEED = 15
ADDNEWARROWRATE = 5
ARROWSIZE = 10
ARROWSPEED = 18
ADDNEWDUSTRATE = 8
DUSTSIZE = 12
DUSTSPEED = 16
ADDNEWEYEBALLRATE = 10
GHOSTSIZE = 20
GHOSTSPEED = 10
ADDNEWGHOSTRATE = 15
NEWASTEROIDSPEED = 30
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 playerHasHitHealth(playerRect, healths):
for h in healths:
if playerRect.colliderect(h['rect']):
return True
return False
def drawAsteroidRotation(ASTEROIDCIRCLESPEED, rotation, asteroids):
for a in asteroids:
left = leftCordinOfAsteroid
pygame.draw.rect(windowSurface, WHITE, (left, ASTEROIDSIZE, ASTEROIDSIZE))
pygame.display.update()
def asteroidAnimation(asteroids):
for rotation in asteroids(ASTEROIDCIRCLESPEED):
drawAsteroidRotation(ASTEROIDCIRCLESPEED, rotation, asteroids)
def bulletHasHitAsteroid(bulletRect, asteroids):
for b in bullets:
if bulletRect.colliderect(b['rect']):
bombExplosion.play()
return True
bombExplosion.stop()
return False
def playerHasHitToken(playerRect, tokens):
for t in tokens:
if playerRect.colliderect(t['rect']):
return True
return False
def playerHasHitBaddie(playerRect, asteroids):
for a in asteroids:
if playerRect.colliderect(a['rect']):
return True
return False
def playerHasHitGhost(playerRect, ghosts):
for g in ghosts:
if playerRect.colliderect(g['rect']):
return True
return False
def playerHasHitEyeball(playerRect, eyeballs):
for e in eyeballs:
if playerRect.colliderect(e['rect']):
return True
return False
def playerHasHitArrow(playerRect, arrows):
for r in arrows:
if playerRect.colliderect(r['rect']):
return True
return False
def playerHasHitDust(playerRect, dusts):
for d in dusts:
if playerRect.colliderect(d['rect']):
return True
return False
def asteroidHasHitBullet(baddieRect, bullets):
for a in asteroids:
if asteroidRect.collierect(a['rect']):
return True
return False
def drawText(text, font, surface, x, y):
font = pygame.font.Font(None, 48)
textobj = font.render(text, 10, TEXTCOLOR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
def version(font, windowSurface, versionbackgroundImage):
while True:
windowSurface.blit(versionBackgroundImage, (0, 0))
drawText('Buy the full game to play more', font, windowSurface, (WINDOWWIDTH / 3) - 200, (WINDOWHEIGHT / 3) - 200)
drawText('levels!! Plus bonus', font, windowSurface, (WINDOWWIDTH / 3) - 200, (WINDOWHEIGHT / 3) - 150)
drawText('updates and new game', font, windowSurface, (WINDOWWIDTH / 3) - 200, (WINDOWHEIGHT / 3) - 100)
drawText('releases!! Presented', font, windowSurface, (WINDOWWIDTH / 3) - 200, (WINDOWHEIGHT / 3) - 50)
drawText('by Desert Labotories', font, windowSurface, (WINDOWWIDTH / 3) - 200, (WINDOWHEIGHT / 3) - 0)
pygame.display.update()
waitForPlayerToPressKey()
return
def Credits(font, windowSurface, creditbackgroundImage):
while True:
windowSurface.blit(creditBackgroundImage, (0, 0))
drawText('Created by Sandy Goetjens', font, windowSurface, (WINDOWWIDTH / 3) - 150, (WINDOWHEIGHT / 3) + 50)
drawText('Presented by Desert Labortories', font, windowSurface, (WINDOWWIDTH / 3) - 150, (WINDOWHEIGHT / 3) + 100)
pygame.display.update()
waitForPlayerToPressKey()
return
def waitForPlayerToEnterKeys():
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE: # pressing escapes quits
terminate()
if event.key == K_c:
Credits(font, windowSurface, creditBackgroundImage)
if event.key == K_x:
version(font, windowSurface, versionBackgroundImage)
return
def Level3(font, windowSurface, level):
while True:
drawText('Buy the full version to', font, windowSurface, (WINDOWWIDTH / 3) - 150, (WINDOWHEIGHT / 3))
drawText('continue playing!', font, windowSurface, (WINDOWWIDTH / 3) - 150, (WINDOWHEIGHT / 3) + 50)
drawText('8 new and challenging levels!', font, windowSurface, (WINDOWWIDTH / 3) - 150, (WINDOWHEIGHT / 3 + 100))
pygame.display.update()
waitForPlayerToPressKey()
return
def Level1(font, windowSurface, level, applauseSound):
while True:
applauseSound.play()
drawText('LEVEL 1 completed!', font, windowSurface, (WINDOWWIDTH / 3) - 100, (WINDOWHEIGHT / 3))
drawText('Press a key to continue.', font, windowSurface, (WINDOWWIDTH / 3) - 100, (WINDOWHEIGHT / 3) + 50)
drawText('By Sandy Goetjens.', font, windowSurface, (WINDOWWIDTH / 3) - 100, (WINDOWHEIGHT / 3) + 150)
drawText('RATE US ON FACEBOOK', font, windowSurface, (WINDOWWIDTH / 3) - 100, (WINDOWHEIGHT / 3) + 200)
drawText('Entering BLUE LANDS', font, windowSurface, (WINDOWWIDTH / 3) - 100, (WINDOWHEIGHT / 3) + 250)
pygame.display.update()
applauseSound.stop()
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
terminate()
if True:
level = 2
kilometres = 3000
return
# set up pygame, the window, and the mouse cursor
pygame.init()
global level, kilometres
mainClock = pygame.time.Clock()
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_icon(pygame.image.load('asteroid.icon'))
pygame.display.set_caption('Asteroid Shower Demo V1.4.5')
pygame.mouse.set_visible(False)
# set up fonts
font = pygame.font.SysFont(None, 48)
# set up sounds
gameOverSound = pygame.mixer.Sound('gameover.wav')
pygame.mixer.music.load('background.mid')
bombExplosion = pygame.mixer.Sound('explosion-01.wav')
warnSound = pygame.mixer.Sound('alarm02.wav')
applauseSound = pygame.mixer.Sound('applause2.wav')
# set up images
playerImage = pygame.image.load('player.png')
playerRect = playerImage.get_rect()
baddieImage = pygame.image.load('asteroid.png')
baddieRect = baddieImage.get_rect()
tokenImage = pygame.image.load('tokens.png')
bulletImage = pygame.image.load('bullet.png')
bulletRect = bulletImage.get_rect()
ghostImage = pygame.image.load('ghosts.png')
healthImage = pygame.image.load('health.png')
eyeballImage = pygame.image.load('eyeball.png')
arrowImage = pygame.image.load('arrow.png')
dustImage = pygame.image.load('dust.png')
versionBackgroundImage = pygame.image.load('background.png')
creditBackgroundImage = pygame.image.load('creditsbackground.png')
creditsPage = pygame.image.load('credits.png')
desertLabs = pygame.image.load('desert labs.png')
# show the "Start" screen
windowSurface.blit(creditsPage, (0, 0))
pygame.time.wait(1000)
drawText('Asteroid Shower ', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 4 - 100))
drawText('Press a key to start.', font, windowSurface, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 4 - 50))
pygame.display.update()
waitForPlayerToEnterKeys()
level = 0
bullet = 50
token = 0
topScore = 0
while True:
# set up the start of the game
tokens = []
asteroids = []
bullets = []
eyeballs = []
arrows = []
dusts = []
ghosts = []
healths = []
score = 0
health = 100
kilometres = 2500
playerRect.topleft = (WINDOWWIDTH / 2, WINDOWHEIGHT - 50)
moveLeft = moveRight = moveUp = moveDown = False
reverseCheat = slowCheat = False
asteroidAddCounter = 0
ghostAddCounter = 0
tokenAddCounter = 0
healthAddCounter = 0
eyeballAddCounter = 0
arrowAddCounter = 0
dustAddCounter = 0
pygame.mixer.music.play(-1, 0.0)
while True: # the game loop runs while the game part is playing
score += 1 # increase score
kilometres -= 1 # decrease kilomteres
if level == 0:
if kilometres == 0:
level = 2
kilometres = 3000
Level1(font, windowSurface, level, applauseSound)
# Go to level 3 title
if level == 2 and kilometres == 0:
Level3(font, windowSurface, level)
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.key == K_z:
if token > 500:
token -= 500
if bullet < 200:
bullet += 50
if event.key == K_x:
if token > 600:
token -= 600
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)
if token > 0:
if event.type == MOUSEBUTTONUP:
# If player clicks mouse bullets will fire
if bullet > 0:
bullet -= 1
newBullet = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-BULLETSIZE), 0 - BULLETSIZE, BULLETSIZE, BULLETSIZE),
'speed': (BULLETSPEED),
'surface':pygame.transform.scale(bulletImage, (BULLETSIZE, BULLETSIZE)),
}
bullets.append(newBullet)
# Add new tokens at the top of the screen, if needed
if not reverseCheat and not slowCheat:
tokenAddCounter += 1
if tokenAddCounter == ADDNEWTOKENRATE:
tokenAddCounter = 0
newToken = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-TOKENSIZE), 0 - TOKENSIZE, TOKENSIZE, TOKENSIZE),
'speed': (TOKENSPEED),
'surface':pygame.transform.scale(tokenImage, (TOKENSIZE, TOKENSIZE)),
}
tokens.append(newToken)
if level == 0:
# 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)
if level == 0:
if not reverseCheat and not slowCheat:
ghostAddCounter += 1
if ghostAddCounter == ADDNEWGHOSTRATE:
ghostAddCounter = 0
newGhost = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-GHOSTSIZE), 0 - GHOSTSIZE, GHOSTSIZE, GHOSTSIZE),
'speed': (GHOSTSPEED),
'surface': pygame.transform.scale(ghostImage, (GHOSTSIZE, GHOSTSIZE)),
}
ghosts.append(newGhost)
if health < 50:
if not reverseCheat and not slowCheat:
healthAddCounter += 1
if healthAddCounter == ADDNEWHEALTHRATE:
healthAddCounter = 0
newHealth = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-HEALTHSIZE), 0 - HEALTHSIZE, HEALTHSIZE, HEALTHSIZE),
'speed': (HEALTHSPEED),
'surface': pygame.transform.scale(healthImage, (HEALTHSIZE, HEALTHSIZE)),
}
healths.append(newHealth)
if level == 2:
if not reverseCheat and not slowCheat:
eyeballAddCounter += 1
if eyeballAddCounter == ADDNEWEYEBALLRATE:
eyeballAddCounter = 0
newEyeball = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-EYEBALLSIZE), 0 - EYEBALLSIZE, EYEBALLSIZE, EYEBALLSIZE),
'speed': (EYEBALLSPEED),
'surface': pygame.transform.scale(eyeballImage, (EYEBALLSIZE, EYEBALLSIZE)),
}
eyeballs.append(newEyeball)
if level == 2:
if not reverseCheat and not slowCheat:
arrowAddCounter += 1
if arrowAddCounter == ADDNEWARROWRATE:
arrowAddCounter = 0
newArrow = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-ARROWSIZE), 0 - ARROWSIZE, ARROWSIZE, ARROWSIZE),
'speed': (ARROWSPEED),
'surface': pygame.transform.scale(arrowImage, (ARROWSIZE, ARROWSIZE)),
}
arrows.append(newArrow)
if level == 2:
if not reverseCheat and not slowCheat:
dustAddCounter += 1
if dustAddCounter == ADDNEWDUSTRATE:
dustAddCounter = 0
newDust = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-DUSTSIZE), 0 - DUSTSIZE, DUSTSIZE, DUSTSIZE),
'speed': (DUSTSPEED),
'surface': pygame.transform.scale(dustImage, (DUSTSIZE, DUSTSIZE)),
}
dusts.append(newDust)
# 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)
for g in ghosts:
if not reverseCheat and not slowCheat:
g['rect'].move_ip(0, g['speed'])
elif reverseCheat:
g['rect'].move_ip(0, -5)
elif slowCheat:
g['rect'].move_ip(0, 1)
# Delete each ghost that have fallen past the bottom
for g in ghosts[:]:
if g['rect'].top > WINDOWHEIGHT:
ghosts.remove(g)
# Move the tokens down
for t in tokens:
if not reverseCheat and not slowCheat:
t['rect'].move_ip(0, t['speed'])
elif reverseCheat:
t['rect'].move_ip(0, -5)
elif slowCheat:
t['rect'].move_ip(0, 1)
# Delete each token that have fallen past the bottom
for t in tokens[:]:
if t['rect'].top > WINDOWHEIGHT:
tokens.remove(t)
# Move bullets down
for b in bullets:
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)
for b in bullets[:]:
if b['rect'].top > WINDOWHEIGHT:
bullets.remove(b)
# Move health down
for h in healths:
if not reverseCheat and not slowCheat:
h['rect'].move_ip(0, h['speed'])
elif reverseCheat:
h['rect'].move_ip(0, -5)
elif slowCheat:
h['rect'].move_ip(0, -1)
for h in healths[:]:
if h['rect'].top > WINDOWHEIGHT:
healths.remove(h)
# Move eyeballs down
for e in eyeballs:
if not reverseCheat and not slowCheat:
e['rect'].move_ip(0, e['speed'])
elif reverseCheat:
e['rect'].move_ip(0, -5)
elif slowCheat:
e['rect'].move_ip(0, -1)
for e in eyeballs[:]:
if e['rect'].top > WINDOWHEIGHT:
eyeballs.remove(e)
for r in arrows:
if not reverseCheat and not slowCheat:
r['rect'].move_ip(0, r['speed'])
elif reverseCheat:
r['rect'].move_ip(0, -5)
elif slowCheat:
r['rect'].move_ip(0, -1)
for r in arrows[:]:
if r['rect'].top > WINDOWHEIGHT:
arrows.remove(r)
for d in dusts:
if not reverseCheat and not slowCheat:
d['rect'].move_ip(0, d['speed'])
elif reverseCheat:
d['rect'].move_ip(0, -5)
elif slowCheat:
d['rect'].move_ip(0, -1)
for d in dusts[:]:
if d['rect'].top > WINDOWHEIGHT:
dusts.remove(d)
# Draw the game world on the window.
windowSurface.fill(BACKGROUNDCOLOR)
if level == 2:
windowSurface.fill(BLUE)
# Draw the score top score, token, how many bombs, health and how much boss life
drawText('Score: %s' % (score), font, windowSurface, 10, 0)
drawText('Top Score: %s' % (topScore), font, windowSurface, 10, 40)
drawText('Token: %s' % (token), font, windowSurface, 10, 80)
drawText('Bombs: %s' % (bullet), font, windowSurface, 10, 120)
drawText('Km: %s' % (kilometres), font, windowSurface, 10, 160)
drawText('Health: %s' % (health), font, windowSurface, 10, 560)
# Draw the player's rectangle
windowSurface.blit(playerImage, playerRect)
# Check the score to enter the next level
# Draw each asteroid
for a in asteroids:
windowSurface.blit(a['surface'], a['rect'])
for g in ghosts:
windowSurface.blit(g['surface'], g['rect'])
# Draw each token
for t in tokens:
windowSurface.blit(t['surface'], t['rect'])
# Draw each bullet
for b in bullets:
windowSurface.blit(b['surface'], b['rect'])
# Draw each health
for h in healths:
windowSurface.blit(h['surface'], h['rect'])
# Draw each eyeball
for e in eyeballs:
windowSurface.blit(e['surface'], e['rect'])
# Draw each arrow
for r in arrows:
windowSurface.blit(r['surface'], r['rect'])
# Draw each dust
for d in dusts:
windowSurface.blit(d['surface'], d['rect'])
pygame.display.update()
# Check if any of the health have hit the player
if playerHasHitHealth(playerRect, healths):
health += 5
if health < 100:
health -= 0
healths.remove(h)
# Cheack if any of the eyeballs have hit the player
if playerHasHitEyeball(playerRect, eyeballs):
health -= 10
if health == 0:
if score > topScore:
topScore = score
break
# Check if any of the arrows have hit the player
if playerHasHitArrow(playerRect, arrows):
health -= 15
if health == 0:
if score > topScore:
topScore = score
break
# Check if any of the dusts have hit the player
if playerHasHitDust(playerRect, dusts):
health -= 5
if health == 0:
if score > topScore:
topScore = score
break
# Check if any of the bullets have hit asteroids.
if bulletHasHitAsteroid(bulletRect, asteroids):
score += 1000
if True:
for a in asteroids:
if a['rect'].colliderect:
asteroids.remove(a)
# Check if any of the tokens have hit the player.
if playerHasHitToken(playerRect, tokens):
score += 10
token += 1
# Check if any of the baddies have hit the player.
if playerHasHitBaddie(playerRect, asteroids):
health -= 5
if health == 0:
if score > topScore:
topScore = score # set new top score
break
if playerHasHitGhost(playerRect, ghosts):
health -= 10
if health == 0:
if score > topScore:
topScore = score # set new top score
break
if health == 0:
if score > topScore:
topScore = 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()
回答by trevorKirkby
A run time error is a type of error that is deliberately raised during program run time (hence the name). For example, in python, a runtime error can only occur when someone writes
运行时错误是一种在程序运行时故意引发的错误类型(因此得名)。比如在python中,只有在有人写的时候才会出现运行时错误
raise RuntimeError
This is meant to be a way to stop the program if there is a type of error that the program interpreter has not detected, but is capable of causing the program to not function as it has to. An example of when a runtime error is required is this function (a wrapper for the termcolor cprint function that takes a number as its color argument):
如果存在程序解释器未检测到但能够导致程序无法正常运行的错误类型,则这是一种停止程序的方法。需要运行时错误的一个示例是此函数( termcolor cprint 函数的包装器,将数字作为其颜色参数):
import termcolor
def coloredprint(text,color):
if color == 1:
termcolor.cprint(text,color='red')
if color == 2:
termcolor.cprint(text,color='green')
In this circumstance, the function will fail to run properly or inform the user of any kind of error if the color argument is not 1 or 2. The way to solve this, and make your program easier to use, is a runtime error (or larger libraries will create their own custom exceptions, this is not important). Basically, because an argument other than 1 or 2 is in fact an error in your program (that python won't catch and raise for you), it will raise an error for the user to diagnose. Here is the new and better version of the function:
在这种情况下,如果颜色参数不是 1 或 2,该函数将无法正常运行或通知用户任何类型的错误。解决此问题并使您的程序更易于使用的方法是运行时错误(或较大的库将创建自己的自定义异常,这并不重要)。基本上,因为 1 或 2 以外的参数实际上是您程序中的一个错误(python 不会为您捕获和引发),它会引发一个错误供用户诊断。这是该功能的新版本和更好的版本:
import termcolor
def coloredprint(text,color):
if color == 1:
termcolor.cprint(text,color='red')
if color == 2:
termcolor.cprint(text,color='green')
else:
print "colored print function: color argument", color, "is not a viable argument, specify 1 or 0"
raise RuntimeError
Now, if the user makes a mistake, the program will catch this as an error, instead of failing to function or doing something unexpected, which would make it difficult to diagnose (and in some cases potentially vulnerable). This is why a runtime error is useful.
现在,如果用户犯了错误,程序会将其捕获为错误,而不是无法运行或做一些意外的事情,这将使诊断变得困难(并且在某些情况下可能容易受到攻击)。这就是运行时错误有用的原因。