Minor optimization

master
mark 2023-08-26 19:26:25 -07:00
parent 003aa55726
commit 187ebbadb6
1 changed files with 30 additions and 50 deletions

View File

@ -18,6 +18,7 @@ function dotgrid:new()
dots.rows = 5 dots.rows = 5
dots.cols = 5 dots.cols = 5
dots.spacing = 2 dots.spacing = 2
dots.last_value = 0
dots.map = {} dots.map = {}
local idx local idx
@ -54,63 +55,44 @@ function dotgrid:new()
-- How many dots should be on -- How many dots should be on
local on = math.floor((self.value / self.max) * (self.rows * self.cols)) local on = math.floor((self.value / self.max) * (self.rows * self.cols))
-- How many dote are currently on local flip
local current_value = 0 while self.last_value > on do
for i=1, dots.rows*dots.cols do -- Flip the nth on dot
if dots.map[i] then flip = math.random(1, self.last_value)
current_value = current_value + 1 for i=1, dots.rows*dots.cols do
end if dots.map[i] then
end if flip == 1 then
dots.map[i] = false
local change, remove self.last_value = self.last_value - 1
if current_value ~= on then break
change = on - current_value else
remove = change < 0 flip = flip - 1
change = math.abs(change)
local flip
for i=1, change do
if remove then
-- Flip the nth on dot
flip = math.random(1, current_value)
for i=1, dots.rows*dots.cols do
if dots.map[i] then
if flip == 1 then
dots.map[i] = false
break
else
flip = flip - 1
end
end
end end
current_value = current_value - 1
else
-- Flip the nth off dot
flip = math.random(1, dots.rows*dots.cols - current_value)
for i=1, dots.rows*dots.cols do
if not dots.map[i] then
if flip == 1 then
dots.map[i] = true
break
else
flip = flip - 1
end
end
end
current_value = current_value + 1
end end
end end
end end
while self.last_value < on do
-- Flip the nth off dot
flip = math.random(1, dots.rows*dots.cols - self.last_value)
for i=1, dots.rows*dots.cols do
if not dots.map[i] then
if flip == 1 then
dots.map[i] = true
self.last_value = self.last_value + 1
break
else
flip = flip - 1
end
end
end
end
local idx
for r=1, self.rows do for r=1, self.rows do
for c=1, self.cols do for c=1, self.cols do
idx = c + ((r-1)*self.cols) idx = c + ((r-1)*self.cols)
--idx_mapped = self.map[idx] - 1
--r_mapped = (idx_mapped % self.rows) + 1
--c_mapped = (idx_mapped // self.cols) + 1
cr:new_path(); cr:new_path();
if self.map[idx] then if self.map[idx] then
cr:set_source_rgb(self.on_color[1], self.on_color[2], self.on_color[3]) cr:set_source_rgb(self.on_color[1], self.on_color[2], self.on_color[3])
@ -127,8 +109,6 @@ function dotgrid:new()
cr:fill() cr:fill()
end end
end end
end end
return dots return dots