当我遇到一个我没有理解的错误时,我只是在python pygame中开始一个胭脂般的游戏。 这是代码:
Main.py
import pygame
import Textures
pygame.init()
Tiles_Size = 32
BLACK = (0, 0, 0)
def create_window():
global window
window = pygame.display.set_mode((800,600),pygame.HWSURFACE|pygame.DOUBLEBUF)
pygame.display.set_caption('RPG')
create_window()
isRunning = True
while isRunning:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a: #Switch to K_A rather than pygame.K_a
isRunning = False # for glitch! :)
window.fill(BLACK)
for x in range(0, 640, Tiles.Size):
for y in range(0, 480, Tiles.Size):
window.blit(Tiles.Wood, (x, y))
pygame.quit()
Textures.py
import pygame
pygame.init()
class Tiles:
Size = 32
def Load_Texture(file, Size):
bitmap = pygame.image.load(file)
bitmap = pygame.transform.scale(bitmap, (Size, Size))
surface = pygame.Surface((Size, Size), pygame.HWSURFACE|pygame.SRCALPHA)
surface.blit(bitmap, (0, 0))
return surface
Wood = Load_Texture("Graphics\\wood.jpg", Size)
这就是我拥有的所有代码,文件如下所示
Graphics
wood.jpg
main.py
textures.py
所以错误很奇怪。当我运行main.py
文件时,该错误相当奇怪。对于变量Tiles.Size
和Tiles.Wood
,它说Tiles
文件中的textures.py
类在很明显的地方没有定义!我被这种故障困扰了一段时间,然后放弃了。然后我再次查看它,但仍然找不到错误。错误是:
Traceback (most recent call last):
File "C:\Users\*********\Desktop\PygameRPG\Main.py", line 26, in <module>
for x in range(0, 640, Tiles.Size):
NameError: name 'Tiles' is not defined
那是我的错误。
一些帮助会很棒!
答案 0 :(得分:0)
您在main.py中导入了Textures.py,但是您忘了一些东西!如果您想这样做:
for x in range(0, 640, Tiles().Size):
您都不应该这样做:
from textures import *
也不将代码更改为此:
for x in range(0, 640, textures.Tiles().Size):
您还忘记了括号。现在,尝试这样的代码,它必须可以工作:
main.py:
import pygame
import textures
pygame.init()
Tiles_Size = 32
BLACK = (0, 0, 0)
def create_window():
global window
window = pygame.display.set_mode((800,600),pygame.HWSURFACE|pygame.DOUBLEBUF)
pygame.display.set_caption('RPG')
create_window()
isRunning = True
while isRunning:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a: #Switch to K_A rather than pygame.K_a
isRunning = False # for glitch! :)
window.fill(BLACK)
for x in range(0, 640, textures.TilesClass().Size):
for y in range(0, 480, textures.TilesClass().Size):
window.blit(textures.TilesClass().Wood, (x, y))
textures.py:
import pygame
pygame.init()
class TilesClass:
Size = 32
def Load_Texture(file, Size):
bitmap = pygame.image.load(file)
bitmap = pygame.transform.scale(bitmap, (Size, Size))
surface = pygame.Surface((Size, Size), pygame.HWSURFACE|pygame.SRCALPHA)
surface.blit(bitmap, (0, 0))
return surface
Wood = Load_Texture("Graphics\\wood.jpg", Size)