importkandinskyimportrandom# 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
classCell:def__init__(self,genes=None):self.genes=genesor[random.randint(0,1)for_inrange(8)]# Define the grid of cells
grid=[[Cell()for_inrange(GRID_SIZE)]for_inrange(GRID_SIZE)]# Define the function to calculate the next generation
defcalculate_next_generation():new_grid=[[Cell()for_inrange(GRID_SIZE)]for_inrange(GRID_SIZE)]foriinrange(GRID_SIZE):forjinrange(GRID_SIZE):# Count the number of living neighbors
num_living_neighbors=0fordi,djin[(1,0),(-1,0),(0,1),(0,-1),(1,1),(1,-1),(-1,1),(-1,-1)]:ni=i+dinj=j+djifni<0ornj<0orni>=GRID_SIZEornj>=GRID_SIZE:continueifgrid[ni][nj].genes[0]==1:num_living_neighbors+=1# Determine the fate of the current cell based on the number of living neighbors
ifgrid[i][j].genes[0]==1andnum_living_neighborsin[2,3]:new_grid[i][j]=grid[i][j]elifgrid[i][j].genes[0]==0andnum_living_neighbors==3:new_grid[i][j]=Cell()returnnew_grid# Main simulation loop
forgenerationinrange(NUM_GENERATIONS):# Draw the current generation
foriinrange(GRID_SIZE):forjinrange(GRID_SIZE):ifgrid[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)
During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:
Ensure the proper functioning of the site (essential cookies); and
Track your browsing to send you personalized communications if you have created a professional account on the site and can be contacted (audience measurement cookies).
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.