about summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorelioat <elioat@tilde.institute>2024-06-07 21:44:04 -0400
committerelioat <elioat@tilde.institute>2024-06-07 21:44:04 -0400
commitda2446b087bc5a78a683607a2219138ae2aae44d (patch)
tree761953fe4bec1e3d0daa366d401008aeabace225
parentee9371073bf7b7f56fb884ee4cce5da13dc35ceb (diff)
downloadtour-da2446b087bc5a78a683607a2219138ae2aae44d.tar.gz
*
-rw-r--r--lua/life.lua77
1 files changed, 77 insertions, 0 deletions
diff --git a/lua/life.lua b/lua/life.lua
new file mode 100644
index 0000000..f4d5a0d
--- /dev/null
+++ b/lua/life.lua
@@ -0,0 +1,77 @@
+local initialBoard = {
+  {0, 1, 0},
+  {0, 0, 1},
+  {1, 1, 1},
+  {0, 0, 0}
+}
+
+local function deepcopy(orig)
+  local orig_type = type(orig)
+  local copy
+  if orig_type == 'table' then
+    copy = {}
+    for orig_key, orig_value in next, orig, nil do
+      copy[deepcopy(orig_key)] = deepcopy(orig_value)
+    end
+    setmetatable(copy, deepcopy(getmetatable(orig)))
+  else -- number, string, boolean, etc
+    copy = orig
+  end
+  return copy
+end
+
+local function getNextState(board)
+  local rows = #board
+  local cols = #board[1]
+
+  local function countLiveNeighbors(board, x, y)
+    local count = 0
+    for dx = -1, 1 do
+      for dy = -1, 1 do
+        if not (dx == 0 and dy == 0) then
+          local nx, ny = x + dx, y + dy
+          if nx >= 1 and nx <= rows and ny >= 1 and ny <= cols then
+            count = count + board[nx][ny]
+          end
+        end
+      end
+    end
+    return count
+  end
+
+  local nextBoard = deepcopy(board)
+
+  for x = 1, rows do
+    for y = 1, cols do
+      local liveNeighbors = countLiveNeighbors(board, x, y)
+      if board[x][y] == 1 and (liveNeighbors < 2 or liveNeighbors > 3) then
+        nextBoard[x][y] = 0
+      elseif board[x][y] == 0 and liveNeighbors == 3 then
+        nextBoard[x][y] = 1
+      end
+    end
+  end
+
+  return nextBoard
+end
+
+local function printBoard(board)
+  io.write("\27[2J\27[H") -- clear console
+  for _, row in ipairs(board) do
+    for _, cell in ipairs(row) do
+      io.write(cell == 1 and "1 " or "0 ")
+    end
+    io.write("\n")
+  end
+end
+
+local function runGame(initialBoard, generations)
+  local board = initialBoard
+  for i = 1, generations do
+    printBoard(board)
+    board = getNextState(board)
+    os.execute("sleep 0.5") -- Wait 0.5 seconds between generations
+  end
+end
+
+runGame(initialBoard, 10)