Certainly! Below is the visualization.py script that loads a trained DQN agent and visualizes the Flappy Rectangle game using images instead of simple colored shapes. This script assumes that you have the necessary image assets (background-day.png, pipe-green.png, yellowbird-downflap.png, yellowbird-midflap.png, yellowbird-upflap.png) placed in an assets directory.
Directory Structure
your_project/
├── assets/
│ ├── background-day.png
│ ├── pipe-green.png
│ ├── yellowbird-downflap.png
│ ├── yellowbird-midflap.png
│ ├── yellowbird-upflap.png
├── models/
│ └── best.pth
├── agent_cuda.py
├── parameters.py
├── visualization.py
└── other_project_files.py
visualization.py
import os
import pygame
import torch
import sys
import numpy as np
from agent_cuda import DQNAgent
from parameters import (
lr,
gamma,
epsilon,
epsilon_decay,
buffer_size,
penalty,
target_update,
RECT_WIDTH,
RECT_HEIGHT,
PIPE_WIDTH,
PIPE_GAP,
GRAVITY,
JUMP_STRENGTH,
PIPE_SPEED,
)
# Configuration for Visualization
model_path = "models/best.pth"
state_dim = 4
action_dim = 2
# Initialize Pygame
pygame.init()
# Screen dimensions
SCREEN_WIDTH = 400
SCREEN_HEIGHT = 600
# Load images
ASSETS_DIR = "assets"
BACKGROUND_IMAGE = pygame.image.load(os.path.join(ASSETS_DIR, "background-day.png")).convert()
PIPE_IMAGE = pygame.image.load(os.path.join(ASSETS_DIR, "pipe-green.png")).convert_alpha()
BIRD_DF_IMAGE = pygame.image.load(os.path.join(ASSETS_DIR, "yellowbird-downflap.png")).convert_alpha()
BIRD_MF_IMAGE = pygame.image.load(os.path.join(ASSETS_DIR, "yellowbird-midflap.png")).convert_alpha()
BIRD_UF_IMAGE = pygame.image.load(os.path.join(ASSETS_DIR, "yellowbird-upflap.png")).convert_alpha()
BIRD_IMAGES = [BIRD_DF_IMAGE, BIRD_MF_IMAGE, BIRD_UF_IMAGE]
BIRD_FLAP_SPEED = 5 # Frames between flaps
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
# Load the trained agent
def load_trained_model(model_path, state_dim, action_dim):
agent = DQNAgent(
state_dim=state_dim,
action_dim=action_dim,
lr=lr,
gamma=gamma,
epsilon=epsilon,
epsilon_decay=epsilon_decay,
epsilon_min=0.01,
buffer_size=buffer_size,
)
agent.policy_net.load_state_dict(torch.load(model_path, map_location=torch.device('cpu')))
agent.policy_net.eval()
return agent
# Rectangle (Bird) Class with Images
class Rectangle:
def __init__(self):
self.x = SCREEN_WIDTH // 4
self.y = SCREEN_HEIGHT // 2
self.y_speed = 0
self.image_index = 0
self.frame_count = 0
def draw(self, screen):
# Animate bird
if self.frame_count % BIRD_FLAP_SPEED == 0:
self.image_index = (self.image_index + 1) % len(BIRD_IMAGES)
self.frame_count += 1
bird_image = BIRD_IMAGES[self.image_index]
screen.blit(bird_image, (self.x, self.y))
def distance(self, pipes):
for pipe in pipes:
if pipe.top.left > self.x:
dist_horizontal = pipe.top.left - self.x
gap_y_center = pipe.top.height + PIPE_GAP // 2
dist_vertically = self.y + RECT_HEIGHT // 2 - gap_y_center
return dist_horizontal, dist_vertically
return None, None
def jump(self):
self.y_speed = JUMP_STRENGTH
def apply_gravity(self):
self.y_speed += GRAVITY
self.y += self.y_speed
# Pipe Class with Image Rendering
class Pipe:
def __init__(self):
self.top = pygame.Rect(
SCREEN_WIDTH,
0,
PIPE_WIDTH,
random.randint(50, SCREEN_HEIGHT - PIPE_GAP - 50),
)
self.bottom = pygame.Rect(
SCREEN_WIDTH,
self.top.height + PIPE_GAP,
PIPE_WIDTH,
SCREEN_HEIGHT - self.top.height - PIPE_GAP,
)
self.passed = False
self.PIPE_TOP_IMAGE = pygame.transform.flip(PIPE_IMAGE, False, True)
self.PIPE_BOTTOM_IMAGE = PIPE_IMAGE
def draw(self, screen):
# Draw top pipe
top_image = pygame.transform.scale(self.PIPE_TOP_IMAGE, (self.top.width, self.top.height))
screen.blit(top_image, (self.top.x, self.top.y))
# Draw bottom pipe
bottom_image = pygame.transform.scale(self.PIPE_BOTTOM_IMAGE, (self.bottom.width, self.bottom.height))
screen.blit(bottom_image, (self.bottom.x, self.bottom.y))
def move(self):
self.top.x -= PIPE_SPEED
self.bottom.x -= PIPE_SPEED
def off_screen(self):
return self.top.right < 0
def has_passed(self, rect_x):
if not self.passed and self.top.right < rect_x:
self.passed = True
return True
return False
# Function to get observation
def get_observation(rectangle, pipes):
dist_horizontal, dist_vertically = rectangle.distance(pipes)
if dist_horizontal is None or dist_vertically is None:
dist_horizontal = SCREEN_WIDTH
dist_vertically = SCREEN_HEIGHT // 2
normalized_horizontal = dist_horizontal / SCREEN_WIDTH
normalized_vertical = dist_vertically / SCREEN_HEIGHT
rect_y_normalized = rectangle.y / SCREEN_HEIGHT
rect_y_speed_normalized = rectangle.y_speed / JUMP_STRENGTH
observation = np.array(
[
normalized_horizontal,
normalized_vertical,
rect_y_normalized,
rect_y_speed_normalized,
]
)
return observation
# Function to take action
def take_action(rectangle, action):
if action == 1:
rectangle.jump()
# Environment Class with Image Rendering
class Environment:
def __init__(self, render=True):
self.render_mode = render
if self.render_mode:
self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Flappy Rectangle Visualization")
self.clock = pygame.time.Clock()
self.font = pygame.font.SysFont(None, 36)
self.reset()
def reset(self):
self.rectangle = Rectangle()
self.pipes = []
self.pipe_timer = 89
self.score = 0
self.game_active = True
return get_observation(self.rectangle, self.pipes)
def step(self, action):
reward = 0.1
done = False
take_action(self.rectangle, action)
self.rectangle.apply_gravity()
self.pipe_timer += 1
if self.pipe_timer > 90:
self.pipes.append(Pipe())
self.pipe_timer = 0
pipes_to_remove = []
for pipe in self.pipes:
pipe.move()
if pipe.has_passed(self.rectangle.x):
self.score += 1
reward += 1
if pipe.off_screen():
pipes_to_remove.append(pipe)
for pipe in pipes_to_remove:
self.pipes.remove(pipe)
if self.render_mode:
self.render_game()
# Collision Detection
rect = pygame.Rect(
self.rectangle.x, self.rectangle.y, RECT_WIDTH, RECT_HEIGHT
)
for pipe in self.pipes:
if rect.colliderect(pipe.top) or rect.colliderect(pipe.bottom):
done = True
reward = penalty
self.game_active = False
break
if self.rectangle.y <= 0 or self.rectangle.y + RECT_HEIGHT >= SCREEN_HEIGHT:
done = True
reward = penalty
self.game_active = False
next_observation = get_observation(self.rectangle, self.pipes)
return next_observation, reward, done
def render_game(self):
# Draw background
background_scaled = pygame.transform.scale(BACKGROUND_IMAGE, (SCREEN_WIDTH, SCREEN_HEIGHT))
self.screen.blit(background_scaled, (0, 0))
# Draw pipes
for pipe in self.pipes:
pipe.draw(self.screen)
# Draw rectangle (bird)
self.rectangle.draw(self.screen)
# Draw score
score_text = self.font.render(f"Score: {self.score}", True, WHITE)
self.screen.blit(score_text, (10, 10))
# Update display
pygame.display.flip()
self.clock.tick(30)
def main():
agent = load_trained_model(model_path, state_dim, action_dim)
env = Environment(render=True)
running = True
while running:
state = env.reset()
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
done = True
break
if not running:
break
# Agent selects action
state_tensor = torch.FloatTensor(state).unsqueeze(0)
with torch.no_grad():
q_values = agent.policy_net(state_tensor)
action = torch.argmax(q_values, dim=1).item()
# Apply action to environment
next_state, reward, done = env.step(action)
state = next_state
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()
Explanation of the visualization.py Script
-
Imports and Configuration
- Imports necessary libraries, including
pygame, torch, and custom modules.
- Sets up configuration variables such as
model_path, state_dim, and action_dim.
-
Loading Images
- Loads all required images from the
assets directory.
BIRD_IMAGES holds the different bird flap states to animate the bird.
-
Loading the Trained Agent
- Defines the
load_trained_model function to load the trained DQN agent from the specified model_path.
- The agent's policy network is loaded and set to evaluation mode.
-
Class Definitions
Rectangle Class: Represents the bird/player using images and handles its physics.
Pipe Class: Represents the pipes using images and handles their movement.
Environment Class: Manages the game state, rendering, and interactions between the bird and pipes.
-
Game Loop in main()
- Loads the trained agent.
- Initializes the environment with rendering enabled.
- Runs the game loop where the agent selects actions based on the current state.
- Renders the game using images, showing the background, pipes, and animated bird.
- Allows the user to quit the visualization by closing the game window.
-
Running the Script
- Ensure that all image assets are correctly placed in the
assets directory.
- Run the visualization using the command:
python visualization.py
- The agent will play the game, and you will see the bird navigating through the pipes with the game's visuals.
Notes
-
Agent Loading: Ensure that the DQNAgent class in agent_cuda.py matches the configuration used during training. The script assumes that the agent can load the policy network's state dictionary correctly.
-
Image Assets: Make sure that the image files are named exactly as specified and placed in the assets directory. Adjust the ASSETS_DIR path if your assets are located elsewhere.
-
Performance: This visualization runs on the CPU. If you have a GPU and want to utilize it, you might need to adjust the map_location in torch.load.
-
Customization: You can modify the PIPE_SPEED, JUMP_STRENGTH, GRAVITY, and other parameters in parameters.py to tweak the game's difficulty and physics.
-
Error Handling: The script includes basic event handling to allow quitting the game gracefully. You can extend this to include more sophisticated controls or logging as needed.
This visualization.py script provides a visual representation of the trained agent playing the Flappy Rectangle game with rich graphics, enhancing the understanding and demonstration of the agent's performance.