-- title: Xếp số (Lua) -- blurb: Xếp số viết lại bằng Lua: ví dụ ứng dụng đầy đủ -- The sliding puzzle of the built-in games, written as a script: board, moves, best score and saving. local N, CELL, GAP, BX, BY = 4, 156, 10, 44, 230 local t = {} -- t[1..16], 0 is the blank local moves, best = 0, 0 local function solved() for i = 1, 15 do if t[i] ~= i then return false end end return t[16] == 0 end local function save() data.save(table.concat(t, ",") .. " " .. moves .. " " .. best) end local function new_game() for i = 1, 15 do t[i] = i end t[16] = 0 local blank, prev = 16, 0 for _ = 1, 300 do local r, c = (blank - 1) // N, (blank - 1) % N local cand = {} if r > 0 then cand[#cand + 1] = blank - N end if r < N - 1 then cand[#cand + 1] = blank + N end if c > 0 then cand[#cand + 1] = blank - 1 end if c < N - 1 then cand[#cand + 1] = blank + 1 end local pick = cand[math.random(#cand)] if pick == prev then pick = cand[(pick == cand[1]) and #cand or 1] end t[blank], t[pick] = t[pick], 0 prev, blank = blank, pick end moves = 0 save() end function open() local s = data.load() local tiles, m, b = (s or ""):match("^([%d,]+) (%d+) (%d+)") if tiles then local i = 0 for v in tiles:gmatch("%d+") do i = i + 1; t[i] = tonumber(v) end moves, best = tonumber(m), tonumber(b) end if #t ~= 16 then new_game() end end local function rect_of(i) local r, c = (i - 1) // N, (i - 1) % N return BX + GAP + c * (CELL + GAP), BY + GAP + r * (CELL + GAP) end function draw() gfx.text(24, 142, "Số lượt: " .. moves, 26, true) if best > 0 then gfx.text(24, 174, "Tốt nhất: " .. best, 22) end gfx.button(500, 138, 239, 52, "Ván mới", 24) local size = N * CELL + (N + 1) * GAP gfx.rect(BX, BY, size, size, 4) for i = 1, 16 do if t[i] ~= 0 then local x, y = rect_of(i) gfx.button(x, y, CELL, CELL, tostring(t[i]), 56, t[i] == i) end end if solved() then gfx.button(BX + 60, BY + 2 * CELL - 30, size - 120, 100, "Đã xếp xong!", 40, true) end end local function slide(i) local b for k = 1, 16 do if t[k] == 0 then b = k end end if i == b then return false end local ir, ic, br, bc = (i - 1) // N, (i - 1) % N, (b - 1) // N, (b - 1) % N local step if ir == br then step = (ic < bc) and 1 or -1 elseif ic == bc then step = (ir < br) and N or -N else return false end local p = b while p ~= i do t[p] = t[p - step]; p = p - step end t[i] = 0 moves = moves + 1 if solved() and (best == 0 or moves < best) then best = moves end save() return true end function tap(x, y) if x >= 500 and y >= 138 and y < 190 then new_game(); return true end if solved() and y > BY then new_game(); return true end for i = 1, 16 do local bx, by = rect_of(i) if x >= bx and x < bx + CELL and y >= by and y < by + CELL then return slide(i) end end return false end