打开它时,Pygame不断崩溃

时间:2016-07-21 02:42:18

标签: python crash pygame

我有这个躲避外星人的游戏并且它无法正常工作。我可以让前面的开始屏幕打开但是当我按下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()

这是我修改后的新代码     import pygame,random,sys     来自pygame.locals import *     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()

1 个答案:

答案 0 :(得分:0)

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

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,并且可以使用鼠标正确退出。但它仍然像一个脚本,如果有人导入它,它会立即执行,这不是我们想要的。所以,让我们解决这个问题,并将其全部包含在这样的主函数中:

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()

如果名称 ==&#34; 主要&#34;:&#39;确保程序在导入时不会执行。

我希望这会有所帮助。请记住:不要一次尝试太多。一个接一个地采取小步骤,并尝试控制您的程序。如果需要,您甚至可以在每行代码后面添加一个print语句,以准确地告诉您程序的功能和顺序。