Certainly! Below is the revised code that incorporates the Bird class and the updated get_state function. This version replaces the Rectangle class with the Bird class, adjusts the state representation for the DQN agent, and ensures all components work seamlessly together.
Key Changes:
- Introduced the
Bird Class: Replaces the Rectangle class to represent the player's character.
- Updated State Representation: The
get_state function now returns a state vector [y_norm, velocity_norm, distance_norm, top_norm, bottom_norm].
- Adjusted DQN Agent Initialization: The state dimension is updated to match the new state representation.
- Modified Pipe Class: Added a
gap attribute to the Pipe class to align with the get_state function.
- Updated Action Handling: Changed the action from
rectangle.jump() to bird.flap().
Revised Code:
import pygame
import random
import torch
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
from collections import deque
from agent_cpu import DQNAgent # Ensure to use the correct DQNAgent that is on CPU
from parameters import lr, gamma, epsilon, epsilon_decay, buffer_size, penalty
pygame.init()
# Screen dimensions
SCREEN_WIDTH = 400
SCREEN_HEIGHT = 600
# Colors
RED = (255, 0, 0)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
# Game constants
BIRD_SIZE = 35
FLAP_STRENGTH = -13
GRAVITY = 1
PIPE_SPEED = 5
PIPE_WIDTH = 70
PIPE_GAP = 220
PIPE_FREQUENCY = 90 # Frames between pipes
class Bird:
def __init__(self):
self.x = 50
self.y = SCREEN_HEIGHT // 2
self.velocity = 0
self.size = BIRD_SIZE
def flap(self):
self.velocity = FLAP_STRENGTH
def update(self):
self.velocity += GRAVITY
self.y += self.velocity
def get_rect(self):
return pygame.Rect(self.x, self.y, self.size, self.size)
def draw(self, screen):
pygame.draw.rect(screen, BLUE, self.get_rect())
class Pipe:
def __init__(self):
self.gap = PIPE_GAP
self.top_height = random.randint(50, SCREEN_HEIGHT - self.gap - 50)
self.top = pygame.Rect(SCREEN_WIDTH, 0, PIPE_WIDTH, self.top_height)
self.bottom = pygame.Rect(SCREEN_WIDTH, self.top_height + self.gap, PIPE_WIDTH, SCREEN_HEIGHT - self.top_height - self.gap)
def draw(self, screen):
pygame.draw.rect(screen, WHITE, self.top)
pygame.draw.rect(screen, WHITE, self.bottom)
def move(self):
self.top.x -= PIPE_SPEED
self.bottom.x -= PIPE_SPEED
def off_screen(self):
return self.top.right < 0
def get_state(bird, pipes):
"""
State includes bird y position, velocity, distance to next pipe,
top and bottom of next pipe.
"""
# Find the next pipe
next_pipe = None
for pipe in pipes:
if pipe.top.right > bird.x:
next_pipe = pipe
break
if next_pipe is None:
# If no pipes are present, provide default values
distance = SCREEN_WIDTH
top = SCREEN_HEIGHT // 2 - PIPE_GAP // 2
bottom = SCREEN_HEIGHT // 2 + PIPE_GAP // 2
else:
distance = (next_pipe.top.x + PIPE_WIDTH) - bird.x
top = next_pipe.top.height
bottom = next_pipe.bottom.y
velocity = bird.velocity
# Normalize state
distance_norm = distance / SCREEN_WIDTH
top_norm = top / SCREEN_HEIGHT
bottom_norm = bottom / SCREEN_HEIGHT
y_norm = bird.y / SCREEN_HEIGHT
velocity_norm = velocity / 10 # Assuming max velocity won't exceed 10 in magnitude
state = np.array([y_norm, velocity_norm, distance_norm, top_norm, bottom_norm], dtype=np.float32)
return state
def take_action(action, bird):
if action == 1: # Flap
bird.flap()
def main():
# Initialize the game components
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Flappy Bird with DQN")
bird = Bird()
pipes = []
pipe_timer = PIPE_FREQUENCY
score = 0
font = pygame.font.SysFont(None, 36)
game_active = True # Start the game immediately
experience_buffer = deque(maxlen=10000)
state_dim = 5
action_dim = 2 # Flap or do nothing
# Initialize the DQN agent on CPU
agent = DQNAgent(state_dim=state_dim, action_dim=action_dim, lr=lr, gamma=gamma,
epsilon=epsilon, epsilon_decay=epsilon_decay, buffer_size=buffer_size)
episode_rewards = []
num_episodes = int(sys.argv[1]) if len(sys.argv) > 1 else 100
for episode in range(num_episodes):
# Reset the game state
bird = Bird()
pipes = []
pipe_timer = PIPE_FREQUENCY
score = 0
game_active = True
episode_reward = 0
while game_active:
screen.fill(BLACK)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Get current state
state = get_state(bird, pipes)
# Select action
action = agent.act(state)
take_action(action, bird)
# Update bird
bird.update()
# Manage pipes
pipe_timer += 1
if pipe_timer > PIPE_FREQUENCY:
pipes.append(Pipe())
pipe_timer = 0
for pipe in pipes:
pipe.move()
if pipe.off_screen():
pipes.remove(pipe)
score += 1
episode_reward += 1 # Reward for passing a pipe
# Draw pipes and bird
for pipe in pipes:
pipe.draw(screen)
bird.draw(screen)
# Check for collisions
done = False
reward = 0.1 # Small reward for being alive
bird_rect = bird.get_rect()
for pipe in pipes:
if bird_rect.colliderect(pipe.top) or bird_rect.colliderect(pipe.bottom):
game_active = False
done = True
reward = -1 # Negative reward for collision
break
if bird.y <= 0 or bird.y + bird.size >= SCREEN_HEIGHT:
game_active = False
done = True
reward = -1 # Negative reward for hitting the ground or ceiling
# Get next state
next_state = get_state(bird, pipes)
# Remember experience
agent.remember(state, action, reward, next_state, done)
episode_reward += reward
# Update the agent
agent.replay(batch_size=32)
# Display the score
score_text = font.render(f"Score: {score}", True, WHITE)
screen.blit(score_text, (10, 10))
pygame.display.flip()
pygame.time.Clock().tick(30) # 30 FPS
episode_rewards.append(episode_reward)
print(f"Episode {episode + 1}/{num_episodes}, Score: {score}, Reward: {episode_reward}, Epsilon: {agent.epsilon:.4f}")
# Save the trained model
os.makedirs('models', exist_ok=True)
existing_models = len(os.listdir('models/'))
torch.save(agent.model.state_dict(), f"models/flappy{existing_models + 1}.pth")
# Plot the rewards
plt.figure(figsize=(12, 6))
plt.plot(range(len(episode_rewards)), episode_rewards)
plt.title("Episode Rewards")
plt.xlabel("Episode")
plt.ylabel("Reward")
plt.show()
pygame.quit()
if __name__ == "__main__":
main()
Detailed Breakdown of Changes:
-
Imports and Initialization:
- Added
BLUE color for the bird.
- Defined
BIRD_SIZE, FLAP_STRENGTH, and PIPE_FREQUENCY for better configurability.
-
Bird Class:
- Represents the player-controlled character.
- Methods:
flap(): Makes the bird jump by setting its velocity.
update(): Applies gravity and updates the bird's position.
get_rect(): Returns the bird's current rectangle for collision detection.
draw(screen): Renders the bird on the screen.
-
Pipe Class:
- Added a
gap attribute to represent the space between the top and bottom pipes.
- The
top_height is randomized to vary the difficulty.
-
State Representation (get_state Function):
- Determines the next pipe that the bird needs to pass.
- Calculates normalized distances and positions to standardize input for the DQN agent.
- Returns a state vector with five elements:
[y_norm, velocity_norm, distance_norm, top_norm, bottom_norm].
-
Action Handling (take_action Function):
- Maps the agent's action to the bird's behavior (flap or do nothing).
-
DQN Agent Initialization:
- Updated
state_dim to 5 to match the new state representation.
- Set
action_dim to 2 (flap or do nothing).
-
Game Loop Adjustments:
- Replaced references from
rectangle to bird.
- Updated collision detection to use the bird's rectangle.
- Adjusted reward structure:
- Small positive reward (
+0.1) for each frame the bird is alive.
- Positive reward (
+1) for passing a pipe.
- Negative reward (
-1) for collisions or hitting boundaries.
-
Model Saving and Plotting:
Additional Recommendations:
- Hyperparameter Tuning: You might need to adjust hyperparameters such as learning rate, gamma, epsilon decay, etc., depending on the agent's performance.
- Experience Replay Buffer: Ensure that the
DQNAgent properly manages the experience replay buffer to avoid correlated samples.
- Model Architecture: Verify that the neural network architecture within
DQNAgent is suitable for the state and action spaces.
- Rendering Optimizations: For faster training, consider disabling rendering during training phases and enabling it only during evaluation.
Dependencies:
Ensure that you have the following dependencies installed and correctly set up:
pygame
torch
numpy
matplotlib
You can install any missing dependencies using pip. For example:
pip install pygame torch numpy matplotlib
Running the Code:
To run the game training, execute the script with an optional argument specifying the number of episodes. For example, to run 200 episodes:
python flappy_bird_dqn.py 200
If no argument is provided, it defaults to 100 episodes.
This revised code should now effectively use the Bird class and the updated state representation, allowing the DQN agent to learn and play the Flappy Bird-like game efficiently. Make sure to monitor the training progress and adjust parameters as necessary to achieve optimal performance.