Je suis actuellement en train d'étendre mes compétences python en programmant un niveau de donjon généré au niveau de la procédure au format texte. Je suis confus quant à savoir pourquoi mes "intersects" définir ne fonctionne pas. Voici la classe contenant la définition:Python - NameError: name '' n'est pas défini
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
Voici où il est appelé:
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)
retraçage complète:
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
J'espère que quelqu'un peut me aider à comprendre pourquoi ce code a gagné » t travail, merci.
J'ai réussi à résoudre le problème. Je suis désolé si ma question n'était pas très bien définie. J'ai seulement appris Python pendant environ 4 semaines et je suis habitué à Java qui a une syntaxe très différente. Voici ma solution:
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
Pouvez-vous s'il vous plaît inclure le retraçage dans votre poste? –
Que voulez-vous * (ou attendre) toutes vos définitions 'global' à faire? –
En outre, cela devrait vraiment être réduit à un MCVE. Sûrement le problème peut être reproduit avec moins de code. –