.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "gallery/snake.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr_gallery_snake.py: Snake game ---------- Simple snake game based on bitmap rendering. Work in progress. .. GENERATED FROM PYTHON SOURCE LINES 7-72 .. code-block:: Python from collections import deque import numpy as np from rendercanvas.auto import RenderCanvas, loop canvas = RenderCanvas( title="Snake on $backend", present_method=None, size=(640, 480), update_mode="continuous", ) context = canvas.get_bitmap_context() world = np.zeros((120, 160), np.uint8) pos = [100, 100] direction = [1, 0] q = deque() @canvas.add_event_handler("key_down") def on_key(event): key = event["key"] if key == "ArrowLeft": direction[0] = -1 direction[1] = 0 elif key == "ArrowRight": direction[0] = 1 direction[1] = 0 elif key == "ArrowUp": direction[0] = 0 direction[1] = -1 elif key == "ArrowDown": direction[0] = 0 direction[1] = 1 @canvas.request_draw def animate(): pos[0] += direction[0] pos[1] += direction[1] if pos[0] < 0: pos[0] = world.shape[1] - 1 elif pos[0] >= world.shape[1]: pos[0] = 0 if pos[1] < 0: pos[1] = world.shape[0] - 1 elif pos[1] >= world.shape[0]: pos[1] = 0 q.append(tuple(pos)) world[pos[1], pos[0]] = 255 while len(q) > 20: old_pos = q.popleft() world[old_pos[1], old_pos[0]] = 0 context.set_bitmap(world) loop.run() .. _sphx_glr_download_gallery_snake.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: snake.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: snake.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: snake.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_ .. only:: html Interactive example =================== This uses Pyodide. If this does not work, your browser may not have sufficient support for wasm/pyodide/wgpu (check your browser dev console). .. raw:: html