|
| 1 | +import sys, os |
| 2 | +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "src"))) |
| 3 | + |
| 4 | + |
| 5 | + |
| 6 | +import numpy as np |
| 7 | +import matplotlib.pyplot as plt |
| 8 | +from matplotlib.animation import FuncAnimation |
| 9 | +from matplotlib.patches import Circle |
| 10 | +from envs.connect4_env import Connect4Action, Connect4Env |
| 11 | + |
| 12 | + |
| 13 | +def render_connect4_board(board, ax, player_colors={1: "red", 2: "yellow", -1: "yellow"}, show=True): |
| 14 | + """ |
| 15 | + Render a Connect 4 board using matplotlib. |
| 16 | +
|
| 17 | + Args: |
| 18 | + board: 2D list, numpy array, or board object (6x7) with values: |
| 19 | + 0 -> empty, 1 -> player 1, 2 -> player 2 (or -1 for player 2) |
| 20 | + player_colors: dict mapping player numbers to colors. |
| 21 | + show: If True, calls plt.show(). If False, returns the figure. |
| 22 | +
|
| 23 | + Returns: |
| 24 | + The matplotlib figure and axis (if show=False). |
| 25 | + """ |
| 26 | + # Extract board data if it's an object with board attribute |
| 27 | + if hasattr(board, 'board'): |
| 28 | + b_map = np.array(board.board) |
| 29 | + elif hasattr(board, '__array__'): |
| 30 | + b_map = np.array(board) |
| 31 | + else: |
| 32 | + b_map = np.array(board) |
| 33 | + |
| 34 | + # Handle different player value representations |
| 35 | + # Some environments use 1 and 2, others use 1 and -1 |
| 36 | + rows, cols = b_map.shape |
| 37 | + |
| 38 | + ax.set_xlim(0, cols) |
| 39 | + ax.set_ylim(0, rows) |
| 40 | + ax.set_aspect("equal") |
| 41 | + ax.axis("off") |
| 42 | + |
| 43 | + # Draw the blue board background |
| 44 | + rect = plt.Rectangle((0, 0), cols, rows, color="#0055FF", zorder=0) |
| 45 | + ax.add_patch(rect) |
| 46 | + |
| 47 | + # Draw circular holes |
| 48 | + for r in range(rows): |
| 49 | + for c in range(cols): |
| 50 | + center = (c + 0.5, rows - 1 - r + 0.5) # Fixed: removed extra -1 |
| 51 | + val = b_map[r, c] |
| 52 | + |
| 53 | + # Handle different value representations |
| 54 | + if val == 1: |
| 55 | + color = player_colors[1] |
| 56 | + elif val == 2 or val == -1: |
| 57 | + color = player_colors.get(2, player_colors.get(-1, "yellow")) |
| 58 | + else: |
| 59 | + color = "white" |
| 60 | + |
| 61 | + circ = Circle(center, 0.4, color=color, ec="black", lw=1.5) |
| 62 | + ax.add_patch(circ) |
| 63 | + |
| 64 | + plt.tight_layout() |
| 65 | + if show: |
| 66 | + plt.show() |
| 67 | + else: |
| 68 | + return ax |
| 69 | + |
| 70 | + |
| 71 | +def main(render=True): |
| 72 | + print("Connecting to Connect4 environment...") |
| 73 | + env = Connect4Env(base_url="http://localhost:8000") |
| 74 | + |
| 75 | + try: |
| 76 | + print("\nResetting environment...") |
| 77 | + result = env.reset() |
| 78 | + |
| 79 | + frames = [] |
| 80 | + rewards = [] |
| 81 | + steps = [] |
| 82 | + |
| 83 | + # Collect all frames |
| 84 | + board = np.array(result.observation.board).reshape(6, 7) |
| 85 | + frames.append(board.copy()) |
| 86 | + rewards.append(result.reward or 0) |
| 87 | + steps.append(0) |
| 88 | + |
| 89 | + for step in range(100): |
| 90 | + if result.done: |
| 91 | + break |
| 92 | + |
| 93 | + action_id = int(np.random.choice(result.observation.legal_actions)) |
| 94 | + result = env.step(Connect4Action(column=action_id)) |
| 95 | + |
| 96 | + board = np.array(result.observation.board).reshape(6, 7) |
| 97 | + frames.append(board.copy()) |
| 98 | + rewards.append(result.reward or 0) |
| 99 | + steps.append(step + 1) |
| 100 | + |
| 101 | + if result.done: |
| 102 | + print(f"Game finished at step {step + 1} with reward {result.reward}") |
| 103 | + break |
| 104 | + |
| 105 | + if render: |
| 106 | + # Create a single figure and update it |
| 107 | + fig, ax = plt.subplots(figsize=(7, 6)) |
| 108 | + |
| 109 | + def animate_frame(i): |
| 110 | + ax.clear() |
| 111 | + # Use the render function but don't show immediately |
| 112 | + render_connect4_board(frames[i], ax=ax, show=False) |
| 113 | + ax.set_title(f"Step: {steps[i]}, Reward: {rewards[i]:.2f}\nTotal: {sum(rewards[:i+1]):.2f}", |
| 114 | + fontsize=12, pad=20) |
| 115 | + return ax.patches |
| 116 | + |
| 117 | + # Create animation |
| 118 | + ani = FuncAnimation(fig, animate_frame, frames=len(frames), |
| 119 | + interval=700, repeat=False, blit=False) |
| 120 | + |
| 121 | + plt.tight_layout() |
| 122 | + plt.show(block=True) |
| 123 | + |
| 124 | + finally: |
| 125 | + env.close() |
| 126 | + print("Environment closed.") |
| 127 | + |
| 128 | + |
| 129 | +if __name__ == "__main__": |
| 130 | + main(render=True) |
0 commit comments