Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- math.randomseed(os.time())
- local realBoard = {}
- local myBoard = {}
- -- settings:
- width = 9 -- board width
- height = 9 -- board height
- mines = 10 -- mine count
- deterministic = false -- avoid 50/50 guess cases
- openFirstMove = false -- ensure first move lands on a tile with 0 surrounding mines
- -- beginner : 9x9/10
- -- intermediate : 16x16/40
- -- expert : 30x16/99
- local function shuffle(table)
- local buffer
- for i = #table, 1, -1 do
- local r = math.random(1,i)
- buffer = table[i]
- table[i] = table[r]
- table[r] = buffer
- end
- end
- local function isValid(x, y)
- return x>0 and x<=width and y>0 and y<=height
- end
- local function getNeighbors(i)
- local neighbors = {}
- local x = (i-1)%width + 1
- local y = math.floor((i-1)/width)+1
- for ix = x-1, x+1 do
- for iy = y-1, y+1 do
- if isValid(ix, iy) then
- table.insert(neighbors, ix+(iy-1)*width)
- end
- end
- end
- return neighbors
- end
- local function labelTiles()
- for i, bomb in ipairs(realBoard) do
- if bomb then
- for _, n in ipairs(getNeighbors(i)) do
- if not realBoard[n] then
- myBoard[n] = myBoard[n]+1
- else
- myBoard[n] = "■"
- end
- end
- end
- end
- end
- local function printBoard()
- for y = 1, height do
- local row = ""
- for x = 1, width do
- local i = x+(y-1)*width
- local v = myBoard[i]
- if v ~= 0 then
- row = row..myBoard[i].." "
- else
- row = row.." "
- end
- end
- print(row)
- end
- end
- local function clamp(n, min, max)
- if n < min then return min end
- if n > max then return max end
- return n
- end
- local function setup()
- realBoard = {}
- myBoard = {}
- mines = clamp(mines, 1, width*height-1)
- for i = 1, width*height do
- myBoard[i] = 0
- realBoard[i] = false
- if i <= mines then
- realBoard[i] = true
- end
- end
- shuffle(realBoard)
- labelTiles()
- end
- setup()
- printBoard()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement