在Pygame中使用类

时间:2016-02-26 03:01:57

标签: python class pygame

好的,所以我开始玩pygame了。但是我遇到了问题。我试图以某种方式提高我的代码,使其有条理,所以我决定在这里使用类。它看起来像这样:

import pygame
from pygame.locals import *
import sys

pygame.init()

class MainWindow:
    def __init__(self, width, height):
        self.width=width
        self.height=height
        self.display=pygame.display.set_mode((self.width,self.height))
        pygame.display.set_caption("Caption")
    def background(self)
        img = pygame.image.load("image.png")
        self.display.blit(img, (0,0))            

mainWindow = MainWindow(800,600)

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.exit()
            sys.exit()
        mainWindow.background()
    pygame.display.update()

好的,有效。但是,如果我想要,例如用白色填充窗户?然后我必须定义一个方法fill(),它只是self.display.fill(),对吧?有没有办法,正常处理它,而不是在我的班级中定义数百个已经存在pygame的方法?

还有一件事。如果我通过使用我的课程来做某事,而且我搞砸了,我总是得到这个消息:

  File "C:/Python35/game.py", line 23, in <module>
    pygame.display.update()
pygame.error

而我实际上并不知道什么是错的。如果我通常这样做,没有课程,那么我会得到诸如pygame object blabla has no method blablabla之类的错误,或者类似的东西,我只知道发生了什么。有没有办法解决这个问题,并找到发生了什么?

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:5)

你在这里所做的是在正确的轨道上,但它是以错误的方式完成的。你的主要“游戏循环”应该在类本身内部作为方法,而不是在实际循环中从类外部调用东西。以下是您应该做的事情的基本示例。

#Load and initialize Modules here
import pygame
pygame.init()

#Window Information
displayw = 800
displayh = 600
window = pygame.display.set_mode((displayw,displayh))

#Clock
windowclock = pygame.time.Clock()

#Load other things such as images and sound files here
image = pygame.image.load("foo.png").convert #Use conver_alpha() for images with transparency

#Main Class
class MainRun(object):
    def __init__(self,displayw,displayh):
        self.dw = displayw
        self.dh = displayh
        self.Main()

    def Main(self):
        #Put all variables up here
        stopped = False

        while stopped == False:
            window.fill((255,255,255)) #Tuple for filling display... Current is white

            #Event Tasking
            #Add all your event tasking things here
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    quit()
                elif event.type == pygame.KEYDOWN:
                    stopped = True

            #Add things like player updates here
            #Also things like score updates or drawing additional items
            #Remember things on top get done first so they will update in the order yours is set at

            #Remember to update your clock and display at the end
            pygame.display.update()
            windowclock.tick(60)

        #If you need to reset variables here
        #This includes things like score resets

    #After your main loop throw in extra things such as a main menu or a pause menu
    #Make sure you throw them in your main loop somewhere where they can be activated by the user

#All player classes and object classes should be made outside of the main class and called inside the class
#The end of your code should look something like this
if __name__ == __main__:
    MainRun()

主循环将在创建对象MainRun()时调用自身。

如果您需要更多关于对象处理等具体事项的示例,请告诉我,我会看看是否可以为您提供更多信息。

我希望这可以帮助您完成编程并祝您好运。

=========================编辑===================== ===========

在这种情况下,这些特殊操作使它们对象特定。而不是使用一个通用方法来blit你的对象,使每个对象都有自己的功能。这样做是为了允许您为每个对象提供更多选项。代码的一般想法如下......我在这里创建了一个简单的播放器对象。

#Simple player object
class Player(object):
    def __init__(self,x,y,image):
        self.x = x
        self.y = y
        self.image = image

    #Method to draw object
    def draw(self):
        window.blit(self.image,(self.x,self.y))

    #Method to move object (special input of speedx and speedy)
    def move(self,speedx,speedy):
        self.x += speedx
        self.y += speedy

现在,您可以使用对象的方法...我已经包含了一个事件循环来帮助演示如何使用move函数。只需将此代码添加到您需要的主循环中,您就可以全部设置。

#Creating a player object
player = Player(0,0,playerimage)

#When you want to draw the player object use its draw() method
player.draw()

#Same for moving the player object
#I have included an event loop to show an example
#I used the arrow keys in this case
speedx = 0
speedy = 0

for event in pygame.event.get():
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_UP:
            speedy = -5
            speedx = 0
        elif event.key == pygame.K_DOWN:
            speedy = 5
            speedx = 0
        elif event.key == pygame.K_RIGHT:
            speedy = 0
            speedx = 5
        elif event.key == pygame.K_LEFT:
            speedy = 0
            speedx = -5
    elif event.type == pygame.KEYUP:
        speedx = 0
        speedy = 0

#Now after you event loop in your object updates section do...
player.move(speedx,speedy)
#And be sure to redraw your player
player.draw()

#The same idea goes for other objects such as obstacles or even scrolling backgrounds

请务必在绘图功能中使用相同的显示名称。