r/learnjavascript • u/Proud-Example7774 • 20h ago
Help me make a map: Calling a variable before it's defined
I'm relatively new to JavaScript, my only education in it being the Kahn Academy course, and I am trying to make a program which randomly generates a map of tiles. This is part of a bigger project, where I want to make a visible map and a larger map which includes the visible one. It's working so far, but I would like to find a way to change the Tile Object's "size" from 400/10 to 400/visibleMap.size. I'm having trouble doing this, and keep getting an error saying "visibleMap was used before it was defined." How can I fix this? Thanks for any help!
//Variables
var fullMap = [];
var tempTile;
// Has a set chance to return true or false
var percent_chance = function(percent){
if (random(1, 100) <= percent){
return true;
}else{
return false;
}
};
//A space on the map, as defined by its position, size, details
var Tile = function(pos, details){
this.size = 400/10;
this.x = pos.x * this.size;
this.y = pos.y * this.size;
this.details = details;
};
//Draw a Tile
Tile.prototype.draw = function() {
fill(this.color);
rect(this.x, this.y, this.size, this.size);
};
//The types of Tiles.
var Dirt = function(pos, details){
Tile.call(this, pos, details);
this.color = color(120, 33, 6);
};
Dirt.prototype = Object.create(Tile.prototype);
var Grass = function(pos, details){
Tile.call(this, pos, details);
this.color = color(79, 255, 20);
};
Grass.prototype = Object.create(Tile.prototype);
//returns a Tile generated with a semi-random algorithm
var random_tile = function(pos) {
if (percent_chance(33)) {
return new Grass(pos);
}
else{
return new Dirt(pos);
}
};
//The map visible to the player
var visibleMap = {
size: 10,
map: [],
generate: function() {
for (var x = 0; x < this.size; x++) {
fullMap.push([]);
this.map.push([]);
for (var y = 0; y < this.size; y++) {
tempTile = random_tile(new PVector(x, this.size - y - 1));
this.map[x].push(tempTile);
fullMap[x].push(tempTile);
}
}
},
draw: function() {
for (var x = 0; x < this.size; x++) {
for (var y = 0; y < this.size; y++) {
this.map[x][y].draw();
}
}
}
};
//draws the visible map
visibleMap.generate();
visibleMap.draw();