Pygame代码实际上不会开始游戏?

时间:2018-03-21 11:32:39

标签: python pygame

我们在学校一直在做Pygame,这是我们第一次使用这种语言。这段代码无法正常启动游戏并通过声音播放游戏。任何解决这个问题的技巧都可以实现。 我从一本名为invent with python(https://inventwithpython.com/invent4thed/chapter21.html)的在线书籍中得到了这段代码,并且应该创建一个游戏,允许角色在屏幕上移动并与敌人交互,但是在按下任何键之后它将改为播放游戏结束。

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

WINDOWWIDTH = 600
WINDOWHEIGHT = 600
TEXTCOLOR = (0,0,0)
BACKGROUNDCOLOR = (255, 255, 255)
FPS = 60
BADDIEMINSIZE= 10
BADDIEMAXSIZE = 40
BADDIEMINSPEED = 1
BADDIEMAXSPEED = 8
ADDNEWBADDIERATE =6
PLAYERMOVERATE = 5

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

pygame.init()
mainClock = pygame.time.Clock()
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption("Dodger")
pygame.mouse.set_visible(False)

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

gameOverSound= pygame.mixer.Sound("gameover.wav")
pygame.mixer.music.load("background.wav")

playerImage = pygame.image.load("Knight.png")
playerRect=playerImage.get_rect()
baddieImage = pygame.image.load("Skeleton.png")

windowSurface.fill(BACKGROUNDCOLOR)
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:
    baddies = []
    score = 0
    playerRect.topleft =(WINDOWWIDTH / 2, WINDOWHEIGHT- 50)
    moveLeft = moveRight = moveUp = moveDown = False
    baddiesAddCounter = 0
    pygame.mixer.music.play(-1,0.0)

while True:
    score += 1

    for event in pygame.event.get():
        if event.type == QUIT:
            terminate()

        if event.type ==KEYDOWN:
            if event.key == K_z:
                reverseCheat = True
            if event.key == K_x:
                slowCheat= True
            if event.key == K_LEFT or event.key == K_a:
                moveRight = False
                moveLeft = True
            if event.key == K_RIGHT or event.key ==K_d:
                moveLeft = False
                moveRight = True
            if event.key == K_UP or event.key == K_w:
                moveDown= False
                moveUp = True
            if event.key == K_DOWNorevent.key == K_s:
                moveUp =False
                moveDown= True

        if event.type == KEYUP:
            if event.key == K_z:
                reverseCheat = True
        if event.key == K_x:
            slowCheat = True
            score = 0
        if event.key == K_ESCAPE:
            terminate()

        if event.key == K_LEFT or event.key == K_a:
            moveLeft = False
        if event.key == K_RIGHT or event.key == K_d:
            moveRight = False
        if event.key == K_UP or event.key == K_w:
            moveUp = False
        if event.key == K_DOWN or event.key == K_s:
            moveDown = False

        if event.type == MOUSEMOTION:
            playerRect.centerx = event.pos[0]
            playerRect.centery = event.pos[1]
        if not reverseCheat and not slowCheat:
            baddiesAddCounter +=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.apped(newBaddie)

        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, 0)
        if moveDown and playerRect.bottom <WINDOWHEIGHT:
            playerRect.move_ip(0, PAYERMOVERATE)

        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)


        for b in baddies[:]:
            if b["rect"].top > WINDOWHEIGHT:
                baddies.remove(b)

        windowSurface.fill(BACKGROUNDCOLOR)

        drawText("Score: %s" % (score), font, windowSurface, 10, 0)
        drawText("Top Score: %s" % (topScore), font, windowSurface, 10, 40)

        windowSurface.blit(playerImage, playerRect)

        for b in baddies:
            windowSurface.blit(b["surface"], b["rect"])

        pygame.display.update()

        if playerHasHitBaddie(playerRect, baddies):
            if score > topScore:
                topScore = score
            break

        mainClock.tick(FPS)

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

1 个答案:

答案 0 :(得分:3)

在我看来,有人在打字时犯了一些错误?源代码列表。

我下载了https://inventwithpython.com/InventWithPython_resources.zip并将您的来源与dodger.py进行了比较。以下是一些差异的例子:

baddiesAddCounter应为baddieAddCounter
topscore应为topScore
baddies.apped应为baddies.append
PAYERMOVERATE应为PLAYERMOVERATE
b["rect"].move_ip(0, b ["Speed"])应为b["rect"].move_ip(0, b ["speed"])Speed - &gt; speed
K_DOWNorevent应为K_DOWN or event
playerRect.move_ip(0, -1 * PLAYERMOVERATE, 0)应为playerRect.move_ip(0, -1 * PLAYERMOVERATE)

一切都不起作用的主要原因:缩进略有错误。例如,有两个while True循环,第二个循环应该是&#34;在&#34;第一个,不低于它。