92 lines
1.8 KiB
Lua
92 lines
1.8 KiB
Lua
function stateGame()
|
|
local board = Board.new()
|
|
|
|
local selectedId = 1
|
|
|
|
local function drawSelectedTile()
|
|
local x, y = board:draw_coords(selectedId)
|
|
local w = board:getTileWidth()
|
|
rect2(x-1, y-1, w+2, w+2, 6)
|
|
end
|
|
|
|
local function create_board()
|
|
printh("a: " .. time())
|
|
|
|
repeat
|
|
board:reset()
|
|
repeat
|
|
board:solveStep(true)
|
|
yield()
|
|
until board:isComplete()
|
|
until board:isValid()
|
|
|
|
printh("b: " .. time())
|
|
-- Remove tiles until randomness is unavoidable
|
|
local previous = {board:getTilesCopy()} -- initial state
|
|
local invalidcount = 0
|
|
while true do
|
|
board:setTiles(previous[#previous])
|
|
-- remove a random tile
|
|
local i = board:getRandomNonZero()
|
|
board:fill(i, 0)
|
|
add(previous, board:getTilesCopy())
|
|
|
|
-- try to solve the board
|
|
local solved = ""
|
|
yield()
|
|
repeat
|
|
solved = board:solveStep()
|
|
until board:isComplete() or solved == "invalid"
|
|
if board:isComplete() then
|
|
invalidcount = 0
|
|
end
|
|
if solved == "invalid" then
|
|
deli(previous)
|
|
invalidcount += 1
|
|
end
|
|
if invalidcount > 50 then
|
|
break
|
|
end
|
|
end -- end while
|
|
printh("c: " .. time())
|
|
|
|
board:setTiles(previous[#previous])
|
|
printh(board:tostring())
|
|
printh(count(board:getTilesCopy(), 0).." zeroes")
|
|
end
|
|
|
|
local function _enter()
|
|
local c = cocreate(create_board)
|
|
end
|
|
|
|
local function _draw()
|
|
cls()
|
|
board:draw()
|
|
drawSelectedTile()
|
|
end
|
|
|
|
local function _update()
|
|
local size = board:getSize()
|
|
local x, y = board:idx_xy(selectedId)
|
|
if btnp(UP) then
|
|
y -= 1
|
|
elseif btnp(DOWN) then
|
|
y += 1
|
|
elseif btnp(LEFT) then
|
|
x -= 1
|
|
elseif btnp(RIGHT) then
|
|
x += 1
|
|
end
|
|
if (x<1) x=size
|
|
if (x>size) x=1
|
|
if (y<1) y=size
|
|
if (y>size) y=1
|
|
selectedId = board:xy_idx(x, y)
|
|
end
|
|
|
|
return {
|
|
_enter = _enter,
|
|
_update = _update,
|
|
_draw = _draw,
|
|
}
|
|
end |