Skip to main content
 首页 » 编程设计

python之在 Pygame 中使用类

2025年05月04日29lori

好的,所以我开始玩 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 已经存在的方法?

还有一件事。如果我使用我的类(class)做了一些事情,但我搞砸了,我总是会收到这个消息:

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

其实我也不知道到底哪里出了问题。如果我在没有类的情况下正常执行此操作,则会出现诸如 pygame object blabla has no method blablabla 之类的错误,我只知道发生了什么。有没有办法解决这个问题,并找出发生了什么?

预先感谢您的帮助!

请您参考如下方法:

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

# 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 convert_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() 时调用自身。

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

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

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

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

#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 

下面是如何使用该对象的方法...我包含了一个事件循环来帮助展示如何使用移动功能。只需将这段代码添加到您的主循环中需要的地方,一切就绪。

#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 

请务必在绘图函数中使用与显示相同的显示名称。