python / pygame图像无法找到相同的文件夹

时间:2012-06-13 21:11:36

标签: python pygame

你好我是python / pygame的新手,并尝试制作一个基本项目。它没有按计划进行,因为我不明白这个错误,如果你能告诉我为什么我的图像没有加载它将非常感激。 Traceback (most recent call last): File "C:\Users\Nicolas\Desktop\template\templat.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()

1 个答案:

答案 0 :(得分:1)

您错过了__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是游戏类的实例。)

我希望我很清楚。 :)