Updated:
- HTML has been updated to use a specific version of PyScript (2023.11.2)
- Python code has been updated for that versions of PyScript
This post shows a simple game created using PyScript in this static website created with Pelican and Markdown files.
The game
How it's implemented
The implementation is quite eclectic (as Frankenstein's monster), it consist of 3 parts:
-
Markdown post: This is used by Pelican to create the post entry in the website, the code is here: https://github.com/rcassani/castoriscausa/blob/master/content/posts/pyscript_toy_example.md
It's very important to modify the Pelican theme to add the link to PyScript in
<head>
:1
<script defer src="https://pyscript.net/latest/pyscript.js"></script>
I made an update in my Pelican theme to do so. The modification can be found here
-
An HTML block in the Markdown file: Indicates which Python script will be used, and how it's connected to the UI elements in the page:
1 2 3 4 5 6 7 8 9 10 11
<div style="border: 2px solid black;padding: 10px;"> <script type="py" src="/scripts/guess_game.py" id="py-internal-0"></script> <strong><p id="game-message-txt"></p></strong> <input py-keydown="new_guess_event" id="new-guess-txt" class="py-input" type="text"> <button id="new-guess-btn" class="py-button" type="submit" py-click="new_guess"> Submit guess </button> <button id="reset-game-btn" class="py-button" type="submit" py-click="new_game"> Reset </button> </div>
-
A Python script: Gets input from the HTML elements, does the game logic and writes on the HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
import random from pyscript import document game_message_txt = document.querySelector("#game-message-txt") new_guess_txt = document.querySelector("#new-guess-txt") def new_game(e): 'Print instructions and set secret number' global x_target game_message_txt.innerText = 'Guess the secret number between 0 and 42' x_target = random.randint(0, 42) new_game(None) def new_guess(e): # ignore empty input if not new_guess_txt.value: return None x_str = new_guess_txt.value # must be a number if not x_str.isnumeric(): game_message_txt.innerText = 'Come on, it needs to be a number' return None else: try: # check it's an integer x = int(x_str) except ValueError as ve: game_message_txt.innerText = 'It needs to be an integer' # check it's in range if x < 0 or x > 42: game_message_txt.innerText = 'It needs to be in the range 0 to 42' return None # game logic if x > x_target: game_message_txt.innerText = 'Go lower than {0}'.format(x) elif x < x_target: game_message_txt.innerText = 'Go higher than {0}'.format(x) elif x == x_target: game_message_txt.innerText = 'Success!!!' def new_guess_event(e): if e.key == "Enter": new_guess(e)
Conclusion
This was a fun experiment, it opens the gates to do very interesting stuff with Python in my website 😎
Comments
comments powered by Disqus