3
\$\begingroup\$

PYTHON 2.7-

I want to make my code OOP. I also want feedback from you on correctness, tidiness, design patterns and so on.

Here's the download link. It's not permanent but it's the best I have time for.

I get this syntax error now, tried multiple things without progress.


The code:

filesDict = {'',
             "backgroundMusicMenu":
             pygame.mixer.Sound('music/Who Likes To Party.ogg'),
             "foxSound": pygame.mixer.Sound('sounds/foxSound.wav'),
             "rabbitSound": pygame.mixer.Sound('sounds/rabbitSound.wav'),
             "buttonStartImage": pygame.image.load('textures/buttonStart.png'),
             "playerImage": pygame.image.load('textures/Fox.png'),
             "playerImageTwo": pygame.image.load('textures/Fox2.png'),
             "rabbitImage": pygame.image.load('textures/topic_rabbit.png'),
             "rabbitImageTwo": pygame.image.load('textures/topic_rabbit2.png'),
             "buttonEasyImage": pygame.image.load('textures/buttonEasy.png'),
             "buttonNormalImage":
             pygame.image.load('textures/buttonNormal.png'),
             "buttonHardImage": pygame.image.load('textures/buttonHard.png'),
             "background_image":
             pygame.image.load('textures/bg.jpg').convert()}

The error:

  File "C:\Users\USER\My Programs\Python\Slutarbete2.2\mainPEP8d.py", line 10
7
    "backgroundMusicMenu": pygame.mixer.sound(
                         ^
SyntaxError: invalid syntax

# -*- coding: utf-8 -*-

#Börjar med att importera alla moduler för att få spelkoden att funka här.
#Importerar först alla tillgängliga moduler till pygame paketet.
#Sedan så sätter jag en begränsad uppsättning av konstanter och funktioner
#i global namespace av scriptet. Efter det importerar jag timern som är
#essentiell i spel osv.

import pygame
import sys
import random
import math
import os
from pygame.locals import *
from threading import Timer

#Börjar sätta upp spel funktionerna och klockan.

pygame.init()
pygame.mixer.init()
mainClock = pygame.time.Clock()


def movementVariables():
    global moveUp
    global moveDown
    global moveLeft
    global moveRight
    global levelOne
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    #Tangentbords variabler
        if event.type == KEYDOWN:
            #testkey
            if event.key == K_SPACE:
                levelOne = False
            if event.key == K_LEFT:
                moveRight = False
                moveLeft = True
            if event.key == K_RIGHT:
                moveRight = True
                moveLeft = False
            if event.key == K_UP:
                moveDown = False
                moveUp = True
            if event.key == K_DOWN:
                moveDown = True
                moveUp = False
        if event.type == KEYUP:
            if event.key == K_ESCAPE:
                pygame.quit()
                sys.exit()
            if event.key == K_LEFT:
                moveLeft = False
            if event.key == K_RIGHT:
                moveRight = False
            if event.key == K_UP:
                moveUp = False
            if event.key == K_DOWN:
                moveDown = False


def movementMechanism():
    if moveDown and player.bottom < WINDOW_HEIGHT:
        player.top += MOVE_SPEED
    if moveUp and player.top > 0:
        player.top -= MOVE_SPEED
    if moveLeft and player.left > 0:
        player.left -= MOVE_SPEED
    if moveRight and player.right < WINDOW_WIDTH:
        player.right += MOVE_SPEED
    windowSurface.blit(playerImage, player)

#Ger resolutionen till spelfönstret samt ger namnet för spelet och fönstret.
WINDOW_WIDTH = 640
WINDOW_HEIGHT = 400
windowSurface = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT), 0)
icon = pygame.image.load('textures/systemicon.png')
pygame.display.set_icon(icon)
pygame.display.set_caption('Catch the rabbits!')

#Ger alla färger dess rgb koder, och vilken font och vinn texten.

BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
WHITE = (255, 255, 255)

textFont = pygame.font.SysFont("impact", 60)
textEnd = textFont.render("YOU WON!", True, (193, 0, 0))

#Spelarens och fiendernas data structurer.
#Fiendernas storlek.
#Laddar alla bitmap (.png) och ljud (.wav) filer till spelaren och fienderna
#samt bakgrundsbilderna
rabbitCounter = 0
NEW_RABBIT = 40
RABBIT_SIZE = 64

#"Who Likes To Party" Kevin MacLeod (incompetech.com)
#"No Frills Salsa" Kevin MacLeod (incompetech.com)
#Licensed under Creative Commons: By Attribution 3.0
#http://creativecommons.org/licenses/by/3.0/

filesDict = {'',
             "backgroundMusicMenu":
             pygame.mixer.Sound('music/Who Likes To Party.ogg'),
             "foxSound": pygame.mixer.Sound('sounds/foxSound.wav'),
             "rabbitSound": pygame.mixer.Sound('sounds/rabbitSound.wav'),
             "buttonStartImage": pygame.image.load('textures/buttonStart.png'),
             "playerImage": pygame.image.load('textures/Fox.png'),
             "playerImageTwo": pygame.image.load('textures/Fox2.png'),
             "rabbitImage": pygame.image.load('textures/topic_rabbit.png'),
             "rabbitImageTwo": pygame.image.load('textures/topic_rabbit2.png'),
             "buttonEasyImage": pygame.image.load('textures/buttonEasy.png'),
             "buttonNormalImage":
             pygame.image.load('textures/buttonNormal.png'),
             "buttonHardImage": pygame.image.load('textures/buttonHard.png'),
             "background_image":
             pygame.image.load('textures/bg.jpg').convert()}

pygame.mixer.music.load('music/No Frills Salsa.ogg')
player = pygame.Rect(420, 100, 40, 40)
buttonStart = pygame.Rect(220, 150, 200, 90)
buttonEasy = pygame.Rect(10, 150, 200, 90)
buttonNormal = pygame.Rect(220, 150, 200, 90)
buttonHard = pygame.Rect(430, 150, 200, 90)

rabbits = []
for i in range(20):
    rabbits.append(pygame.Rect(random.randint(0, WINDOW_WIDTH
                   - RABBIT_SIZE), random.randint
                   (0, WINDOW_HEIGHT - RABBIT_SIZE),
                   RABBIT_SIZE, RABBIT_SIZE))

#Rörlighetsvariablerna

moveLeft = False
moveRight = False
moveUp = False
moveDown = False

#Rörlighetshastigheten

MOVE_SPEED = 0

#Start Meny
menuMusic = False
endit = False
while not endit:
    filesDict["backgroundMusicMenu"].play(-1)
    windowSurface.fill(WHITE)
    for event in pygame.event.get():
            if (event.type == pygame.MOUSEBUTTONDOWN and event.button == 1):
                mouse_coordinates = pygame.mouse.get_pos()
                if buttonStart.collidepoint(mouse_coordinates):
                    end_it = True
    windowSurface.blit(filesDict["buttonStartImage"], buttonStart)
    pygame.display.flip()

#Svårighetsgrader
enditlevel = False
while not enditlevels:
    windowSurface.fill(WHITE)
    for event in pygame.event.get():
        if (event.type == pygame.MOUSEBUTTONDOWN and event.button == 1):
            mouse_coordinates = pygame.mouse.get_pos()
            if buttonEasy.collidepoint(mouse_coordinates):
                MOVE_SPEED = 9
                NEW_RABBIT = 40
                end_it_levels = True
        if (event.type == pygame.MOUSEBUTTONDOWN and event.button == 1):
            mouse_coordinates = pygame.mouse.get_pos()
            if buttonNormal.collidepoint(mouse_coordinates):
                MOVE_SPEED = 7
                NEW_RABBIT = 30
                end_it_levels = True
        if (event.type == pygame.MOUSEBUTTONDOWN and event.button == 1):
            mouse_coordinates = pygame.mouse.get_pos()
            if buttonHard.collidepoint(mouse_coordinates):
                MOVE_SPEED = 5
                NEW_RABBIT = 20
                end_it_levels = True
    windowSurface.blit(get_image('textures/buttonEasy.png'), buttonEasy)
    windowSurface.blit(get_image('textures/buttonNormal.png'), buttonNormal)
    windowSurface.blit(get_image('textures/buttonHard.png'), buttonHard)
    pygame.display.flip()

#Spel loopen
backgroundMusicMenu.stop()
levelOne = True
if levelOne is True:
    rabbitSound.play()
    foxSound.play()
    pygame.mixer.music.play()
#Checkar ifall quit
    movementVariables()

#Gör en loop som gör att det spawnar mera och mera kaniner
    rabbitCounter += 1
    if rabbitCounter >= NEW_RABBIT:
        rabbitCounter = 0
        rabbits.append(pygame.Rect(random.randint(0, WINDOW_WIDTH
                       - RABBIT_SIZE), random.randint
                       (0, WINDOW_HEIGHT - RABBIT_SIZE),
                       RABBIT_SIZE, RABBIT_SIZE))

#Snöbakgrunden sätts på bakgrunden när man väljt svårighetsgrad

    windowSurface.blit(get_image('textures/bg.jpg'), [0, 0])

#Rörlighets mekanism så att spelaren inte går utanför skärmen samt inte går
#för fort.
    movementMechanism()

#Kaninernas texture blits
    for rabbit in rabbits:
        windowSurface.blit(get_image('rabbitImage.png'), rabbit)

#Random movement för kaninerna

    stepMovementNegativeRabbit = random.randrange(0, -3, -2)

    stepMovementPositiveRabbit = random.randrange(0, 3, 2)

    rabbitMovement = ['',
                      ((stepMovementNegativeRabbit), 0),
                      ((stepMovementPositiveRabbit), 0),
                      (0, (stepMovementNegativeRabbit)),
                      (0, (stepMovementPositiveRabbit))]
    for rabbit in rabbits:
        rabbit.move_ip(*random.choice(rabbitMovement))

#Checkning ifall spelaren rört en kanin
    for rabbit in rabbits[:]:

        if player.colliderect(rabbit):
            windowSurface.blit(get_image('textures/topic_rabbit2.png'), rabbit)
            windowSurface.blit(get_image('textures/Fox.png'), player)

        def explosionRabbit():
            for rabbit in rabbits:
                if player.colliderect(rabbit) and (moveLeft is False and
                                                   moveRight is False and
                                                   moveUp is False and
                                                   moveDown is False):
                    rabbits.remove(rabbit)

        if player.colliderect(rabbit) and (moveLeft is False and
                                           moveRight is False and
                                           moveUp is False and
                                           moveDown is False):
            #timer inställningar
            tRabbit = Timer(0.1, explosionRabbit)
            tRabbit.start()

    if len(rabbits) == 0:
        rabbitCounter = 0
        windowSurface.blit(get_image(textLevelOne.png), (100, 104))
        levelOne = False
        windowSurface.fill((0, 0, 0))

    #Ritar fönstret
    pygame.display.update()
    mainClock.tick(60)
\$\endgroup\$
  • \$\begingroup\$ Hello and Welcome! Please add a short description to your question about what kind of game this is, it will be much easier to understand your code and will make it easier to give a better review that way. / Hej och välkommen, lägg gärna till en beskrivning om vad din kod gör. Det blir lättare att förstå din kod och ge en bra review då. (Lucky for you I'm Swedish!) \$\endgroup\$ – Simon Forsberg Feb 2 '14 at 13:41
  • \$\begingroup\$ Information to provide can be: Is it a platform game? Is it a strategy game? What does the bunny have to do with anything? \$\endgroup\$ – Simon Forsberg Feb 2 '14 at 13:42
  • 1
    \$\begingroup\$ It's a simple game with the player being a blitted fox 40x40 pixels which when hovering over the rabbits that are also 40x40 blits dissappear and respawn over a period of some amount of time and when all the rabbits have been "eaten" it will stop the game essentially. The rabbits also spawn randomly on screen each time. First the start game screen comes up, then the difficulty screen and then the actual game where the things i said previous to this sentance exist. (And yes I'm swedish too!, but sticking to English.) \$\endgroup\$ – alsetalokin Feb 2 '14 at 14:03
  • \$\begingroup\$ Guess you can say it's a 2d game? \$\endgroup\$ – alsetalokin Feb 2 '14 at 14:14
  • 1
    \$\begingroup\$ Could you make the assets available for download, so that we can try playing the game? \$\endgroup\$ – Gareth Rees Feb 2 '14 at 16:40
2
\$\begingroup\$

I haven't played your game and I haven't understood much of the code but here are a few comments.

A few things are not quite pythonic. You can make your code go through some automatic checks with pep8online (PEP8 is the Style Guide for Python Code) and pylint. Among the things that could be applied to your code :

Don't compare boolean values to True or False using ==

For sequences, (strings, lists, tuples), use the fact that empty sequences are false.


I have troubles understanding the point of startSoundLevelOne in :

startSoundLevelOne = True
while levelOne == True:
    while startSoundLevelOne == True:
        rabbitSound.play()
        foxSound.play()
        pygame.mixer.music.play()
        startSoundLevelOne = False

Same thing applies to menuMusic.


You should try to avoid magic numbers.


Your code does not take into account that when something is moving up, it is not also moving down (and the same thing for left/right). It might make things easier for you to track if instead of move<Right/Left/Up/Down>, you had a variable for vertical move moveVert taking values -1, 0 and 1 (or anything else you fancy) for up/none/down and the same kind of thing for horizontal move. This could also be a single variable altogether.

\$\endgroup\$
  • \$\begingroup\$ Well I reformatted all the coding to PEP-8 styling. Removed all the useless styleSoundLevelOne and menuMusic. Haven't tried to make the magic numbers less used in the coding because I'm not really sure how to do that. Gonna try to change the movement variables. \$\endgroup\$ – alsetalokin Feb 3 '14 at 17:31
  • \$\begingroup\$ Can you recommend some good programming text editors? I'm using IDLE for using the Python Shell and Notepad++ for editing the code. Maybe some editor with built-in debugging perhaps? \$\endgroup\$ – alsetalokin Feb 3 '14 at 17:35
  • \$\begingroup\$ Nothing special to recommend. Notepad++ is good enough as far as I can tell. \$\endgroup\$ – SylvainD Feb 4 '14 at 8:38

Not the answer you're looking for? Browse other questions tagged or ask your own question.