There's 2 problems within this code. First is that after it reaches the frame 100 it stops and asks for demonstration phase 2 and to press enter to start. I do not want that. I want to only stop demonstration phase 1 when I press Q in the game Superfighters Deluxe window, Also it's capturing all my desktop is it possible to make so it only captures the Superfighters Deluxe window?
import threading
import re
import os
import cv2
import logging
import pydirectinput
import torch
import torch.nn as nn
import torch.optim as optim
import random
import pygetwindow as gw
import numpy as np
import subprocess
import pyautogui
import torchvision.models as models
import time
from collections import namedtuple
from pathlib import Path
from PIL import Image
class DQN(nn.Module):
def init(self, input_size, output_size, use_pretrained=False):
super(DQN, self).init()
code
Assistant
User
(venv) C:\WINDOWS\system32>python test.py
Resuming training from Episode 1
Starting training with no best reward information
Expert Demonstration 1
Press Enter when ready to start demonstration...
Error getting game state: Error code from Windows: 0 - The operation completed successfully.
An error occurred: Error code from Windows: 0 - The operation completed successfully.
It gave me an error when changing window, I want to be able to change windows but still capture the game screenshots
Assistant
# Use a pre-trained model (e.g., ResNet18) as the feature extractor
if use_pretrained:
self.feature_extractor = models.resnet18(pretrained=True)
self.feature_extractor.fc = nn.Identity() # Remove the fully connected layer
else:
# Define your own convolutional layers for feature extraction
self.conv1 = nn.Conv2d(in_channels=input_size[0], out_channels=32, kernel_size=8, stride=4)
self.conv2 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=4, stride=2)
self.conv3 = nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1)
# Common layers for both cases
self.fc1 = nn.Linear(64 * 7 * 7, 512) # Set the correct input size
self.fc2 = nn.Linear(512, output_size)
def forward(self, x):
if hasattr(self, 'feature_extractor'): # Check if using a pre-trained model
x = self.feature_extractor(x)
x = x.view(x.size(0), -1) # Flatten the output
else:
x = x / 255.0 # Normalize pixel values
x = torch.as_tensor(x, dtype=torch.float32) # Remove clone().detach()
x = x.permute(0, 3, 1, 2) # Change the order of dimensions (N, H, W, C) to (N, C, H, W)
x = self.conv1(x)
x = torch.relu(x)
x = self.conv2(x)
x = torch.relu(x)
x = self.conv3(x)
x = torch.relu(x)
# Print the shape of the tensor at this point
print("Shape after convolutional layers:", x.shape)
x = torch.flatten(x, start_dim=1) # Flatten the output
# Update the fully connected layers with the correct input size
self.fc1 = nn.Linear(x.size(1), 512)
self.fc2 = nn.Linear(512, output_size)
x = self.fc1(x)
x = torch.relu(x)
x = self.fc2(x)
return x
Define the process frame
def process_frame(frame):
try:
# Implement any necessary preprocessing here (e.g., resizing, cropping, converting to grayscale)
processed_frame = cv2.resize(frame, (650, 650))
return processed_frame
except Exception as e:
logger.error(f"Error processing frame: {str(e)}")
raise
Function to simulate actions based on the agent's output
def simulate_action(action):
if action == 0:
# Randomly choose between Jump / ClimbLadder and Move to the Left or Move to the Right
if np.random.rand() < 0.5:
pydirectinput.keyDown('up')
pydirectinput.keyDown('left')
logger.info("Simulating action: Jump / ClimbLadder and Move to the Left")
else:
pydirectinput.keyDown('up')
pydirectinput.keyDown('right')
logger.info("Simulating action: Jump / ClimbLadder and Move to the Right")
elif action == 1:
pydirectinput.keyDown('down') # Crouch / SlideDownLadder
logger.info("Simulating action: Crouch / SlideDownLadder")
elif action == 2:
# Move to the left
pydirectinput.keyDown('left')
logger.info("Simulating action: Move to the left")
elif action == 3:
# Move to the right
pydirectinput.keyDown('right')
logger.info("Simulating action: Move to the right")
def expert_action(state):
# This is a placeholder example for a simple expert action function.
# The actual logic will depend on the specifics of your game.
code
# Suppose the state is an image represented as a NumPy array
# You might use basic image processing or heuristics to make decisions
# Example: If the average pixel intensity in the top region of the screen is high, jump.
top_region_intensity = np.mean(state[:100, :, :])
# Example: If the player is close to the right edge, move left; otherwise, move right.
player_position = np.argmax(state[:, :, 0]) # Assuming the player is represented by channel 0
right_edge_threshold = 600 # Adjust based on your game's resolution
if player_position > right_edge_threshold:
action = 2 # Move left
else:
action = 3 # Move right
return action
def main():
global output_size # Declare output_size as global
code
input_size = (3, 650, 650)
output_size = 4
agent = DQNAgent(input_size, output_size)
agent.model.to(device)
agent.target_model.to(device)
NUM_DEMONSTRATIONS = 10 # Number of expert demonstrations
DEMONSTRATION_DELAY = 5 # Delay between expert demonstrations
BATCH_SIZE = 32
EPISODE_DELAY = 10
LOG_FILE = r"C:\Users\Ninja.000\Downloads\SFD_AI\training_log.txt"
MODEL_SAVE_PATH = r"C:\Users\Ninja.000\Downloads\SFD_AI\dqn_model.pth"
BEST_MODEL_SAVE_PATH = r"C:\Users\Ninja.000\Downloads\SFD_AI\best_dqn_model.pth"
# Flag to indicate expert demonstration phase
expert_demonstration_phase = True
train_agent = False # Set to False for demonstration phase
# Add a console handler to the logger
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
logger.addHandler(console_handler)
MAX_EPISODE_LENGTH = 100 # Set an appropriate value based on your application
TUTORIAL_FOLDER = r"C:\Users\Ninja.000\Downloads\SFD_AI\gameplay\Tutorial"
try:
# Load the model and its parameters if it exists
if os.path.exists(MODEL_SAVE_PATH):
agent.model.load_state_dict(torch.load(MODEL_SAVE_PATH))
# Extract episode number from the model path
match = re.search(r'\d+', os.path.basename(MODEL_SAVE_PATH))
episode_start = int(match.group()) if match else 0
logger.info(f"Resuming training from Episode {episode_start + 1}")
else:
episode_start = 0
logger.info("Starting training from Episode 1")
# Load the best model parameters if it exists
if os.path.exists(BEST_MODEL_SAVE_PATH):
agent.best_model.load_state_dict(torch.load(BEST_MODEL_SAVE_PATH))
best_reward = max(np.load(LOG_FILE), default=float('-inf'))
logger.info(f"Resuming training with the best reward: {best_reward}")
else:
best_reward = float('-inf')
logger.info("Starting training with no best reward information")
episode_rewards = []
# Expert demonstration phase
if expert_demonstration_phase:
for demonstration in range(NUM_DEMONSTRATIONS):
logger.info(f"Expert Demonstration {demonstration + 1}")
input("Press Enter when ready to start demonstration...")
frames = [] # Collect frames for processing
key_listener_thread = threading.Thread(target=key_listener)
key_listener_thread.start()
for t in range(1, MAX_EPISODE_LENGTH + 1):
state = get_state()
frames.append(state)
time.sleep(0.1)
# Save the frame to the tutorial folder
frame_path = os.path.join(TUTORIAL_FOLDER, f"frame_{t}.jpg")
cv2.imwrite(frame_path, cv2.cvtColor(state, cv2.COLOR_RGB2BGR))
key_listener_thread.join() # Wait for the key listener thread to finish
for t in range(len(frames) - 1):
next_state = frames[t + 1]
action = expert_action(next_state) # Modified to take next_state as input
# During expert demonstration phase, actions are not simulated
state = frames[t]
# Save experiences for later training only if train_agent is True
if train_agent:
agent.replay_buffer.push(Transition(state, action, 0, next_state, False)) # No reward during demonstration
time.sleep(DEMONSTRATION_DELAY)
# Training phase (Skipped if expert_demonstration_phase is True)
if not expert_demonstration_phase and train_agent:
for episode in range(episode_start, episode_start + NUM_EPISODES):
logger.info(f"Episode {episode + 1}")
total_reward = 0
experiences = [] # Collect experiences for training
action = None # Initialize action variable
frames = [] # Collect frames for processing
for t in range(1, MAX_EPISODE_LENGTH, 1):
frame_path = f"C:\\Users\\Ninja.000\\Downloads\\SFD_AI\\gameplay\\Tutorial\\frame_{t}.jpg"
logger.info(f"Observing frame: {frame_path}")
# Process the frame
state = process_frame(frame_path)
frames.append(state)
for t in range(len(frames) - 1):
next_state = frames[t + 1]
if expert_demonstration_phase:
# During expert demonstration phase, use expert actions
action = expert_action(next_state)
else:
# During training phase, use DQN actions
action = agent.select_action(state)
# Simulate action only during the training phase
simulate_action(action)
state = frames[t]
reward, done = calculate_reward_and_check_termination(state, next_state)
agent.replay_buffer.push(Transition(state, action, reward, next_state, done))
# Process the frame
state = process_frame(frame_path)
frames.append(state)
for t in range(len(frames) - 1):
# Capture the next frame for the experience
next_state = frames[t + 1]
# DQN action
action = agent.select_action(state)
simulate_action(action)
# Replace the placeholder reward and termination condition with actual logic
reward, done = calculate_reward_and_check_termination(state, next_state)
total_reward += reward
experiences.append(Transition(state, action, reward, next_state, done))
episode_rewards.append(total_reward)
logger.info(f"Episode {episode + 1}, Total Reward: {total_reward}")
# Train the agent using collected experiences
for _ in range(BATCH_SIZE):
agent.replay_buffer.push(random.choice(experiences))
agent.train(BATCH_SIZE)
agent.update_target_model()
# Save the model parameters at the end of each episode
torch.save(agent.model.state_dict(), MODEL_SAVE_PATH)
# Check if this episode achieved the best reward
if total_reward > best_reward:
best_reward = total_reward
torch.save(agent.model.state_dict(), BEST_MODEL_SAVE_PATH)
# Save the best reward information
np.save(LOG_FILE, [best_reward])
# Clear experiences for the next episode
experiences.clear()
time.sleep(EPISODE_DELAY)
except KeyboardInterrupt:
logger.info("Training interrupted by user. Saving the model before exiting...")
torch.save(agent.model.state_dict(), MODEL_SAVE_PATH)
np.save(LOG_FILE, [best_reward]) # Save the best reward information
except Exception as e:
logger.error(f"An error occurred: {str(e)}")
finally:
exit()
if name == "main":
main()
To address your first issue, the current implementation does not provide the functionality for you to stop the demonstration phase when you press the 'Q' key in the game Superfighters Deluxe window. You can modify the loop within the expert demonstration phase to check for key presses using the keyboard or pynput library. You would need to install the keyboard library if you choose to use it. Below is an example of how you could use keyboard to achieve this:
python
# Add this import near the top of your script
import keyboard
# ...
# Where the for loop inside the expert demonstration phase, replace it with this:
for t in range(1, MAX_EPISODE_LENGTH + 1):
if keyboard.is_pressed('q'): # Check if Q key is pressed
logger.info("Q key pressed, stopping the demonstration...")
break # Break out of the loop
state = get_state()
frames.append(state)
time.sleep(0.1)
# Save the frame to the tutorial folder
frame_path = os.path.join(TUTORIAL_FOLDER, f"frame_{t}.jpg")
cv2.imwrite(frame_path, cv2.cvtColor(state, cv2.COLOR_RGB2BGR))
For the second problem, capturing only the Superfighters Deluxe window, you will need to locate the window's position and size and then capture that part of the screen. This can be done using the pygetwindow library that you are already using to check if the game is open. Here's how you could modify the get_state() function:
python
# Modify this function
def get_state():
try:
game_window = gw.getWindowsWithTitle('Superfighters Deluxe')[0]
if game_window:
game_window.restore()
game_window.activate()
# Make sure the game window is in the foreground before capturing
pyautogui.sleep(0.2) # A short delay to ensure the window comes to the front
x, y, width, height = game_window.left, game_window.top, game_window.width, game_window.height
screenshot = pyautogui.screenshot(region=(x, y, width, height))
state = np.array(screenshot)
return state
else:
raise Exception("Game window not found")
except Exception as e:
logger.error(f"Error getting game state: {str(e)}")
raise
Please note, however, to properly execute actions in the part of the code where you intend to simulate agent actions based on the agent.select_action(state) method. You will need to ensure that the captured frames are correctly pre-processed and passed to the model so it can predict the appropriate actions.
Also, make sure you have the necessary permissions to control the game window. Some games might have protections against simulated keystrokes and mouse movements.
Remember that capturing and controlling game windows might not work as expected if you are running your Python script with different privileges than the game or if the game uses DirectX/OpenGL in a way that prevents the window capture or simulating keystrokes.
Lastly, if you use the keyboard library, it requires administrative privileges to recognize keypresses globally and may not work in a packaged executable game. Always ensure that your use of these scripts aligns with the game's terms of service.
The error message you're receiving indicates there is some problem when trying to capture the state of the Superfighters Deluxe window. This could be caused by many factors, including permission issues, compatibility problems, or incorrect window handling code.
One possible point of failure is using the system path C:\WINDOWS\system32 as your working directory. Scripts running from system32 can have issues with permissions and unexpected behavior, so it is recommended to run your Python scripts from a different directory, ideally a user directory or a project-specific folder.
Please follow these steps to possibly resolve the issue:
Change your working directory to a non-system directory (preferably where your project is located).
Ensure that your game window is named exactly 'Superfighters Deluxe'. The window title must match exactly for gw.getWindowsWithTitle('Superfighters Deluxe') to work properly.
Make sure that the game window is not minimized and is on the active desktop (if you have multiple desktops configured).
The error message "The operation completed successfully." is a bit of a misnomer and might be caused due to the unusual behavior of the pygetwindow library. The error could also be due to the pyautogui.screenshot() method if it does not have access to capture the screen.
You may need to run your script as an administrator to allow screen capture and global keyboard listening with the keyboard library.
Try adding an additional delay after activating the window, as sometimes there can be a race condition where the screenshot is taken before the window has time to redraw on the screen:
python
game_window.activate()
time.sleep(1) # A delay to ensure the game is in the foreground before taking a screenshot
If you're still facing issues, you might want to use alternative methods to capture the game window. For example, using the win32gui library from PyWin32 or using mss library which is specialized for fast screenshots:
python
from mss import mss
# ...
def get_state():
game_window = gw.getWindowsWithTitle('Superfighters Deluxe')[0]
if game_window:
with mss() as sct:
bbox = (game_window.left, game_window.top, game_window.left + game_window.width, game_window.top + game_window.height)
screenshot = sct.grab(bbox)
# Convert to an np.array
state = np.array(screenshot)
# Convert from BGRA to BGR (if needed)
if state.shape[2] == 4:
state = state[..., :3]
return state
else:
raise Exception("Game window not found")
Remember to test your program with these modifications and ensure that you have the necessary permissions to read the state of the game window and take screenshots. If the game still cannot be captured properly, consider looking at the permissions of the game and whether the game uses a rendering method that prevents regular capture methods from accessing its visuals.