{"id":15157754,"url":"https://github.com/shivamgupta92/reinforcement_learning_snakegameai","last_synced_at":"2026-01-19T06:33:32.817Z","repository":{"id":253491319,"uuid":"843675070","full_name":"ShivamGupta92/Reinforcement_learning_SnakeGameAI","owner":"ShivamGupta92","description":"Deep Q-Networks (DQN) to train an AI agent to play the Snake game. The AI controls the snake, making decisions in real-time to maximize its score while avoiding collisions. The agent learns to improve its performance by playing multiple games and adjusting its strategy based on rewards and penalties.","archived":false,"fork":false,"pushed_at":"2024-08-17T04:45:57.000Z","size":1067,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-13T17:18:01.601Z","etag":null,"topics":["agent-based-modeling","artificial-intelligence","dqn-pytorch","neural-network","pygame","python3","pytorch","qlearning-algorithm","reinforcement-learning","snake-game"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ShivamGupta92.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-08-17T04:40:00.000Z","updated_at":"2024-09-01T05:58:24.000Z","dependencies_parsed_at":"2024-08-17T05:37:48.890Z","dependency_job_id":"2fe9680c-11f0-48e6-99b9-314166c56f7e","html_url":"https://github.com/ShivamGupta92/Reinforcement_learning_SnakeGameAI","commit_stats":null,"previous_names":["shivamgupta92/reinforcement_learning_snakegameai"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ShivamGupta92%2FReinforcement_learning_SnakeGameAI","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ShivamGupta92%2FReinforcement_learning_SnakeGameAI/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ShivamGupta92%2FReinforcement_learning_SnakeGameAI/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ShivamGupta92%2FReinforcement_learning_SnakeGameAI/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ShivamGupta92","download_url":"https://codeload.github.com/ShivamGupta92/Reinforcement_learning_SnakeGameAI/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247675632,"owners_count":20977376,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["agent-based-modeling","artificial-intelligence","dqn-pytorch","neural-network","pygame","python3","pytorch","qlearning-algorithm","reinforcement-learning","snake-game"],"created_at":"2024-09-26T20:02:41.753Z","updated_at":"2026-01-19T06:33:32.778Z","avatar_url":"https://github.com/ShivamGupta92.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Snake Game AI using Deep Q-Network (DQN)\n\nThis project implements a Snake game AI using a Deep Q-Network (DQN) approach, a type of reinforcement learning algorithm. The AI learns to play the Snake game by maximizing its score over time through trial and error. Deep Q-Networks (DQN) to train an AI agent to play the Snake game. The AI controls the snake, making decisions in real-time to maximize its score while avoiding collisions. The agent learns to improve its performance by playing multiple games and adjusting its strategy based on rewards and penalties.\n\n## Installation\n\nTo run this project locally, you'll need Python and a few dependencies installed. Follow these steps:\n\n1. **Clone the Repository:**\n   ```sh\n   git clone https://github.com/ShivamGupta92/Reinforcement_learning_SnakeGameA.git\n   cd snake-game-ai-dqn\n   ```\n\n2. **Create a Virtual Environment:**\n   ```sh\n   python3 -m venv venv\n   source venv/bin/activate   # On Windows: venv\\Scripts\\activate\n   ```\n\n3. **Install Required Packages:**\n   ```sh\n   pip install -r requirements.txt\n   ```\n\n4. **Run the Game:**\n   ```sh\n   python agent.py\n   ```\n\n## Usage\n\nOnce the environment is set up, you can start training the AI by running the `agent.py` script. The AI will begin playing the Snake game and gradually learn to improve its score through repeated gameplay.\n\nDuring the training, the AI's performance (score) will be displayed, and a plot of the scores and the moving average will be shown.\n\n## Reinforcement Learning Approach\n\nThe AI uses a **Deep Q-Network (DQN)** for learning how to play the Snake game:\n\n- **Q-Learning:** The AI learns a Q-function, which estimates the expected future rewards for taking a given action in a given state.\n- **Deep Neural Network:** The Q-function is approximated using a neural network, allowing the AI to handle the large state space of the game.\n- **Rewards:** The AI receives positive rewards for eating food and negative rewards for collisions.\n\n## Model Architecture\n\nThe neural network used in this project is a fully connected feedforward network with the following architecture:\n\n- **Input Layer:** Takes in the game state, represented as an 11-dimensional vector.\n- **Hidden Layers:**\n  - Two hidden layers with ReLU activation.\n  - Dropout is applied to the first hidden layer to prevent overfitting.\n- **Output Layer:** Outputs Q-values for each possible action (left, right, straight).\n\n### Model Summary\n\n- **Input Size:** 11\n- **Hidden Layers:** 256, 512 units\n- **Output Size:** 3 (corresponding to the three possible actions)\n- **Activation Function:** ReLU\n- **Dropout:** 20% applied after the first hidden layer\n\n## Training Process\n\nThe training process is handled by the `QTrainer` class, which manages:\n\n- **Forward Pass:** Computes the predicted Q-values for the current state.\n- **Loss Calculation:** The loss is calculated as the difference between predicted and target Q-values using SmoothL1Loss.\n- **Backpropagation:** The loss is backpropagated to update the model's parameters using the AdamW optimizer.\n- **Learning Rate Scheduling:** The learning rate is adjusted periodically to improve convergence.\n\n### Training Details\n\n- **Memory Replay:** The agent stores its experiences in a memory buffer and samples random batches for training to break the correlation between consecutive experiences.\n- **Exploration vs. Exploitation:** An epsilon-greedy strategy is used to balance exploration of new strategies and exploitation of known good strategies.\n- **Model Saving:** The model is periodically saved to a file (`model.pth`) when it achieves a new high score.\n\n## Customization\n\nYou can customize various aspects of the AI and game:\n\n- **Game Settings:** Modify the snake's speed, block size, and screen dimensions in `game.py`.\n- **Model Architecture:** Adjust the neural network structure in `model.py`.\n- **Training Parameters:** Change learning rate, gamma (discount factor), and memory size in `agent.py`.\n\n## Contributing\n   ```sh\n- SHIVAM GUPTA\n   ```\nContributions are welcome! If you'd like to contribute to this project, please fork the repository and submit a pull request with your improvements.\n\n## License\n\nThis project is licensed under the MIT License. See the [MIT LICENSE](LICENSE) file for details.\n\n---\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fshivamgupta92%2Freinforcement_learning_snakegameai","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fshivamgupta92%2Freinforcement_learning_snakegameai","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fshivamgupta92%2Freinforcement_learning_snakegameai/lists"}