First I had to clean up your code lol:
Lua Code:
gridWidth = 9
gridHeight = 14
grid = {}
for i=1, gridWidth, 1 do
grid[i] = {}
end
function tappedRect(event)
if event.target.ship then
event.target.ship = true
event.target:setFillColor(255, 0, 0)
else
event.target.ship = false
event.target:setFillColor(0,255, 0)
end
end
squareWidth = 25
squareHeight = 25
gap = 5
for i =1, gridWidth, 1 do
for j =1, gridHeight, 1 do
grid[i][j] = display.newRect((gap* i) + (i*squareWidth) , (gap* j) + (j* squareHeight), squareWidth, squareHeight)
end
end
for i =1, gridWidth, 1 do
for j =1, gridHeight, 1 do
grid[i][j].ship = false
grid[i][j]:addEventListener("tap", tappedRect)
end
end
function addShip(shipSize)
x = math.random(1, gridWidth)
y = math.random(1, gridHeight)
for i = 1, shipSize-1, 1 do
if grid[x-1][y].ship then
grid[x-i][y]:setFillColor(255,0,0)
end
end
end
addShip(2)
Then I saw
Lua Code:
for i=1, gridWidth, 1 do
grid[i] = {}
end
which I'm pretty sure creates nested tables at keys of 1-9-1, which is a bit redundant. Should just be
Then you try to perform an if check that will always be false as you never declared the event table:
Lua Code:
if event.target.ship then
event.target.ship = true
event.target:setFillColor(255, 0, 0)
else
event.target.ship = false
event.target:setFillColor(0,255, 0)
end
More redundancy of for loops over writing table values
Lua Code:
for i =1, gridWidth, 1 do
for j =1, gridHeight, 1 do
So, quite a bit of work (more than I posted) needs to be done to make this functional!