Code to generate grids/patterns (plus an example of a grid-based game)

I wanted to share some Javascript code that can be used to generate a grid, like this:
1-basic
There are many ways to use grids in various projects. I’ll include an example of a grid-based game further down. This code can also be used to generated any kind of evenly-spaced objects, for patterns and such. For now, here is the basic project just focused on the code:
grid-generator.wick (2.1 KB)
Some notes for using this code:

  • The most essential parts of the code (only a few lines)
Notes

This code generates a grid by cloning a clip. In this case, the clip is named tile. When adapting this into your own project, you need to make sure to replace all instances of “tile” in the code with the name of clip you’ll be using (or you could just name your clip tile).

The only other lines of code you will probably change in most projects are these four, which are all located at the top of the script:

startX = 100; //set how far left grid starts
startY = 0; //set how far down grid starts
totalRows = 4; //set number of rows
totalCols = 4; //set number of columns

The startX and startY variables determine where the top leftmost cell of your grid starts (all other grid squares expand right and downwards from it). You can change the numbers to change the overall position of your grid.

  • Tips for creating different grid types (or patterns)
Notes

Your “tile” clip can be any kind of shape or image. For grids, you’d probably want to use a square tile, but rectangles could also function just as well:
2-diffshapes
I also included a line of code to demonstrate grid cells having different appearances from each other:

gridCellsArray[i].gotoAndStop(random.integer(1, 3));

By default this code is commented out. Uncommenting it will tell each cell to stop on a random frame. In this case, the tile has three frames, each with a different color, so the result will be something like this:
3-diffcolors

When creating patterns rather than grids, you will probably want to add some amount of spacing in-between objects. By default, these two lines of code determine the spacing between objects.

startX+=tile.width;
startY+=tile.height;

Since this code is designed for a grid, the result is tiles that are lined up side by side with no spacing. But if you were to increase tile.width and tile.height to larger values (by multiplying them, for example), you’d be increasing the distance between objects, and you’d be left with gaps as a result. For example, by multiplying both values by 2, like this:

startX+=tile.width*2;
startY+=tile.height*2;

You’d get this result:
gaps

Lastly, I wanted to provide an example of how this code could be adapted into a game, so here’s a little project I came up with:
grid-game.wick (5.8 KB)
dog grid game

5 Likes