Skip to content

Instantly share code, notes, and snippets.

@oivvio
Created August 3, 2020 08:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oivvio/b47fb6ac2074d036ccf520d500d94207 to your computer and use it in GitHub Desktop.
Save oivvio/b47fb6ac2074d036ccf520d500d94207 to your computer and use it in GitHub Desktop.
import curses
from random import choice
class Field:
def __init__(self, cols, rows):
self.cols = cols
self.rows = rows
self.data = [[0 for col in range(cols)] for row in range(rows)]
def getindex(self, value, max_value):
""" Cells at the borders wrap around """
if value == max_value:
return 0
if value == -1:
return max_value - 1
return value
def getvalue(self, col, row):
col = self.getindex(col, self.cols)
row = self.getindex(row, self.rows)
return self.data[row][col]
def setvalue(self, col, row, value):
col = self.getindex(col, self.cols)
row = self.getindex(row, self.rows)
self.data[row][col] = value
def marker(self, col, row):
value = self.getvalue(col, row)
if value == 1:
return "O"
else:
return " "
def randomize(self):
for col in range(self.cols):
for row in range(self.rows):
self.setvalue(col, row, choice([0, 1]))
def count_neighbours(self, col, row):
count = 0
count += self.getvalue(col - 1, row - 1)
count += self.getvalue(col, row - 1)
count += self.getvalue(col + 1, row - 1)
count += self.getvalue(col - 1, row)
count += self.getvalue(col + 1, row)
count += self.getvalue(col - 1, row + 1)
count += self.getvalue(col, row + 1)
count += self.getvalue(col + 1, row + 1)
return count
def next(self):
newfield = Field(self.cols, self.rows)
for col in range(self.cols):
for row in range(self.rows):
neighbours = self.count_neighbours(col, row)
current_value = self.getvalue(col, row)
if current_value == 1 and (neighbours == 2 or neighbours == 3):
newfield.setvalue(col, row, 1)
if current_value == 0 and neighbours == 3:
newfield.setvalue(col, row, 1)
return newfield
def draw(self, margin, screen):
for col in range(margin, self.cols):
for row in range(margin, self.rows):
screen.addstr(row, col, self.marker(col, row))
screen.refresh()
def main(stdscr):
stdscr.clear()
maxx, maxy = stdscr.getmaxyx()
margin = 1
rows = maxx - margin * 2
cols = maxy - margin * 2
field = Field(cols, rows)
field.randomize()
while True:
field = field.next()
field.draw(margin, stdscr)
sleep(1.0/24)
curses.wrapper(main)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment