summaryrefslogtreecommitdiffstats
path: root/apps/plugins/picross.lua
blob: ec9b6ef7a9643d02e1a0da22eafbc34fd80676f8 (plain)
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
--[[
             __________               __   ___.
   Open      \______   \ ____   ____ |  | _\_ |__   _______  ___
   Source     |       _//  _ \_/ ___\|  |/ /| __ \ /  _ \  \/  /
   Jukebox    |    |   (  <_> )  \___|    < | \_\ (  <_> > <  <
   Firmware   |____|_  /\____/ \___  >__|_ \|___  /\____/__/\_ \
                     \/            \/     \/    \/            \/

Port of Picross (aka. Picture Crossword, Nonograms, Paint By Numbers)
Copyright (c) 2012 by Nathan Korth

See http://en.wikipedia.org/wiki/Nonogram for details on how to play, and
http://nkorth.com/picross for more puzzles.

]]--

require "actions"
require "luadir"
require("rbsettings")
require("settings")

local _nums = require("draw_num")
local _clr   = require("color") -- clrset, clrinc provides device independent colors
local _lcd   = require("lcd")   -- lcd helper functions

local plugindir = rb.PLUGIN_GAMES_DATA_DIR
local userdir = plugindir .. "/.picross"

local wrap = rb.settings.read('global_settings', rb.system.global_settings.list_wraparound)
wrap = (wrap or 1) == 1

do     -- free up some ram by removing items we don't need
    local function strip_functions(t, ...)
        local t_keep = {...}
        local keep
        for key, val in pairs(t) do
            keep = false
            for _, v in ipairs(t_keep) do
                if string.find (key, v) then
                    keep = true; break
                end
            end
            if keep ~= true then
                t[key] = nil
            end
        end
    end

    strip_functions(rb.actions, "PLA_", "TOUCHSCREEN", "_NONE")
    rb.contexts = nil

    _clr.inc = nil
    rb.metadata = nil -- remove metadata settings
    rb.system = nil -- remove system settings
    rb.settings = nil --remove setting read/write fns
end

--colors for fg/bg ------------------------
local WHITE = _clr.set(-1, 255, 255, 255)
local BLACK = _clr.set(0, 0, 0, 0)
-------------------------------------------

-- set colors on color targets
if rb.lcd_rgbpack ~= nil then
    rb.lcd_set_background(rb.lcd_rgbpack(255, 255, 255))
    rb.lcd_set_foreground(rb.lcd_rgbpack(0, 0, 0))
end

local TEXT_COLOR = BLACK

if rb.LCD_DEPTH == 2 then TEXT_COLOR = bit.bnot(TEXT_COLOR) end

--[[
-- load images
local img_numbers = rb.read_bmp_file(rb.current_path().."picross_numbers.bmp")

-- image helper function
function draw_image(img, x, y, w, h, tilenum)

    local func = rb.lcd_bitmap_transparent_part
              or rb.lcd_bitmap_part      -- Fallback version for grayscale targets
              or rb.lcd_mono_bitmap_part -- Fallback version for mono targets

    func(img, 0, (tilenum * h), w, x, y, w, h)
end
]]

function draw_number(x, y, w, tilenum, scale)
    scale = scale or 1
    _nums.print(_LCD, tilenum, x, y, w, TEXT_COLOR, nil, nil, true, scale, scale)
end

function showComplete(self)
    if self:isComplete() then
        rb.splash(rb.HZ * 2, "Puzzle complete!")
        self:saveGame()
        self.puzzleh = 50
        self.puzzlew = 50
        local old_boardh, old_boardw = self.boardh, self.boardw
        local old_numbersw, old_numbersh = self.numbersw, self.numbersh
        while self.numbersh > 0 do -- remove the number rows
            table.remove (self.board, 1)
            self.numbersh = self.numbersh - 1
        end
        self.numbersh = 0
        self.numbersw = 0
        self.solution = nil
        self.boardh = self.puzzleh
        self.boardw = self.puzzlew
        self.freedraw = 0
        -- find a free number
        while rb.file_exists(string.format("%s/user_freedraw_%d.picross",
                                                userdir, self.freedraw)) do
            self.freedraw = self.freedraw + 1
        end

        for r = 1, self.boardh do
            local old_row = self.board[r] or {}

            self.board[r] = {}
            -- copy over the last drawing
            for c = 1, self.boardw do
                local ch = old_row[c + old_numbersw]
                if not ch or ch ~= '*' then
                    self.board[r][c] = '.'
                else
                    self.board[r][c] = '*'
                end
            end
        end
        rb.splash(rb.HZ * 3, "Free Draw!")
        self.cursor.x = 1
        self.cursor.y = 1
        self.showComplete = function() end --show once, then remove the reference
    end
end

local State = {
    puzzlew = 0,
    puzzleh = 0,
    numbersw = 0,
    numbersh = 0,
    boardw = 0,
    boardh = 0,
    board = {},
    solution = {},
    filename = '',
    cursor = {x = 0, y = 0},
    scale = 1,
    freedraw = false
}

--[[

Notes on how puzzles work in the code:

The "board" array is bigger than the actual puzzle, so the numbers
above and to the left of it can be stored and do not need to be recalculated
for every draw. (The "solution" array is the same size as the puzzle, however.)
The various width/height variables help keep track of where everything is.
(they should be fairly self-explanatory)

The width/height of the numbers section is always half the width/height of the
puzzle. For odd-number-sized puzzles, the value must be rounded up. This is
because strings of squares must have at least one blank space in between. For
example, on a board 5 wide, the maximum set of row numbers is "1 1 1".

Here are the values used in the "board" array:
    ' ': empty space
    '.': unfilled square
    '*': filled square
    [number]: number (not a string)

The .picross puzzle files are text files which look pretty much the same as the
"board" array, with two differences:

  - puzzle files should not contain numbers, because they will be generated
    based on the puzzle at runtime
  - blank lines and lines starting with '#' are ignored

]]--

function State:initBoard()
    if self.freedraw then
        -- clear board (set the puzzle area to '.' and everything else to ' ')
        self.board = {}
        for r = 1,self.boardh do
            self.board[r] = {}
            for c = 1,self.boardw do
                if r > self.numbersh and c > self.numbersw then
                    self.board[r][c] = '.'
                else
                    self.board[r][c] = ' '
                end
            end
        end

        -- reset cursor
        self.cursor.x = 1
        self.cursor.y = 1
        return
    end --freedraw

    -- metrics
    self.puzzleh = #self.solution
    self.puzzlew = #self.solution[1]
    self.numbersh = math.floor(self.puzzleh / 2) + 1
    self.numbersw = math.floor(self.puzzlew / 2) + 1
    self.boardh = self.puzzleh + self.numbersh
    self.boardw = self.puzzlew + self.numbersw
    self.showComplete = showComplete

    -- clear board (set the puzzle area to '.' and everything else to ' ')
    self.board = {}
    for r = 1,self.boardh do
        self.board[r] = {}
        for c = 1,self.boardw do
            if r > self.numbersh and c > self.numbersw then
                self.board[r][c] = '.'
            else
                self.board[r][c] = ' '
            end
        end
    end

    -- reset cursor
    self.cursor.x = self.numbersw + 1
    self.cursor.y = self.numbersh + 1

    -- calculate row numbers
    local rownums = {}
    for r = 1,self.puzzleh do
        rownums[r] = {}
        local count = 0
        for c = 1,self.puzzlew do
            if self.solution[r][c] == '*' then
                -- filled square
                count = count + 1
            else
                -- empty square
                if count > 0 then
                    table.insert(rownums[r], count)
                    count = 0
                end
            end
        end
        -- if there were no empty squares
        if count > 0 then
            table.insert(rownums[r], count)
            count = 0
        end
    end

    -- calculate column numbers
    local columnnums = {}
    for c = 1,self.puzzlew do
        columnnums[c] = {}
        local count = 0
        for r = 1,self.puzzleh do
            if self.solution[r][c] == '*' then
                -- filled square
                count = count + 1
            else
                -- empty square
                if count > 0 then
                    table.insert(columnnums[c], count)
                    count = 0
                end
            end
        end
        -- if there were no empty squares
        if count > 0 then
            table.insert(columnnums[c], count)
            count = 0
        end
    end

    -- add row numbers to board
    for r = 1,self.puzzleh do
        for i,num in ipairs(rownums[r]) do
            self.board[self.numbersh + r][self.numbersw - #rownums[r] + i] = num
        end
    end

    -- add column numbers to board
    for c = 1,self.puzzlew do
        for i,num in ipairs(columnnums[c]) do
            self.board[self.numbersh - #columnnums[c] + i][self.numbersw + c] = num
        end
    end
end

function State:saveGame()
    local file
    local boardw, boardh = self.boardw, self.boardh

    if self.freedraw then
        self.filename = string.format("%s/user_freedraw_%d.picross", userdir, self.freedraw)


        --remove blank lines from the end
        while boardh > 1 and not string.find(table.concat(self.board[boardh]), "\*") do
            boardh = boardh - 1
        end
        --remove blank lines from right
        local max_w = 0
        for r = self.numbersh + 1, boardh do
            for c = max_w + 1, boardw do
                if self.board[r][c] == '*' then
                    max_w = c
                end
            end
        end
        boardw = max_w
        if max_w == 0 then return end--nothing to save

        file = io.open(self.filename, 'w')
    else
        file = io.open(plugindir .. '/picross.sav', 'w')
    end

    if file then
        file:write("#"..self.filename.."\n")
        for r = self.numbersh + 1, boardh do
            for c = self.numbersw + 1, boardw do
                file:write(self.board[r][c])
            end
            file:write("\n")
        end
        file:close()
        if self.freedraw then
            rb.splash(rb.HZ, "Freedraw saved.")
        else
            rb.splash(rb.HZ, "Game saved.")
        end
        return true
    else
        rb.splash(rb.HZ * 2, "Failed to open save file")
        return false
    end
end

function State:loadSave()
    local file = io.open(plugindir .. '/picross.sav')
    if file then
        -- first line is commented path of original puzzle
        path = file:read('*l')
        path = path:sub(2,-1)
        -- prepare original puzzle
        if self:loadFile(path) then
            -- load saved board
            contents = file:read('*all')
            file:close()
            local r = 1
            for line in contents:gmatch("[^\r\n]+") do
                local c = 1
                for char in line:gmatch('.') do
                    self.board[self.numbersh + r][self.numbersw + c] = char
                    c = c + 1
                end
                r = r + 1
            end

            return true
        else
            return false
        end
    else
        return false
    end
end

function State:loadDefault()
    return self:loadFile(userdir .. '/picross_default.picross')
end

function State:loadFile(path)
    local file = io.open(path)
    if file then
        self.freedraw = false
        local board = {}
        local boardwidth = 0
        local count = 0
        contents = file:read('*all')

        for line in contents:gmatch("[^\r\n]+") do
            count = count + 1
            -- ignore blank lines and comments
            if line ~= '' and line:sub(1, 1) ~= '#' then
                table.insert(board, {}) -- add a new row

                -- ensure all lines are the same width
                if boardwidth == 0 then
                    boardwidth = #line
                elseif #line ~= boardwidth then
                    -- a line was the wrong width
                    local err = "Invalid puzzle file!"
                    local msg =
                     string.format("%s (wrong line width ln: %d w: %d)", err, count, #line)
                    rb.splash(rb.HZ * 2, msg)
                    return false
                end
                local pos = 0
                for char in line:gmatch('.') do
                    pos = pos + 1
                    if char == '*' or char == '.' then
                        table.insert(board[#board], char)
                    else
                        local err = "Invalid puzzle file!"
                        local msg = string.format("%s (invalid character ln: %d '%s' @ %d)",
                                                                       err, count, char, pos)
                        -- invalid character in puzzle area
                        rb.splash(rb.HZ * 2, msg)
                        return false
                    end
                end
            else
                -- display puzzle comments
                --rb.splash(rb.HZ, line:sub(2,#line))
            end
        end

        if #board == 0 then
           -- empty file
           rb.splash(rb.HZ * 2, "Invalid puzzle file! (empty)")
           return false
        end

        file:close()

        self.solution = board
        self.filename = path
        if self.puzzleh < 100 and self.puzzlew < 100 then
            self:initBoard()
            return true
        else
            -- puzzle too big
            rb.splash(rb.HZ * 2, "Invalid puzzle file! (too big)")
            return false
        end
    else
        -- file open failed
        rb.splash(rb.HZ * 2, "Failed to open file!")
        return false
    end
end

function State:drawBoard()
    local tw, th = 10 * self.scale, 10 * self.scale -- tile width and height (including bottom+right padding)

    local ofsx = rb.LCD_WIDTH/2 - 4 - (self.cursor.x * tw)
    local ofsy = rb.LCD_HEIGHT/2 - 4 - (self.cursor.y * th)

    rb.lcd_clear_display()

    -- guide lines
    for r = 0, self.puzzleh do
        local x1, x2, y =
            ofsx + tw - 1,
            ofsx + ((self.boardw + 1) * tw) - 1,
            ofsy + ((self.numbersh + 1 + r) * th) - 1
        if r % 5 == 0 or r == self.puzzleh then
            rb.lcd_hline(x1, x2, y)
        else
            for x = x1, x2, 2 do
                rb.lcd_drawpixel(x, y)
            end
        end
    end
    for c = 0, self.puzzlew do
        local x, y1, y2 =
        ofsx + ((self.numbersw + 1 + c) * tw) - 1,
        ofsy + th - 1,
        ofsy + ((self.boardh + 1) * th) - 1
        if c % 5 == 0 or c == self.puzzlew then
            rb.lcd_vline(x, y1, y2)
        else
            for y = y1,y2, 2 do
                rb.lcd_drawpixel(x, y)
            end
        end
    end

    -- cursor
    local cx, cy = ofsx + (self.cursor.x * tw) - 1, ofsy + (self.cursor.y * th) - 1
    rb.lcd_drawrect(cx, cy, tw + 1, th + 1)
    local n_width = tw / self.scale / 2 - 1
    local xc = (tw - 5 * self.scale) / 2
    -- tiles
    for r = 1, self.boardh do
        for c = 1, self.boardw do
            local x, y = ofsx + (c * tw) + 1, ofsy + (r * th) + 1

            if self.board[r][c] == '.' then
                -- unfilled square
            elseif self.board[r][c] == '*' then
                -- filled square
                rb.lcd_fillrect(x, y, tw - 3, th - 3)
            elseif self.board[r][c] == 'x' then
                -- eliminated square
                rb.lcd_drawline(x + 1, y + 1, x + tw - 5, y + th - 5)
                rb.lcd_drawline(x + tw - 5, y + 1, x + 1, y + th - 5)
            elseif self.board[r][c] == ' ' then
                -- empty space
            elseif self.board[r][c] > 0 and self.board[r][c] < 100 then
                -- number
                local num = self.board[r][c]
                if num < 10 then
                    draw_number(x + xc, y, n_width, num, self.scale)
                    draw_number(x + xc + 1, y, n_width, num, self.scale)
                else
                    draw_number(x, y, n_width, num, self.scale)
                    draw_number(x + 1, y, n_width, num, self.scale)
                end
            end
        end
    end

    rb.lcd_update()
end

function State:isComplete()
    for r = 1,self.puzzleh do
        for c = 1,self.puzzlew do
            if self.solution[r][c] == '*' and
               self.board[self.numbersh + r][self.numbersw + c] ~= '*' then
                return false
            end
        end
    end

    return true
end

function State:moveCursor(dir)
    -- The cursor isn't allowed to move in the top-left quadrant of the board.
    -- This has to be checked in up and left moves.
    local in_board_area = (self.cursor.y > (self.numbersh + 1)
                          and self.cursor.x > self.numbersw + 1)

    if dir == 'left' then
        if (self.cursor.x > (self.numbersw + 1) or self.cursor.y > self.numbersh)
        and self.cursor.x > 1 then
            self.cursor.x = self.cursor.x - 1
        elseif wrap == true then
            if in_board_area then
                self.cursor.x = 1
            else
                self.cursor.x = self.boardw
            end
            dir = 'up'
        end
    elseif dir == 'right' then
        if self.cursor.x < self.boardw then
            self.cursor.x = self.cursor.x + 1
        elseif wrap == true then
            if in_board_area then
                self.cursor.x = 1
            else
                self.cursor.x = self.numbersw + 1
            end
            dir = 'down'
        end
    end

    if dir == 'up' then
        if (self.cursor.y > (self.numbersh + 1) or self.cursor.x > self.numbersw)
        and self.cursor.y > 1 then
                self.cursor.y = self.cursor.y - 1
        elseif wrap == true then
            if in_board_area then
                self.cursor.y = 1
            else
                self.cursor.y = self.boardh
            end
        end
    elseif dir == 'down' then
        if self.cursor.y < self.boardh then
            self.cursor.y = self.cursor.y + 1
        elseif wrap == true then
            if in_board_area then
                self.cursor.y = 1
            else
                self.cursor.y = self.numbersh + 1
            end
        end
    end
end

function State:fillSquare(mode)
    mode = mode or 0
    if self.cursor.x > self.numbersw and self.cursor.y > self.numbersh then
        if self.board[self.cursor.y][self.cursor.x] == '*' and mode ~= 2 then
            -- clear square
            self.board[self.cursor.y][self.cursor.x] = '.'
        elseif mode ~= 1 then -- '.' or 'x'
            -- fill square
            local x, y = self.cursor.x - self.numbersw, self.cursor.y - self.numbersh
            if not self.solution or  self.solution[y][x] == '*' then
                self.board[self.cursor.y][self.cursor.x] = '*'
            else
                rb.splash(rb.HZ * 2, "Invalid move!")
                -- "x" square for convenience
                self.board[self.cursor.y][self.cursor.x] = 'x'
            end
        end
    end

    self:showComplete()
end

function State:eliminateSquare()
    if not self.freedraw
       and self.cursor.x > self.numbersw
       and self.cursor.y > self.numbersh then
        if self.board[self.cursor.y][self.cursor.x] == 'x' then
            -- clear square
            self.board[self.cursor.y][self.cursor.x] = '.'
        else-- '.' or '*'
            -- "x" square
            self.board[self.cursor.y][self.cursor.x] = 'x'
        end
    else
        self.board[self.cursor.y][self.cursor.x] = '.'
    end
end

-- main code ------------------------------------------------------------------

local function mainMenu()
    local menu = {
        "Resume",
        "View picture",
        "Restart puzzle",
        "Load puzzle",
        "Zoom " .. State.scale - 1,
        "Save progress",
        "Save and quit",
        "Quit without saving"
    }
    local start

    if State.freedraw then
        menu[6] = "Save freedraw " .. State.freedraw --Save Progress
    end
    while true do
        local s = rb.do_menu("Picross", menu, start, false)
        start = s
        if s == 0 then
            -- resume
            return
        elseif s == 1 then
            -- view picture
            viewPicture()
            start = 0 --resume
        elseif s == 2 then
            -- restart
            State:initBoard()
            return
        elseif s == 3 then
            -- choose puzzle
            if puzzleList() then
                return
            end
        elseif s == 4 then
            -- zoom
            State.scale = State.scale + 1
            if State.scale > 4 then
                State.scale = 1
            end
            menu[5] = "Zoom " .. State.scale - 1
        elseif s == 5 then
            -- save
            if State:saveGame() then
                return
            end
        elseif s == 6 then
            -- save and quit
            if State:saveGame() then
                os.exit()
            end
        elseif s == 7 then
            -- quit
            os.exit()
        elseif s == -2 then
            -- back button pressed
            return
        else
            -- something strange happened
            rb.splash(rb.HZ * 2, "Invalid menu index: "..s)
        end
    end
end

function puzzleList()
    if rb.dir_exists(userdir) then
        local files = {}
        for file in luadir.dir(userdir) do
            if file ~= '.' and file ~= '..' then
                table.insert(files, file)
            end
        end

        table.sort(files)
        local udir = userdir .. "/"
        if #files > 0 then
            local s = rb.do_menu("Puzzles", files, nil, false)
            if s >= 0 and s < #files then
                if State:loadFile(udir..files[s+1]) then
                    return true -- return to puzzle screen
                else
                    -- puzzle failed to load, return to main menu
                    return false
                end
            elseif s == -2 then
                -- back button pressed, return to main menu
                return false
            else
                -- something strange happened
                rb.splash(rb.HZ * 2, "Invalid menu index: "..s)
                return false
            end
        else
            rb.splash(rb.HZ * 2, "No puzzles found! Put .picross files in " .. userdir)
            return false
        end
    else
        rb.splash(rb.HZ * 2, "Put .picross files in " .. userdir)
        return false
    end
end

function viewPicture()
    rb.lcd_clear_display()

    -- draw filled squares as pixels (scaled 2x)
    for r = State.numbersh + 1, State.boardh do
        for c = State.numbersw + 1, State.boardw do
            if State.board[r][c] == '*' then
                --rb.lcd_drawpixel(c - State.numbersw, r - State.numbersh)
                local px = (c - State.numbersw) * State.scale - State.scale + 1
                local py = (r - State.numbersh) * State.scale - State.scale + 1

                rb.lcd_fillrect(px, py, State.scale, State.scale)
            end
        end
    end

    rb.lcd_update()

    -- exit on button press
    while true do
        local action = rb.get_plugin_action(0)

        if action == rb.actions.PLA_EXIT
        or action == rb.actions.PLA_CANCEL
        or action == rb.actions.PLA_SELECT then
            return
        end

        rb.yield()
    end
end

if not State:loadSave() then
    if not State:loadDefault() then
    return;
    end
end

local act = rb.actions
local action = act.ACTION_NONE
local lockdraw = false

while true do
    action = rb.get_plugin_action(0)
    if action == rb.actions.PLA_EXIT then
        lockdraw = false
        mainMenu()
    elseif action == act.PLA_UP or action == act.PLA_UP_REPEAT then
        State:moveCursor('up')
    elseif action == act.PLA_DOWN or action == act.PLA_DOWN_REPEAT then
        State:moveCursor('down')
    elseif action == act.PLA_LEFT or action == act.PLA_LEFT_REPEAT then
        State:moveCursor('left')
    elseif action == act.PLA_RIGHT or action == act.PLA_RIGHT_REPEAT then
        State:moveCursor('right')
    elseif action == act.PLA_SELECT then
        if lockdraw then
            lockdraw = lockdraw - 1
            if lockdraw < 0 then
                lockdraw = false
            elseif lockdraw == 1 then
                rb.splash(50, "clear")
            else
                rb.splash(50, "invert")
            end
        else
            State:fillSquare()
        end
        action = act.ACTION_NONE
    elseif action == act.PLA_SELECT_REPEAT then
        if State.freedraw and not lockdraw then
            lockdraw = 2
            rb.splash(50, "draw")
            action = act.ACTION_NONE
        end
    elseif action == act.PLA_CANCEL then
        State:eliminateSquare()
        action = act.ACTION_NONE
    else
        action = act.ACTION_NONE
    end

    if lockdraw and action ~= act.ACTION_NONE then
        State:fillSquare(lockdraw)
    end

    State:drawBoard()

    rb.yield()
end