Game is not starting from PyGame

0 votes

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.

Sep 28, 2018 in Python by bug_seeker
• 15,520 points
1,323 views
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 answer to this question.

0 votes

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.

answered Sep 28, 2018 by Priyaj
• 58,100 points

Related Questions In Python

0 votes
1 answer

Raw_input method is not working in python3. How to use it?

raw_input is not supported anymore in python3. ...READ MORE

answered May 5, 2018 in Python by aayushi
• 750 points
3,298 views
0 votes
1 answer

Is there anyway to obtain the full abstract from a 'PUBmed' article using bioPython

Hey Charlie, it's certainly possible to pull ...READ MORE

answered Aug 24, 2018 in Python by aryya
• 7,460 points
3,228 views
0 votes
1 answer

Python `if x is not None` or `if not x is None`?

There's no performance difference, as they compile ...READ MORE

answered Sep 3, 2018 in Python by Priyaj
• 58,100 points
2,601 views
0 votes
2 answers

NameError: name 'raw_input' is not defined

Hi, There may a problem with your python ...READ MORE

answered Jun 25, 2020 in Python by MD
• 95,460 points
32,519 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,342 views
0 votes
1 answer
0 votes
3 answers

'python' is not recognized as an internal or external command

Try "py" instead of "python" from command line: C:\Users\Cpsa>py Python 3.4.1 (v3.4.1:c0e311e010fc, May ...READ MORE

answered Feb 8, 2022 in Python by Rahul
• 9,680 points
2,451 views
0 votes
1 answer

Linux command-line call not returning what it should from os.system?

What gets returned is the return value ...READ MORE

answered Aug 29, 2018 in Python by Priyaj
• 58,100 points
831 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP