added robot module to python environment which provides access to sensor data fed from game state

master
Jake 2025-03-24 10:42:56 +08:00
parent e16c94f273
commit b9bf772aef
2 changed files with 49 additions and 13 deletions

View File

@ -72,6 +72,21 @@
pyodideWorker.postMessage({ code });
});
// ✅ Update "distance" and "speed" every 2 seconds with random values
function updateSensorData() {
const distance = Math.random() * 100; // Random distance (0-100)
const speed = Math.random() * 10; // Random speed (0-10)
pyodideWorker.postMessage({
type: "sensor_update",
data: { distance, speed }
});
//logToConsole(`📡 Sensor Update - Distance: ${distance.toFixed(2)}, Speed: ${speed.toFixed(2)}`);
}
setInterval(updateSensorData, 2000); // Call every 2 seconds
</script>
</body>

View File

@ -1,37 +1,53 @@
importScripts("https://cdn.jsdelivr.net/pyodide/v0.23.4/full/pyodide.js");
let sensorData = {}; // ✅ Declare sensorData globally
async function initializePyodide() {
self.pyodide = await loadPyodide({
indexURL: "https://cdn.jsdelivr.net/pyodide/v0.23.4/full/"
});
// Expose a function to send messages from Python to JavaScript
// ✅ Explicitly define send_to_main before running Python
self.pyodide.globals.set("send_to_main", (event, data) => {
self.postMessage({ type: event, data: data });
});
// Define the fire() and turn(deg) functions in Python
// ✅ Now set get_sensor_data AFTER Pyodide is initialized
self.pyodide.globals.set("get_sensor_data", (name) => {
return sensorData[name] ?? null; // Return sensor value or null if not set
});
// ✅ Define the robot module in Python
self.pyodide.runPython(`
import sys
import pyodide
class RobotModule:
def get_sensor(self, name):
return get_sensor_data(name) # This should now work!
robot = RobotModule()
def fire():
pyodide.ffi.to_js(send_to_main)("fire", None)
send_to_main("fire", None)
def turn(deg):
pyodide.ffi.to_js(send_to_main)("turn", deg)
send_to_main("turn", deg)
class ConsoleOutput:
def write(self, text):
if text.strip(): # Avoid empty writes
pyodide.ffi.to_js(send_to_main)("console", text)
return None # Prevent 'undefined' from appearing
send_to_main("console", text) # send_to_main is now properly defined
return None
def flush(self):
pass
sys.stdout = ConsoleOutput()
sys.stderr = ConsoleOutput()
# Register robot module in sys.modules
sys.modules["robot"] = robot
`);
self.postMessage({ type: "ready" }); // Notify main thread that Pyodide is ready
@ -45,6 +61,10 @@ self.onmessage = async (event) => {
return;
}
if (event.data.type === "sensor_update") {
// ✅ Update sensorData when receiving a sensor update
Object.assign(sensorData, event.data.data);
} else {
try {
let result = await self.pyodide.runPythonAsync(event.data.code);
@ -54,4 +74,5 @@ self.onmessage = async (event) => {
} catch (error) {
self.postMessage({ type: "error", message: error.toString() });
}
}
};