We are about to switch to a new forum software. Until then we have removed the registration on this forum.
So if I did code like this. I would want to use a .txt file instead of declaring worldGrid.
The txt file would be
1,1,1,1,1,1,1,1,1,1
1,0,0,0,0,0,0,0,0,0 ect.
How would I need to lay things out to do this?
int GRID_TILE_WIDTH=48;
int [][] worldGrid={
{1,1,1,1,1,1,1,1,1,1},
{1,0,0,0,0,0,0,0,0,1},
{1,0,1,1,1,1,0,1,0,1},
{1,0,1,0,1,0,0,1,0,1},
{1,0,0,0,1,0,0,1,0,1},
{1,1,1,0,1,0,1,1,1,1},
{1,0,0,0,0,0,0,0,0,1},
{1,0,1,1,0,1,0,1,0,1},
{1,0,0,1,0,1,0,1,0,1},
{1,1,1,1,1,1,1,1,1,1}
};
int pCol=8,pRow=1;
void setup()
{
size(GRID_TILE_WIDTH*10,GRID_TILE_WIDTH*10);
}
void draw()
{
worldDrawGrid();
}
void worldDrawGrid()
{
for(int row=0;row<worldGrid.length; row++)
{
for(int col=0;col<worldGrid[row].length; col++)
{
if(worldGrid[row][col]==1)
{
fill(0);
rect(col*GRID_TILE_WIDTH,row*GRID_TILE_WIDTH,GRID_TILE_WIDTH,GRID_TILE_WIDTH);
}else
{
fill(255);
rect(col*GRID_TILE_WIDTH,row*GRID_TILE_WIDTH,GRID_TILE_WIDTH,GRID_TILE_WIDTH);
}
}
}
}
Answers
loadStrings, split.
or Table.
all in the reference.
koogs, our answers tend to get shorter with the time...
;-)
sometimes people just need to know what methods exist and the reference examples are enough to get them rolling. if not they'll ask follow up questions. this one, for instance, has done all the hard work of the display code, just wants the data from a file rather than an array.
and the Common Questions links are there to be used - i am fed up of answering the same 'how can i display something for n seconds' / 'click on a button' / 'ball doesn't bounce' type questions four times a week...
I fully agree.
I understand that, and I'm sorry the problem I run into is that I use worldgrid to load the text file is that it says it can't load a int [][] as a String []. I also don't to have it read as the row and col.
given your file is actually a csv (comma separated values) file perhaps Table is a better bet? you can tell it that each column is an int and it'll read it as an int...
or, my preference, is to use a png where each block is a single pixel...
your grid array doesn't need to be an int[][], a 2d array of anything will do as long as you can differentiate between the blocks and non blocks.
you wrote:
can you show your code?
This is usually done by for looping over the lines and for each line use
split()
and for loop over the result of that (each comma separated value inside the line) to fill int [][] from String [].Here is a simple example of a function,
tableToArray
, which loads a csv into a Table of ints and copies the Table into an array.The sketch also writes a 2D printout of the (identical) contents of the Table and the array.
This can be made much more concise -- but it demonstrates the concepts.
Output (twice):