我不知道我做错了什么。打开pygame窗口的代码

问题描述 投票:-1回答:1
import pygame
import sys
from pygame.locals import *


DISPLAY_SURF = pygame.display.set_mode((640,480))
#Sets the resolution to 640 pixels by 720 pixels

class Game:
    def __init__(self):
        pygame.init()
        self.FPS = 60
        self.fps_clock = pygame.time.Clock()
        self.surface = pygame.display.set_mode((640, 480))
        pygame.display.set_caption("The Hunt")
        img = pygame.image.load("Graphics/background.png")
        self.surface.blit(img)
        #This class sets the basic attributes for the window.
        #The clock is set to 60 and the name of the window
        #is set to The Hunt which is a working title for my project


    def run(self):
        while True:
            pygame.display.update()
            self.fps_clock.tick(self.FPS)
            self.process_game()

            #This updates the window display to refresh every clock tick


    def process_game(self):
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()


game = Game()
#This creates an instance of the class Game which gives all the attributes
#  and behaviours to this instance
game.run()
#Calling this function generates a window with the attributes defined.

我需要一些帮助。我已经检查过它是否在同一个文件夹中,该文件肯定是一个png,我正确地拼写了所有文件夹名称和目的地。我愿意接受任何建议

python image python-3.x background window
1个回答
0
投票

我将回答这个问题,尽管它对Stack Overflow来说并不是一个好问题。在这个网站上,你必须更具体和详细,因为没有人打算为你阅读大量的代码。然而,我确实提到了一些我认为可以修复的东西(其中一些是基于意见的,你的问题永远不会强迫答案),但是......这里无论如何:

对于初学者,当你构造一个类时,你在类名后面使用括号,即使它不会从另一个类继承任何东西。因此,将构建Game类的行更改为:

class Game():

关于这段代码的第二件事是,如果你要在Game()类中创建pygame窗口表面,我不明白你为什么要在代码的开头创建另一个窗口。如果有这个原因,请在代码中的注释中解释。

最后一件事是基于意见的。我不知道有多少人像这样创建Pygame GUI应用程序,但是不使用类会更简单,这样你就可以更好地理解代码。当我创建一个Pygame GUI时,我定义了窗口,然后定义了精灵,然后我在While循环中运行主游戏循环。以下是我通常如何构建您的程序:

#import pygame
import pygame, sys
from pygame.locals import *

#Initialize pygame and define colours
pygame.init()
white = 255,255,255

#Sets the resolution to 640 pixels by 720 pixels and caption for pygame window
DISPLAY_SURF = pygame.display.set_mode((640,480))
pygame.display.set_caption("The Hunt!")

#Create a clock object
clock = pygame.time.Clock()
FPS = 60

#Define a variable to refer to image
image = pygame.image.load("download.jpg")

#Start main loop
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    DISPLAY_SURF.fill(white)
    DISPLAY_SURF.blit(image,(0,0))
    pygame.display.update()

我在创建精灵时使用了类,所以我可以创建它的几个实例,以及将我想要在精灵上执行的函数保存在一个地方。为WHOLE程序执行此操作确实有效,并且我认为它更“pythonic”(因为python是面向对象的)但对于类似的东西仍然是不必要的。以下是teaches pygame in a similar way to how I code it的参考资料,我个人觉得这是一个很好的教程。

许多人还将此代码放在main()函数中然后运行它,这也是一种广泛使用和接受的实践。

© www.soinside.com 2019 - 2024. All rights reserved.