Hey everyone! I’m trying to make an AI that can play Snake. I’m pretty new to this stuff so I could use some help.
Here’s what I’ve got so far:
- Input: 3 layers of a 10x10 grid (snake body, apple, snake head)
- Output: 4 values for moving up, down, left, or right
I’m not sure if this is the best way to set it up. Any ideas on what kind of neural network I should use? Or if there’s a better way to represent the game state?
Here’s a simple example of how I’m thinking about it:
def get_game_state():
grid = [[[0 for _ in range(10)] for _ in range(10)] for _ in range(3)]
# Fill in grid with game info
return grid
def make_move(direction):
# Update snake position based on direction
pass
# Neural network would go here
Thanks for any advice!
hey there! i’ve played around with snake AIs before. your approach isnt bad, but maybe simplify the input? instead of a full grid, try using distances/directions to nearest wall, apple, and own body. this could make training faster. also, consider using a reinforcement learning algorithm like Q-learning instead of a traditional neural network. good luck with ur project!
I’ve implemented a Snake AI using a different approach that might be worth considering. Instead of a grid-based input, I found success with a more compact representation:
Input: distance and direction to nearest wall, food, and body segment in each of 8 directions (N, NE, E, SE, S, SW, W, NW).
This reduced the input size significantly while still capturing essential information. For the network architecture, I used a simple feedforward network with two hidden layers (64 and 32 neurons) and ReLU activation.
The output remained similar to yours - 4 nodes for movement directions.
This setup allowed for faster training and generalization to different board sizes. You might want to experiment with it and see if it improves your results.
As someone who’s dabbled in game AI, I can share a bit from my experience with Snake. Your approach is solid, but consider a few tweaks. I found that using a convolutional neural network (CNN) works well with grid-based input because it can capture spatial patterns effectively. In my experience, an architecture that combines several convolutional layers with max pooling and follows up with dense layers—using ReLU for hidden nodes and softmax for the final output—is quite effective. I also experimented with adding a vision input by casting rays in eight directions from the snake’s head to detect distances to walls, body, and food, which added a more natural perception of the environment. Finally, defining a reward function that balances survival time, snake length, and proximity to food is key. Training these networks takes time, so patience is essential. Good luck with your project!