Search code examples
multidimensional-arraygame-enginegame-maker-studio-2

2d array gamemaker2 studio


Experienced programmer playing around with Gamemaker2 Studio.

Trying to draw some random squares on the screen using a 2D array to store the "map"

Step 1 : declare a 2D array MyMap[25,25] this works

Step 2 : Set 100 random locations in Map[]=1 this works

I get a crash when I try to look up the values I have stored in the array.

Its crashing with: **Execution Error - Variable Index [3,14] out of range [26,14] **

So it looks like it is trying to read 26 element, when you can see from my code the for next loop only goes to 20 and the array bound is 25.

Oddly enough it does the first two loops just fine?

Looking like a bug, I've spent so much time trying to work it out, anyone got an idea what is going on?

var tx=0;
var ty=0;
var t=0;

MyMap[25,25]=99;                         **// Works**

for( t=1; t<100; t+=1 )                  **// Works** 
{
    MyMap[random(20),random(15)]=1
}


for( tx=1; tx<20; tx+=1 )
{
  for( ty=1; ty<15; ty+=1 )     
  { 
  show_debug_message(string(tx) + ":" + string(ty))
  t = MyMap[tx,ty];  ///  **<---- Crashes Here**
  if t=1 then {draw_rectangle(tx*32,ty*32,tx*32+32,ty*32+32,false) }
  }
}

Solution

  • The line MyMap[random(20),random(15)]=1 does not initialize values in the entire array, creating a sparse array(where some elements do not exist).

    The line MyMap[25,25]=99; Should read:

    for( tx=1; tx<20; tx+=1 )
    {
      for( ty=1; ty<15; ty+=1 )     
      {
        MyMap[tx,ty]=99;
      }
    }
    

    This will pre-initialize the all of the array values to 99. Filling out the array.

    Then you can randomly assign the ones. (You will probably get less than 100 ones the due to duplicates in the random function and the random returning zeros.)

    You should have the above code in the Create Event, or in another single fire or controlled fire event, and move the loops for the draw into the Draw Event.

    All draw calls should be in the Draw Event. If the entire block were in Draw, it would randomize the blocks each step.