Code: Select all
FallingSand = Object:extend()
local WIDTH = 500
local HEIGHT = 300
local m_size = 5
local m_cols
local m_rows
local m_grid = {}
local m_nextGrid = {}
local m_clicked = false
local m_hueValue = 0
function FallingSand:new()
m_cols = math.floor(WIDTH / m_size)
m_rows = math.floor(HEIGHT / m_size)
for i = 1, m_cols do
m_grid[i] = {}
m_nextGrid[i] = {}
for j = 1, m_rows do
m_grid[i][j] = 0
m_nextGrid[i][j] = 0
end
end
end
function FallingSand:update(dt)
local mouseX, mouseY
local mouseCol = 1
local mouseRow = 1
local matrix = 5
local extent = math.floor(matrix / 2)
if input:down('leftButton') then
mouseX, mouseY = love.mouse.getPosition()
mouseCol = math.floor(mouseX / m_size)
mouseRow = math.floor(mouseY / m_size)
for i = -extent, extent do
for j = -extent, extent do
local randomValue = love.math.random(100)
if randomValue < 75 then
local col = mouseCol + i + 1
local row = mouseRow + j + 1
if FallingSand:withinCols(col) and FallingSand:withinRows(row) then
--*********** here is m_grid[i][j] set to 100
m_grid[col][row] = 100
end
end
end
end
for i = 1, m_cols do
for j = 1, m_rows do
m_nextGrid[i][j] = 0
end
end
for i = 1, m_cols do
for j = 1, m_rows do
-- What is the state?
--*********** state always is set to 0 from m_grid[i][j]
local state = m_grid[i][j]
-- Randomly fall left or right
if state > 0 then
local below = m_grid[i][j + 1]
-- Randomly fall left or right
local dir = 1
if love.math.random(100) < 50 then
dir = dir * -1
end
--Check below left or right
local belowA = -1
local belowB = -1
if FallingSand:withinCols(i + dir) then
belowA = m_grid[i + dir][j + 1]
end
if FallingSand:withinCols(i - dir) then
belowB = m_grid[i - dir][j + 1]
end
-- Can it fall below or left or right?
if below == 0 then
m_nextGrid[i][j + 1] = state
elseif belowA == 0 then
m_nextGrid[i + dir][j + 1] = state
elseif belowB == 0 then
m_nextGrid[i - dir][j + 1] = state;
-- Stay put!
else
m_nextGrid[i][j] = state;
end
end
end
end
m_grid = m_nextGrid
end
end
function FallingSand:draw()
love.graphics.print("Falling Sand", 0, 0)
for i = 1, m_cols do
for j = 1, m_rows do
if m_grid[i][j] > 0 then
love.graphics.setColor(0.5, 1.0, 1.0)
local x = (i - 1) * m_size
local y = (j - 1) * m_size
love.graphics.rectangle('fill', x, y, m_size, m_size)
end
end
end
end
function FallingSand:withinCols(x)
return x >= 1 and x <= m_cols
end
function FallingSand:withinRows(y)
return y >= 1 and y <= m_rows
end