【问题标题】:Pygame keeps crashing when I open it当我打开 Pygame 时,它​​总是崩溃
【发布时间】:2016-07-21 02:42:18
【问题描述】:

我有这个躲避外星人的游戏,但它不工作。我可以打开前面的开始屏幕,但是当我按 Enter 键启动它时,它会崩溃并死机。我尝试从 python.exe 而不是 IDLE 运行它,但在这种情况下它只是弹出然后立即关闭。我尝试运行它的前几次弹出了一些错误,但现在没有错误表明可能是错误的。它只是停止响应。我在这里做错了什么?

import pygame, random, sys
from pygame.locals import *


def startGame():
    if event.type == K_ENTER:
        if event.key == K_ESCAPE:
            sys.exit()
        return

def playerCollision():
    for a in aliens:
        if playerRect.colliderect(b['rect']):
            return True
    return False

pygame.init()

screen = pygame.display.set_mode((750,750))
clock = pygame.time.Clock()
pygame.display.set_caption('Dodge the Aliens')

font = pygame.font.SysFont(None, 55)

playerImage = pygame.image.load('')
playerRect = playerImage.get_rect()
alienImage = pygame.image.load('')

drawText('Dodge the Aliens!', font, screen, (750 / 3), (750 / 3))
drawText('Press ENTER to start.', font, screen, (750 / 3) - 45, (750 / 3) +    65)
pygame.display.update()

topScore = 0
while True:
    aliens = []
    score = 0
    playerRect.topleft = (750 /2, 750 - 50)
    alienAdd = 0
    while True:
        score += 1
        pressed = pygame.key.get_pressed()
        if pressed[pygame.K_LEFT]: x -=3
        if pressed[pygame.K_RIGHT]: x += 3
        if pressed[pygame.K_ESCAPE]: sys.exit()
    alienAdd += 1

    if alienAdd == addedaliens:
        aliendAdd = 0
        alienSize = random.randint(10, 40)
        newAlien = {'rect': pygame.Rect(random.randint(0, 750 - alienSize), 0 -alienSize, alienSize, alienSize), 'speed': random.randint(1, 8), 'surface':pygame.transform.scale(alienImage, (alienSize, alienSize)), }
        aliens.append(newAlien)
    for a in aliens[:]:
        if a['rect'].top > 750:
            aliens.remove(a)
    screen.fill(0,0,0)
    drawText('Score %s' % (score), font, screen, 10, 0)
    screen.blit(playerImage, playerRect)
    for a in aliens:
        screen.blit(b['surface'], b['rect'])
    pygame.display.update()


    if playerCollision(playerRect, aliens):
        if score > topScore:
            topScore = score
        break

    clock.tick(60)

    drawText('Game Over!', font, screen, (750 / 3), ( 750 / 3))
    drawText('Press ENTER To Play Again.', font, screen, ( 750 / 3) - 80, (750 / 3) + 50)
    pygame.display.update()
    startGame()

这是我修改后的新代码 导入pygame,随机,系统 从 pygame.locals 导入* Alienimg = pygame.image.load('C:\Python27\alien.png') playerimg = pygame.image.load('C:\Python27\spaceship.png')

def playerCollision(): # a function for when the player hits an alien
    for a in aliens:
        if playerRect.colliderect(b['rect']):
            return True
    return False

def screenText(text, font, screen, x, y): #text display function
    textobj = font.render(text, 1, (255, 255, 255))
    textrect = textobj.get_rect()
    textrect.topleft = (x,y)
    screen.blit(textobj, textrect)

def main(): #this is the main function that starts the game

    pygame.init()
    screen = pygame.display.set_mode((750,750))
    clock = pygame.time.Clock()

    pygame.display.set_caption('Dodge the Aliens') 
    font = pygame.font.SysFont("monospace", 55)


    pressed = pygame.key.get_pressed()

    aliens = []
    score = 0
    alienAdd = 0
    addedaliens = 0

    while True: #our while loop that actually runs the game



        for event in pygame.event.get(): #key controls
            if event.type == KEYDOWN and event.key == pygame.K_ESCAPE: 
                sys.exit()
            elif event.type == KEYDOWN and event.key == pygame.K_LEFT: 
                playerRect.x -= 3

            elif event.type == KEYDOWN and event.key == pygame.K_RIGHT:
                playerRect.x += 3


          playerImage = pygame.image.load('C:\\Python27\\spaceship.png').convert() # the player images
        playerRect = playerImage.get_rect()
        playerRect.topleft = (750 /2, 750 - 50)
        alienImage = pygame.image.load('C:\\Python27\\alien.png').convert() #alien images   

        alienAdd += 1

        pygame.display.update()

        if alienAdd == addedaliens: # randomly adding aliens of different sizes and speeds
            aliendAdd = 0
            alienSize = random.randint(10, 40)
            newAlien = {'rect': pygame.Rect(random.randint(0, 750 - alienSize), 0 -alienSize, alienSize, alienSize), 'speed': random.randint(1, 8), 'surface':pygame.transform.scale(alienImage, (alienSize, alienSize)), }
            aliens.append(newAlien)
        for a in aliens[:]:
            if a['rect'].top > 750:
                aliens.remove(a) #removes the aliens when they get to the bottom of the screen

        screen.blit(screen, (0,0))
        screenText('Score %s' % (score), font, screen, 10, 0)
        screen.blit(playerImage, playerRect)
        for a in aliens:
            screen.blit(b['surface'], b['rect'])
        pygame.display.flip()


        if playerCollision(playerRect, aliens):
            if score > topScore:
                topScore = score
            break


        clock.tick(60)

        screenText('Game Over!', font, screen, (750 / 6), ( 750 / 6))
        screenText('Press ENTER To Play Again.', font, screen, ( 750 / 6) - 80, (750 / 6) + 50)
        pygame.display.update()

main()

【问题讨论】:

    标签: python crash pygame


    【解决方案1】:

    我仍然看到您的代码存在几个问题,我认为您一开始就试图一次做太多事情。尽量保持简单。尝试创建一个显示并绘制一些图像:

    import pygame
    
    pygame.init()
    
    display = pygame.display.set_mode((750, 750))
    img = pygame.image.load("""C:\\Game Dev\\alien.png""")
    display.blit(img, (0, 0))
    pygame.display.flip()
    

    当然,您必须调整 img 路径。运行这个你应该得到一个明确的错误(然后你应该在另一个线程中发布)或者在屏幕上看到你的 img。但是程序不会响应,因为没有事件处理,也没有主循环。

    为避免这种情况,您可以引入如下主循环:

    import sys
    import pygame
    
    pygame.init()
    
    RESOLUTION = (750, 750)
    FPS = 60
    
    display = pygame.display.set_mode(RESOLUTION)
    clock = pygame.time.Clock()
    img = pygame.image.load("""C:\\Game Dev\\alien.png""")
    
    while True:  # <--- game loop
    
        # check quit program
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
        # clear the screen
        display.fill((0, 0, 0))
        # draw the image
        display.blit(img, (0, 0))
        # update the screen
        pygame.display.flip()
        # tick the clock
        clock.tick(FPS)
    

    这应该会导致程序一遍又一遍地显示相同的 img,并且可以使用鼠标正确退出。但它仍然像一个脚本,如果有人导入它,它会立即执行,这不是我们想要的。因此,让我们也解决这个问题,并将其全部封装在一个 main 函数中,如下所示:

    import sys
    import pygame
    
    #defining some constants
    RESOLUTION = (750, 750)
    FPS = 60
    
    def main(): # <--- program starts here
    
        # setting things up
        pygame.init()
        display = pygame.display.set_mode(RESOLUTION)
        clock = pygame.time.Clock()
        img = pygame.image.load("""C:\\Game Dev\\alien.png""")
    
        while True:  # <--- game loop
    
            # check quit program
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()
            # clear the screen
            display.fill((0, 0, 0))
            # draw the image
            display.blit(img, (0, 0))
            # update the screen
            pygame.display.flip()
            # tick the clock
            clock.tick(FPS)
    
    if __name__ == "__main__":
        main()
    

    'if name == "ma​​in":' 确保程序在导入时不会执行。

    我希望这会有所帮助。请记住:不要一次尝试太多。一步一步地采取小步骤,并尝试保持对程序的控制。如果需要,您甚至可以在每一行代码之后添加一个 print 语句,以准确地让您知道您的程序做了什么以及按照什么顺序。

    【讨论】:

    • 我能建议您举一个例子来说明您对@ndoll 的建议吗?
    • 谢谢。我还不是最擅长python,但我正在努力学习。所以为了澄清一下,while 循环应该在我的 main 函数中?
    • 我将第一个 while 循环变成了 main 函数,但我仍然遇到同样的问题 :(
    猜你喜欢
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    • 2022-08-15
    • 1970-01-01
    • 2017-03-01
    相关资源
    最近更新 更多