Conway's Game of Life in Python
Skills:
AI Pair Programming80%
Key Takeaways
The video implements Conway's Game of Life in Python, covering the basics of the game and its implementation in Python.
Full Transcript
what is going on guys welcome back in today's video we're going to learn how to build the game of life in python so let's get right into [Music] it all right so let me just show you what we're going to end up with this is the game of life implemented in python using pygame and now i can use my mouse here to place individual cells i can also drag my mouse to place multiple cells and the game of life for those who don't know it uh has some very basic rules if a cell that is alive right now so a cell like this one here is surrounded by zero or just one cell it's gonna die due to loneliness if a cell is surrounded by two or three neighbors it's gonna survive if it's surrounded by more than uh three neighbors it's gonna die due to overpopulation and if a cell that is not alive like any of those cells here that are not clicked yet if one of those cells is surrounded or neighbors three active cells it is going to come to life and now i have this playing field here i can also add some more stuff here if i want to and now if i press space you can see that the game of life is happening i can also pause and i can press space again and that is essentially how the game of life works these basic rules uh produce these structures now you can also i think i can also add some cells while i'm doing this here so i can also manipulate the game while it's going and we're going to learn how to do this today in python all right so first things first we need to install pygame and for that we open up a command line and we type pip install pi game like that in my case already installed in addition to that we're also going to need numpy so we're going to type pip install numpy like that in my case installed as well and once we have that we're going to start by importing the core python module time for obvious reasons we're going to import pygame and we're going to import numpy snp and the first thing i want to do here in the code besides the imports is i want to define some basic colors because we're going to reuse colors quite often and we don't want to constantly remember the rgb coats and copy them we want to have some constants here so i'm going to start with a color for the background and this is going to be a pretty dark gray so 10 10 10 i want to have a color for the grit this is going to be still pretty dark but a little bit lighter so 40 40 40. those are rgb values um and then i want to have a color for die next die next iteration so basically want to have white if you're alive and you're going to stay alive and want to have um a very light gray but still not white if you're going to die next round so something like 170 170 170 and then color alive next is going to be just pure white so 255 255 255. those are the colors now the main function we're going to use for basically everything is going to be the update function in addition to the update function we're only going to have the main function which is going to execute everything but the update function has the whole game logic and the whole uh drawing process in it so we're going to say update and we want to have the parameters screen this is going to be the ordinary pi pi game screen that we're going to pass here when i have cells this is going to be the whole playing field so the whole um the whole state of the individual cells and want to have the size this is going to be the size of an individual cell and then last but not least we want to have with progress which is a boolean and want to set it to actually false so the basic idea here is that sometimes we want to update uh the screen without moving to the next generation so we just want to update the screen to see the changes uh to to plot everything but we don't want to go to the next generation we don't want to make a step so to say um so in this case with progress is going to be false and with progress equals true would be also executing the next steps applying the game rule so to say so we're going to start here with updated cells which are going to be returned at the end of the function and this is going to be an np dot empty so an empty numpy array of the following shape it's going to be the cells cells shape 0 and cells shape 1 like that um so this basically creates it takes the shape of the already existing cells and it creates an empty array so basically nothing in there and based on that we're going to then uh in this in this updated cells array we're going we're going to apply the changes so what we're going to do is we're going to say for row and column in npnd index cell shape so what this does essentially takes the shape of the cells of the playing field and it lets us iterate over each individual cell rolling uh row and column y so we take the first cell then the next one the next one next one so on so we go through all the cells all the individual cells and we're going to apply the game rules now so we're going to say okay calculate the number of alive neighboring cells so what we're going to do is we have the cell itself and then we want to see okay all the cells surrounding it how many of those are alive how do we do that we say np sum and we go to cells row minus one so we go one to the uh one one to the top so one up and we want to go until row plus two now y plus two why not plus one uh this is not because of the game logic this is because of how python works when we slice lists because when you say for example one colon five the one is included the five is not so one colon five would actually go up to four including four it would not include five so if we want to include row plus one we need to say row plus two that's just basic slicing and column minus one column plus two so the basic idea is you take a cell you take the top left cell and the bottom right cell everything in between you sum it up and then you have the amount of alive cells in that range now you want to subtract from that the cell itself so cells row call because that cell is also part of that range here and if it's one you have one more life cell that you actually don't want to count so you subtract whatever the cell is if it's zero it basically doesn't change anything if it's one it subtracts one so then what we're going to do is we're going to say okay the color by default we're going to set the color in the if else structure below here but we're going to say okay by default the color is going to be color underscore background if the cells row column is equal to zero else it's going to be color alive next like that and now we're gonna apply the game rules and this is what i talked about in the preview we're gonna say okay if a cell so if cells row column the current cell that we're looking at has the state one so is alive then we said okay if it is alone or only has one neighbor it's gonna die if it has two or three neighbors it's gonna survive if it has more it's gonna die as well so those are the rules that we need to check so we say if alive is less than two and remember alive is the sum of all the neighbors that are alive if it's less than two so basically one or zero or if it's greater than three so overpopulation then we're going to die so this cell is going to die then and this only happens if we have with progress equal to true otherwise we don't apply the game rules remember um so what we do is we say okay color equals color underscore um [Music] die next like that um the other situation that we have is that um two is less or equal to alive less or equal to three then what we do is we say that the updated cells um actually yeah actually this works a row column at this cell is going to be one so if we have that case we essentially just set the updated cells to one in that position because that means we survive the next generation um and then what we do here as well is we say okay if the progress is being applied if we want to display the progress we say uh color alive next that's the basic idea here we don't know anything because uh yeah we we die anyways right so here we don't have to update anything um the other branch is okay the cell is not alive but remember if we have three exactly three neighbors the cell will be alive so we're gonna say okay if alive equals to exactly three we're gonna say okay this cell now is also a live row column and if we also display the progress we're going to set the color to color alive like that um yeah so that's the basic idea and the last thing we do here is we say pie game draw dot rectangle so basically drawing the individual pixels in the color we draw onto the screen that was passed to the function with the color that was determined and now we right we we go to the column times the size row times the size so we go to the position an individual cell has a certain size so we need to go as many cells as columns to write and as many rows as we have down and then we say size minus one size minus one and this plots a rectangle and the last but at least we return the updated cells i hope i didn't make any mistakes here but that's the basic code that's the basic idea that we use here so now we take that function and we use it in the main function so we say main def main and we want to do here first of all we want to initialize pygame we want to create a screen by saying pi game [Music] dot display dot set mode and we're gonna use a classic uh 800 600 so basically if you want to to keep the size flexible you would um define something like a size 10 for example then you would say uh 80 times 10 or 80 times the size and so on but i'm just going to go with 800 and 600 so um that's the idea here and we're going to initialize the cells here as being np zeros and we're gonna have uh the shape 60 and 80. now it's important that we have the shapes the other way around now let me just see if i because i remembered that there was a little bit of confusion while i was preparing the code because we need to um to flip the dimensions here we need to say 6080 not 8060 but besides that we just create the cells and then we fill the screen with the background color so with color bg we're actually no we fill the screen with color grid and then this produces the grid later on and what we do now is we say update screen cells 10 without progress so this basically means we have the grid color as the background and what we do is we go to each individual cell and we fill it with the background color unless we have a reason not to because there is a cell so in the beginning we don't we don't have any cells because we only have zeros which means that after filling with the grit and putting all the empty cells onto the screen we're going to have mostly the background color that's the idea of filling the screen with the grid and then we say pygame dot display dot flip and oh come on and update like that and then all we need to do is we need to say running running equals false while true and now here we have the game loop and the basic idea of the game loop is that uh we're going to to be asking for key inputs all the time and if we notice that i'm pressing the space button for example it's going to trigger that running is going to be set to true and this is going to trigger the update process being executed with progress so that is what we're going to do here we have this endless loop and we're going to say now for event that happens in pygame event dot get so for each event we get here if the event type is equal to pie game dot quit so that's just the ordinary uh quitting in pie game um [Music] then what happens is we basically just exit so we say pie game dot quit and then we return from that function otherwise if the type of event and this is where we now add the key if the event type is pi game dot key down um then what we're going to do is we're going to ask which key it was because we don't want to react to every key if the event dot key is equal to pi game dot k underscore space so if we press the space button that means that we're going to now change the state so this is going to toggle the running because we also want to be able to pause the whole thing so you're going to say running is essentially not running changing the state of running which means that if it's true it's now going to be false if it's font's now going to be true and so on um and then we're going to update the screen the cells with the signed size 10. the basic idea of this is that when we pause we want to have an updated screen and we don't want to to um have more stuff happening just because we didn't update uh when we stopped so graphically it just looks better and then we're going to say pie game display dot update so that we can see now okay we're done uh we're pausing or we're continuing and what we're going to do now is we're going to say if pie game this is the probably the most important part because we want to add some cells if pie game dot mouse dot get pressed so if we have pressed the mouse uh we want to know okay where is it pressed we want to get the position so we're going to say pause equals pie game dot mouse dot get pause for get position and then we're gonna say that the cells at that position the cell at that position is gonna be set to one because with a mouse we activated that cell so we're gonna say okay position one again think invertedly here position one floor divided by ten four divided by the size if you have a constant and position zero floor divided by that ten going to be set to 1. and then we're going to update the screen cells 10 and we're going to say pie game display update there you go and every time we're gonna fill the screen again so screen dot fill with color grid that's the basic idea now we don't have yet the whole progress with the progress so we say okay if running is actually true so if we press space and now the whole thing is running we're going to say cells equal and this is important the first time now we get the actual return value cells equals update screen cells 10 with progress true so this is the actual simulation and then pi game display update and last but not least time sleep zero zero one zero zero zero one actually okay and now if name equals main then call me that is the whole thing now before we recap the code let me see if that actually works so here i can now play some things there you go there you go there you go okay almost some some problem here let me see where we did that i think it has to be somewhere in the update function okay so i think i found my mistake actually quite a stupid mistake especially since i did a numpy course just recently of course we don't want to use the empty function because the empty function just allocates space and it leaves the values that are there by default so it doesn't initialize that with zeros and if we have something that's not a zero of course uh yeah this is problematic so we want to use the zeros function instead not the mt function and now i think it should work so if i just create some cells here again there you go now this looks like it works yeah okay so that's the basic idea now let's recap the code so that we can summarize what we have been doing here um here we have the constants for the colors here the update function is the most important function it's the function that applies the game rules and also updates uh the the display so basically plots all the individual cells so we create an updated cells now with zeros not with empty because we want to have zeros in there not just some random values we iterate over all the individual cells by iterating through rows and columns we calculate the live cells alive neighbor cells we determine the color based on this uh whether the cell is alive or not so the default color and then we apply the rules and if we have the with progress on which is only in the last call of the function we do in every iteration um we change the color depending on the game rules which you can see here then we draw the rectangle and here all we do is we initialize uh a playing field with 60 times 80 or 80 times 60 with the respective resolution we plot the grid on top of the grid we plot all the individual cells we update the display and now we wait for key presses so if we have space we change the state of the boolean running and if we press the mouse we determine the position of the mouse and we set that respective cell to one and if the whole thing is running we update the cells and actually also visually update the cells and we return and then we repeat the whole process this is how you implement the game of life in python so that's it for today's video i hope you enjoyed it and hope you learned something if so let me know by hitting a like button and leaving a comment in the comment section down below and of course don't forget to subscribe to this channel and hit the notification bell to not miss a single future video for free other than that thank you much for watching see you next video and bye [Music] you
Original Description
In this video, we will implement Conway's Game of Life in Python.
◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾
📚 Programming Books & Merch 📚
🐍 The Python Bible Book: https://www.neuralnine.com/books/
💻 The Algorithm Bible Book: https://www.neuralnine.com/books/
👕 Programming Merch: https://www.neuralnine.com/shop
🌐 Social Media & Contact 🌐
📱 Website: https://www.neuralnine.com/
📷 Instagram: https://www.instagram.com/neuralnine
🐦 Twitter: https://twitter.com/neuralnine
🤵 LinkedIn: https://www.linkedin.com/company/neuralnine/
📁 GitHub: https://github.com/NeuralNine
🎙 Discord: https://discord.gg/JU4xr8U3dm
🎵 Outro Music From: https://www.bensound.com/
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from NeuralNine · NeuralNine · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Visualizing Stock Data With Candlestick Charts in Python
NeuralNine
Python Beginner Tutorial #1 - Installation and First Program
NeuralNine
Python Beginner Tutorial #2 - Variables and Data Types
NeuralNine
Python Beginner Tutorial #3 - Operators and User Input
NeuralNine
Python Beginner Tutorial #4 - If Statements and Conditions
NeuralNine
Python Beginner Tutorial #5 - Loops
NeuralNine
Python Beginner Tutorial #6 - Sequences and Collections
NeuralNine
Python Beginner Tutorial #7 - Functions
NeuralNine
Python Beginner Tutorial #8 - Exception Handling
NeuralNine
Python Beginner Tutorial #9 - File Operations
NeuralNine
Python Beginner Tutorial #10 - String Functions
NeuralNine
Python Intermediate Tutorial #1 - Classes and Objects
NeuralNine
Python Intermediate Tutorial #2 - Inheritance
NeuralNine
Python Intermediate Tutorial #3 - Multithreading
NeuralNine
Python Intermediate Tutorial #4 - Synchronizing Threads
NeuralNine
Python Intermediate Tutorial #5 - Events and Daemon Threads
NeuralNine
Python Intermediate Tutorial #6 - Queues
NeuralNine
Python Intermediate Tutorial #7 - Sockets and Network Programming
NeuralNine
Python Intermediate Tutorial #8 - Database Programming
NeuralNine
Python Intermediate Tutorial #9 - Recursion
NeuralNine
Python Intermediate Tutorial #10 - XML Processing
NeuralNine
Python Intermediate Tutorial #11 - Logging
NeuralNine
Python Data Science Tutorial #1 - Anaconda and PyCharm Setup
NeuralNine
Python Data Science Tutorial #2 - NumPy Arrays
NeuralNine
Python Data Science Tutorial #3 - Numpy Functions
NeuralNine
Python Data Science Tutorial #4 - Plotting Functions With Matplotlib
NeuralNine
Python Data Science Tutorial #5 - Subplots and Multiple Windows
NeuralNine
Python Data Science Tutorial #6 - Matplotlib Styling
NeuralNine
Python Data Science Tutorial #7 - Bar Charts with Matplotlib
NeuralNine
Python Data Science Tutorial #8 - Pie Charts with Matplotlib
NeuralNine
Python Data Science Tutorial #9 - Plotting Histograms with Matplotlib
NeuralNine
Python Data Science Tutorial #10 - Scatter Plots with Matplotlib
NeuralNine
Python Data Science Tutorial #11 - 3D Plotting with Matplotlib
NeuralNine
Python Data Science Tutorial #12 - Pandas Series
NeuralNine
Python Data Science Tutorial #13 - Pandas Data Frames
NeuralNine
Python Data Science Tutorial #14 - Pandas Statistics
NeuralNine
Python Data Science Tutorial #15 - Pandas Sorting and Functions
NeuralNine
Python Data Science Tutorial #16 - Pandas Merging Data Frames
NeuralNine
Python Data Science Tutorial #17 - Pandas Queries
NeuralNine
Python Machine Learning Tutorial #1 - What is Machine Learning?
NeuralNine
Python Machine Learning Tutorial #2 - Linear Regression
NeuralNine
Python Machine Learning Tutorial #3 - K-Nearest Neighbors Classification
NeuralNine
Python Machine Learning #4 - Support Vector Machines
NeuralNine
Python Machine Learning Tutorial #5 - Decision Trees and Random Forest Classification
NeuralNine
Python Machine Learning Tutorial #6 - K-Means Clustering
NeuralNine
Python Machine Learning Tutorial #7 - Neural Networks
NeuralNine
Python Machine Learning Tutorial #8 - Handwritten Digit Recognition with Tensorflow
NeuralNine
Generating Poetic Texts with Recurrent Neural Networks in Python
NeuralNine
Stock Portfolio Visualization with Matplotlib in Python
NeuralNine
Analyzing Coronavirus with Python (COVID-19)
NeuralNine
Making Text Images Readable Again with Python and OpenCV
NeuralNine
Neural Networks Simply Explained (Theory)
NeuralNine
Motion Filtering with OpenCV in Python
NeuralNine
Top 5 Programming Languages To Learn in 2020
NeuralNine
Simple TCP Chat Room in Python
NeuralNine
Image Classification with Neural Networks in Python
NeuralNine
Edge Detection with OpenCV in Python
NeuralNine
S&P 500 Web Scraping with Python
NeuralNine
Simple Sentiment Text Analysis in Python
NeuralNine
Introduction - Algorithms & Data Structures #1
NeuralNine
More on: AI Pair Programming
View skill →Related Reads
📰
📰
📰
📰
Building Production-Ready AI Features in Next.js: Beyond the Chatbot
Medium · Programming
How I Built Transcriber - Local Whisper Voice Backend for Browser AI Tools
Dev.to AI
Where Code Meets Medicine, Chemistry, and Even Religion
Dev.to · Daniel Ioni
Fable 5 Costs 5x More Per Task Than Grok 4.5. Here’s Whether That Actually Matters.
Medium · AI
🎓
Tutor Explanation
DeepCamp AI