Skip to content

Instantly share code, notes, and snippets.

@randrews
Created June 16, 2011 04:50
Show Gist options
  • Save randrews/1028685 to your computer and use it in GitHub Desktop.
Save randrews/1028685 to your computer and use it in GitHub Desktop.
Console version of Lua puzzle game
function make_board(size)
local board = { size = size }
setmetatable(board, { __tostring = board_tostring })
for n = 0, size * size - 1 do
board[n] = 0
end
return board
end
function populate_board(board, filled, seed)
local size = board.size
if seed then math.randomseed(seed) end
filled = filled or size * size * 3 / 4
local function rand()
local c
repeat c = math.random(size * size) - 1 until board[c] == 0
return c
end
if filled > 0 then
for _,v in ipairs{'a','b','c','d'} do board[rand()] = v end
for n = 1, filled-4 do
board[rand()] = math.random(4)
end
return fall(board)
end
end
function board_tostring(board)
local lines = {}
local size = board.size
for y = 0, size - 1 do
local line = "|"
for x = 0, size - 1 do
line = line .. " " .. board[x+y*size]
end
table.insert(lines, line .. " |")
end
return table.concat(lines,"\n")
end
function fall(board)
local size = board.size
local new_board = make_board(size, 0)
local function fall_column(col)
local dest = size - 1
for y = size-1, 0, -1 do
if board[y*size + col] ~= 0 then
new_board[dest*size + col] = board[y*size + col]
dest = dest - 1
end
end
end
for x=0, size-1 do
fall_column(x)
end
return new_board
end
function rotate(board)
local size = board.size
local new_board = make_board(size, 0)
for y = 0, size-1 do
local dest_col = size - 1 - y
for n = 0, size-1 do
new_board[n*size + dest_col] = board[y*size + n]
end
end
return new_board
end
function crush(board)
local size = board.size
local new_board = make_board(size, 0)
local crushers = {'a','b','c','d'}
for n=0, size-1 do
new_board[n] = board[n]
end
for n = size, size*size - 1 do
if board[n-size] == crushers[board[n]] then
new_board[n] = 0
else
new_board[n] = board[n]
end
end
return new_board
end
function game()
local board = populate_board(make_board(8))
local line = nil
repeat
print(board)
line = io.read()
local valid = false
if line == 'r' then
valid, board = true, rotate(board)
elseif line == 'l' then
valid, board = true, rotate(rotate(rotate(board)))
elseif line == 'exit' then
valid = true
end
if valid then
board = fall(crush(fall(board)))
else
print "Didn't understand that. Type 'l', 'r', or 'exit'."
end
until line == 'exit'
end
@ammananna
Copy link

how to execute this code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment