game_of_life_conway.py

Created by naul

Created on March 25, 2023

1.61 KB

Le Jeu de la vie de Conway. Créé par ChatGPT


# Import necessary modules
import time 
import random

# Set the size of the grid and the number of generations to simulate
GRID_SIZE = 10
GENERATIONS = 20

# Create an empty grid
grid = [[0 for x in range(GRID_SIZE)] for y in range(GRID_SIZE)]

# Randomly populate the grid
for y in range(GRID_SIZE):
    for x in range(GRID_SIZE):
        grid[y][x] = random.randint(0, 1)

# Define a function to print the grid
def print_grid():
    for row in grid:
        print(' '.join(['#' if cell else '.' for cell in row]))

# Define a function to calculate the next generation of cells
def next_generation():
    new_grid = [[0 for x in range(GRID_SIZE)] for y in range(GRID_SIZE)]
    for y in range(GRID_SIZE):
        for x in range(GRID_SIZE):
            neighbors = 0
            for dy in [-1, 0, 1]:
                for dx in [-1, 0, 1]:
                    if dx == 0 and dy == 0:
                        continue
                    if y+dy < 0 or y+dy >= GRID_SIZE or x+dx < 0 or x+dx >= GRID_SIZE:
                        continue
                    if grid[y+dy][x+dx] == 1:
                        neighbors += 1
            if grid[y][x] == 1:
                if neighbors < 2 or neighbors > 3:
                    new_grid[y][x] = 0
                else:
                    new_grid[y][x] = 1
            else:
                if neighbors == 3:
                    new_grid[y][x] = 1
    return new_grid

# Print the initial grid
print_grid()

# Simulate the generations
for i in range(GENERATIONS):
    grid = next_generation()
    time.sleep(0.5)
    print('\033[2J') # Clear the screen
    print_grid()

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.