在Pygame中使用类

min*_*234 1 python pygame class

好的,所以我开始玩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()
Run Code Online (Sandbox Code Playgroud)

好吧,工作。但是,如果我想例如用白色填充窗户怎么办?然后,我必须定义一个方法fill(),这将只是self.display.fill(),对不对?有没有一种方法可以正常处理它,而无需在我的课程中定义数百个pygame已经存在的方法?

还有另一件事。如果我通过使用我的课程来做某事并且搞砸了,那么我总是会得到以下消息:

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

而且我实际上不知道到底是怎么了。如果我正常地这样做,没有上课,那么我就会遇到 pygame object blabla has no method blablabla诸如此类的错误,我只知道发生了什么。有没有办法解决这个问题,并找出正在发生的事情?

在此先感谢您的帮助!

Tac*_*e11 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()
Run Code Online (Sandbox Code Playgroud)

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

如果您需要有关特定事物(例如对象处理)的更多示例,请告诉我,我会看看是否可以为您提供更多信息。

希望这对您的编程有所帮助,并祝您好运。

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

在这种情况下,对于这些特殊操作,使其成为特定于对象的。不要使用一种通用方法来泛化对象,而是使每个对象都有其自己的功能。这样做是为了为您制作的每个对象提供更多选项。代码的一般思路如下...我在这里创建了一个简单的播放器对象。

#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
Run Code Online (Sandbox Code Playgroud)

现在这是您使用对象的方法的方式...我包括一个事件循环,以帮助显示如何使用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
Run Code Online (Sandbox Code Playgroud)

确保在绘图功能中使用与显示器相同的显示名称。