local Screen = require("screen") local scrn, map1, map2, width, height function _init() local c scrn = Screen:new("Life!", 10, 4) makepointer() scrn:palette(1, 0, 0, 3) scrn:palette(2, 0, 3, 0) scrn:palette(3, 0, 3, 3) scrn:palette(4, 3, 0, 0) scrn:palette(5, 3, 0, 3) scrn:palette(6, 3, 3, 0) scrn:palette(7, 3, 3, 3) scrn:palette(8, 0, 0, 15) scrn:palette(9, 0, 15, 0) scrn:palette(10, 0, 15, 15) scrn:palette(11, 15, 0, 0) scrn:palette(12, 15, 0, 15) scrn:palette(13, 15, 15, 0) scrn:palette(14, 15, 15, 15) scrn:autocolor() width, height = scrn:size() map1 = {} map2 = {} sys.stepinterval(0) for y = 0, height - 1 do for x = 0, width - 1 do c = math.floor(math.random(1024)) % 15 map1[xy(x, y)] = c end end end function _step(t) local map, live, neis scrn:step(t) if input.hotkey() == "q" then sys.exit(0) end for y = 0, height - 1 do for x = 0, width - 1 do live = map1[xy(x, y)] neis = nei(x, y) if live > 7 then if (neis < 2) or (neis > 3) then set(x, y, live - 7) else set(x, y, live) end else if neis == 3 then set(x, y, procreate(x, y)) else set(x, y, live) end end end end local mx, my, mb = input.mouse() if mb == 1 then local c = (map2[xy(mx, my)] % 8) + 7 set(mx - 1, my - 1, c) set(mx + 1, my + 0, c) set(mx - 1, my + 1, c) set(mx + 0, my + 1, c) set(mx + 0, my + 0, c) end map = map1 map1 = map2 map2 = map end function xy(x, y) return (y * width + x) % (width * height) end function nei(x, y) local lives = 0 for _y = -1, 1 do for _x = -1, 1 do if (map1[xy(x + _x, y + _y)] or 0) > 7 then lives = lives + 1 end end end if map1[xy(x, y)] > 7 then lives = lives - 1 end return lives end function procreate(x, y) local r, g, b = 0, 0, 0 for _y = -1, 1 do for _x = -1, 1 do if (map1[xy(x + _x, y + _y)] or 0) > 7 then local c = map1[xy(x + _x, y + _y)] - 7 r = r + (c & 4) / 4 g = g + (c & 2) / 2 b = b + (c & 1) end end end local child = 0 if r > 1 then child = child + 4 end if g > 1 then child = child + 2 end if b > 1 then child = child + 1 end if child == 0 then child = 1 + (math.floor(math.random(128)) % 7) end return child + 7 end function set(x, y, alive) if map1[xy(x, y)] ~= alive or map2[xy(x, y)] ~= alive then map2[xy(x, y)] = alive gfx.pixel(x, y, map2[xy(x, y)] or 0) end end function makepointer() gfx.fgcolor(2) gfx.line(0, 5, 10, 5) gfx.line(5, 0, 5, 10) gfx.fgcolor(0) gfx.plot(5, 5) local pimg = image.new(11, 11, 2) image.copy(pimg, 0, 0, 0, 0, 11, 11) image.pointer(pimg, 5, 5) end