This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| snake = t.zeros((32, 32), dtype=t.int) | |
| snake[0, :3] = T([1, 2, -1]) | |
| fig, ax = plt.subplots(1, 1) | |
| img = ax.imshow(snake) | |
| action = {'val': 1} | |
| action_dict = {'a': 0, 'd': 2} | |
| fig.canvas.mpl_connect('key_press_event', lambda e: | |
| action.__setitem__('val', action_dict[e.key])) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def do(snake: t.Tensor, action: int): | |
| positions = snake.flatten().topk(2)[1] | |
| [pos_cur, pos_prev] = [T(unravel(x, snake.shape)) for x in positions] | |
| rotation = T([[0, -1], [1, 0]]).matrix_power(3 + action) | |
| pos_next = (pos_cur + (pos_cur - pos_prev) @ rotation) % T(snake.shape) | |
| if (snake[tuple(pos_next)] > 0).any(): | |
| return (snake[tuple(pos_cur)] - 2).item() | |
| if snake[tuple(pos_next)] == -1: | |
| pos_food = (snake == 0).flatten().to(t.float).multinomial(1)[0] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| positions = snake.flatten().topk(2)[1] | |
| [pos_cur, pos_prev] = [T(unravel(x, snake.shape)) for x in positions] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| positions = snake.flatten().topk(2)[1] | |
| [pos_cur, pos_prev] = [T(unravel(x, snake.shape)) for x in positions] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import torch as t | |
| from torch import tensor as T | |
| from numpy import unravel_index as unravel | |
| import matplotlib.pyplot as plt | |
| def do(snake, action): | |
| '''This is where the magic happens :) ''' |