This tutorial demonstrates how to create a custom Snake Game environment using OpenAI Gymnasium and Stable Baselines3 for reinforcement learning. The environment is built by defining a grid-based game state with numpy arrays, where values represent empty spaces, snake tiles, walls, and food. Key components include defining action spaces (straight, left, right), observation spaces (head position, direction, full grid), and reward systems that incentivize moving toward food while punishing death. The tutorial covers implementing the reset method to restore initial states, the step function to process agent actions and update game state, and rendering functions for visualization. The model uses Proximal Policy Optimization (PPO) with multi-input policy, and training involves millions of time steps to achieve competent snake gameplay.
Reinforcement Learning Snake AI: Stable Baselines3 Tutorial
Added:in this video I'm going to show you how I made an AI play Snake Game using stable baselines 3 and open AI gymnasium in under 10 minutes credit where it's due I got a fair bit of the code from Mr David ganof and his towards data science article lastly I will assume familiarity with basic python numpy arrays and reinforcement learning now let's get started first Imports we'll use numpy arrays to build the grid of the game map plot lib to render the animations and open AI gymnasium to build the environment next to the skeleton for the environment we will build a class for the snake game which inherit from open AI gymnasium we initialize the environment and in it observations are the inputs to the reinforcement learning model step is where we Define the possible actions the agent can take reset is how the agent will prepare the environment for the model to run we will also Define functions grid distance snake plot and render to be used a little later we start with the Snake Game class before the init I'll talk more about metadata later when we build the render function but for now let's let's just set these two modes console and RGB array we want our snake to have three actions available keep going straight turn left or turn right as I mentioned the snake game itself is represented by a numpy array making a grid and its values will be a0 1 2 or three representing empty spaces snake tiles walls or food next UP Rewards as with most reinforcement learning models the goal of the agent is to maximize its reward in our case we will reward the agent for steps towards the food and actually getting food while we'll punish the agent for dying finally to avoid infinite Loops we'll set a maximum number of steps without food at 200 before we continue let's quickly Define the grid distance function since we will use it in the init method we want to record the distance between any two points on the grid to do that we'll quickly fill this function with a numpy command linal to find the distance between two points on the array now for the init method the goal of the init method is to initialize the grid that the agent to play on Define the action space and Define the observation space we set the grid size to 10 for some relatively fast training that still looks good we are counting steps as well so that we can cut it off if there are too many steps without food then we build the grid with walls surrounding the edges the snake in the top left corner and food a bit closer to the center we also want to record the distance from the snake's head to the food since we give the agent reward every time it gets closer to food we copy the grid and qu values so we can manipulate and use these later without changing the originals and now we're ready to move on to the spaces we already defined n actions for how many possible actions there are and the observations we want to give the agent are the position of the head the direction the snake is facing and the full grid now the reset method we're basically just resetting the environment back to its initial state to do so we reset the step num and food steps back to zero and then reset the grid snake and distance values back to their initial States we use the random seating this way for convenience in training the model but it's not too important here if you want to learn more about random seeds look up random B tables to learn more about how computers and calculators Generate random numbers lastly we want to return the observation and some information there isn't any extra information for our environment here though so we'll just leave it as an empty dictionary in regards to the observation we'll Define the observation method now remember the observations we want to give the agent are the position of the head the direction the snake is facing and the full grid we can find the direction by just subtracting the head snakes coordinates by the coordinates of the snake body tile right before it the position is just the head's coordinates and the grid was previously defined now the step function we start by again finding the direction and then testing the various actions so if the agent tries to turn the snake right we want the snake to actually turn right and so on we put the head in the new place and add it to the snake coordinates list then we set done to false and reward to Zero by default setting reward to zero is important here and it's also very important to note that this is not self.
reward as the agent goes along it records how much reward it receives each step and adds this to its own internal total we as a programmers do not have to keep track of its reward when using stable baselines 3 at this point we have increased the snake size by default whether it has gotten any food or not though so let's fix that first we check if it has actually gotten food if so we need to reward the agent then we need to add more food wherever there is space if there's no space on the grid that means the snake is taking up 100% of the map except walls so the agent wins the game we can set done true then if the agent did not get any food we remove the snake extension and perform a further check to ensure it has not died yet if it has we need to punish it assuming the agent hasn't died yet we need to refresh the value for the distance between the snake's head and the food if it's getting closer to food we want to reward it and if it's getting further we want to punish it lastly if it has been over the maximum allowed steps without food for us that's 200 we want to kill the snake to avoid infinite Loops two functions left render and snake plot we'll start with snake plot first off we get the indices of the walls snake body and food in the grid then we build a 3D color array using numpy walls will be shown as black food as red and the snake as green we're choosing these colors using RGB something important to note is that the snake plot function is only for us to visualize in the render function the agent itself never sees the color arrays it only sees the numbers that make up the numpy array grid which is why it will be able to train very quickly now finally render the function itself is very simple if you want to see results in the console use mode console and if you want to visualize the results as a snake game use RGB you may recall that these are the values from the metadata at the start of our program and in our case all they really are is identifiers for the type of output you want to see we're done creating the environment and now we want to give it a quick check to be sure everything is working fine before we get started with actually training we we can use the built-in command given by stable baselines 3 to make sure the environment is in an acceptable format and if we get no warnings we're good to go two more things before we actually start training you need a place to store the model and a model itself to deal with storage we set up a folder in our local directory with a simple OS command then we can wrap it with a monitor and apply a call back function to more easily keep track of the progress as the snake trains now for the model itself the model we'll be using is a proc proximal policy optimization model or a PO from stable baselines 3 and we use a multi-input policy also if we already have a model from prior training we want to start there instead of resetting the training each time finally we've customized the model arguments to speed up learning the learning rate is the rate at which the model will make changes to its algorithm gamma values range from 0 to 1 and they're a measure of how much to prioritize future rewards verbose allows for an even more detailed view of training seed returns to random seating again check out random B tables if you're interested in how computers and calculators Generate random numbers the entropy coefficient is a measure of how much exploration is encouraged and the clip range affects the probability of actions occurring with these arguments in place let's train the model 6 million time steps will give you a good idea if everything's working fine my computer will take about 2 hours to train these 6 million time steps though that time will probably be different depending on the strength and quality of your computers then we reset the environment and prepare a framework to save the results the frames variable is a list that carries each frame that occurs in the animation one step at a time lastly we want to visualize the animation into a gif matplot Libs animation command that we imported in the previous chunk is very useful here with it we can easily save the animation as a gif and view the progress of the AI on screen now is a gif of my snake AI after roughly a day of training as you can see it performs quite well and has even learned some strategies though they are different from what we as humans are used to
Up Next

Automating Hyperparameter Tuning for Reinforcement Learning Agents
@MachineLearningwithPhil
5K views•2019-06-08

IFS Therapy Demonstration: Complete Session with Unburdening
@IFSCA
95.9K views•2021-01-13

FastAPI vs Flask vs Django: Choosing the Right Python Web Framework
@TechWithTim
302.5K views•2024-05-26

Game of Thrones Opening Credits: A Cinematic Analysis
@gameofthrones
46.3M views•2011-04-18
Related Study Plans & Knowledge Roadmaps
Structured learning paths in General & Interdisciplinary Studies


![Lesson-21 | Class Inheritance or Subclasses | [OOP in Python]](https://i.ytimg.com/vi_webp/3XxODqGw1Sg/maxresdefault.webp)










![[Week Extra] Introduction to Machine Learning (noc25-cs46)](https://i.ytimg.com/vi/PZaUQvXcZqU/maxresdefault.jpg)

















![[WiSDOM] An Intriguing Failing of Convolutional NNs & the CoordConv Solution -- Rosanne Liu](https://i.ytimg.com/vi/gMGL-shl3P8/maxresdefault.jpg)







