Creating an advanced Q-learning AI for the Snake game involves several key components:
- Snake Game Environment: A simulation where the snake moves, eats food, and avoids collisions.
- Q-Learning Agent: Implements the Q-learning algorithm to learn optimal actions based on states.
- State Representation: Efficiently encodes the game state to make learning feasible.
- Training Loop: Runs episodes where the agent interacts with the environment and updates its knowledge.
- Logging: Records important metrics and observations for analysis.
Below is a comprehensive Python implementation of such an AI, complete with detailed comments and logging capabilities.
Dependencies
First, ensure you have the following dependencies installed:
pip install pygame numpy pandas
1. Snake Game Environment
We'll use pygame to create the Snake game environment. The environment will provide necessary information to the agent, such as the snake's position, food position, and possible actions.
import pygame
import random
from enum import Enum
from collections import namedtuple
import numpy as np
import pandas as pd
import os
import sys
import math
import time
import logging
# Initialize logging
logging.basicConfig(
filename='q_learning_snake.log',
level=logging.INFO,
format='%(asctime)s:%(levelname)s:%(message)s'
)
# Define directions
class Direction(Enum):
RIGHT = 1
LEFT = 2
UP = 3
DOWN = 4
# Define a simple Point structure
Point = namedtuple('Point', 'x, y')
# RGB Colors
WHITE = (255, 255, 255)
RED = (200,0,0)
BLUE1 = (0, 0, 255)
BLUE2 = (0, 100, 255)
BLACK = (0,0,0)
# Game settings
BLOCK_SIZE = 20
SPEED = 100 # Initial speed
class SnakeGameAI:
def __init__(self, w=640, h=480):
self.w = w
self.h = h
# Initialize pygame
pygame.init()
self.display = pygame.display.set_mode((self.w, self.h))
pygame.display.set_caption('Snake AI')
self.clock = pygame.time.Clock()
self.reset()
def reset(self):
# Initialize game state
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):
'''
action: [straight, right, left]
'''
self.frame_iteration += 1
# 1. Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# 2. Move
self._move(action) # Update the head
self.snake.insert(0, self.head)
# 3. 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
# 4. Place new food or just move
if self.head == self.food:
self.score += 1
reward = 10
self._place_food()
else:
self.snake.pop()
# 5. Update UI and clock
self._update_ui()
self.clock.tick(SPEED)
# 6. Return game over and score
return reward, game_over, self.score
def is_collision(self, pt=None):
if pt is None:
pt = self.head
# Hits boundary
if pt.x > self.w - BLOCK_SIZE or pt.x < 0 or pt.y > self.h - BLOCK_SIZE or pt.y < 0:
return True
# Hits itself
if pt in self.snake[1:]:
return True
return False
def _update_ui(self):
self.display.fill(BLACK)
for pt in self.snake:
pygame.draw.rect(self.display, BLUE1, pygame.Rect(pt.x, pt.y, BLOCK_SIZE, BLOCK_SIZE))
pygame.draw.rect(self.display, BLUE2, pygame.Rect(pt.x+4, pt.y+4, 12, 12))
pygame.draw.rect(self.display, RED, pygame.Rect(self.food.x, self.food.y, BLOCK_SIZE, BLOCK_SIZE))
font = pygame.font.SysFont('arial', 25)
text = font.render("Score: " + str(self.score), True, WHITE)
self.display.blit(text, [0, 0])
pygame.display.flip()
def _move(self, action):
'''
action is a list: [straight, right, left]
'''
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)
2. Q-Learning Agent
The agent uses Q-learning to decide actions based on the current state. It maintains a Q-table that maps state-action pairs to Q-values.
class QLearningAgent:
def __init__(self):
self.q_table = {} # {(state): [action_values]}
self.learning_rate = 0.1
self.discount_factor = 0.9
self.epsilon = 1.0 # Exploration rate
self.epsilon_decay = 0.995
self.epsilon_min = 0.01
self.actions = [0, 1, 2] # straight, right, left
def get_state(self, game):
head = game.head
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 game.direction == Direction.RIGHT:
danger_straight = game.is_collision(point_r)
danger_right = game.is_collision(point_d)
danger_left = game.is_collision(point_u)
elif game.direction == Direction.LEFT:
danger_straight = game.is_collision(point_l)
danger_right = game.is_collision(point_u)
danger_left = game.is_collision(point_d)
elif game.direction == Direction.UP:
danger_straight = game.is_collision(point_u)
danger_right = game.is_collision(point_r)
danger_left = game.is_collision(point_l)
elif game.direction == Direction.DOWN:
danger_straight = game.is_collision(point_d)
danger_right = game.is_collision(point_l)
danger_left = game.is_collision(point_r)
# 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 get_action(self, state):
# Initialize Q-values for new states
if state not in self.q_table:
self.q_table[state] = [0, 0, 0] # for each action
# Epsilon-greedy action selection
if np.random.rand() < self.epsilon:
action = random.choice(self.actions)
else:
state_values = self.q_table[state]
max_value = max(state_values)
actions_with_max = [i for i, val in enumerate(state_values) if val == max_value]
action = random.choice(actions_with_max)
return action
def update_q_table(self, state, action, reward, next_state, done):
if state not in self.q_table:
self.q_table[state] = [0, 0, 0]
if next_state not in self.q_table:
self.q_table[next_state] = [0, 0, 0]
q_predict = self.q_table[state][action]
if done:
q_target = reward
else:
q_target = reward + self.discount_factor * max(self.q_table[next_state])
self.q_table[state][action] += self.learning_rate * (q_target - q_predict)
# Decay epsilon
if done:
if self.epsilon > self.epsilon_min:
self.epsilon *= self.epsilon_decay
3. Training Loop
The training loop runs multiple episodes where the agent interacts with the game environment, learns from experiences, and updates its Q-table.
def train():
scores = []
record = 0
agent = QLearningAgent()
game = SnakeGameAI()
# For logging
training_data = []
num_episodes = 1000
start_time = time.time()
for episode in range(num_episodes):
game.reset()
state = agent.get_state(game)
done = False
total_reward = 0
while not done:
action = agent.get_action(state)
# Convert action to [straight, right, left]
action_one_hot = [0,0,0]
action_one_hot[action] = 1
reward, done, score = game.play_step(action_one_hot)
next_state = agent.get_state(game)
agent.update_q_table(state, action, reward, next_state, done)
state = next_state
total_reward += reward
if done:
scores.append(score)
if score > record:
record = score
# Log episode data
logging.info(f"Episode: {episode}, Score: {score}, Total Reward: {total_reward}, Epsilon: {agent.epsilon}")
print(f"Episode {episode} - Score: {score}, Record: {record}, Epsilon: {agent.epsilon:.4f}")
end_time = time.time()
duration = end_time - start_time
logging.info(f"Training completed in {duration} seconds.")
# Save Q-table
pd.to_pickle(agent.q_table, "q_table.pkl")
print('Training completed.')
if __name__ == '__main__':
train()
4. Logging and Observations
The implementation uses Python's built-in logging module to record important information such as episode number, score, total reward, and exploration rate (epsilon). Logs are saved to q_learning_snake.log. Additionally, the Q-table is saved as a pickle file (q_table.pkl) for future use or analysis.
You can further enhance logging by saving more detailed observations or plotting the training progress. For example, you can store scores and plot them using libraries like matplotlib.
5. Playing with the Trained Agent
After training, you can use the saved Q-table to have the agent play the game without exploration (i.e., greedy actions). Here's how you can implement a simple play mode:
def play():
agent = QLearningAgent()
# Load the trained Q-table
if os.path.exists("q_table.pkl"):
agent.q_table = pd.read_pickle("q_table.pkl")
agent.epsilon = 0 # No exploration
else:
print("No trained Q-table found. Please train the agent first.")
return
game = SnakeGameAI()
game.reset()
state = agent.get_state(game)
done = False
score = 0
while not done:
action = agent.get_action(state)
action_one_hot = [0,0,0]
action_one_hot[action] = 1
reward, done, score = game.play_step(action_one_hot)
state = agent.get_state(game)
if done:
print(f'Final Score: {score}')
break
pygame.quit()
if __name__ == '__main__':
play()
6. Enhancements and Considerations
-
State Representation: The state is represented using a combination of danger flags, current direction, and food location relative to the snake's head. This compact representation helps in keeping the Q-table manageable.
-
Q-Table Size: Even with this compact state representation, the Q-table can grow large. To handle larger state spaces, consider using function approximation methods like Deep Q-Networks (DQN).
-
Reward Structure: The reward system encourages the agent to eat food (+10), avoid collisions (-10), and implicitly encourages longer survival (higher scores).
-
Exploration Strategy: The agent uses an epsilon-greedy strategy with decay to balance exploration and exploitation.
-
Frame Iteration Limit: To prevent the game from running indefinitely without progress, a frame iteration limit based on the snake's length is set.
-
Performance: Training can be time-consuming, especially with high episode counts. Consider parallelizing the training process or implementing more efficient state representations.
7. Running the Code
-
Train the Agent:
Run the training script. This will train the agent over the specified number of episodes and log progress.
python your_script.py
-
Play with the Trained Agent:
After training, run the play function to see the agent in action using the learned Q-table.
python your_script.py
Ensure you handle the main function appropriately to switch between training and playing modes.
8. Conclusion
This implementation provides a solid foundation for a Q-learning-based Snake AI. While it uses a tabular approach suitable for smaller state spaces, more complex representations and algorithms can be explored for improved performance. Logging facilitates monitoring the training progress and diagnosing issues, making it easier to iterate and enhance the agent's capabilities.