Skip to content

Instantly share code, notes, and snippets.

@axlan
Created March 2, 2024 06:23
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 axlan/416ba0560db02552b700c8d49c6bc98c to your computer and use it in GitHub Desktop.
Save axlan/416ba0560db02552b700c8d49c6bc98c to your computer and use it in GitHub Desktop.
I did a really quick proof of concept of playing different sound effects when rolling 1's and 20's. This is using QPython to run a web server that handles the web requests from the Pixels Dice app (https://gamewithpixels.com/).
#qpy:webapp:Hello QPython
#qpy://127.0.0.1:8080/
"""
This is a sample for qpython webapp
"""
import os
import time
import androidhelper
from bottle import Bottle, ServerAdapter
from bottle import run, debug, route, error, static_file, template, request
import logging
logger = logging.getLogger('my_logger')
indexes = {
'good': 0,
'bad': 0
}
GOOD_SOUNDS = ['https://www.myinstants.com/media/sounds/final-fantasy-vii-victory-fanfare-1.mp3',
'https://www.myinstants.com/media/sounds/anime-wow-sound-effect.mp3',
'https://www.myinstants.com/media/sounds/mlg-airhorn.mp3',
'https://www.myinstants.com/media/sounds/zelda-chest-opening-and-item-catch.mp3',
'https://www.myinstants.com/media/sounds/kids-saying-yay-sound-effect_3.mp3']
BAD_SOUNDS = ['https://www.myinstants.com/media/sounds/dun-dun-dun-sound-effect-brass_8nFBccR.mp3',
'https://www.myinstants.com/media/sounds/the-price-is-right-losing-horn.mp3',
'https://www.myinstants.com/media/sounds/meme-de-creditos-finales.mp3',
'https://www.myinstants.com/media/sounds/awkward-cricket-sound-effect.mp3',
'https://www.myinstants.com/media/sounds/heknew.mp3']
######### QPYTHON WEB SERVER ###############
class MyWSGIRefServer(ServerAdapter):
server = None
def run(self, handler):
from wsgiref.simple_server import make_server, WSGIRequestHandler
if self.quiet:
class QuietHandler(WSGIRequestHandler):
def log_request(*args, **kw): pass
self.options['handler_class'] = QuietHandler
self.server = make_server(self.host, self.port, handler, **self.options)
self.server.serve_forever()
def stop(self):
#sys.stderr.close()
import threading
threading.Thread(target=self.server.shutdown).start()
#self.server.shutdown()
self.server.server_close() #<--- alternative but causes bad fd exception
print("# qpyhttpd stop")
######### BUILT-IN ROUTERS ###############
@route('/__exit', method=['GET','HEAD'])
def __exit():
global server
server.stop()
@route('/__ping')
def __ping():
return "ok"
@route('/__play')
def __play():
droid = androidhelper.Android()
url = None
if request.json['faceValue'] == 20:
url = GOOD_SOUNDS[indexes['good'] % len(GOOD_SOUNDS)]
indexes['good'] += 1
elif request.json['faceValue'] == 1:
url = BAD_SOUNDS[indexes['bad'] % len(BAD_SOUNDS)]
indexes['bad'] += 1
if url is not None:
droid.mediaPlay(url,play=True)
print(request.json)
logger.error(request.json)
return "ok"
@route('/assets/<filepath:path>')
def server_static(filepath):
return static_file(filepath, root=os.path.dirname(os.path.abspath(__file__)))
######### WEBAPP ROUTERS ###############
@route('/')
def home():
name='QPython'
file=os.path.basename(__file__)
cont=f'''
<h1>Hello {name} !</h1><a href="/assets/{file}">View source</a><br><br>
<a href="__exit">>> Exit</a><br>
<a href="http://wiki.qpython.org/doc/program_guide/web_app/">>> About QPython Web App</a>
'''
return template(cont)
######### WEBAPP ROUTERS ###############
app = Bottle()
app.route('/', method='GET')(home)
app.route('/__exit', method=['GET','HEAD'])(__exit)
app.route('/__ping', method=['GET','HEAD'])(__ping)
app.route('/__play', method=['POST','HEAD'])(__play)
app.route('/assets/<filepath:path>', method='GET')(server_static)
try:
server = MyWSGIRefServer(host="127.0.0.1", port="8080")
app.run(server=server,reloader=False)
except (Exception) as ex:
print("Exception: %s" % repr(ex))
@axlan
Copy link
Author

axlan commented Mar 2, 2024

Demo video: https://www.youtube.com/watch?v=oZFggJm8ZQ4

Dice web request just needs to send the JSON payload to 127.0.0.1:8080/__play

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