Game Development Reference
In-Depth Information
Using a Grid in a Game
If you ever end up creating a simple board game, you will realize that the game is basically a grid
made up of squares that hold items. This example will look at this type of organization. For simplicity's
sake, each square on the board shall hold only one piece per slot on the board.
local board={} -- Note that this is a single-dimension array only
local i,j
local boardW, boardH=5,5.. -- A 5x5 board
for i=1,boardH do
board[i]={}
for j=1,boardW do
board[i][j]=0 -- Initialize it to nothing; i.e., 0
end
× 5 board that can hold the tiles. Let's fill the board with some item (i.e., a
={} -- Note that this is a single-dimension array only
=5,5 -- A 5x5 board
=1,boardH do
board[i]={} -- Now we create the second dimension for the array
for j=1,boardW do
board[i][j]=0 -- Initialize it to nothing; i.e., 0
end
end
for i=1,7 do -- Let's place 7 items randomly in some of the 25 slots
local xCo, yCo=math.random(1,boardW), math.random(1,boardH)
board[yCo][xCo]=1
end
for i=1,boardH do
for j=1,boardW do
print(i, j, board[i][j])
end
end
We can see which of the squares are randomly filled.
Snakes and Ladders
You very likely played this game as a child. It consists of a 10 × 10-square board with some ladders
and some snakes drawn on the board. You roll the dice and move the number of squares you rolled.
If you land on a square that has the top of a ladder, you move to the square that has the bottom of
the ladder, and if you land on a snake, you move to the tail of the snake (see Figures 4-1 and 4-2 ).
 
Search WWH ::




Custom Search