DEV Community 👩‍💻👨‍💻

Cover image for Game Of Life in Python
Bek Brace
Bek Brace

Posted on

Game Of Life in Python

Hey!
Let me show you, how to code Game OF Life simulation in my favorite language: Python.
At first, I did not fully understand what Game Of Life was all about, from multiple resources - not only wikipedia 😄- I gathered the idea, and step by step, the whole concept was revealed: Evolution!

Please subscribe to my channel, I post a video per week, trying to share what I know without talking, just coding in silence.

The code is below 🙂

''This is Game Of Life (Thrones 😄) 
   simulation coded in Python '''

from random import choice
from turtle import *
import turtle
from freegames import square

cells = {}

# 1 Initialization function
def initialize():
    '''Here, we will randomly initialize the cells'''
    for x in range( -200, 200, 10):
        for y in range( -200, 200, 10):
            cells[x,y] = False

    for x in range(-50, 50, 10):
        for y in range(-50, 50 ,10):
            cells[x,y] = choice([True, False])

# 2 Step function
def step():
    '''Here, we will compute one step in the game of life.'''
    neighbors = {}

    for x in range(-190, 190, 10):
        for y in range(-190, 190, 10):
            count = -cells[x,y]
            for h in [-10, 0, 10]:
                for v in [-10, 0, 10]:
                    count += cells[ x + h, y + v ]
            neighbors[x,y] = count

    for cell, count in neighbors.items():
        if cells[cell]:
            if count < 2 or count > 3:
                cells[cell] = False 
        elif count == 3:
            cells[cell] = True


# 3 The drawing function
def draw():
    '''Here, we are going to draw all the green squares, i choose green to match the channel's theme 😄'''
    step()
    clear()
    for (x,y), alive in cells.items():
        color = 'green' if alive else 'black'
        square(x,y,10,color)
    update()
    ontimer(draw, 100)

'''Setting up the turtle window'''
turtle.title("Game of life")
setup(420, 420, 370, 0)
hideturtle()
tracer(False)
initialize()
draw()
done() 
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
tylim88 profile image
Acid Coder

speaking of game of life

Collapse
bekbrace profile image
Bek Brace Author

Thank you for sharing this :)

🌚 Life is too short to browse without dark mode