Now make code for training AI, for playing snake game, using RL and encoding image of…
- User
Now make code for training AI, for playing snake game, using RL and encoding image of the game with vision model. Vision model choosed by you
- Assistant
Now make code for training AI, for playing snake game, using RL and encoding image of the game with vision model. Vision model choosed by you
Certainly! Below is a Python code that sets up and trains an AI agent to play the Snake game using Reinforcement Learning (RL). The agent uses a convolutional neural network (CNN) as the vision model to encode the game images. We'll use the PyTorch library for building the neural network and training the agent.
Dependencies:
# Install required packages
!pip install pygame
!pip install torch torchvision
Code Implementation:
import random
import numpy as np
from collections import deque
from PIL import Image
import pygame
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as T
# Define the game environment
class SnakeGameAI:
def __init__(self, w=640, h=480):
self.w = w
self.h = h
self.reset()
def reset(self):
self.direction = 'RIGHT'
self.head = [self.w/2, self.h/2]
self.snake_body = [self.head[:], [self.head[0]-10, self.head[1]], [self.head[0]-20, self.head[1]]]
self.food_pos = self.spawn_food()
self.score = 0
self.frame_iteration = 0
def spawn_food(self):
x = random.randrange(1, (self.w//10)) * 10
y = random.randrange(1, (self.h//10)) * 10
return [x, y]
def play_step(self, action):
self.frame_iteration += 1
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
# Move
self._move(action)
self.snake_body.insert(0, self.head[:])
# Check if game over
reward = 0
game_over = False
if self.is_collision():
game_over = True
reward = -10
return reward, game_over, self.score
# Eat food
if self.head == self.food_pos:
self.score += 1
reward = 10
self.food_pos = self.spawn_food()
else:
self.snake_body.pop()
# Update UI
self.update_ui()
pygame.time.delay(50)
return reward, game_over, self.score
def is_collision(self):
# Hits boundary
if self.head[0] >= self.w or self.head[0] < 0 or self.head[1] >= self.h or self.head[1] < 0:
return True
# Hits itself
if self.head in self.snake_body[1:]:
return True
return False
def _move(self, action):
# [Straight, Right, Left]
clock_wise = ['RIGHT', 'DOWN', 'LEFT', '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
self.direction = new_dir
x, y = self.head
if self.direction == 'RIGHT':
x += 10
elif self.direction == 'LEFT':
x -= 10
elif self.direction == 'UP':
y -= 10
elif self.direction == 'DOWN':
y += 10
self.head = [x, y]
def update_ui(self):
display.fill((0,0,0))
for pos in self.snake_body:
pygame.draw.rect(display, (0,255,0), pygame.Rect(pos[0], pos[1], 10, 10))
pygame.draw.rect(display, (255,0,0), pygame.Rect(self.food_pos[0], self.food_pos[1], 10, 10))
pygame.display.flip()
# Define the agent with a CNN model
class Agent:
def __init__(self):
self.n_games = 0
self.epsilon = 0 # Exploration rate
self.gamma = 0.9 # Discount rate
self.memory = deque(maxlen=100_000)
self.batch_size = 1000
self.model = Linear_QNet()
self.optimizer = optim.Adam(self.model.parameters(), lr=0.001)
self.criterion = nn.MSELoss()
def get_state(self, game):
# Capture the screen
surface = pygame.surfarray.array3d(display)
image = Image.fromarray(surface)
transform = T.Compose([
T.Resize((84, 84)),
T.Grayscale(),
T.ToTensor()
])
state = transform(image)
return state.unsqueeze(0)
def remember(self, state, action, reward, next_state, done):
self.memory.append((state, action, reward, next_state, done))
def train_long_memory(self):
if len(self.memory) > self.batch_size:
mini_sample = random.sample(self.memory, self.batch_size)
else:
mini_sample = self.memory
states, actions, rewards, next_states, dones = zip(*mini_sample)
self.train_step(states, actions, rewards, next_states, dones)
def train_step(self, states, actions, rewards, next_states, dones):
states = torch.cat(states)
next_states = torch.cat(next_states)
actions = torch.Tensor(actions)
rewards = torch.Tensor(rewards)
dones = torch.Tensor(dones)
# Predicted Q values with current state
pred = self.model(states).gather(1, actions.long().unsqueeze(1)).squeeze(1)
# Q targets
next_pred = self.model(next_states).max(1)[0]
target = rewards + self.gamma * next_pred * (1 - dones)
# Loss
loss = self.criterion(pred, target)
self.optimizer.zero_grad()
loss.backward()
self.optimizer.step()
def get_action(self, state):
self.epsilon = 80 - self.n_games
final_move = [0,0,0]
if random.randint(0,200) < self.epsilon:
move = random.randint(0,2)
final_move[move] = 1
else:
with torch.no_grad():
prediction = self.model(state)
move = torch.argmax(prediction).item()
final_move[move] = 1
return final_move
# Define the CNN model
class Linear_QNet(nn.Module):
def __init__(self):
super().__init__()
self.cnn_layers = nn.Sequential(
nn.Conv2d(1, 32, kernel_size=8, stride=4),
nn.ReLU(),
nn.Conv2d(32,64,kernel_size=4,stride=2),
nn.ReLU(),
nn.Conv2d(64,64,kernel_size=3,stride=1),
nn.ReLU()
)
self.linear_layers = nn.Sequential(
nn.Linear(7*7*64, 512),
nn.ReLU(),
nn.Linear(512, 3)
)
def forward(self, x):
x = x / 255.0
x = self.cnn_layers(x)
x = x.view(x.size(0), -1)
x = self.linear_layers(x)
return x
# Main training loop
def train():
global display
pygame.init()
display = pygame.display.set_mode((640,480))
pygame.display.set_caption('Snake RL')
clock = pygame.time.Clock()
agent = Agent()
game = SnakeGameAI()
while True:
state_old = agent.get_state(game)
# Get move
final_move = agent.get_action(state_old)
# Perform move and get new state
reward, done, score = game.play_step(final_move)
state_new = agent.get_state(game)
# Train short memory
agent.train_step([state_old], [final_move.index(1)], [reward], [state_new], [done])
# Remember
agent.remember(state_old, final_move.index(1), reward, state_new, done)
if done:
game.reset()
agent.n_games += 1
agent.train_long_memory()
print('Game', agent.n_games, 'Score', score)
if __name__ == '__main__':
train()
Explanation:
SnakeGameAI Class: Defines the game environment, including the snake's movement, collision detection, and rendering.
Agent Class: Implements the reinforcement learning agent. It captures the game screen, processes the image, and decides on the next action using an epsilon-greedy policy.
Linear_QNet Class: A CNN model that processes the game image and outputs Q-values for each possible action. The network consists of convolutional layers followed by linear layers.
train Function: Contains the main loop where the agent interacts with the game environment, learns from experiences, and improves over time.
Action Representation: Actions are represented as one-hot encoded vectors:
[1, 0, 0] - Continue in the same direction.[0, 1, 0] - Turn right.[0, 0, 1] - Turn left.State Representation: The game screen is captured, resized, converted to grayscale, and transformed into a tensor to be fed into the CNN.
Note:
epsilon, gamma, and batch_size as needed.Dependencies Installation:
Before running the code, ensure you have all the necessary libraries installed:
pip install pygame torch torchvision numpy pillow
Running the Code:
Simply run the script, and the training will start. You will see the game window displaying the Snake game, and the console will output the game number and score after each game.
Not yet included in a published release.