Skip to content

Instantly share code, notes, and snippets.

@DavidBuchanan314
Created April 10, 2018 12:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidBuchanan314/a9ae08db6ac9f30e363ebce0c349d002 to your computer and use it in GitHub Desktop.
Save DavidBuchanan314/a9ae08db6ac9f30e363ebce0c349d002 to your computer and use it in GitHub Desktop.
import sys
import time
import _nx
from glob import glob
import os
import runpy
sys.argv = [""] # workaround needed for runpy
KEY_A = 1
KEY_UP = 0x222000
KEY_DOWN = 0x888000
CONTROLLER_P1_AUTO = 10
GfxMode_TiledDouble = 1
class AnsiMenu():
def __init__(self, entries, console=sys.stdout.buffer):
self.entries = entries
self.console = console
def query(self):
self.selected_idx = 0
self.render()
while True:
if self.poll_input():
break
time.sleep(0.01)
self.console.write(b"\x1b[%dB" % (len(self.entries)-self.selected_idx))
self.console.flush()
return self.selected_idx
def poll_input(self):
_nx.hid_scan_input()
keys_down = _nx.hid_keys_down(CONTROLLER_P1_AUTO)
if keys_down & KEY_A:
return True
elif keys_down & KEY_UP:
if self.selected_idx > 0:
self.selected_idx -= 1
self.console.write(b" \x1b[1A\r>\r")
self.console.flush()
elif keys_down & KEY_DOWN:
if self.selected_idx < len(self.entries)-1:
self.selected_idx += 1
self.console.write(b" \n\r>\r")
self.console.flush()
return False
def render(self):
for i, label in enumerate(self.entries):
marker = b">" if (i == self.selected_idx) else b" "
self.console.write(b"%s %s\n" % (marker, label.encode()))
self.console.write(b"\x1b[%dA" % len(self.entries))
self.console.flush()
#os.chdir("examples")
while True:
dirs = ["../"] + glob("*/")
scripts = glob("*.py")
listing = dirs+scripts
file_menu = AnsiMenu(listing)
print("Listing for {}:".format(os.getcwd()), flush=True)
selected = listing[file_menu.query()]
sys.stdout.buffer.write(b"\x1b[2J")
sys.stdout.buffer.flush()
if selected in dirs:
os.chdir(selected)
else:
runpy.run_path(selected, run_name="__main__")
_nx.gfx_set_mode(GfxMode_TiledDouble)
print("{} Exited.".format(selected), flush=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment