Generate a Q-Learning TF model in Python that plays Snake.
- User
Generate a Q-Learning TF model in Python that plays Snake.
- Assistant
Generate a Q-Learning TF model in Python that plays Snake.
Creating a Q-Learning agent using TensorFlow to play the classic Snake game involves several steps:
pygame to create the Snake game environment.Below is a comprehensive Python script that accomplishes this. Make sure you have the required libraries installed before running the code.
Ensure you have the following libraries installed:
pip install pygame tensorflow numpy
import pygame
import random
import numpy as np
from collections import deque
import tensorflow as tf
from tensorflow.keras import layers, models, optimizers
import sys
# ---------------------------
# 1. Define the Snake Game Environment
# ---------------------------
class SnakeGame:
def __init__(self, width=400, height=400, block_size=20):
self.width = width
self.height = height
self.block_size = block_size
self.reset()
pygame.init()
self.display = pygame.display.set_mode((self.width, self.height))
pygame.display.set_caption('Snake AI')
self.clock = pygame.time.Clock()
self.font = pygame.font.SysFont('arial', 25)
def reset(self):
self.snake = [(self.width // 2, self.height // 2)]
self.direction = random.choice(['UP', 'DOWN', 'LEFT', 'RIGHT'])
self.spawn_food()
self.score = 0
self.frame_iteration = 0
self.done = False
def spawn_food(self):
while True:
x = random.randint(0, (self.width - self.block_size) // self.block_size) * self.block_size
y = random.randint(0, (self.height - self.block_size) // self.block_size) * self.block_size
if (x, y) not in self.snake:
self.food = (x, y)
break
def step(self, action):
self.frame_iteration += 1
# Update direction based on action
self.update_direction(action)
# Move snake
head_x, head_y = self.snake[0]
if self.direction == 'UP':
head_y -= self.block_size
elif self.direction == 'DOWN':
head_y += self.block_size
elif self.direction == 'LEFT':
head_x -= self.block_size
elif self.direction == 'RIGHT':
head_x += self.block_size
new_head = (head_x, head_y)
# Check for collision
reward = 0
if self.is_collision(new_head):
self.done = True
reward = -10
return self.get_state(), reward, self.done
# Move snake
self.snake.insert(0, new_head)
# Check if food is eaten
if new_head == self.food:
reward = 10
self.score += 1
self.spawn_food()
else:
self.snake.pop()
# Optionally, add a small negative reward for each step to encourage quicker solutions
reward += -0.1
return self.get_state(), reward, self.done
def is_collision(self, point):
x, y = point
if x < 0 or x >= self.width or y < 0 or y >= self.height:
return True
if point in self.snake:
return True
return False
def update_direction(self, action):
# Action is one of [straight, right, left] relative to current direction
directions = ['UP', 'RIGHT', 'DOWN', 'LEFT']
idx = directions.index(self.direction)
if np.array_equal(action, [1, 0, 0]):
new_dir = self.direction # Straight
elif np.array_equal(action, [0, 1, 0]):
new_dir = directions[(idx + 1) % 4] # Right turn
else:
new_dir = directions[(idx - 1) % 4] # Left turn
self.direction = new_dir
def get_state(self):
head = self.snake[0]
point_l = (head[0] - self.block_size, head[1])
point_r = (head[0] + self.block_size, head[1])
point_u = (head[0], head[1] - self.block_size)
point_d = (head[0], head[1] + self.block_size)
dir_up = self.direction == 'UP'
dir_down = self.direction == 'DOWN'
dir_left = self.direction == 'LEFT'
dir_right = self.direction == 'RIGHT'
state = [
# Danger straight
(dir_up and self.is_collision(point_u)) or
(dir_down and self.is_collision(point_d)) or
(dir_left and self.is_collision(point_l)) or
(dir_right and self.is_collision(point_r)),
# Danger right
(dir_up and self.is_collision(point_r)) or
(dir_right and self.is_collision(point_d)) or
(dir_down and self.is_collision(point_l)) or
(dir_left and self.is_collision(point_u)),
# Danger left
(dir_up and self.is_collision(point_l)) or
(dir_left and self.is_collision(point_d)) or
(dir_down and self.is_collision(point_r)) or
(dir_right and self.is_collision(point_u)),
# Move direction
dir_up,
dir_down,
dir_left,
dir_right,
# Food location
self.food[0] < head[0], # food left
self.food[0] > head[0], # food right
self.food[1] < head[1], # food up
self.food[1] > head[1] # food down
]
return np.array(state, dtype=int)
def render(self):
self.display.fill((0, 0, 0))
for pos in self.snake:
pygame.draw.rect(self.display, (0, 255, 0), pygame.Rect(pos[0], pos[1], self.block_size, self.block_size))
pygame.draw.rect(self.display, (255, 0, 0), pygame.Rect(self.food[0], self.food[1], self.block_size, self.block_size))
text = self.font.render(f'Score: {self.score}', True, (255, 255, 255))
self.display.blit(text, [0, 0])
pygame.display.flip()
self.clock.tick(10) # Control game speed
def close(self):
pygame.quit()
# ---------------------------
# 2. Define the Q-Learning Agent
# ---------------------------
class DQNAgent:
def __init__(self, state_size, action_size):
self.state_size = state_size # e.g., 11
self.action_size = action_size # e.g., 3
self.memory = deque(maxlen=2000)
self.gamma = 0.95 # discount rate
self.epsilon = 1.0 # exploration rate
self.epsilon_min = 0.01
self.epsilon_decay = 0.995
self.learning_rate = 0.001
self.model = self._build_model()
def _build_model(self):
# Neural Network for Deep Q-Learning
model = models.Sequential()
model.add(layers.Dense(24, input_dim=self.state_size, activation='relu'))
model.add(layers.Dense(24, activation='relu'))
model.add(layers.Dense(self.action_size, activation='linear'))
model.compile(loss='mse',
optimizer=optimizers.Adam(lr=self.learning_rate))
return model
def remember(self, state, action, reward, next_state, done):
# Store experience in replay buffer
self.memory.append((state, action, reward, next_state, done))
def act(self, state):
# Epsilon-greedy action selection
if np.random.rand() <= self.epsilon:
return random.randrange(self.action_size)
act_values = self.model.predict(state[np.newaxis, :])
return np.argmax(act_values[0]) # returns action
def replay(self, batch_size):
# Train the model using randomly sampled experiences from memory
minibatch = random.sample(self.memory, batch_size)
for state, action, reward, next_state, done in minibatch:
target = reward
if not done:
# Predict the future discounted reward
target = reward + self.gamma * np.amax(self.model.predict(next_state[np.newaxis, :])[0])
target_f = self.model.predict(state[np.newaxis, :])
target_f[0][action] = target
# Train the network
self.model.fit(state[np.newaxis, :], target_f, epochs=1, verbose=0)
# Decrease epsilon to reduce exploration over time
if self.epsilon > self.epsilon_min:
self.epsilon *= self.epsilon_decay
# ---------------------------
# 3. Training the Agent
# ---------------------------
def train():
rewards = []
episodes = 1000
batch_size = 64
game = SnakeGame()
state_size = 11 # As defined in get_state
action_size = 3 # [straight, right, left]
agent = DQNAgent(state_size, action_size)
for e in range(episodes):
game.reset()
state = game.get_state()
total_reward = 0
while True:
# Uncomment to watch the game
# game.render()
action = agent.act(state)
# Convert action index to action array
act = [0, 0, 0]
act[action] = 1
next_state, reward, done = game.step(act)
agent.remember(state, action, reward, next_state, done)
state = next_state
total_reward += reward
if done:
rewards.append(total_reward)
print(f"Episode: {e+1}/{episodes}, Score: {game.score}, Epsilon: {agent.epsilon:.2}")
break
if len(agent.memory) > batch_size:
agent.replay(batch_size)
# Save the trained model
agent.model.save('snake_dqn.h5')
game.close()
# Plotting Rewards (optional)
import matplotlib.pyplot as plt
plt.plot(rewards)
plt.xlabel('Episode')
plt.ylabel('Reward')
plt.show()
# ---------------------------
# 4. Run the Training
# ---------------------------
if __name__ == "__main__":
train()
SnakeGame Class:
get_state method encodes the current state into a binary array indicating dangers (immediate collisions) and the relative position of the food.DQNAgent Class:
Training Loop:
Running the Script:
train function initializes the game and agent, then starts the training loop.Performance: Training a DQN agent can be computationally intensive and may take considerable time depending on your hardware. Consider reducing the number of episodes or adjusting the network architecture for faster training during experimentation.
Rendering: By default, the game does not render (i.e., you don't see the game window) to speed up training. If you want to watch the agent play, uncomment the game.render() line in the training loop. Keep in mind that rendering can significantly slow down training.
Model Persistence: The trained model is saved as snake_dqn.h5. You can load this model later to evaluate or further train your agent.
Improvements:
After training, you can create a separate script to load the trained model and let the agent play the game without training:
import pygame
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import load_model
# Use the existing SnakeGame class from above
class SnakeGame:
# [Same as above without changes]
# ... (copy the SnakeGame class here)
def play():
game = SnakeGame()
model = load_model('snake_dqn.h5')
while True:
game.reset()
state = game.get_state()
while True:
game.render()
action = np.argmax(model.predict(state[np.newaxis, :])[0])
act = [0, 0, 0]
act[action] = 1
next_state, reward, done = game.step(act)
state = next_state
if done:
print(f"Game Over! Score: {game.score}")
break
game.close()
if __name__ == "__main__":
play()
Ensure that the SnakeGame class in the playback script is identical to the one used during training.
This script provides a foundational implementation of a DQN agent to play Snake using TensorFlow. Depending on your requirements and computational resources, you can further optimize and expand upon this basic framework to achieve better performance and more sophisticated behaviors.
Not yet included in a published release.