conway_s_game_of_life.py

Created by valmontechno

Created on June 09, 2024

1.38 KB

Le jeu de la Vie (Game of Life) est un automate cellulaire imaginé par John Horton Conway en 1970. Malgré des règles très simples, il est Turing-complet.

À chaque itération, l’état d’une cellule est entièrement déterminé par l’état de ses huit cellules voisines, selon les règles suivantes :
• Une cellule morte possédant exactement trois cellules voisines vivantes devient vivante (elle naît).
• Une cellule vivante possédant deux ou trois cellules voisines vivantes le reste, sinon elle meurt.


import kandinsky as kd
from ion import keydown, KEY_SHIFT
from random import getrandbits

COLORS = ('#ffffff', '#000000')
CELL_SIZE = 5

WIDTH = 320 // CELL_SIZE
HEIGHT = 222 // CELL_SIZE

if keydown(KEY_SHIFT):
    grid = (0b010 << 0) | (0b100 << WIDTH) | (0b111 << (2 * WIDTH))
else:
    grid = 0
    for i in range(0, WIDTH*HEIGHT, 32):
        grid = (grid << 32) | getrandbits(32)

i = 0
for y in range(HEIGHT):
    for x in range(WIDTH):
        kd.fill_rect(x*CELL_SIZE, y*CELL_SIZE, CELL_SIZE, CELL_SIZE, COLORS[(grid >> i) & 1])
        i += 1

def getCell(x, y):
    return (grid >> (y % HEIGHT) * WIDTH + (x % WIDTH)) & 1

def countNeighbors(x, y):
    neighbors = 0
    for i in range(-1, 2):
        for j in range(-1, 2):
            if (i, j) == (0, 0): continue
            neighbors += getCell(x + j, y + i)
    return neighbors

while True:
    nextGrid = 0
    for y in range(HEIGHT):
        for x in range(WIDTH):
            i = (y % HEIGHT) * WIDTH + (x % WIDTH)
            state = (grid >> i) & 1
            neighbors = countNeighbors(x, y)
            nextState = (state and (neighbors == 2 or neighbors == 3)) or (not state and neighbors == 3)
            if nextState:
                nextGrid |= (1 << i)
            if state != nextState:
                kd.fill_rect(x*CELL_SIZE, y*CELL_SIZE, CELL_SIZE, CELL_SIZE, COLORS[nextState])
    grid = nextGrid

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.