james stretch
james stretch

Reputation: 1

Pygame code will not actually start game?

We have been doing Pygame at school and its our first time ever using the language. This piece of code does not start the game properly and plays the game over sound. Any tips for fixing this so it actually works. I got this piece of code from an online book called invent with python(https://inventwithpython.com/invent4thed/chapter21.html) and should be creating a game that allows for characters to move around the screen and interact with enemies but instead after pressing any key it will instead play the game over clip.

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

Upvotes: 0

Views: 159

Answers (1)

sneep
sneep

Reputation: 1918

It seems to me like someone made some mistakes when typing out? the source code listing.

I downloaded https://inventwithpython.com/InventWithPython_resources.zip and compared your source with dodger.py. Here are some examples of the differences:

baddiesAddCounter should be baddieAddCounter
topscore should be topScore
baddies.apped should be baddies.append
PAYERMOVERATE should be PLAYERMOVERATE
b["rect"].move_ip(0, b ["Speed"]) should be b["rect"].move_ip(0, b ["speed"]) (Speed --> speed)
K_DOWNorevent should be K_DOWN or event
playerRect.move_ip(0, -1 * PLAYERMOVERATE, 0) should be playerRect.move_ip(0, -1 * PLAYERMOVERATE)

And the main reason everything doesn't work: the indentation is slightly wrong. For example, there are two while True loops, and the second one should be "in" the first one, not below it.

Upvotes: 3

Related Questions