Python/pygame镜像找不到同一个文件夹



你好,我是Python/pygame的新手,并尝试制作一个基本项目。 结果没有按计划进行,因为我不明白这个错误,如果你能告诉我为什么我的图像没有加载,它将不胜感激。 Traceback (most recent call last): File "C:UsersNicolasDesktoptemplatetemplat.py", line 15, in <module> screen.fill(background_colour) NameError: name 'background_colour' is not defined

这是我所说的错误,但是我已经修复了。 现在屏幕打开显示背景并崩溃。

   import pygame, sys
pygame.init()

def game():
 background_colour = (255,255,255)
(width, height) = (800, 600)
screen = pygame.display.set_mode((width, height))

pygame.display.set_caption('Tutorial 1')
pygame.display.set_icon(pygame.image.load('baller.jpg'))
background=pygame.image.load('path.png')
target = pygame.image.load('Player.png')
targetpos =target.get_rect()

screen.blit(target,targetpos)
screen.blit(background,(0,0))
pygame.display.update()
while True:
  screen.blit(background,(0,0))
  screen.blit(target,targetpos)

running = True
while running:
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      running = False
      if__name__==('__main__')
  game()

你错过了__init__定义!

虽然你的代码确实在运行,但它不是你想要的。在类的定义中有一个无限循环,这意味着,无论你运行它,都缺少一些东西。您应该将此代码(至少大部分代码)放在 __init__ 函数中,然后创建该类的实例。

这就是我假设你想要的:

import pygame, sys
class game():
    width, height = 600,400
    def __init__(self):
        ball_filename = "Ball.png"
        path_filename = "path.png"
        self.screen = pygame.display.set_mode((self.width, self.height))
        pygame.display.set_caption('Star catcher')
        self.background = pygame.image.load(path_filename)
        self.screen.blit(self.background,(0,0))
        self.target = pygame.image.load(ball_filename)
    def run(self):
        while True:
            self.screen.blit(self.background, (0,0))
            targetpos = self.target.get_rect()
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
if __name__ == "__main__":
    # To run this
    pygame.init()
    g = game()
    g.run()

更新:

我做了比你必须做的更多的修改,但它们可能很有用。我没有测试这个,但应该没问题。

未定义宽度和高度的错误是因为它们不是局部/全局变量,而是绑定到类和/或类的实例,因此在其命名空间中。因此,您需要通过game.width(每个类)或self.width(每个实例,仅在类中定义的方法内)或g.width(每个实例,如果您在类定义之外并且g是游戏类的实例)访问它们。

我希望我清楚。:)

相关内容