Advertisement
Doob

[OpenComputers] Elementary Cellular Automata

Jul 28th, 2016
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.51 KB | None | 0 0
  1. -- eca.lua <rule_number> <1/2>
  2. local rule = 22
  3. local r, tn = math.random, tonumber
  4. local gpu = require("component").gpu
  5. local w, h = gpu.getResolution()
  6. local tWorld, tBuffer, tRule = {}, {}, {}
  7. local tArgs = {...}
  8.  
  9. local function set(a)
  10.   if a == 1 then
  11.     for i = 1, w do tWorld[i] = 0 end
  12.     tWorld[math.floor(w/2)] = 1
  13.   elseif a == 2 then
  14.     for i = 1, w do tWorld[i] = r(0, 1) end
  15.   end
  16. end
  17.  
  18. local function dot(x, y, color)
  19.   local n = y%2
  20.   y = (y+n)/2
  21.   local c, Fc, Bc = gpu.get(x, y)
  22.   local c1, Fc1, Bc1 = c, Fc, Bc
  23.   if c ~= "▄" then Fc = Bc end
  24.   if n == 0 then Fc = color else Bc = color end
  25.   if Fc1 ~= Fc or Bc1 ~= Bc1 then
  26.     gpu.setForeground(Fc)
  27.     gpu.setBackground(Bc)
  28.     gpu.set(x, y, "▄")
  29.   end
  30. end
  31.  
  32. if #tArgs == 2 then
  33.   rule = tn(tArgs[1])
  34.   set(tn(tArgs[2]))
  35. else
  36.   set(2)
  37. end
  38.  
  39. for m = 0, 7 do tRule[m] = bit32.extract(rule, m) end
  40. gpu.fill(1, 1, w, h, " ")
  41. for j = 1, h*2 do
  42.   tWorld, tBuffer = {table.unpack(tBuffer)}, {table.unpack(tWorld)}
  43.   for x = 1, #tWorld do
  44.     if tWorld[x] == 1 then
  45.       dot(x, j-1, 65280)
  46.     end
  47.   end
  48.   for i = 1, #tWorld do
  49.     if tWorld[i-1] and tWorld[i+1] then
  50.       tBuffer[i] = tRule[tn(tWorld[i-1]..tWorld[i]..tWorld[i+1], 2)]
  51.     elseif not tWorld[i-1] then
  52.      tBuffer[i] = tRule[tn(tWorld[#tWorld]..tWorld[i]..tWorld[i+1], 2)]
  53.     elseif not tWorld[i+1] then
  54.       tBuffer[i] = tRule[tn(tWorld[i-1]..tWorld[i]..tWorld[1], 2)]
  55.     end
  56.   end
  57.   os.sleep()
  58. end
  59. gpu.setBackground(0)
  60. gpu.setForeground(0xFFFFFF)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement