Hi, here's a little code I wrote to generate random room names, but it gives me the following error:
-
Cannot read property "controller" of undefined, the code is the following:
function getRandomInt(max) { return Math.floor(Math.random() * Math.floor(max)); } function getRoomName(NameOfTheRoom){ let Yletter = 'S'; let Ycoord; let Xletter = 'E'; let Xcoord; let roomDescomposed; let numY = NameOfTheRoom.split("S"); if(numY.length == 1){ Yletter = 'N'; numY = NameOfTheRoom.split("N"); } let numX = numY[0].split('E'); if(numX.length == 1){ Xletter = 'W'; numX = numY[0].split("W"); } Ycoord = numY[1]; Xcoord = numX[1]; roomDescomposed = [Xletter, Xcoord, Yletter, Ycoord]; return roomDescomposed; } function getRandomRoom(roomArray, limit){ let newRoom = roomArray; if(getRandomInt(2) == 0){ newRoom[1] = Number(roomArray[1])+getRandomInt(limit + 1); newRoom[3] = Number(roomArray[3])+getRandomInt(limit + 1); } else{ newRoom[1] = Number(roomArray[1])-getRandomInt(limit + 1); newRoom[3] = Number(roomArray[3])-getRandomInt(limit + 1); } if(newRoom[1] < 0){ newRoom[1] = Math.abs(newRoom[1]); if(newRoom[0] == 'E'){ newRoom[0] = 'W'; } else{ newRoom[0] = 'E'; } } if(newRoom[3] < 0){ newRoom[3] = Math.abs(newRoom[3]); if(newRoom[2] == 'N'){ newRoom[2] = 'S'; } else{ newRoom[2] = 'N'; } } newRoom = (newRoom[0]+newRoom[1]+newRoom[2]+newRoom[3]).toString(); console.log(newRoom); //here it returns the name of the room correctly v(·_·)v if(Game.rooms[newRoom].controller.reservation.my || Game.rooms[newRoom].controller.my){ newRoom = undefined; } return newRoom; } creep.memory.MyRoom = getRoomName(creep.room.name); if(creep.memory.target == undefined || creep.memory.target == creep.memory.MyRoom){ creep.memory.target = getRandomRoom(creep.memory.MyRoom, 3);
-
Game.rooms only contains rooms visible to your code and a room is visible to your code if you have a creep or an owned structure in it (or ran observeRoom on it with an observer the previous tick).
So you'll need to add another check to your if statement to see if Game.rooms[newRoom] exists before using Game.rooms[newRoom].controller.
Additionally, some rooms don't have controllers so you should also check if the controller exists before using that too.
-
Additionally, owned rooms and unreserved rooms doesn't have
controller.reservation
.
-
thanks everyone, I forgot that silly thing. Problem solved
-
@charlycreeper charly, If the question has been answered, consider marking the topic as resolved.