From e7b67d85a92d1b1b22d76e4a8a9e149e8404e915 Mon Sep 17 00:00:00 2001 From: Kai-Philipp Nosper Date: Sat, 5 Feb 2022 11:53:01 +0100 Subject: [PATCH] Add game of life example --- examples/game_of_life.nek | 118 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 118 insertions(+) create mode 100644 examples/game_of_life.nek diff --git a/examples/game_of_life.nek b/examples/game_of_life.nek new file mode 100644 index 0000000..8a5475b --- /dev/null +++ b/examples/game_of_life.nek @@ -0,0 +1,118 @@ +width <- 10; +height <- 10; + +field <- [width*height]; +field2 <- [width*height]; + +field[1] = 1; +field[12] = 1; +field[20] = 1; +field[21] = 1; +field[22] = 1; + + +runs <- 0; +loop runs < 20; runs = runs + 1 { + // Print the field + y <- 0; + loop y < height; y = y+1 { + x <- 0; + loop x < width; x = x+1 { + if field[y*height + x] { + print "# "; + } else { + print ". "; + } + } + print "\n"; + } + print "\n"; + + // Update from field into field2 + y <- 0; + loop y < height; y = y+1 { + x <- 0; + loop x < width; x = x+1 { + + neighbours <- 0; + + if y > 0 { + if x > 0 { + // Top left + if field[(y-1)*width + (x-1)] { + neighbours = neighbours + 1; + } + } + + // Top + if field[(y-1)*width + x] { + neighbours = neighbours + 1; + } + + if x < width-1 { + // Top right + if field[(y-1)*width + (x+1)] { + neighbours = neighbours + 1; + } + } + } + + if x > 0 { + // Left + if field[y*width + (x-1)] { + neighbours = neighbours + 1; + } + } + + if x < width-1 { + // Right + if field[y*width + (x+1)] { + neighbours = neighbours + 1; + } + } + + + if y < height-1 { + if x > 0 { + // Bottom left + if field[(y+1)*width + (x-1)] { + neighbours = neighbours + 1; + } + } + + // Bottom + if field[(y+1)*width + x] { + neighbours = neighbours + 1; + } + + if x < width-1 { + // Bottom right + if field[(y+1)*width + (x+1)] { + neighbours = neighbours + 1; + } + } + } + + + if neighbours < 2 || neighbours > 3 { + field2[y*width + x] = 0; + } else { + if neighbours == 3 { + field2[y*width + x] = 1; + } else { + field2[y*width + x] = field[y*width + x]; + } + } + + } + } + + // Transfer from field2 to field + y <- 0; + loop y < height; y = y+1 { + x <- 0; + loop x < width; x = x+1 { + field[y*width + x] = field2[y*width + x]; + } + } +}