Add support for edges of universe
authorJC <dev@jacobcasper.com>
Mon, 31 Jul 2023 02:55:25 +0000 (21:55 -0500)
committerJC <dev@jacobcasper.com>
Mon, 31 Jul 2023 02:55:25 +0000 (21:55 -0500)
source/main.lua

index 62891be..889fa60 100644 (file)
@@ -7,6 +7,7 @@ local CELL_SIZE <const> = 16
 
 -- Convenience function for iterating over 8 neighbors
 function neighbors(g1, x, y)
+    -- center tiles
     if (x - 1) > 0 and x < WIDTH and (y - 1) > 0 and y < HEIGHT then
         return ipairs({
             g1[x-1][y-1],
@@ -17,20 +18,40 @@ function neighbors(g1, x, y)
             g1[x+1][y-1],
             g1[x+1][y],
             g1[x+1][y+1]})
-    else
-        -- TODO corners
-        return ipairs({
-            { live = false },
-            { live = false },
-            { live = false },
-            { live = false },
-            { live = false },
-            { live = false },
-            { live = false },
-            { live = false },
-            { live = false },
-        })
     end
+
+    -- edge cases
+    ne = { live = false }
+    n  = { live = false }
+    nw = { live = false }
+    e  = { live = false }
+    w  = { live = false }
+    se = { live = false }
+    s  = { live = false }
+    sw = { live = false }
+    if g1[x-1] then
+        e = g1[x-1][y]
+        if g1[y-1] then
+            ne = g1[x-1][y-1]
+            n = g1[x][y-1]
+        end
+        if g1[y+1] then
+            se = g1[x-1][y+1]
+            s = g1[x][y+1]
+        end
+    end
+    if g1[x+1] then
+        w = g1[x+1][y]
+        if g1[y-1] then
+            nw = g1[x+1][y-1]
+            n = g1[x][y-1]
+        end
+        if g1[y+1] then
+            sw = g1[x+1][y+1]
+            s = g1[x][y+1]
+        end
+    end
+    return ipairs({ne, n, nw, e, w, se, s, sw})
 end
 
 function generation(g1)