Static 5x5 grid for tabular SARSA / Q-learning. agent=[col,row].
| 58 | |
| 59 | # --------------------------------------------------------------------------- |
| 60 | class Env: |
| 61 | """Static 5x5 grid for tabular SARSA / Q-learning. agent=[col,row].""" |
| 62 | n_actions = 4 |
| 63 | HUD = 32 |
| 64 | |
| 65 | def __init__(self, title="GridWorld"): |
| 66 | self.title = title |
| 67 | self.agent = [0, 0] |
| 68 | self.obstacles = [[1, 2], [2, 1]] |
| 69 | self.goal = [2, 2] |
| 70 | self.q_overlay = None # set by print_value_all; rendered on next render() |
| 71 | self.episode = 0 # current episode index |
| 72 | self.steps = 0 # steps taken in the current episode |
| 73 | self.last_reward = None # terminal reward from the previous episode |
| 74 | self._screen = None |
| 75 | |
| 76 | def reset(self): |
| 77 | # Open a new episode (skipped at the very first reset). |
| 78 | if self.steps > 0: |
| 79 | self.episode += 1 |
| 80 | self.agent = [0, 0] |
| 81 | self.steps = 0 |
| 82 | if self._screen is not None: |
| 83 | self.render() |
| 84 | time.sleep(0.3) |
| 85 | return list(self.agent) |
| 86 | |
| 87 | def step(self, action): |
| 88 | x, y = self.agent |
| 89 | if action == 0 and y > 0: y -= 1 |
| 90 | elif action == 1 and y < HEIGHT - 1: y += 1 |
| 91 | elif action == 2 and x > 0: x -= 1 |
| 92 | elif action == 3 and x < WIDTH - 1: x += 1 |
| 93 | self.agent = [x, y] |
| 94 | self.steps += 1 |
| 95 | if self.agent == self.goal: |
| 96 | self.last_reward = 100 |
| 97 | return list(self.agent), 100, True |
| 98 | if self.agent in self.obstacles: |
| 99 | self.last_reward = -100 |
| 100 | return list(self.agent), -100, True |
| 101 | return list(self.agent), 0, False |
| 102 | |
| 103 | def print_value_all(self, q_table): |
| 104 | self.q_overlay = q_table |
| 105 | |
| 106 | def render(self): |
| 107 | if self._screen is None: |
| 108 | self._screen = _open(self.title, (WIDTH * UNIT, HEIGHT * UNIT + self.HUD)) |
| 109 | self._font = pygame.font.SysFont(None, 18) |
| 110 | self._hud_font = pygame.font.SysFont(None, 22) |
| 111 | _pump_events() |
| 112 | s = self._screen |
| 113 | hud = self.HUD |
| 114 | s.fill(WHITE) |
| 115 | # HUD bar. |
| 116 | pygame.draw.rect(s, (30, 30, 30), pygame.Rect(0, 0, WIDTH * UNIT, hud)) |
| 117 | # Steps display rounds down to the nearest 5 so the number doesn't |
no outgoing calls
no test coverage detected