-
Notifications
You must be signed in to change notification settings - Fork 2
/
grid.lua
109 lines (91 loc) · 2.26 KB
/
grid.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
local gridSquareFunctions = {
left = function(gridSquare)
if gridSquare.x == 0 then
return gridSquare
else
return gridSquare.grid[gridSquare.y][gridSquare.x - 1]
end
end,
right = function(gridSquare)
if gridSquare.x + 1 == gridSquare.grid.xSquares then
return gridSquare
else
return gridSquare.grid[gridSquare.y][gridSquare.x + 1]
end
end,
above = function(gridSquare)
if gridSquare.y == 0 then
return gridSquare
else
return gridSquare.grid[gridSquare.y - 1][gridSquare.x]
end
end,
below = function(gridSquare)
if gridSquare.y + 1 == gridSquare.grid.ySquares then
return gridSquare
else
return gridSquare.grid[gridSquare.y + 1][gridSquare.x]
end
end,
}
local gridFunctions = {
eachSquare = function(grid, doEach)
for y = 0, grid.ySquares - 1 do
for x = 0, grid.xSquares - 1 do
doEach(grid[y][x])
end
end
return grid
end,
setLocation = function(grid, x, y)
grid.displayGroup.x = x
grid.displayGroup.y = y
return grid
end,
show = function(grid)
grid.displayGroup.isVisible = true
end,
hide = function(grid)
grid.displayGroup.isVisible = false
end,
}
local Grid = {}
Grid.newGridRow = function(y)
return { y = y }
end
Grid.newGridSquare = function(grid, y, x)
local gridSquare = {}
gridSquare.y = y
gridSquare.x = x
local square = display.newRect(grid.displayGroup,
grid.squareSize * x, grid.squareSize * y,
grid.squareSize, grid.squareSize)
gridSquare.displayObject = square
gridSquare.left = gridSquareFunctions.left
gridSquare.right = gridSquareFunctions.right
gridSquare.above = gridSquareFunctions.above
gridSquare.below = gridSquareFunctions.below
gridSquare.grid = grid
return gridSquare
end
Grid.newGrid = function(xSquares, ySquares, totalWidth)
-- Initialize the grid object
local grid = {}
grid.xSquares = xSquares
grid.ySquares = ySquares
grid.totalWidth = totalWidth
grid.squareSize = totalWidth / xSquares
grid.displayGroup = display.newGroup()
for y = 0, ySquares - 1 do
grid[y] = Grid.newGridRow(y)
for x = 0, xSquares - 1 do
grid[y][x] = Grid.newGridSquare(grid, y, x)
end
end
grid.eachSquare = gridFunctions.eachSquare
grid.setLocation = gridFunctions.setLocation
grid.show = gridFunctions.show
grid.hide = gridFunctions.hide
return grid
end
return Grid