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
• 14,970 points
59 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.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
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
• 56,120 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 4, 2018 in Python by aayushi
• 750 points
83 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 23, 2018 in Python by ariaholic
• 7,320 points
157 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
• 56,120 points
95 views
0 votes
1 answer

Raw_Input() Is Not Defined

For Python 3.x, use input(). For Python 2.x, ...READ MORE

answered Sep 3, 2018 in Python by Priyaj
• 56,120 points
642 views
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 1,400 points
25 views
0 votes
1 answer

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

I have met same issue when I ...READ MORE

answered Aug 24, 2018 in Python by Priyaj
• 56,120 points
64 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
• 56,120 points
21 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.