|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Simple example demonstrating Atari Environment usage. |
| 4 | +
|
| 5 | +This example shows how to: |
| 6 | +1. Connect to an Atari environment |
| 7 | +2. Reset the environment |
| 8 | +3. Take random actions |
| 9 | +4. Process observations |
| 10 | +
|
| 11 | +Usage: |
| 12 | + # First, start the server: |
| 13 | + python -m envs.atari_env.server.app |
| 14 | +
|
| 15 | + # Then run this script: |
| 16 | + python examples/atari_simple.py |
| 17 | +""" |
| 18 | + |
| 19 | +import numpy as np |
| 20 | +from envs.atari_env import AtariEnv, AtariAction |
| 21 | + |
| 22 | + |
| 23 | +def main(): |
| 24 | + """Run a simple Atari episode.""" |
| 25 | + # Connect to the Atari environment server |
| 26 | + print("Connecting to Atari environment...") |
| 27 | + env = AtariEnv(base_url="http://localhost:8000") |
| 28 | + |
| 29 | + try: |
| 30 | + # Reset the environment |
| 31 | + print("\nResetting environment...") |
| 32 | + result = env.reset() |
| 33 | + print(f"Screen shape: {result.observation.screen_shape}") |
| 34 | + print(f"Legal actions: {result.observation.legal_actions}") |
| 35 | + print(f"Lives: {result.observation.lives}") |
| 36 | + |
| 37 | + # Run a few steps with random actions |
| 38 | + print("\nTaking random actions...") |
| 39 | + episode_reward = 0 |
| 40 | + steps = 0 |
| 41 | + |
| 42 | + for step in range(100): |
| 43 | + # Random action |
| 44 | + action_id = np.random.choice(result.observation.legal_actions) |
| 45 | + |
| 46 | + # Take action |
| 47 | + result = env.step(AtariAction(action_id=action_id)) |
| 48 | + |
| 49 | + episode_reward += result.reward or 0 |
| 50 | + steps += 1 |
| 51 | + |
| 52 | + # Print progress |
| 53 | + if step % 10 == 0: |
| 54 | + print( |
| 55 | + f"Step {step}: reward={result.reward:.2f}, " |
| 56 | + f"lives={result.observation.lives}, done={result.done}" |
| 57 | + ) |
| 58 | + |
| 59 | + if result.done: |
| 60 | + print(f"\nEpisode finished after {steps} steps!") |
| 61 | + break |
| 62 | + |
| 63 | + print(f"\nTotal episode reward: {episode_reward:.2f}") |
| 64 | + |
| 65 | + # Get environment state |
| 66 | + state = env.state() |
| 67 | + print(f"\nEnvironment state:") |
| 68 | + print(f" Game: {state.game_name}") |
| 69 | + print(f" Episode: {state.episode_id}") |
| 70 | + print(f" Steps: {state.step_count}") |
| 71 | + print(f" Obs type: {state.obs_type}") |
| 72 | + |
| 73 | + finally: |
| 74 | + # Cleanup |
| 75 | + print("\nClosing environment...") |
| 76 | + env.close() |
| 77 | + print("Done!") |
| 78 | + |
| 79 | + |
| 80 | +if __name__ == "__main__": |
| 81 | + main() |
0 commit comments