From 187ebbadb6c3bc6e312c2d171de0f21981ef4500 Mon Sep 17 00:00:00 2001 From: mark Date: Sat, 26 Aug 2023 19:26:25 -0700 Subject: [PATCH] Minor optimization --- widgets/dotgrid.lua | 80 +++++++++++++++++---------------------------- 1 file changed, 30 insertions(+), 50 deletions(-) diff --git a/widgets/dotgrid.lua b/widgets/dotgrid.lua index fae5f7c..1a53162 100644 --- a/widgets/dotgrid.lua +++ b/widgets/dotgrid.lua @@ -18,6 +18,7 @@ function dotgrid:new() dots.rows = 5 dots.cols = 5 dots.spacing = 2 + dots.last_value = 0 dots.map = {} local idx @@ -54,63 +55,44 @@ function dotgrid:new() -- How many dots should be on local on = math.floor((self.value / self.max) * (self.rows * self.cols)) - -- How many dote are currently on - local current_value = 0 - for i=1, dots.rows*dots.cols do - if dots.map[i] then - current_value = current_value + 1 - end - end - - local change, remove - if current_value ~= on then - change = on - current_value - remove = change < 0 - 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 + local flip + while self.last_value > on do + -- Flip the nth on dot + flip = math.random(1, self.last_value) + for i=1, dots.rows*dots.cols do + if dots.map[i] then + if flip == 1 then + dots.map[i] = false + self.last_value = self.last_value - 1 + break + else + flip = flip - 1 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 + 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 c=1, self.cols do 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(); if self.map[idx] then 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() end end - - end return dots