onlinecodesimulator/old.html

139 lines
3.7 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Python Web Executor</title>
<script src="https://cdn.jsdelivr.net/pyodide/v0.24.0/full/pyodide.js"></script>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
}
textarea {
width: 80%;
height: 150px;
}
button {
margin-top: 10px;
}
pre {
background: #f4f4f4;
padding: 10px;
}
</style>
</head>
<body>
<h2>Python Web Executor</h2>
<textarea id="code" placeholder="Write Python code here..."></textarea><br>
<button onclick="runPython()">Run</button>
<h3>Console Output:</h3>
<pre id="console-output"></pre>
<script>
async function loadPyodideAndSetup() {
window.pyodide = await loadPyodide();
// Define the external JavaScript print function
function jsPrint(text) {
console.log(text); // Log to the browser console
const outputElement = document.getElementById("console-output");
outputElement.textContent += text + "\n"; // Append to visible console
}
// Expose jsPrint to Python
window.jsPrint = jsPrint;
// Redirect Python's stdout to JavaScript and override time.sleep()
await pyodide.runPythonAsync(`
import asyncio
import time
import sys
from js import jsPrint
class JSConsoleWriter:
def write(self, text):
jsPrint(text)
def flush(self):
pass
sys.stdout = JSConsoleWriter()
# Override time.sleep to add periodic yielding
def sleep(seconds):
loop = asyncio.get_event_loop()
if loop.is_running():
# If we're inside an async environment, yield control back to browser
coro = asyncio.sleep(seconds)
loop.run_until_complete(coro)
time.sleep(seconds)
else:
# Fallback for non-async environments
print(":-(")
time.sleep(seconds)
#time.sleep = non_blocking_sleep
`);
}
// JavaScript functions for controlling the tank
function fire2() {
console.log("Tank fired!");
document.getElementById("console-output").textContent += "Tank fired!\n";
}
function move_forward() {
console.log("Tank moved forward!");
document.getElementById("console-output").textContent += "Tank moved forward!\n";
}
async function runPython() {
let code = document.getElementById("code").value;
let consoleOutput = document.getElementById("console-output");
consoleOutput.textContent = ""; // Clear the console before running
try {
// Define a helper function in Python to yield back control
await pyodide.runPythonAsync(`
import sys
import time
from js import jsPrint
class JSConsoleWriter:
def write(self, text):
jsPrint(text)
def flush(self):
pass
sys.stdout = JSConsoleWriter()
`);
// Run the user code directly, no wrapping or indentation modification
await pyodide.runPythonAsync(code);
// Introduce periodic yielding back to the browser
for (let i = 0; i < code.split("\n").length; i++) {
await new Promise(resolve => setTimeout(resolve, 0)); // Yield to the browser
}
} catch (err) {
consoleOutput.textContent += "Error: " + err + "\n";
}
}
loadPyodideAndSetup();
</script>
</body>
</html>