gameoflife.py

Created by naul

Created on March 23, 2023

1.72 KB


import time
from random import randint

class GameOfLife:
    def __init__(self, rows, cols):
        self.rows = rows
        self.cols = cols
        self.grid = [[0 for _ in range(cols)] for _ in range(rows)]

    def set_alive(self, row, col):
        self.grid[row][col] = 1

    def is_alive(self, row, col):
        return self.grid[row][col] == 1

    def count_neighbors(self, row, col):
        count = 0
        for r in range(max(row - 1, 0), min(row + 2, self.rows)):
            for c in range(max(col - 1, 0), min(col + 2, self.cols)):
                if (r, c) != (row, col) and self.is_alive(r, c):
                    count += 1
        return count

    def next_generation(self):
        new_grid = [[0 for _ in range(self.cols)] for _ in range(self.rows)]
        for r in range(self.rows):
            for c in range(self.cols):
                n = self.count_neighbors(r, c)
                if self.is_alive(r, c):
                    if n < 2 or n > 3:
                        new_grid[r][c] = 0
                    else:
                        new_grid[r][c] = 1
                else:
                    if n == 3:
                        new_grid[r][c] = 1
        self.grid = new_grid

def main():
    rows = 15
    cols = 15
    game = GameOfLife(rows, cols)
    
    # Initialize with random live cells
    for i in range(rows*cols//4):
        game.set_alive(randint(0, rows-1), randint(0, cols-1))

    # Main loop
    while True:
        for r in range(rows):
            for c in range(cols):
                if game.is_alive(r, c):
                    display.pixel(r, c, 1)
                else:
                    display.pixel(r, c, 0)
        game.next_generation()
        time.sleep(0.5)
        
main()

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.