-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
50 lines (40 loc) · 1.27 KB
/
index.js
File metadata and controls
50 lines (40 loc) · 1.27 KB
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
45
46
47
48
49
50
document.addEventListener('DOMContentLoaded', async () => {
const pyodide = await loadPyodide();
const button = document.getElementById('runGameButton')!;
const gameOutput = document.getElementById('gameOutput')!;
button.addEventListener('click', async () => {
const pythonCode = `
import random
def number_guessing_game():
number_to_guess = random.randint(1, 100)
guess = None
attempts = 0
while guess != number_to_guess:
guess = int(input("Guess a number between 1 and 100: "))
attempts += 1
if guess < number_to_guess:
print("Too low!")
elif guess > number_to_guess:
print("Too high!")
print(f"Congratulations! You've guessed the number in {attempts} attempts.")
number_guessing_game()
`;
pyodide.runPythonAsync(`
from js import document
import sys
from io import StringIO
class OutputCatcher:
def __init__(self):
self.output = StringIO()
def write(self, msg):
self.output.write(msg)
def flush(self):
pass
sys.stdout = OutputCatcher()
sys.stderr = OutputCatcher()
${pythonCode}
output = sys.stdout.output.getvalue() + sys.stderr.output.getvalue()
document.getElementById("gameOutput").textContent = output
`);
});
});