[PYTHON] Create a life game that is manually updated with tkinter

After taking Paiza's Python course, when I was looking for what to make on google, how to make a life game in [Python starting from zero] in Mynavi News (https://news.mynavi.jp/article/zeropython- Since there was 9 /), I tried to make a life game to update manually with reference to it.

When executed, the following black screen will appear, image.png

Click to place or cancel cells. The following is an arrangement called [pentadecathlon] image.png

Updates each time the [Enter] key is pressed. image.png

The arrangement of [pentadecathlon] repeats at regular intervals and does not perish, By adding one cell in the middle, image.png The balance is lost and a new shape is created. image.png

import tkinter as tk

WIDTH, HEIGHT = 600, 400  #Canvas size
cell = {'size': 20, 'color': 'green'}  #Cell information
COLS, ROWS = WIDTH//cell['size'], HEIGHT//cell['size']  #Number of columns and rows of Canvas
data = [[False for x in range(COLS)] for y in range(ROWS)]  #Existence of cell

win = tk.Tk()
win.title('LifeGame')

#Generation update count
text = tk.StringVar()  #Widget variable that holds a string
update = 0  #Initial value of update count
text.set(update)  #Set the number of updates
label = tk.Label(win, textvariable=text,  font=('IPAex Gothic', '24'))
label.pack()

#Canvas settings
cv = tk.Canvas(win, width=WIDTH, height=HEIGHT, bg='black')
cv.pack()


#Draw lines in a grid to make it easier to arrange cells
def draw_grid():
    for x in range(COLS):
        x1 = x * cell['size']
        cv.create_line(x1, 0, x1, HEIGHT, fill='white')
    for y in range(ROWS):
        y1 = y * cell['size']
        cv.create_line(0, y1, WIDTH, y1, fill='white')


#Place and cancel cells with mouse clicks
def place_cells(e):
    draw_grid()
    #Calculate the index to draw the cell from the clicked coordinates
    x, y = e.x // cell['size'], e.y // cell['size']
    #Delete the cell that has already been drawn.
    if data[y][x]:
        cv.delete('current')
        data[y][x] = False
    #Draw a cell.
    else:
        x1, y1 = x * cell['size'], y * cell['size']
        cv.create_oval(x1, y1, x1+cell['size'], y1+cell['size'], fill=cell['color'])
        data[y][x] = True


cv.bind('<Button>', place_cells)  #When Canvas is clicked


#How many cells around you are alive determines your destiny for the next generation
def check_cells(x, y):
    #Relative coordinates of surrounding cells
    tbl = [(-1, -1), (0, -1), (1, -1), (1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0)]
    cnt = 0  #Number of living cells around
    #Check the surrounding cells one by one
    for t in tbl:
        xx, yy = x + t[0], y + t[1]  #Calculate the absolute value of the surrounding cells.
        if not 0 <= xx < COLS or not 0 <= yy < ROWS:
            continue
        if data[yy][xx]:
            cnt += 1  #Count if the surrounding cells are alive.

    if cnt == 3:
        return True  #birth
    if data[y][x]:  #If you are alive
        if 2 <= cnt <= 3:
            return True  #Survival
        return False  #Overcrowding, depopulation
    return data[y][x]  #Maintain the status quo


#Find out the fate of the next generation of cells.
def next_turn(e):
    global data
    global update
    #Save the updated data at 1 o'clock
    data2 = [[check_cells(x, y) for x in range(COLS)] for y in range(ROWS)]
    data = data2  #Update data
    update += 1  #Count the number of updates
    text.set(update)  #Update the number of generations
    draw()


win.bind('<Return>', next_turn)  #When Enter is pressed


#Draw a cell.
def draw():
    cv.delete('all')
    for y in range(ROWS):
        for x in range(COLS):
            if data[y][x]:
                x1, y1 = x * cell['size'], y * cell['size']
                cv.create_oval(x1, y1, x1+cell['size'], y1+cell['size'], fill=cell['color'])


win.mainloop()

Life games seem to have various patterns. https://ja.wikipedia.org/wiki/%E3%83%A9%E3%82%A4%E3%83%95%E3%82%B2%E3%83%BC%E3%83%A0 image.png

Recommended Posts

Create a life game that is manually updated with tkinter
[Learning record] Create a mysterious dungeon game with Pyhton's Tkinter
Create a GUI app with Python's Tkinter
I made a life game with Numpy
Create a frame with transparent background with tkinter [Python]
Create a GUI executable file created with tkinter
Create a game UI from scratch with pygame2!
Create a page that loads infinitely with python
Create a matrix with PythonGUI (tkinter combo box)
Create a fake class that also cheats is instance
Create a native GUI app with Py2app and Tkinter
Try to dynamically create a Checkbutton with Python's Tkinter
Create a chatbot that supports free input with Word2Vec
I want to manually create a legend with matplotlib
[Python] Create a Tkinter program distribution file with cx_Freeze
Create a web application that recognizes numbers with a neural network
Create a PythonBox that outputs with Random after PEPPER Input
[Python] Create a file & folder path specification screen with tkinter
Generate a password that is easy to remember with apg
Let's create a script that registers with Ideone.com in Python.
Create a homepage with django
Create Image Viewer with Tkinter
Create a heatmap with pyqtgraph
I made a puzzle game (like) with Tkinter in Python
Tornado-Let's create a Web API that easily returns JSON with JSON
Create a web API that can deliver images with Django
Create a directory with python
Life game with Python [I made it] (on the terminal & Tkinter)
Create a program that can generate your favorite images with Selenium
Make a Spinbox that can be displayed in Binary with Tkinter
[LINE Messaging API] Create a BOT that connects with someone with Python
Create a poster with matplotlib to visualize multiplication tables that remember multiplication
Make a Spinbox that can be displayed in HEX with Tkinter
I made a program that automatically calculates the zodiac with tkinter
[Python] What is a with statement?
Create a python GUI using tkinter
Create a virtual environment with Python!
Life game with Python! (Conway's Game of Life)
Zura made like a life game
Create a poisson stepper with numpy.random
Create a file uploader with Django
Create a BOT that can call images registered with Discord like pictograms
Create a web app that can be easily visualized with Plotly Dash
Macbook Air with M1 is here! Quickly create a Python computing environment
Create a Python function decorator with Class
[Python] A program that creates stairs with #
Let's make a shiritori game with Python
Build a blockchain with Python ① Create a class
Create a dummy image with Python + PIL.
[Python] Create a virtual environment with Anaconda
Let's create a free group with Python
Create a large text file with shellscript
Create a star system with Blender 2.80 script
Create a virtual environment with Python_Mac version
Create a VM with a YAML file (KVM)
Create a simple web app with flask
Create a new dict that combines dicts
Create a word frequency counter with Python 3.4
Live a typingless Twitter life with Alexa
[Python] Create a LineBot that runs regularly
Create a Connecting Nearest Neighbor with NetworkX