什么是运行时错误?

时间:2013-11-04 08:07:00

标签: python pygame windows-vista compatibility cx-freeze

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

我不明白这里发生了什么。我尝试解决问题,但没有运气。然后我在谷歌搜索运行时错误,它说它可能是兼容性。我在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()

2 个答案:

答案 0 :(得分:3)

运行时错误是程序运行期间故意引发的一种错误(因此名称)。例如,在python中,只有在有人写

时才会发生运行时错误
raise RuntimeError

如果程序解释器没有检测到某种类型的错误,但是能够导致程序无法正常运行,则这是一种停止程序的方法。需要运行时错误的一个示例是此函数(termcolor cprint函数的包装器,它以数字作为颜色参数):

import termcolor

def coloredprint(text,color):
    if color == 1:
        termcolor.cprint(text,color='red')
    if color == 2:
        termcolor.cprint(text,color='green')

在这种情况下,如果颜色参数不是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

现在,如果用户犯了错误,程序会将此作为错误捕获,而不是无法运行或执行意外操作,这将使诊断变得困难(并且在某些情况下可能容易受到攻击)。这就是运行时错误有用的原因。

答案 1 :(得分:-1)

运行时异常表示某些错误逻辑,导致您正在运行的程序突然终止。因为您没有编写任何逻辑来处理它们,所以导致运行时异常。