Creating an advanced Q-learning AI for the classic Snake game in Python involves several steps:
-
Implementing the Snake Game: We'll use the pygame library to create the game environment where the AI will learn to play.
-
Designing the Q-Learning Agent: The agent will interact with the game environment, learning optimal actions based on rewards.
-
Training the AI: The agent will undergo multiple episodes of gameplay, updating its Q-table based on experiences.
-
Observing Training Progress: We'll include print statements to monitor the training progress, such as episode numbers and scores.
Below is a complete implementation of a Q-learning Snake AI in Python. Ensure you have pygame and numpy installed in your environment. You can install them using pip if you haven't already:
pip install pygame numpy
1. Import Necessary Libraries
import pygame
import random
import numpy as np
from enum import Enum
from collections import deque
import sys
import math
2. Define Game Constants and Enums
# Initialize pygame
pygame.init()
font = pygame.font.Font(None, 36)
# Screen dimensions
BLOCK_SIZE = 20
SNAKE_SPEED = 15 # Initial speed
class Direction(Enum):
RIGHT = 1
LEFT = 2
UP = 3
DOWN = 4
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
3. Implement the Snake Game Environment
class SnakeGameAI:
def __init__(self, w=640, h=480):
self.w = w
self.h = h
self.display = pygame.display.set_mode((self.w, self.h))
pygame.display.set_caption('Q-Learning Snake AI')
self.clock = pygame.time.Clock()
self.reset()
def reset(self):
self.direction = Direction.RIGHT
self.head = Point(self.w / 2, self.h / 2)
self.snake = [self.head,
Point(self.head.x - BLOCK_SIZE, self.head.y),
Point(self.head.x - (2 * BLOCK_SIZE), self.head.y)]
self.score = 0
self.food = None
self._place_food()
self.frame_iteration = 0
def _place_food(self):
x = random.randint(0, (self.w - BLOCK_SIZE )//BLOCK_SIZE ) * BLOCK_SIZE
y = random.randint(0, (self.h - BLOCK_SIZE )//BLOCK_SIZE ) * BLOCK_SIZE
self.food = Point(x, y)
if self.food in self.snake:
self._place_food()
def play_step(self, action):
self.frame_iteration += 1
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Move
self._move(action) # Update the head
self.snake.insert(0, self.head)
# Check if game over
reward = 0
game_over = False
if self._is_collision() or self.frame_iteration > 100 * len(self.snake):
game_over = True
reward = -10
return reward, game_over, self.score
# Place new food or just move
if self.head.x == self.food.x and self.head.y == self.food.y:
self.score += 1
reward = 10
self._place_food()
else:
self.snake.pop()
# Update UI and clock
self._update_ui()
self.clock.tick(SNAKE_SPEED)
# Return game over and score
return reward, game_over, self.score
def _is_collision(self, point=None):
if point is None:
point = self.head
# Hits boundary
if point.x > self.w - BLOCK_SIZE or point.x < 0 or point.y > self.h - BLOCK_SIZE or point.y < 0:
return True
# Hits itself
if point in self.snake[1:]:
return True
return False
def _update_ui(self):
self.display.fill((0,0,0))
for pt in self.snake:
pygame.draw.rect(self.display, (0,255,0), pygame.Rect(pt.x, pt.y, BLOCK_SIZE, BLOCK_SIZE))
pygame.draw.rect(self.display, (0,200,0), pygame.Rect(pt.x+4, pt.y+4, 12, 12))
pygame.draw.rect(self.display, (255,0,0), pygame.Rect(self.food.x, self.food.y, BLOCK_SIZE, BLOCK_SIZE))
text = font.render("Score: " + str(self.score), True, (255,255,255))
self.display.blit(text, [0, 0])
pygame.display.flip()
def _move(self, action):
# [straight, right, left] relative to current direction
clock_wise = [Direction.RIGHT, Direction.DOWN, Direction.LEFT, Direction.UP]
idx = clock_wise.index(self.direction)
if np.array_equal(action, [1, 0, 0]):
new_dir = clock_wise[idx] # no change
elif np.array_equal(action, [0, 1, 0]):
next_idx = (idx + 1) % 4
new_dir = clock_wise[next_idx] # right turn r -> d -> l -> u
else: # [0, 0, 1]
next_idx = (idx - 1) % 4
new_dir = clock_wise[next_idx] # left turn r -> u -> l -> d
self.direction = new_dir
x = self.head.x
y = self.head.y
if self.direction == Direction.RIGHT:
x += BLOCK_SIZE
elif self.direction == Direction.LEFT:
x -= BLOCK_SIZE
elif self.direction == Direction.DOWN:
y += BLOCK_SIZE
elif self.direction == Direction.UP:
y -= BLOCK_SIZE
self.head = Point(x, y)
4. Define the Q-Learning Agent
class QLearningAgent:
def __init__(self, state_size, action_size):
self.state_size = state_size # Number of possible states
self.action_size = action_size # Number of possible actions
self.q_table = {} # Initialize Q-table as a dictionary
self.epsilon = 1.0 # Exploration rate
self.epsilon_decay = 0.995
self.epsilon_min = 0.01
self.gamma = 0.9 # Discount factor
self.alpha = 0.1 # Learning rate
def get_state(self, game):
head = game.snake[0]
point_l = Point(head.x - BLOCK_SIZE, head.y)
point_r = Point(head.x + BLOCK_SIZE, head.y)
point_u = Point(head.x, head.y - BLOCK_SIZE)
point_d = Point(head.x, head.y + BLOCK_SIZE)
dir_l = game.direction == Direction.LEFT
dir_r = game.direction == Direction.RIGHT
dir_u = game.direction == Direction.UP
dir_d = game.direction == Direction.DOWN
# Danger straight
if dir_r:
dir_straight = [head.x + BLOCK_SIZE, head.y]
dir_right = [head.x, head.y + BLOCK_SIZE]
dir_left = [head.x, head.y - BLOCK_SIZE]
elif dir_l:
dir_straight = [head.x - BLOCK_SIZE, head.y]
dir_right = [head.x, head.y - BLOCK_SIZE]
dir_left = [head.x, head.y + BLOCK_SIZE]
elif dir_u:
dir_straight = [head.x, head.y - BLOCK_SIZE]
dir_right = [head.x + BLOCK_SIZE, head.y]
dir_left = [head.x - BLOCK_SIZE, head.y]
elif dir_d:
dir_straight = [head.x, head.y + BLOCK_SIZE]
dir_right = [head.x - BLOCK_SIZE, head.y]
dir_left = [head.x + BLOCK_SIZE, head.y]
# Danger in each direction
danger_straight = game._is_collision(Point(dir_straight[0], dir_straight[1]))
danger_right = game._is_collision(Point(dir_right[0], dir_right[1]))
danger_left = game._is_collision(Point(dir_left[0], dir_left[1]))
# Food location
food_left = game.food.x < game.head.x
food_right = game.food.x > game.head.x
food_up = game.food.y < game.head.y
food_down = game.food.y > game.head.y
state = (
danger_straight,
danger_right,
danger_left,
dir_l,
dir_r,
dir_u,
dir_d,
food_left,
food_right,
food_up,
food_down
)
return state
def choose_action(self, state):
if state not in self.q_table:
self.q_table[state] = np.zeros(self.action_size)
if np.random.rand() < self.epsilon:
action = random.randint(0, self.action_size -1)
else:
action = np.argmax(self.q_table[state])
return action
def learn(self, state, action, reward, next_state, done):
if state not in self.q_table:
self.q_table[state] = np.zeros(self.action_size)
if next_state not in self.q_table:
self.q_table[next_state] = np.zeros(self.action_size)
predict = self.q_table[state][action]
if done:
target = reward
else:
target = reward + self.gamma * np.max(self.q_table[next_state])
self.q_table[state][action] += self.alpha * (target - predict)
if done:
if self.epsilon > self.epsilon_min:
self.epsilon *= self.epsilon_decay
5. Training the AI
def train():
num_episodes = 1000
game = SnakeGameAI()
state_size = 11 # As defined in get_state
action_size = 3 # [straight, right, left]
agent = QLearningAgent(state_size, action_size)
scores = deque(maxlen=100)
for episode in range(num_episodes):
game.reset()
state = agent.get_state(game)
done = False
total_reward = 0
while not done:
action = agent.choose_action(state)
action_onehot = [0,0,0]
action_onehot[action] = 1
reward, done, score = game.play_step(action_onehot)
next_state = agent.get_state(game)
agent.learn(state, action, reward, next_state, done)
state = next_state
total_reward += reward
scores.append(score)
mean_score = sum(scores)/len(scores)
print(f"Episode {episode+1} | Score: {score} | Mean Score: {mean_score:.2f} | Epsilon: {agent.epsilon:.2f}")
print("Training completed.")
6. Running the Training
if __name__ == "__main__":
train()
7. Explanation of Key Components
-
State Representation: The state consists of 11 boolean flags indicating dangers and the current direction, as well as the relative position of the food. This compact representation helps the agent make decisions without an overwhelming state space.
-
Actions: The agent has three possible actions:
[1, 0, 0]: Move straight.
[0, 1, 0]: Turn right.
[0, 0, 1]: Turn left.
-
Q-Learning Parameters:
- Epsilon (ε): Controls exploration vs. exploitation. It starts at 1.0 (full exploration) and decays over time.
- Gamma (γ): Discount factor for future rewards.
- Alpha (α): Learning rate determining how much new information overrides old information.
-
Reward Structure:
- +10: When the snake eats food.
- -10: When the game is over (collision).
- 0: For every other step.
-
Training Loop:
- For each episode, the game is reset.
- The agent interacts with the environment by choosing actions based on the current state.
- After each action, the agent learns from the experience and updates its Q-table.
- Training progress is printed, showing the episode number, current score, mean score over the last 100 episodes, and the current epsilon value.
8. Enhancements for Advanced Learning
While the above implementation provides a foundational Q-learning AI for Snake, here are some enhancements you can consider for more advanced learning:
-
Function Approximation: Instead of using a Q-table, utilize neural networks to approximate the Q-values. Libraries like TensorFlow or PyTorch can be integrated for this purpose.
-
Experience Replay: Store experiences and sample random mini-batches to break the correlation between sequential data, improving learning stability.
-
Double Q-Learning: Use two separate Q-tables or networks to reduce overestimation of Q-values.
-
Prioritized Experience Replay: Prioritize important experiences to learn more effectively from critical mistakes or successes.
-
Deep Q-Networks (DQN): Combining deep learning with Q-learning to handle larger state spaces more effectively.
9. Final Notes
-
Performance Considerations: Q-learning with a Q-table can become inefficient for large state spaces. If you plan to scale this project, consider moving towards deep reinforcement learning approaches.
-
Visualization: The pygame window will display the game during training. You can adjust the SNAKE_SPEED to control the training speed. Setting it to a higher value speeds up training.
-
Saving and Loading the Q-Table: To preserve the learned Q-table between sessions, implement saving mechanisms using pickle or similar libraries.
-
Hyperparameter Tuning: Experiment with different values for epsilon_decay, gamma, alpha, and other hyperparameters to achieve better performance.
This implementation provides a solid starting point for creating a Q-learning AI to play Snake. As you experiment and enhance the agent, you'll gain deeper insights into reinforcement learning and its applications.