### Install VideoGameBench dependencies Source: https://github.com/alexzhang13/videogamebench/blob/main/README.md Set up the conda environment and install required packages including Playwright for DOS game support. ```bash conda create -n videogamebench python=3.10 conda activate videogamebench pip install -r requirements.txt pip install -e . playwright install # Install playwright for DOS games ``` -------------------------------- ### Initialize Game and Window Events Source: https://github.com/alexzhang13/videogamebench/blob/main/configs/calibration_dragging/game.html Sets up the window resize listener and loads the initial game level. ```javascript // Window Resize Event window.addEventListener('resize', resizeCanvas); // --- Initialization --- loadLevel(0); // Start game at level 1 (index 0) ``` -------------------------------- ### Warcraft 2 Campaign Initialization Script Source: https://github.com/alexzhang13/videogamebench/blob/main/configs/warcraft2/preload.txt Automates the game startup process by waiting for load times and navigating menus via mouse and keyboard inputs. ```bash # Wait for initial game load sleep 12 # Get on screen move_mouse 320 200 click 320 200 # Start game sleep 3 press_key Enter # New campaign sleep 3 press_key Enter # Orc campaign sleep 3 press_key Enter # Confirm orc campaign sleep 4 press_key Enter ``` -------------------------------- ### Automate Quake Game Startup Source: https://github.com/alexzhang13/videogamebench/blob/main/configs/quake/preload.txt Executes a sequence of delays, mouse clicks, and key presses to navigate the game menu. ```text # Wait for initial game load sleep 12 # Get on screen move_mouse 320 200 click 320 200 # Start game sleep 3 press_key 1 sleep 3 press_key Enter sleep 3 press_key Enter # Orc campaign sleep 3 press_key Enter sleep 4 press_key Enter ``` -------------------------------- ### Automate Game Startup Sequence Source: https://github.com/alexzhang13/videogamebench/blob/main/configs/need_for_speed/preload.txt Executes a sequence of delays and key inputs to bypass initial menus. Ensure the game is launched before running this script. ```text # Wait for initial game load sleep 25 # Start game press_key Enter sleep 3 press_key Enter sleep 1 press_key ArrowUp sleep 1 press_key ArrowUp sleep 1 press_key ArrowUp sleep 3 press_key Enter sleep 3 press_key Enter ``` -------------------------------- ### Initialize Civilization DOSBox Source: https://github.com/alexzhang13/videogamebench/blob/main/configs/civ_custom/game.html Configures the DOSBox environment and sets up F10 key handling for pointer locking. ```javascript // Add resize handler to update grid coordinates window.addEventListener('resize', addGridCoordinates); // Initial grid setup addGridCoordinates(); // Modified Civilization game setup Dos(document.getElementById("jsdos"), { wdosboxUrl: "https://js-dos.com/6.22/current/wdosbox.js" }).ready((fs, main) => { fs.createFile("dosbox.conf", ` [sdl] autolock=false sensitivity=100 waitonerror=true [dosbox] captures=capture machine=svga_s3 `); // Create a ci instance to handle mouse capture fs.extract("roms/civ.zip").then(() => { const ci = main(["-conf", "dosbox.conf", "-c", "cd civ1", "-c", "CIV.EXE"]); // Add F10 handler for toggling mouse capture let isLocked = false; document.addEventListener('keydown', (e) => { if (e.code === 'F10') { isLocked = !isLocked; ci.simulateKeyPress(0x3B); // F1 key to toggle mouse in DOSBox if (isLocked) { document.body.requestPointerLock(); } else { document.exitPointerLock(); } } }); // Handle pointer lock change document.addEventListener('pointerlockchange', () => { isLocked = !!document.pointerLockElement; }); }); }); ``` -------------------------------- ### Command Line Arguments Source: https://github.com/alexzhang13/videogamebench/blob/main/README.md List of common and DOS-specific command line flags for configuring game execution and agent behavior. ```text Common options: --emulator {dos,gba} Which emulator to use (default: none) --game GAME Picks a game from the configs list --lite Enable lite mode for the game, meaning pause enabled while model is thinking --model MODEL The VLM model to use (using LiteLLM syntax). Defaults to gpt-4o --enable-ui Run the game with the agent UI enabled --max-steps MAX_STEPS Maximum number of steps to run. Defaults to 15000 DOS-specific options: --website-only Just open the website without agent interaction ``` -------------------------------- ### Initialize Maze Game Logic Source: https://github.com/alexzhang13/videogamebench/blob/main/configs/calibration_navigation/game.html Sets up the game environment, defines level grids, and initializes the first level upon DOM content loading. ```javascript document.addEventListener('DOMContentLoaded', () => { const mazeContainer = document.getElementById('maze-container'); const levelDisplay = document.getElementById('level-display'); const messageDisplay = document.getElementById('message-display'); const cellSize = 30; // Must match CSS .cell width/height // Maze Definitions: // 'S': Start, 'E': End, '0': Path, '1': Wall const levels = [ // Level 1: Straight line { grid: [ ['S', '0', '0', '0', 'E'] ] }, // Level 2: 90-degree turn { grid: [ ['S', '0', '0', '0', '1'], ['1', '1', '1', '0', '1'], ['1', '1', '1', '0', 'E'] ] }, // Level 3: Simple U-turn { grid: [ ['S', '0', '0', '1', '1'], ['1', '1', '0', '0', '1'], ['1', '1', '1', '0', 'E'] ] }, // Level 4: A bit more challenging box with turns { grid: [ ['1', '1', '1', '1', '1', '1'], ['1', 'S', '0', '1', 'E', '1'], ['1', '1', '0', '0', '0', '1'], ['1', '1', '1', '1', '1', '1'] ] }, // Level 5: A bit longer path { grid: [ ['S', '0', '1', '1', '1'], ['1', '0', '0', '0', '1'], ['1', '1', '1', '0', 'E'] ] }, // Level 6: Multiple turns { grid: [ ['S', '0', '0', '1', '1'], ['1', '1', '0', '1', 'E'], ['1', '1', '0', '0', '0'] ] }, // Level 7: Dead end and a detour { grid: [ ['1', 'S', '0', '0', '1'], ['1', '1', '1', '0', '1'], ['E', '0', '0', '0', '1'], ['1', '1', '1', '0', '1'], ['1', '1', '1', '0', '1'] ] }, // Level 8: Slightly more complex with choices { grid: [ ['S', '0', '1', '0', '0'], ['1', '0', '1', '0', '1'], ['0', '0', '0', '0', 'E'], ['0', '1', '1', '1', '1'], ['0', '0', '0', '0', '0'] ] }, // Level 9: A little zig-zag with a false path { grid: [ ['S', '0', '1', '1', '1', '1'], ['1', '0', '0', '0', '1', '0'], ['1', '1', '1', '0', '1', '1'], ['1', 'E', '0', '0', '0', '1'] ] }, // Level 10: Final challenge { grid: [ ['S', '0', '0', '1', '0', '0'], ['1', '1', '0', '1', '0', '1'], ['0', '0', '0', '0', '0', '1'], ['0', '1', '1', '0', '1', '1'], ['0', '0', 'E', '0', '0', '0'] ] } ]; let currentLevelIndex = 0; let playerPos = { x: 0, y: 0 }; let currentMaze; function findChar(char, grid) { for (let y = 0; y < grid.length; y++) { for (let x = 0; x < grid[y].length; x++) { if (grid[y][x] === char) { return { x, y }; } } } console.error("Character " + char + " not found in grid!"); return null; } function loadLevel(levelIndex) { if (levelIndex >= levels.length) { mazeContainer.innerHTML = ''; // Clear maze messageDisplay.textContent = "Congratulations! You beat all levels!"; messageDisplay.style.color = 'blue'; window.removeEventListener('keydown', handleKeyPress); // Stop listening for keys return; } currentLevelIndex = levelIndex; currentMaze = levels[currentLevelIndex].grid; const startPos = findChar('S', currentMaze); if (!startPos) return; playerPos = { ...startPos }; levelDisplay.textContent = currentLevelIndex + 1; messageDisplay.textContent = ''; drawMaze(); } function drawMaze() { if (!currentMaze) return; mazeContainer.innerHTML = ''; const rows = currentMaze.length; const cols = currentMaze[0].length; mazeContainer.style.gridTemplateColumns = `repeat(${cols}, ${cellSize}px)`; mazeContainer.style.gridTemplateRows = `repeat(${rows}, ${cellSize}px)`; mazeContainer.style.width = `${cols * cellSize}px`; mazeContainer.style.height = `${rows * cellSize}px`; for (let y = 0; y < rows; y++) { for (let x = 0; x < cols; x++) { const cell = document.createElement('div'); cell.classList.add('cell'); const cellType = currentMaze[y][x]; if (cellType === '1') { cell.classList.add('wall'); } else if (cellType === '0') { cell.classList.add('path'); } else if (cellType === 'S') { cell.classList.add('start', 'path'); } else if (cellType === 'E') { cell.classList.add('end', 'path'); } if (playerPos.x === x && playerPos.y === y) { cell.classList.add('player'); } mazeContainer.appendChild(cell); } } } function movePlayer(dx, dy) { if (!currentMaze) return; const newX = playerPos.x + dx; const newY = playerPos.y + dy; if (newX < 0 || newX >= currentMaze[0].length || newY < 0 || newY >= currentMaze.length) { return; } if (currentMaze[newY][newX] === '1') { return; } playerPos.x = newX; playerPos.y = newY; drawMaze(); if (currentMaze[playerPos.y][playerPos.x] === 'E') { messageDisplay.textContent = `Level ${currentLevelIndex + 1} Complete!`; messageDisplay.style.color = 'green'; window.removeEventListener('keydown', handleKeyPress); setTimeout(() => { loadLevel(currentLevelIndex + 1); if (currentLevelIndex < levels.length) { window.addEventListener('keydown', handleKeyPress); } }, 1000); } } function handleKeyPress(event) { if (["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"].includes(event.key)) { event.preventDefault(); } switch (event.key) { case 'ArrowUp': movePlayer(0, -1); break; case 'ArrowDown': movePlayer(0, 1); break; case 'ArrowLeft': movePlayer(-1, 0); break; case 'ArrowRight': movePlayer(1, 0); break; } } window.addEventListener('keydown', handleKeyPress); loadLevel(0); }); ``` -------------------------------- ### Doom 2 Automation Script Source: https://github.com/alexzhang13/videogamebench/blob/main/configs/doom2/preload.txt Automates the game startup sequence, including waiting for load times and navigating through menu screens. ```text # Wait for initial game load sleep 15 click 320 200 # Get on screen move_mouse 320 200 click 320 200 sleep 1 press_key Enter # Start game sleep 10 press_key Enter # New campaign sleep 2 press_key Enter sleep 1 ``` -------------------------------- ### Initialize Grid and JS-DOS Player Source: https://github.com/alexzhang13/videogamebench/blob/main/configs/warcraft2/game.html JavaScript functions to generate coordinate labels and initialize the Dos player instance. ```javascript // Add grid coordinates function addGridCoordinates() { const container = document.getElementById('gridContainer'); const viewportWidth = Math.ceil(window.innerWidth / 100); const viewportHeight = Math.ceil(window.innerHeight / 100); container.innerHTML = ''; for (let x = 0; x < viewportWidth; x++) { for (let y = 0; y < viewportHeight; y++) { const point = document.createElement('div'); point.className = 'grid-point'; point.style.left = (x * 100) + 'px'; point.style.top = (y * 100) + 'px'; point.textContent = `(${x},${y})`; container.appendChild(point); } } } // Add resize handler to update grid coordinates window.addEventListener('resize', addGridCoordinates); // Initial grid setup addGridCoordinates(); const props = Dos(document.getElementById("dos"), { url: "https://cdn.dos.zone/custom/dos/war2.jsdos", autoStart: true, }); ``` -------------------------------- ### Run games with local Ollama models Source: https://github.com/alexzhang13/videogamebench/blob/main/README.md Connect to a local Ollama server by specifying the API base URL. ```bash # First start ollama server python main.py --game kirby --model ollama/llama2 --api-base http://localhost:11434 --enable-ui ``` -------------------------------- ### Game Configuration and Level Definitions Source: https://github.com/alexzhang13/videogamebench/blob/main/configs/calibration_dragging/game.html Initializes game constants, state variables, and defines the path coordinates for ten distinct levels. ```javascript const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d'); const gameContainer = document.getElementById('game-container'); const levelDisplay = document.getElementById('level-display'); const messageDiv = document.getElementById('message'); const mouseIndicator = document.getElementById('mouseIndicator'); // --- Game Configuration --- const dotRadius = 15; const pathWidth = 12; // << INCREASED PATH WIDTH const pathColor = '#000000'; const dotColor = '#FF0000'; const startColor = '#008000'; // Green const endColor = '#008000'; // Green const endpointRadius = pathWidth * 0.8; // Make endpoint slightly larger than half path width const checkTolerance = pathWidth / 2 + dotRadius * 0.8; // How far off the path is allowed (center of dot can go slightly past path edge) const endProximity = dotRadius * 1.5; // How close to the end point to win let currentLevel = 0; let dotPos = { x: 0, y: 0 }; let isDragging = false; let levels = []; let scaleX = 1; let scaleY = 1; // --- Level Definitions --- // Paths are arrays of {x, y} points. Coordinates are based on a nominal 600x450 canvas. // They will be scaled if the canvas size differs. const nominalWidth = 600; const nominalHeight = 450; levels = [ // Level 1: Straight Line { path: [{ x: 50, y: 225 }, { x: 550, y: 225 }] }, // Level 2: Simple Curve Down { path: [{ x: 50, y: 100 }, { x: 250, y: 250 }, { x: 550, y: 330 }] }, // Level 3: Simple Curve Up { path: [{ x: 50, y: 350 }, { x: 350, y: 150 }, { x: 450, y: 125 }, { x: 550, y: 120 }] }, // Level 4: S Curve { path: [{ x: 50, y: 100 }, { x: 150, y: 200 }, { x: 250, y: 100 }, { x: 350, y: 200 }, { x: 450, y: 300 }, { x: 550, y: 350 }] }, // Level 5: Square Shape (Modified Endpoint) { path: [{ x: 100, y: 100 }, { x: 500, y: 100 }, { x: 500, y: 350 }, { x: 100, y: 350 }, { x: 100, y: 150 }, { x: 150, y: 150 }] }, // << MODIFIED: Endpoint is now {x: 150, y: 150} // Level 6: Loop (Modified Endpoint) { path: [{ x: 300, y: 100 }, { x: 450, y: 150 }, { x: 500, y: 225 }, { x: 450, y: 300 }, { x: 300, y: 350 }, { x: 150, y: 300 }, { x: 100, y: 225 }, { x: 150, y: 150 }, { x: 250, y: 125 }] }, // << MODIFIED: Endpoint is now {x: 250, y: 125} // Level 7: Zig Zag { path: [{ x: 50, y: 100 }, { x: 150, y: 200 }, { x: 50, y: 300 }, { x: 150, y: 400 }, { x: 250, y: 100 }, { x: 350, y: 200 }, { x: 250, y: 300 }, {x: 350, y: 400}, {x: 450, y: 200}, {x: 550, y: 100}] }, // Level 8: Gentle Wave { path: [{ x: 50, y: 200 }, { x: 100, y: 150 }, { x: 150, y: 130 }, { x: 200, y: 150 }, { x: 250, y: 200 }, { x: 300, y: 250 }, { x: 350, y: 270 }, { x: 400, y: 250 }, { x: 450, y: 200 }, { x: 500, y: 150 }, { x: 550, y: 130 }] }, // Level 9: Spiral Inwards (Approx) { path: [ {x: 300, y: 50}, {x: 450, y: 50}, {x: 500, y: 100}, {x: 500, y: 350}, {x: 450, y: 400}, {x: 150, y: 400}, {x: 100, y: 350}, {x: 100, y: 150}, {x: 150, y: 100}, {x: 350, y: 100}, {x: 400, y: 150}, {x: 400, y: 300}, {x: 350, y: 350}, {x: 200, y: 350}, {x: 150, y: 300}, {x: 150, y: 200}, {x: 200, y: 150}, {x: 300, y: 150 }, {x: 350, y: 200}, {x: 350, y: 250}, {x: 300, y: 300}, {x: 250, y: 300}, {x: 200, y: 250}, {x: 200, y: 200}, {x: 250, y: 180}, {x: 300, y: 225}] }, // Ends near center // Level 10: Complex Path { path: [{ x: 50, y: 400 }, { x: 100, y: 100 }, { x: 150, y: 350 }, { x: 200, y: 50 }, { x: 250, y: 400 }, { x: 300, y: 150 }, { x: 350, y: 300 }, { x: 400, y: 100 }, { x: 450, y: 250 }, { x: 500, y: 50 }, { x: 550, y: 225 }] }, ]; ``` -------------------------------- ### Run Lite games Source: https://github.com/alexzhang13/videogamebench/blob/main/README.md Execute games in lite mode using the --lite flag. ```bash python main.py --game doom2 --model gemini/gemini-2.5-pro-preview-03-25 --lite ``` -------------------------------- ### Import Dependencies Source: https://github.com/alexzhang13/videogamebench/blob/main/notebooks/generate_clips.ipynb Required libraries for file system operations and image processing. ```python import os import cv2 import numpy as np ``` -------------------------------- ### Game State and Level Management Source: https://github.com/alexzhang13/videogamebench/blob/main/configs/calibration_dragging/game.html Logic for displaying messages, loading levels, and resetting the game state. ```javascript // --- Game Logic --- function showMessage(text, duration = 1500) { messageDiv.textContent = text; messageDiv.style.display = 'block'; if (duration > 0) { setTimeout(() => { messageDiv.style.display = 'none'; }, duration); } } function loadLevel(levelIndex) { if (levelIndex >= levels.length) { showMessage("Congratulations! You finished all levels!", -1); isDragging = false; return; } currentLevel = levelIndex; const level = levels[currentLevel]; const startPoint = scaleCoord(level.path[0]); dotPos = { x: startPoint.x, y: startPoint.y }; levelDisplay.textContent = currentLevel + 1; isDragging = false; resizeCanvas(); // Recalculate scales and draw } function resetDot() { const level = levels[currentLevel]; if (!level) return; const startPoint = scaleCoord(level.path[0]); dotPos = { x: startPoint.x, y: startPoint.y }; isDragging = false; // Stop dragging on reset drawLevel(); // Add a little visual feedback for resetting (optional) gameContainer.style.backgroundColor = '#ffdddd'; // Flash light red setTimeout(() => { gameContainer.style.backgroundColor = '#fff'; }, 200); } ``` -------------------------------- ### Run Game Boy games Source: https://github.com/alexzhang13/videogamebench/blob/main/README.md Execute the VideoGameAgent for Game Boy ROMs placed in the roms/ directory. ```bash # Run with a Game Boy ROM file python main.py --game pokemon_red --model gpt-4o ``` -------------------------------- ### Wolfenstein Menu Automation Script Source: https://github.com/alexzhang13/videogamebench/blob/main/configs/wolfenstein/preload.txt Automates the initial game load and campaign selection process using sleep, mouse movement, and key presses. ```bash # Wait for initial game load sleep 10 # Get on screen move_mouse 320 200 click 320 200 press_key Enter # Start game sleep 5 press_key Enter sleep 5 press_key Enter sleep 5 press_key Enter sleep 3 press_key Enter # Select campaign (1) sleep 3 press_key Enter # New campaign sleep 2 press_key ArrowUp sleep 2 press_key ArrowUp sleep 2 press_key Enter sleep 4 ``` -------------------------------- ### Generate Video from Image Sequences Source: https://github.com/alexzhang13/videogamebench/blob/main/notebooks/generate_clips.ipynb Processes image files from specified directories, resizes them to fit an emulator template, and writes the combined frames to an MP4 video file. ```python import os import cv2 import numpy as np # _____ ____ ___ _____ # / ____|| _ \ / _ \ / ____| #| | __ | |_) | |_| || | __ __ _ _ __ ___ ___ #| | |_ || _ <| _ || | |_ | / _` | '_ ` _ \ / _ \ #| |__| || |_) | | | || |__| || (_| | | | | | | __/ # \_____||____/|_| |_| \_____| \__,_|_| |_| |_|\___| # Define paths base_folder = '../exps/videogamebench/zelda/gemini-2.5-pro/' emulator_image_path = '../media/img/emulator.png' game_screen_folder = os.path.join(base_folder, 'game_screen') monitor_folder = os.path.join(game_screen_folder, 'monitor') output_video_path = os.path.join(base_folder, 'output_video.mp4') frame_rate = 20 # Define emulator screen position (x, y, width, height) emulator_screen_rect = (60, 60, 140, 140) # Example values # Get sorted list of image filenames by frame number game_screen_files = sorted([ f for f in os.listdir(game_screen_folder) if f.startswith('screenshot_') and f.endswith('.png') ], key=lambda x: int(x.split('_')[1].split('.')[0])) monitor_files = sorted([ f for f in os.listdir(monitor_folder) if f.startswith('screenshot_') and f.endswith('.jpg') ], key=lambda x: int(x.split('_')[1].split('.')[0])) # Ensure equal number of frames print(len(game_screen_files), len(monitor_files)) num_frames = min(len(game_screen_files), len(monitor_files)) game_screen_files = game_screen_files[0:num_frames] monitor_files = monitor_files[0:num_frames] # Load first images to determine sizes img_game_screen = cv2.imread(os.path.join(game_screen_folder, game_screen_files[0])) img_monitor = cv2.imread(os.path.join(monitor_folder, monitor_files[0])) img_emulator = cv2.imread(emulator_image_path) # Emulator screen dimensions and frame height em_x, em_y, em_w, em_h = emulator_screen_rect frame_height = max(img_emulator.shape[0], img_monitor.shape[0]) # Resize emulator image to match frame height scale_ratio = frame_height / img_emulator.shape[0] img_emulator_resized = cv2.resize(img_emulator, None, fx=scale_ratio, fy=scale_ratio, interpolation=cv2.INTER_LINEAR) # Update emulator screen rect coordinates after resizing em_x = int(em_x * scale_ratio) em_y = int(em_y * scale_ratio) em_w = int(em_w * scale_ratio) em_h = int(em_h * scale_ratio) # Determine the size of the combined frame frame_width = img_emulator_resized.shape[1] + img_monitor.shape[1] # Initialize the video writer fourcc = cv2.VideoWriter_fourcc(*'mp4v') out = cv2.VideoWriter(output_video_path, fourcc, frame_rate, (frame_width, frame_height)) # Define the game title game_title = "Gemini 2.5 Pro" # Font settings font = cv2.FONT_HERSHEY_SIMPLEX font_scale = 1.0 font_thickness = 2 text_color = (0, 255, 0) # Process and write frames for gs_file, mon_file in zip(game_screen_files, monitor_files): img_game = cv2.imread(os.path.join(game_screen_folder, gs_file)) img_mon = cv2.imread(os.path.join(monitor_folder, mon_file)) base_emulator = img_emulator_resized.copy() # ----- Add title text (no background) ----- (text_width, text_height), _ = cv2.getTextSize(game_title, font, font_scale, font_thickness) text_x = (base_emulator.shape[1] - text_width) // 2 text_y = text_height + 30 cv2.putText(base_emulator, game_title, (text_x, text_y), font, font_scale, text_color, font_thickness, cv2.LINE_AA) # ------------------------------------------ # Resize game screen image to fit emulator screen img_game_resized = cv2.resize(img_game, (em_w, em_h)) # Overlay resized game screen onto emulator base_emulator[em_y:em_y+em_h, em_x:em_x+em_w] = img_game_resized # Create combined frame by concatenating emulator with monitor image padded_monitor = np.zeros((frame_height, img_monitor.shape[1], 3), dtype=np.uint8) padded_monitor[:img_monitor.shape[0], :] = img_mon combined_img = np.hstack((base_emulator, padded_monitor)) # Write to video out.write(combined_img) # Release the video writer out.release() print(f"Video saved to {output_video_path}") ``` ```text Output: 2930 2930 Video saved to ../exps/videogamebench/zelda/gemini-2.5-pro/output_video.mp4 ``` -------------------------------- ### Project Directory Structure Source: https://github.com/alexzhang13/videogamebench/blob/main/README.md Visual representation of the project's source code organization, separating evaluators, emulators, and agent logic. ```text src/ ├── evaluator.py # Main evaluation loop and episode management ├── run_dos.py # DOS-specific game runner ├── run_gb.py # Game Boy-specific emulator runner ├── emulators/ │ ├── dos/ # DOS-specific emulator logic │ ├── gba/ # Game Boy-specific emulator logic │ ├── interface_base.py # Base interface class for emulators ├── llm/ # Folder for LLM and Agent logic. ├──── llm_client.py # LLMLite logic ├──── vgagent.py # VG-Agent logic for both GB and DOS main.py # Entrypoint for launching VideoGameBench ``` -------------------------------- ### Register Mouse and Touch Event Listeners Source: https://github.com/alexzhang13/videogamebench/blob/main/configs/calibration_dragging/game.html Configures event listeners for mouse and touch inputs to drive game interactions. ```javascript // Mouse Events canvas.addEventListener('mousedown', (e) => { e.preventDefault(); handleStart(e.clientX, e.clientY); }); canvas.addEventListener('mousemove', (e) => { e.preventDefault(); handleMove(e.clientX, e.clientY); const x = e.clientX; const y = e.clientY; mouseIndicator.style.left = x + 'px'; mouseIndicator.style.top = y + 'px'; }); canvas.addEventListener('mouseup', (e) => { e.preventDefault(); handleEnd(); }); canvas.addEventListener('mouseleave', (e) => { if (isDragging) { resetDot(); // Reset if mouse leaves canvas while dragging } }); // Touch Events canvas.addEventListener('touchstart', (e) => { e.preventDefault(); if (e.touches.length > 0) { handleStart(e.touches[0].clientX, e.touches[0].clientY); } }); canvas.addEventListener('touchmove', (e) => { e.preventDefault(); if (e.touches.length > 0) { handleMove(e.touches[0].clientX, e.touches[0].clientY); } }); canvas.addEventListener('touchend', (e) => { e.preventDefault(); handleEnd(); }); canvas.addEventListener('touchcancel', (e) => { e.preventDefault(); resetDot(); // Treat cancel like leaving the area }); ``` -------------------------------- ### Automate Civilization Menu Navigation Source: https://github.com/alexzhang13/videogamebench/blob/main/configs/civ_custom/preload.txt Executes a sequence of mouse and keyboard inputs to navigate through the game's initial menus. ```text # Initial load sleep 5 # Get on screen and handle setup move_mouse 320 200 click 320 200 press_key 1 sleep 0.5 press_key 1 sleep 0.5 press_key 1 sleep 0.5 press_key Enter # Navigate menus sleep 2 press_key Enter sleep 3 press_key Enter sleep 3 press_key Enter sleep 3 press_key Enter sleep 3 press_key Enter sleep 3 press_key Enter ``` -------------------------------- ### Define Grid Overlay Styles Source: https://github.com/alexzhang13/videogamebench/blob/main/configs/warcraft2/game.html CSS styles to create a fixed, transparent grid overlay on the viewport. ```css body { margin: 0; position: relative; } .grid-container { position: fixed; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; z-index: 1000; } .grid { position: fixed; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; z-index: 999; background-image: linear-gradient(to right, rgba(255,0,0,0.15) 1px, transparent 1px), linear-gradient(to bottom, rgba(255,0,0,0.15) 1px, transparent 1px); background-size: 100px 100px; } .grid-point { position: absolute; font-size: 10px; color: rgba(255, 0, 0, 1.0); transform: translate(-50%, -50%); pointer-events: none; } ``` -------------------------------- ### Run DOS games Source: https://github.com/alexzhang13/videogamebench/blob/main/README.md Execute DOS games using various AI models and optional UI configurations. ```bash # Run Doom2 with Gemini 2.5 Pro python main.py --game doom2 --model gemini/gemini-2.5-pro-preview-03-25 # Run CIV with claude 3-7 and the agent state UI side by side python main.py --game civ --model anthropic/claude-3-7-sonnet-20250219 --enable-ui # Run Warcraft 2 in lite mode, so game pauses while model thinks python main.py --game warcraft2 --model together_ai/meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8 --enable-ui # Run website-only mode to play the game yourself python main.py --game quake --website-only ``` -------------------------------- ### Game Logic and Mouse Tracking Source: https://github.com/alexzhang13/videogamebench/blob/main/configs/calibration_clicking/game.html Handles target movement, click events, and mouse position visualization. ```javascript const GAME_AREA_WIDTH = 640; const GAME_AREA_HEIGHT = 400; const CIRCLE_DIAMETER = 40; const TARGET_CLICKS = 10; const gameArea = document.getElementById('gameArea'); const circle = document.getElementById('circle'); const winMessage = document.getElementById('winMessage'); const restartButton = document.getElementById('restartButton'); const scoreDisplay = document.getElementById('scoreDisplay'); let currentScore = 0; let gameActive = true; function moveCircle() { // Get actual available space const availableWidth = gameArea.clientWidth; const availableHeight = gameArea.clientHeight; // Calculate maximum positions const maxLeft = availableWidth - CIRCLE_DIAMETER; const maxTop = availableHeight - CIRCLE_DIAMETER; // Generate random positions const randomLeft = Math.floor(Math.random() * maxLeft); const randomTop = Math.floor(Math.random() * maxTop); // Apply positions circle.style.left = `${randomLeft}px`; circle.style.top = `${randomTop}px`; console.log(`Circle at ${randomLeft},${randomTop} in space ${availableWidth}x${availableHeight}`); scoreDisplay.textContent = `Score: ${currentScore}`; } function handleCircleClick() { if (!gameActive) return; currentScore++; scoreDisplay.textContent = `Score: ${currentScore}`; if (currentScore >= TARGET_CLICKS) { gameActive = false; circle.classList.add('hidden'); winMessage.classList.remove('hidden'); } else { moveCircle(); } } function restartGame() { currentScore = 0; gameActive = true; winMessage.classList.add('hidden'); circle.classList.remove('hidden'); scoreDisplay.textContent = `Score: ${currentScore}`; moveCircle(); } circle.addEventListener('click', handleCircleClick); restartButton.addEventListener('click', restartGame); moveCircle(); // Only activate overlay and mouse tracking if mouse_overlay is true let mouse_overlay = false; // Always show mouse icon at mouse position const mousePosition = document.getElementById('mousePosition'); mousePosition.classList.remove('hidden'); mousePosition.classList.add('mouse-icon-only'); // Single mousemove handler document.addEventListener('mousemove', (e) => { const x = e.clientX; const y = e.clientY; mousePosition.style.left = x + 'px'; mousePosition.style.top = y + 'px'; if (mouse_overlay) { // Show detailed position with coordinates mousePosition.classList.remove('mouse-icon-only'); mousePosition.textContent = `(${x},${y})`; } else { // Show simple mouse icon mousePosition.classList.add('mouse-icon-only'); mousePosition.textContent = ''; } }); if (mouse_overlay === true) { // Show overlay elements mousePosition.classList.remove('mouse-icon-only'); // Hide the up/down/left/right points document.getElementById('mousePointUp').classList.add('hidden'); document.getElementById('mousePointDown').classList.add('hidden'); document.getElementById('mousePointLeft').classList.add('hidden'); document.getElementById('mousePointRight').classList.add('hidden'); document.getElementById('gridContainer').classList.remove('hidden'); document.querySelector('.grid-lines').classList.remove('hidden'); // Add grid coordinates function addGridCoordinates() { const container = document.getElementById('gridContainer'); container.innerHTML = ''; // Clear previous points const gridSpacing = 50; const viewportWidth = window.innerWidth; const viewportHeight = window.innerHeight; for (let x = 0; x <= viewportWidth; x += gridSpacing) { for (let y = 0; y <= viewportHeight; y += gridSpacing) { const point = document.createElement('div'); point.className = 'grid-point'; point.style.left = x + 'px'; point.style.top = y + 'px'; point.style.fontSize = '10px'; point.textContent = `(${x},${y})`; container.appendChild(point); } } } // Add resize handler to update grid coordinates window.addEventListener('resize', () => { const container = document.getElementById('gridContainer'); container.innerHTML = ''; addGridCoordinates(); }); // Initial grid setup addGridCoordinates(); } ``` -------------------------------- ### Generate Side-by-Side Video Source: https://github.com/alexzhang13/videogamebench/blob/main/notebooks/generate_clips.ipynb Processes image files from two directories, aligns them by step index, resizes them, and writes them to an MP4 video file. ```python # _____ _____ _____ _____ _____ # | | __| | | __| # | | | |__ | | | | |__ | # |_|_|_|_____|_____|_____|_____| # _____ _____ _____ _____ _____ # | __| _ | | __| __| # | | | | | | | __|__ | # |_____|__|__|_|_|_|_____|_____| # Define paths base_folder = '../exps/videogamebench/incredible_machine/claude-3.7/' game_screen_folder = os.path.join(base_folder, 'game_screen') monitor_folder = os.path.join(base_folder, 'monitor') output_video_path = os.path.join(base_folder, 'output_video.mp4') frame_rate = 5 # Get sorted list of image filenames game_screen_files = sorted([ f for f in os.listdir(game_screen_folder) if f.startswith('game_screen_step_') and f.endswith('.jpg') ], key=lambda x: int(x.split('_')[3].split('.')[0])) monitor_files = sorted([ f for f in os.listdir(monitor_folder) if f.startswith('game_screen_step_') and f.endswith('.jpg') ], key=lambda x: int(x.split('_')[3].split('.')[0])) # Ensure equal number of frames num_frames = min(len(game_screen_files), len(monitor_files)) game_screen_files = game_screen_files[:num_frames] monitor_files = monitor_files[:num_frames] print(len(game_screen_files), len(monitor_files)) # Load first images to determine sizes img_game_screen = cv2.imread(os.path.join(game_screen_folder, game_screen_files[0])) img_monitor = cv2.imread(os.path.join(monitor_folder, monitor_files[0])) # Crop game screen to 640x400 cropped_game_screen = img_game_screen[0:400, 0:640] # Resize game screen to match monitor height monitor_height = img_monitor.shape[0] scale_ratio = monitor_height / cropped_game_screen.shape[0] new_game_screen_width = int(cropped_game_screen.shape[1] * scale_ratio) # Determine the size of the combined frame frame_width = new_game_screen_width + img_monitor.shape[1] frame_height = monitor_height # Initialize the video writer fourcc = cv2.VideoWriter_fourcc(*'mp4v') out = cv2.VideoWriter(output_video_path, fourcc, frame_rate, (frame_width, frame_height)) # Process and write frames for gs_file, mon_file in zip(game_screen_files, monitor_files): img_game = cv2.imread(os.path.join(game_screen_folder, gs_file)) img_mon = cv2.imread(os.path.join(monitor_folder, mon_file)) # Crop game screen to 640x400 then chop off the left 50 pixels img_game_cropped = img_game[0:400, 0:640] # Resize game screen image img_game_resized = cv2.resize(img_game_cropped, (new_game_screen_width, monitor_height)) # Concatenate images side by side combined_img = np.hstack((img_game_resized, img_mon)) # Write to video out.write(combined_img) # Release the video writer out.release() print(f"Video saved to {output_video_path}") ``` -------------------------------- ### Input Event Handling Source: https://github.com/alexzhang13/videogamebench/blob/main/configs/calibration_dragging/game.html Functions to calculate relative mouse/touch positions and initiate dragging interactions. ```javascript // --- Event Handlers --- function getRelativePos(clientX, clientY) { const rect = canvas.getBoundingClientRect(); const scaleRatioX = canvas.width / (window.devicePixelRatio || 1) / rect.width; const scaleRatioY = canvas.height / (window.devicePixelRatio || 1) / rect.height; return { x: (clientX - rect.left) * scaleRatioX, y: (clientY - rect.top) * scaleRatioY }; } function handleStart(clientX, clientY) { const pos = getRelativePos(clientX, clientY); if (!pos) return; const dx = pos.x - dotPos.x; const dy = pos.y - dotPos.y; // Only start dragging if click/touch is ON the dot if (dx * dx + dy * dy < dotRadius ** 2) { isDragging = true; // Move dot exactly to cursor start point only if starting ON the dot // This prevents snapping from afar if the tolerance was larger dotPos = pos; drawLevel(); // Update visual immediately } else { // Optional: Check if click is near the *start* point of the path const level = levels[currentLevel]; if (level) { const startPoint = scaleCoord(level.path[0]); const startDx = pos.x - startPoint.x; const startDy = pos.y - startPoint.y; // Allow starting if clicking near the green start circle too if (startDx * startDx + startDy * startDy < (endpointRadius * 1.5)**2) { isDragging = ``` -------------------------------- ### Render Grid Coordinates Source: https://github.com/alexzhang13/videogamebench/blob/main/configs/civ_custom/game.html Generates a grid of coordinate points based on the current viewport dimensions. ```javascript // Add grid coordinates function addGridCoordinates() { const container = document.getElementById('gridContainer'); const viewportWidth = Math.ceil(window.innerWidth / 100); const viewportHeight = Math.ceil(window.innerHeight / 100); container.innerHTML = ''; for (let x = 0; x < viewportWidth; x++) { for (let y = 0; y < viewportHeight; y++) { const point = document.createElement('div'); point.className = 'grid-point'; point.style.left = (x * 100) + 'px'; point.style.top = (y * 100) + 'px'; point.textContent = `(${x},${y})`; container.appendChild(point); } } } ``` -------------------------------- ### Canvas Resizing Logic Source: https://github.com/alexzhang13/videogamebench/blob/main/configs/calibration_dragging/game.html Handles canvas scaling based on device pixel ratio and container dimensions. ```javascript function resizeCanvas() { const dpr = window.devicePixelRatio || 1; const rect = gameContainer.getBoundingClientRect(); canvas.width = rect.width * dpr; canvas.height = rect.height * dpr; ``` -------------------------------- ### Canvas Rendering and Coordinate Scaling Source: https://github.com/alexzhang13/videogamebench/blob/main/configs/calibration_dragging/game.html Functions to handle canvas coordinate scaling and rendering of paths, start/end points, and the interactive dot. ```javascript ctx.scale(dpr, dpr); scaleX = rect.width / nominalWidth; scaleY = rect.height / nominalHeight; if (levels.length > 0) { drawLevel(); } } function scaleCoord(coord) { return { x: coord.x * scaleX, y: coord.y * scaleY }; } function drawPath(level) { if (!level || !level.path || level.path.length < 2) return; const scaledPath = level.path.map(scaleCoord); ctx.strokeStyle = pathColor; ctx.lineWidth = pathWidth; // Uses the updated thicker width ctx.lineCap = 'round'; ctx.lineJoin = 'round'; ctx.beginPath(); ctx.moveTo(scaledPath[0].x, scaledPath[0].y); for (let i = 1; i < scaledPath.length; i++) { ctx.lineTo(scaledPath[i].x, scaledPath[i].y); } ctx.stroke(); // Draw Start Point ctx.fillStyle = startColor; ctx.beginPath(); ctx.arc(scaledPath[0].x, scaledPath[0].y, endpointRadius, 0, Math.PI * 2); ctx.fill(); // Draw End Point const endPoint = scaledPath[scaledPath.length - 1]; ctx.fillStyle = endColor; ctx.beginPath(); ctx.arc(endPoint.x, endPoint.y, endpointRadius, 0, Math.PI * 2); ctx.fill(); } function drawDot() { ctx.fillStyle = dotColor; ctx.beginPath(); ctx.arc(dotPos.x, dotPos.y, dotRadius, 0, Math.PI * 2); ctx.fill(); } function drawLevel() { const logicalWidth = canvas.width / (window.devicePixelRatio || 1); const logicalHeight = canvas.height / (window.devicePixelRatio || 1); ctx.clearRect(0, 0, logicalWidth, logicalHeight); const level = levels[currentLevel]; if (level) { drawPath(level); drawDot(); } else { console.log("No more levels or level data missing!"); } } ``` -------------------------------- ### Handle Dragging Movement and Win Conditions Source: https://github.com/alexzhang13/videogamebench/blob/main/configs/calibration_dragging/game.html Updates the dot position during drag events and checks if the player has reached the win condition. ```javascript function handleMove(clientX, clientY) { if (!isDragging) return; const pos = getRelativePos(clientX, clientY); if (!pos) return; const level = levels[currentLevel]; if (!level) return; // Check if the *new* position is on the path if (isDotOnPath(level, pos)) { dotPos = pos; // Update dot position drawLevel(); // Redraw // Check for win condition if (checkWinCondition(level, dotPos)) { isDragging = false; showMessage("Level Complete!"); setTimeout(() => { loadLevel(currentLevel + 1); }, 1500); // Wait a bit before loading next level } } else { // Off the path - reset! resetDot(); } } ```