-2

Ok, so me and a friend are making a JS game together. It's a God Game kinda thing in which the user uses resources to build houses and other buildings. IT IS IN VERY EARLY DEVELOPMENT!

I use variables as grid references, so they can be set to a certain building. e.g.:

var OneOne = none

So the grid would look like this:

  • OneOne, OneTwo, OneThree
  • TwoOne, TwoTwo, TwoThree
  • ThreeOne, ThreeTwo, ThreeThree

My problem is somewhere in the building phase, I use a function called Build(type, loc) that is used for adding a building to the map. I do this with a switch statement that looks at the loc parameter and sets the corresponding grid reference to the value of the building. So if this.loc === OneOne, then OneOne = this.type.

The desired outcome of this script is to set OneOne to WoodHut.

In Theory, if you were to print off the grid line by line, having just done Build(WoodHut, OneOne), you should get something like:

  • WoodHut, none, none
  • none, none, none
  • none, none, none

But this will not work! I can't really figure out why this isn't working... The REAL outcome i get is:

  • none, none, none
  • none, none, none
  • none, none, none

Here is my source code: JS

And the HTML I use to run the script and the functions: HTML

Please have a read through them and spot my error! A hint or tutorial would be much appreciated. Thanks in advance!

nemesv
  • 138,284
  • 16
  • 416
  • 359
Corwen
  • 1
  • 3

1 Answers1

0
var OneOne = none;
var OneTwo = none;
var OneThree = none;
var OneFour = none;
var OneFive = none;

var TwoOne = none;
var TwoTwo = none;
var TwoThree = none;
var TwoFour = none;
var TwoFive = none;

var ThreeOne = none;
var ThreeTwo = none;
var ThreeThree = TownHall;
var ThreeFour = none;
var ThreeFive = none;

var FourOne = none;
var FourTwo = none;
var FourThree = none;
var FourFour = none;
var FourFive = none;

var FiveOne = none;
var FiveTwo = none;
var FiveThree = none;
var FiveFour = none;
var OneFive = none;

Don't do that. Use arrays instead. Below is a way to do this with an array of arrays; e.g. a matrix.

var tiles = [];
var rowCount = 5; // put as many as you like
var columnCount = 5; // put as many as you like

// Assign the none string to all tiles.
for (var r = 0; r < rowCount; r++)
{
    tiles[r] = [];
    for (var c = 0; c < columnCount; c++)
    {
        var currentRow = tiles[r];
        currentRow[c] = "--none--";
    }
}

// Now access FourTwo (row 4, column 2). Remember arrays are 0-based.
console.log(tiles[3][1]);

// Assign something to FiveThree
tiles[4][2] = "WoodHut"
Judah Gabriel Himango
  • 58,906
  • 38
  • 158
  • 212
  • You need to initialize `tiles[r] = []` as the first statement of your 'for (var r' loop. – HBP Jun 05 '13 at 18:03