Advertisement
SneakySquid

Lua Minesweeper

Feb 11th, 2019
278
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.82 KB | None | 0 0
  1. -- Made for the use with NotSoBot.
  2.  
  3. local Grid, Counters = {}, {
  4.     ":one:", ":two:",
  5.     ":three:", ":four:",
  6.     ":five:", ":six:",
  7.     ":seven:", ":eight:",
  8. }
  9.  
  10. local Rows = math.max(1, tonumber("{arg:0}") or 10)
  11. local Columns = math.max(1, tonumber("{arg:1}") or 10)
  12. local MineChance = math.max(0, math.min(tonumber("{arg:2}") or 20, 100)) * 0.01
  13.  
  14. function Grid:Create()
  15.     if (Rows * Columns < 9) then
  16.         return "Grid is too small. There needs to be at least 9 tiles."
  17.     end
  18.  
  19.     for r = 1, Rows do
  20.         local row = {}
  21.  
  22.         for c = 1, Columns do
  23.             table.insert(row, ":white_large_square:")
  24.         end
  25.  
  26.         table.insert(self, row)
  27.     end
  28.  
  29.     self:ScatterMines()
  30.     self:CountMines()
  31.  
  32.     return self:Format()
  33. end
  34.  
  35. function Grid:ScatterMines()
  36.     math.randomseed(os.time())
  37.  
  38.     local mines = 0
  39.  
  40.     for r, row in ipairs(self) do
  41.         for c, square in ipairs(row) do
  42.             if (math.random() <= MineChance) then
  43.                 row[c] = ":bomb:"
  44.                 mines = mines + 1
  45.             end
  46.         end
  47.     end
  48.  
  49.     if (MineChance > 0 and mines == 0) then
  50.         local r = self[math.random(Rows)]
  51.         local c = math.random(Columns)
  52.  
  53.         r[c] = ":bomb:"
  54.     end
  55. end
  56.  
  57. function Grid:CountMines()
  58.     for r, row in ipairs(self) do
  59.         for c, s in ipairs(row) do
  60.             if (s ~= ":bomb:") then
  61.                 local mines = 0
  62.  
  63.                 for x = -1, 1 do
  64.                     for y = -1, 1 do
  65.                         local r = self[r + x]
  66.  
  67.                         if (r and r[c + y] == ":bomb:") then
  68.                             mines = mines + 1
  69.                         end
  70.                     end
  71.                 end
  72.  
  73.                 if (mines > 0) then
  74.                     row[c] = Counters[mines]
  75.                 end
  76.             end
  77.         end
  78.     end
  79. end
  80.  
  81. function Grid:Format()
  82.     local grid = {}
  83.  
  84.     for i, r in ipairs(self) do
  85.         r = table.concat(r, "\124\124\124\124")
  86.         table.insert(grid, string.format("\124\124%s\124\124", r))
  87.     end
  88.  
  89.     grid = table.concat(grid, "\n")
  90.  
  91.     return #grid > 2000 and "Grid is too large. 2,000 character limit met." or grid
  92. end
  93.  
  94. print(Grid:Create())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement