OOP(面向对象的编程)困境



所以我需要一些建议/帮助,以使该代码/程序更加OOP(面向对象的编程)。

我将在此处发布整个代码。我打算做单独的模块,但我真的是个菜鸟。

关于游戏的一些背景故事:这是一个带有首发游戏屏幕的游戏,然后是难度屏幕,然后是绵羊和狐狸(player)的级别的游戏,然后是2级,而不是兔子。还计划三种类型的敌人的第三级。

因此,任何帮助都得到赞赏,我只需要一些提示即可将此代码转换为面向对象的编码,这更容易阅读,并且不会对CPU造成太大的压力。

main.py文件上的更多进度:

# -*- coding: utf-8 -*-
#Så jag ska försöka göra koden objekt orienterad så man förstår bättre
#det är samt enklare att läsa.
import pygame, sys, random, math
from rabbits import Rabbit
from pigs import Pig
from boars import Boar
from pygame.locals import *
from threading import Timer
pygame.init()
pygame.mixer.init()
mainClock = pygame.time.Clock()
soundsDict = {"foxSound" : pygame.mixer.sound(sound/foxSound.wav), 
"rabbitSound" : pygame.mixer.Sound('sounds/rabbitSound.wav'), 
"pigSound" : pygame.mixer.Sound('sounds/pigSound.wav'), 
"boarSound" : pygame.mixer.Sound('sounds/boarSound.wav')}
musicDict = {"musicMenu" : pygame.mixer.Sound('music/Who Likes To Party.ogg')}
spriteDict = {"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'), 
"pigImage" : pygame.image.load('textures/Pig.png'), 
"pigImageTwo" : pygame.image.load('textures/Pig2.png'), 
"boarImage" : pygame.image.load('textures/Boar.png'), 
"boarImageTwo" : pygame.image.load('textures/Boar2.png')}
buttonDict = {"buttonEasyImage" : pygame.image.load('textures/buttonEasy.png'), 
"buttonNormalImage" : pygame.image.load('textures/buttonNormal.png'), 
"buttonHardImage" : pygame.image.load('textures/buttonHard.png')}

level = 1
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if level == 1:
            player.update()
            for rabbit in rabbits:
                rabbit.update()
        elif level == 2:
            player.update()
            for pig in pigs:
                pig.update()
    surface.fill((0, 0, 0))
    MOVE_SPEED = 0
    if level == 1:
        # Play level 2 music
        # Draw level 1 state to screen
        Player.update()
        Player.draw()
        for rabbit in rabbits:
            rabbit.draw(surface)
    elif level == 2: #I get a weird indentation error here*
        # Play level 2 music
        # Draw level 2 state to screen
        Player.update()
        Player.draw()
        for pig in pigs:
            pig.draw(surface)
        for boar in boars:
            boar.draw(surface)
    pygame.display.update()
    mainClock.tick(60)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~所以我取得了一些进步,只想想到您的意见可以说正确的方向。

这是player.py文件和boars.py文件(例如更新):

player.py
# -*- coding: utf-8 -*-
import pygame, sys, random, math
class Player(object):
    def __init__(self):
        self.moveRight = False
        self.moveLeft = False
        self.moveUp = False
        self.moveDown = False
    def process_event(event):
        if event.type == KEYDOWN:
            if event.key == K_SPACE:
                levelOne = False
            if event.key == K_LEFT:
                self.moveRight = False
                self.moveLeft = True
            if event.key == K_RIGHT:
                self.moveRight = True
                self.moveLeft = False
            if event.key == K_UP:
                self.moveDown = False
                self.moveUp = True
            if event.key == K_DOWN:
                self.moveDown = True
                self.moveUp = False
        if event.type == KEYUP:
            if event.key == K_LEFT:
                self.moveLeft = False
            if event.key == K_RIGHT:
                self.moveRight = False
            if event.key == K_UP:
                self.moveUp = False
            if event.key == K_DOWN:
                self.moveDown = False
    def update(self):
        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

    def draw(self, surface):
        windowSurface.blit(playerImage, player)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

boars.py
# -*- coding: utf-8 -*-
import pygame, sys, random, math
class Boar(object):
    boarCounter = 0
    NEW_BOAR = 40
    BOAR_SIZE = 64
    boars = []
        for i in range (10):
            boars.append(pygame.Rect(random.randint(0, WINDOW_WIDTH
            - BOAR_SIZE), random.randint (0, WINDOW_HEIGHT - BOAR_SIZE),
            BOAR_SIZE, BOAR_SIZE))
    def __init__(self):
        pass
    def update(self):
        stepMovementNegativeBoar = random.randrange(0, -6, -2)
        stepMovementPositiveBoar = random.randrange(0, 6, 2)
        boarMovement = [((stepMovementNegativeBoar),0), ((stepMovementPositiveBoar), 0)
                          , (0, (stepMovementNegativeBoar)), (0, (stepMovementPositiveBoar))]
        for boar in boars:
            boar.move_ip(*random.choice(boarMovement))
        for boar in boars[:]:
            if player.colliderect(boar):
                windowSurface.blit(boarImageTwo, boar)
                windowSurface.blit(playerImageTwo, player)
            def explosionBoar():
                for boar in boars:
                    if player.colliderect(boar) and (moveLeft == False and
            moveRight == False and moveUp == False and
            moveDown == False):
                         boars.remove(boar)
            if player.colliderect(boar) and (moveLeft == False and
            moveRight == False and moveUp == False and moveDown == False):
                #timer inställningar
                tBoar = Timer(10, explosionPig)
                tBoar.start()
    def draw(self, surface):
        boarCounter += 1
        if boarCounter >= NEW_BOAR:
            boarCounter = 0
            boars.append(pygame.Rect(random.randint(0, WINDOW_WIDTH
        - BOAR_SIZE), random.randint (0, WINDOW_HEIGHT - BOAR_SIZE),
        BOAR_SIZE, BOAR_SIZE))

让我们从文件开始。

您可以将代码分为包含特定代码的较小文件。例如,您可以拥有一个将显示菜单的文件主,并且在选择难度之后,它将创建一个游戏对象并启动游戏。

您可以拥有兔子,野猪等的类,这些课程将具有drawupdate方法,您可以在其更新方法中保持其行为。您也可以将类也保留在单独的文件中。

所有图像和声音都可以放入字典中。这样,您将避免有20个变量,而是将有1个变量,例如Sound_dict,其中包含诸如Fox,Rabbit等键。

您还可以拥有一个玩家类,该类别将具有与其他类相同的方法,也可以使用一种可以响应玩家输入的方法。我会沿着这些行做一些事情:

def process_event(event):
    if event.type == MOUSEDOWN:
       if event.key == K_LEFT:
           self.x -= MOVESPEED

这样,您可以在游戏中有1个事件循环,并调用所有需要处理它的必要对象。它将动作响应移至各个对象。

for event in pygame.event.get():
    player.process_event(event)

如果您的水平相似,但是有不同的敌人,则可能只有游戏循环,并且取决于水平,只需相应地准备要播放的水平即可。

如果敌人之间没有区别,则可以将它们保留在一个列表中。他们可以做出不同的反应,因为他们在更新方法中有不同的事情。

功能使代码更容易阅读,不要害怕使用太多。

编辑:

代码看起来好一些,但是您的播放器活动处理中有一些不必要的东西。玩家不应处理退出事件,这应该在主事件循环中完成。

而不是让一类Boars具有一类Boar,它将具有1个公猪的信息。野猪将有一个位置。截至目前,您在Draw功能中添加新板。您应该创建一次公猪列表,并在每个野猪上调用一个抽奖方法。

您有一个空的播放器__init__方法。由于播放器具有状态-Moveleft,因此您可以通过编写self.moveRight = False初始化它们。然后,事件处理将分配给trim.self.moveright。

最新更新