neural.py

Created by naul

Created on March 26, 2023

1.98 KB


import kandinsky
import random

# Set the size of the grid
GRID_SIZE = 10

# Set the number of generations to simulate
NUM_GENERATIONS = 100

# Define the colors for the living and dead cells
LIVING_COLOR = (255, 255, 255)
DEAD_COLOR = (0, 0, 0)

# Define the genes for each cell
class Cell:
    def __init__(self, genes=None):
        self.genes = genes or [random.randint(0, 1) for _ in range(8)]

# Define the grid of cells
grid = [[Cell() for _ in range(GRID_SIZE)] for _ in range(GRID_SIZE)]

# Define the function to calculate the next generation
def calculate_next_generation():
    new_grid = [[Cell() for _ in range(GRID_SIZE)] for _ in range(GRID_SIZE)]
    for i in range(GRID_SIZE):
        for j in range(GRID_SIZE):
            # Count the number of living neighbors
            num_living_neighbors = 0
            for di, dj in [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)]:
                ni = i + di
                nj = j + dj
                if ni < 0 or nj < 0 or ni >= GRID_SIZE or nj >= GRID_SIZE:
                    continue
                if grid[ni][nj].genes[0] == 1:
                    num_living_neighbors += 1

            # Determine the fate of the current cell based on the number of living neighbors
            if grid[i][j].genes[0] == 1 and num_living_neighbors in [2, 3]:
                new_grid[i][j] = grid[i][j]
            elif grid[i][j].genes[0] == 0 and num_living_neighbors == 3:
                new_grid[i][j] = Cell()

    return new_grid

# Main simulation loop
for generation in range(NUM_GENERATIONS):
    # Draw the current generation
    for i in range(GRID_SIZE):
        for j in range(GRID_SIZE):
            if grid[i][j].genes[0] == 1:
                kandinsky.set_pixel(i, j, *LIVING_COLOR)
            else:
                kandinsky.set_pixel(i, j, *DEAD_COLOR)

    # Calculate the next generation
    grid = calculate_next_generation()

    # Wait for a short period of time to visualize the simulation
    time.sleep(0.1)