Skip to content

Instantly share code, notes, and snippets.

@eliasffyksen
Last active November 20, 2022 17:49
Show Gist options
  • Save eliasffyksen/1c3dae8bdf680a55996a3d3ac478f908 to your computer and use it in GitHub Desktop.
Save eliasffyksen/1c3dae8bdf680a55996a3d3ac478f908 to your computer and use it in GitHub Desktop.
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]))
score = None
while score is None:
img.set_data(snake)
fig.canvas.draw_idle()
plt.pause(0.1)
score = do(snake, action['val'])
action['val'] = 1
print('Score:', score)
@tln
Copy link

tln commented Aug 11, 2022

This line doesn't change the default value of the dictionary, it sets action_dict[1] to None.

action_dict.setdefault(1)

May I suggest:

LEFT, STRAIGHT, RIGHT = 0, 1, 2
keys = {'a': LEFT, 'd': RIGHT}
action = STRAIGHT
def on_key(e):
  global action
  action = keys.get(e.key, STRAIGHT)

fig.canvas.mpl_connect('key_press_event', on_key)

score = None
while score is None:
    img.set_data(snake)
    fig.canvas.draw_idle()
    plt.pause(0.1)
    score = do(snake, action)
    action = STRAIGHT

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment