DEV Community 👩‍💻👨‍💻

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

Posted on

Game Of Life in Python

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 😄'''
    for (x,y), alive in cells.items():
        color = 'green' if alive else 'black'
    ontimer(draw, 100)

'''Setting up the turtle window'''
turtle.title("Game of life")
setup(420, 420, 370, 0)
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

tylim88 profile image
Acid Coder

speaking of game of life

bekbrace profile image
Bek Brace Author

Thank you for sharing this :)

Head to your account's Settings to...

🌚 Enable dark mode
🔠 Change your default font
📚 Adjust your experience level to see more relevant content