【发布时间】:2015-10-23 20:20:10
【问题描述】:
我目前正在通过以文本格式编写程序生成的地牢关卡来扩展 Python 技能。我对为什么我的“相交”定义不起作用感到困惑。这是包含 def 的类:
class Room:
global x1
global x2
global y1
global y2
global w
global h
global centre
def __init__(self,x,y,w,h):
x1 = x
x2 = x + w
y1 = y
y2 = y + h
self.x = x
self.y = y
self.w = w
self.h = h
centre = math.floor((x1 + x2) / 2),math.floor((y1 + y2) / 2)
#function that checks if the rooms intersect by comparing corner pins relative to the x,y tile map
def intersects(self,room):
if x1 <= room.x2 and x2 >= room.x1 and y1 <= room.y2 and room.y2 >= room.y1:
return True
return False
这里是它的名字:
def placeRooms(r):
rooms = []
#Where the room data is stored
for r in range(0,r):
w = minRoomSize + randint(minRoomSize,maxRoomSize)
h = minRoomSize + randint(minRoomSize,maxRoomSize)
x = randint(1,map_width - w - 1) + 1
y = randint(1,map_height - h - 1) + 1
newRoom = Room(x,y,w,h)
failed = False
#for every room generated, this function checks if new room intersects with the last one
for otherRoom in rooms:
if newRoom.intersects(otherRoom):
failed = True
break
if failed == False:
createRoom(newRoom)
rooms.append(newRoom)
完整的追溯:
Traceback (most recent call last):
File "C:\Users\Max\Desktop\LiClipse Workspace\testing\RandomDungeon.py", line 78, in <module>
placeRooms(2)
File "C:\Users\Max\Desktop\LiClipse Workspace\testing\RandomDungeon.py", line 65, in placeRooms
if newRoom.intersects(otherRoom):
File "C:\Users\Max\Desktop\LiClipse Workspace\testing\RandomDungeon.py", line 41, in intersects
if x1 <= room.x2 and x2 >= room.x1 and y1 <= room.y2 and room.y2 >= room.y1:
NameError: name 'x1' is not defined
我希望有人能帮助我理解为什么这段代码不起作用,谢谢。
我已经设法解决了这个问题。如果我的问题没有很好地定义,我很抱歉。我只学习了大约 4 周的 Python,而且我已经习惯了 Java,它的语法非常不同。这是我的解决方案:
def __init__(self,x,y,w,h):
self.x1 = x
self.x2 = x + w
self.y1 = y
self.y2 = y + h
self.x = x
self.y = y
self.w = w
self.h = h
【问题讨论】:
-
您能否在您的帖子中包含完整的追溯信息?
-
你想要(或期望)你所有的
global定义做什么? -
您应该将关键字
global的任何实例视为代码中的错误。 -
你一直用那个
globalkeyword,我不认为它意味着你认为它的意思。 -
我包含了完整的回溯。 @MorganThrapp
标签: python class undefined nameerror function