Compare commits

..

No commits in common. "5766cc7ab3705aec640e9af78b8e8ef0c7acceea" and "97e02d28c152f7664fec866fad852741320cc574" have entirely different histories.

12 changed files with 277 additions and 2608 deletions

View File

@ -1,3 +0,0 @@
{
"liveServer.settings.port": 5501
}

File diff suppressed because it is too large Load Diff

10
data/lessons.json Normal file
View File

@ -0,0 +1,10 @@
[
{
"title": "Lesson 1",
"content": "Welcome to Python. We are going to learn how to use python to control robots, but we need some basics first.</br>Let's start with the basics of Python programming. Python is a versatile language that is easy to learn and widely used in robotics.<br>"
},
{
"title": "Lesson 2",
"content": "Now let's learn about interrupts..."
}
]

View File

@ -5,50 +5,32 @@
"player": {
"position": {
"x": 200,
"y": 75
"y": 200
}
}
},
"waypoints": [
{
"position": {
"x": 420,
"y": 200
},
"vertices": [
{
"x": 300,
"y": 40
"x": -50,
"y": -50
},
{
"x": 300,
"y": 110
"x": 50,
"y": -50
},
{
"x": 320,
"y": 110
"x": 50,
"y": 50
},
{
"x": 320,
"y": 40
}
],
"strokeColor": "#0000FF",
"fillColor": "#0000CC"
},
{
"vertices": [
{
"x": 100,
"y": 40
},
{
"x": 100,
"y": 110
},
{
"x": 120,
"y": 110
},
{
"x": 120,
"y": 40
"x": -50,
"y": 50
}
],
"strokeColor": "#0000FF",
@ -59,88 +41,130 @@
{
"vertices": [
{
"x": 0,
"x": -100,
"y": -100
},
{
"x": 100,
"y": -100
},
{
"x": 100,
"y": 100
},
{
"x": -100,
"y": 100
}
],
"position": {
"x": 800,
"y": 300
},
"strokeColor": "#999999",
"fillColor": "#CCCCCC"
},
{
"vertices": [
{
"x": -10,
"y": -10
},
{
"x": 1010,
"y": -10
},
{
"x": 1010,
"y": 10
},
{
"x": -10,
"y": 10
}
],
"position": {
"x": 500,
"y": 0
},
{
"x": 850,
"y": 0
},
{
"x": 850,
"y": 20
},
{
"x": 0,
"y": 20
}
],
"strokeColor": "#999999",
"fillColor": "#CCCCCC"
},
{
"vertices": [
{
"x": 830,
"y": 20
"x": -10,
"y": -10
},
{
"x": 850,
"y": 20
"x": 1010,
"y": -10
},
{
"x": 850,
"y": 600
"x": 1010,
"y": 10
},
{
"x": 830,
"y": 600
"x": -10,
"y": 10
}
],
"strokeColor": "#999999",
"fillColor": "#CCCCCC"
},
{
"vertices": [
{
"x": 0,
"y": 600
},
{
"x": 850,
"y": 600
},
{
"x": 850,
"position": {
"x": 500,
"y": 620
},
{
"x": 0,
"y": 620
}
],
"strokeColor": "#999999",
"fillColor": "#CCCCCC"
},
{
"vertices": [
{
"x": 0,
"y": 20
"x": -10,
"y": 10
},
{
"x": 20,
"y": 20
"x": 10,
"y": 10
},
{
"x": 20,
"y": 600
"x": 10,
"y": 610
},
{
"x": 0,
"y": 600
"x": -10,
"y": 610
}
],
"position": {
"x": 0,
"y": 310
},
"strokeColor": "#999999",
"fillColor": "#CCCCCC"
},
{
"vertices": [
{
"x": -10,
"y": 10
},
{
"x": 10,
"y": 10
},
{
"x": 10,
"y": 610
},
{
"x": -10,
"y": 610
}
],
"position": {
"x": 1000,
"y": 310
},
"strokeColor": "#999999",
"fillColor": "#CCCCCC"
}
@ -152,178 +176,35 @@
"player": {
"position": {
"x": 200,
"y": 75
"y": 200
}
}
},
"waypoints": [
{
"vertices": [
{
"x": 300,
"y": 40
},
{
"x": 300,
"y": 110
},
{
"x": 320,
"y": 110
},
{
"x": 320,
"y": 40
}
],
"strokeColor": "#0000FF",
"fillColor": "#0000CC"
},
{
"vertices": [
{
"x": 300,
"y": 200
},
{
"x": 320,
"y": 200
},
{
"x": 320,
"y": 280
},
{
"x": 300,
"y": 280
}
],
"strokeColor": "#0000FF",
"fillColor": "#0000CC"
}
],
"obstacles": [
{
"vertices": [
{
"x": 0,
"y": 0
},
{
"x": 850,
"y": 0
},
{
"x": 850,
"y": 20
},
{
"x": 0,
"y": 20
}
],
"strokeColor": "#999999",
"fillColor": "#CCCCCC"
},
{
"vertices": [
{
"x": 830,
"y": 20
},
{
"x": 850,
"y": 20
},
{
"x": 850,
"y": 600
},
{
"x": 830,
"y": 600
}
],
"strokeColor": "#999999",
"fillColor": "#CCCCCC"
},
{
"vertices": [
{
"x": 0,
"y": 600
},
{
"x": 850,
"y": 600
},
{
"x": 850,
"y": 620
},
{
"x": 0,
"y": 620
}
],
"strokeColor": "#999999",
"fillColor": "#CCCCCC"
},
{
"vertices": [
{
"x": 0,
"y": 20
},
{
"x": 20,
"y": 20
},
{
"x": 20,
"y": 600
},
{
"x": 0,
"y": 600
}
],
"strokeColor": "#999999",
"fillColor": "#CCCCCC"
}
]
},
{
"name": "Level 3",
"robots": {
"player": {
"position": {
"x": 50,
"y": 70
}
}
"x": 220,
"y": 500
},
"waypoints": [
{
"vertices": [
{
"x": 340,
"y": 270
"x": -50,
"y": -50
},
{
"x": 340,
"y": 360
"x": 50,
"y": -50
},
{
"x": 360,
"y": 360
"x": 50,
"y": 50
},
{
"x": 360,
"y": 270
"x": -50,
"y": 50
}
],
"strokeColor": "#0000FF",
"strokeColor": "#000099",
"fillColor": "#0000CC"
}
],
@ -331,362 +212,130 @@
{
"vertices": [
{
"x": 0,
"x": -100,
"y": -100
},
{
"x": 100,
"y": -100
},
{
"x": 100,
"y": 100
},
{
"x": -100,
"y": 100
}
],
"position": {
"x": 200,
"y": 300
},
"strokeColor": "#999999",
"fillColor": "#CCCCCC"
},
{
"vertices": [
{
"x": -10,
"y": -10
},
{
"x": 1010,
"y": -10
},
{
"x": 1010,
"y": 10
},
{
"x": -10,
"y": 10
}
],
"position": {
"x": 500,
"y": 0
},
{
"x": 850,
"y": 0
},
{
"x": 850,
"y": 20
},
{
"x": 0,
"y": 20
}
],
"strokeColor": "#999999",
"fillColor": "#CCCCCC"
},
{
"vertices": [
{
"x": 830,
"y": 20
"x": -10,
"y": -10
},
{
"x": 850,
"y": 20
"x": 1010,
"y": -10
},
{
"x": 850,
"y": 600
"x": 1010,
"y": 10
},
{
"x": 830,
"y": 600
"x": -10,
"y": 10
}
],
"strokeColor": "#999999",
"fillColor": "#CCCCCC"
},
{
"vertices": [
{
"x": 0,
"y": 600
},
{
"x": 850,
"y": 600
},
{
"x": 850,
"position": {
"x": 500,
"y": 620
},
"strokeColor": "#999999",
"fillColor": "#CCCCCC"
},
{
"vertices": [
{
"x": -10,
"y": 10
},
{
"x": 10,
"y": 10
},
{
"x": 10,
"y": 610
},
{
"x": -10,
"y": 610
}
],
"position": {
"x": 0,
"y": 620
}
],
"y": 310
},
"strokeColor": "#999999",
"fillColor": "#CCCCCC"
},
{
"vertices": [
{
"x": 0,
"y": 20
"x": -10,
"y": 10
},
{
"x": 20,
"y": 20
"x": 10,
"y": 10
},
{
"x": 20,
"y": 600
"x": 10,
"y": 610
},
{
"x": 0,
"y": 600
"x": -10,
"y": 610
}
],
"strokeColor": "#999999",
"fillColor": "#CCCCCC"
"position": {
"x": 1000,
"y": 310
},
{
"vertices": [
{
"x": 330,
"y": 20
},
{
"x": 410,
"y": 100
},
{
"x": 430,
"y": 100
},
{
"x": 430,
"y": 20
}
],
"strokeColor": "#999999",
"fillColor": "#CCCCCC"
},
{
"vertices": [
{
"x": 410,
"y": 100
},
{
"x": 410,
"y": 160
},
{
"x": 430,
"y": 160
},
{
"x": 430,
"y": 100
}
],
"strokeColor": "#999999",
"fillColor": "#CCCCCC"
},
{
"vertices": [
{
"x": 410,
"y": 160
},
{
"x": 330,
"y": 240
},
{
"x": 330,
"y": 260
},
{
"x": 430,
"y": 260
},
{
"x": 430,
"y": 160
}
],
"strokeColor": "#999999",
"fillColor": "#CCCCCC"
},
{
"vertices": [
{
"x": 330,
"y": 240
},
{
"x": 130,
"y": 240
},
{
"x": 130,
"y": 260
},
{
"x": 330,
"y": 260
}
],
"strokeColor": "#999999",
"fillColor": "#CCCCCC"
},
{
"vertices": [
{
"x": 300,
"y": 120
},
{
"x": 300,
"y": 140
},
{
"x": 20,
"y": 140
},
{
"x": 20,
"y": 120
}
],
"strokeColor": "#999999",
"fillColor": "#CCCCCC"
},
{
"vertices": [
{
"x": 20,
"y": 140
},
{
"x": 90,
"y": 140
},
{
"x": 20,
"y": 210
}
],
"strokeColor": "#999999",
"fillColor": "#CCCCCC"
},
{
"vertices": [
{
"x": 130,
"y": 260
},
{
"x": 130,
"y": 480
},
{
"x": 150,
"y": 480
},
{
"x": 150,
"y": 260
}
],
"strokeColor": "#999999",
"fillColor": "#CCCCCC"
},
{
"vertices": [
{
"x": 20,
"y": 530
},
{
"x": 90,
"y": 600
},
{
"x": 20,
"y": 600
}
],
"strokeColor": "#999999",
"fillColor": "#CCCCCC"
},
{
"vertices": [
{
"x": 260,
"y": 600
},
{
"x": 260,
"y": 370
},
{
"x": 280,
"y": 370
},
{
"x": 280,
"y": 600
}
],
"strokeColor": "#999999",
"fillColor": "#CCCCCC"
},
{
"vertices": [
{
"x": 150,
"y": 350
},
{
"x": 240,
"y": 260
},
{
"x": 150,
"y": 260
}
],
"strokeColor": "#999999",
"fillColor": "#CCCCCC"
},
{
"vertices": [
{
"x": 280,
"y": 370
},
{
"x": 430,
"y": 370
},
{
"x": 430,
"y": 390
},
{
"x": 280,
"y": 390
}
],
"strokeColor": "#999999",
"fillColor": "#CCCCCC"
},
{
"vertices": [
{
"x": 430,
"y": 260
},
{
"x": 430,
"y": 370
},
{
"x": 410,
"y": 370
},
{
"x": 410,
"y": 260
}
],
"strokeColor": "#999999",
"fillColor": "#CCCCCC"
},
{
"vertices": [
{
"x": 170,
"y": 600
},
{
"x": 260,
"y": 510
},
{
"x": 260,
"y": 600
}
],
"strokeColor": "#999999",
"fillColor": "#CCCCCC"
}

View File

@ -1,39 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Level Editor with Absolute Vertices and Level Load</title>
<style>
canvas {
border: 1px solid black;
cursor: crosshair;
}
body {
font-family: sans-serif;
margin: 20px;
}
</style>
</head>
<body>
<h2>Level Editor</h2>
<label>Level Name: <input type="text" id="levelName" value="Level 1" /></label><br /><br />
<label>Mode:
<select id="drawMode">
<option value="waypoints">Waypoint</option>
<option value="obstacles">Obstacle</option>
</select>
</label><br /><br />
<!-- Load Level UI -->
<label>Load Level:
<select id="levelSelect"><option>Loading...</option></select>
<button id="loadLevelBtn">Load</button>
</label><br /><br />
<canvas id="canvas" width="1000" height="640"></canvas><br />
<button id="saveJSON">Download JSON</button>
<script src="editor.js" defer></script>
</body>
</html>

279
editor.js
View File

@ -1,279 +0,0 @@
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const gridSize = 10;
let currentPolygon = [];
let shapes = {
robots: {
player: { position: { x: 200, y: 200 } }
},
waypoints: [],
obstacles: []
};
let view = {
zoom: 1,
offsetX: 0,
offsetY: 0
};
let loadedLevels = []; // store loaded levels here
// Coordinate conversions
function worldToScreen(x, y) {
return {
x: (x - view.offsetX) * view.zoom,
y: (y - view.offsetY) * view.zoom
};
}
function screenToWorld(x, y) {
return {
x: x / view.zoom + view.offsetX,
y: y / view.zoom + view.offsetY
};
}
// Draw grid
function drawGrid() {
const step = gridSize;
const bounds = {
left: view.offsetX,
right: view.offsetX + canvas.width / view.zoom,
top: view.offsetY,
bottom: view.offsetY + canvas.height / view.zoom
};
ctx.strokeStyle = "#eee";
ctx.lineWidth = 1;
ctx.beginPath();
for (let x = Math.floor(bounds.left / step) * step; x < bounds.right; x += step) {
const sx = worldToScreen(x, 0).x;
ctx.moveTo(sx, 0);
ctx.lineTo(sx, canvas.height);
}
for (let y = Math.floor(bounds.top / step) * step; y < bounds.bottom; y += step) {
const sy = worldToScreen(0, y).y;
ctx.moveTo(0, sy);
ctx.lineTo(canvas.width, sy);
}
ctx.stroke();
}
// Draw a circle (for vertices)
function drawCircle(x, y, radius = 4) {
const screen = worldToScreen(x, y);
ctx.beginPath();
ctx.arc(screen.x, screen.y, radius, 0, Math.PI * 2);
ctx.fill();
}
// Draw polygon from absolute vertices
function drawPolygon(vertices, stroke = "#000", fill = "#ccc") {
if (vertices.length === 0) return;
ctx.beginPath();
const first = worldToScreen(vertices[0].x, vertices[0].y);
ctx.moveTo(first.x, first.y);
for (let i = 1; i < vertices.length; i++) {
const p = worldToScreen(vertices[i].x, vertices[i].y);
ctx.lineTo(p.x, p.y);
}
ctx.closePath();
ctx.fillStyle = fill;
ctx.fill();
ctx.strokeStyle = stroke;
ctx.stroke();
}
// Redraw entire canvas
function redrawAll() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawGrid();
for (let w of shapes.waypoints) {
drawPolygon(w.vertices, w.strokeColor, w.fillColor);
}
for (let o of shapes.obstacles) {
drawPolygon(o.vertices, o.strokeColor, o.fillColor);
}
if (currentPolygon.length > 0) {
ctx.strokeStyle = "#000";
ctx.fillStyle = "black";
for (let p of currentPolygon) {
drawCircle(p.x, p.y);
}
ctx.beginPath();
const start = worldToScreen(currentPolygon[0].x, currentPolygon[0].y);
ctx.moveTo(start.x, start.y);
for (let i = 1; i < currentPolygon.length; i++) {
const p = worldToScreen(currentPolygon[i].x, currentPolygon[i].y);
ctx.lineTo(p.x, p.y);
}
ctx.stroke();
}
}
// Snap to grid if ctrl pressed
function snapToGrid(x, y) {
return {
x: Math.round(x / gridSize) * gridSize,
y: Math.round(y / gridSize) * gridSize
};
}
// Canvas click event to add vertices
canvas.addEventListener("click", (e) => {
const rect = canvas.getBoundingClientRect();
let sx = e.clientX - rect.left;
let sy = e.clientY - rect.top;
let { x, y } = screenToWorld(sx, sy);
if (e.ctrlKey) {
({ x, y } = snapToGrid(x, y));
}
if (currentPolygon.length > 0) {
const dx = x - currentPolygon[0].x;
const dy = y - currentPolygon[0].y;
if (Math.sqrt(dx * dx + dy * dy) < 10 / view.zoom) {
finishPolygon();
return;
}
}
currentPolygon.push({ x, y });
redrawAll();
});
// Finish polygon and add to shapes
function finishPolygon() {
if (currentPolygon.length < 3) return;
const type = document.getElementById("drawMode").value;
const shape = {
vertices: [...currentPolygon],
strokeColor: type === "waypoints" ? "#0000FF" : "#999999",
fillColor: type === "waypoints" ? "#0000CC" : "#CCCCCC"
};
shapes[type].push(shape);
currentPolygon = [];
redrawAll();
}
//document.getElementById("finishPolygon").addEventListener("click", finishPolygon);
// Save JSON to file
document.getElementById("saveJSON").addEventListener("click", () => {
const levelName = document.getElementById("levelName").value;
const exportData = [{
name: levelName,
...shapes
}];
const blob = new Blob([JSON.stringify(exportData, null, 4)], { type: "application/json" });
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = levelName.replace(/\s+/g, "_") + ".json";
a.click();
});
// Zoom with mouse wheel, zoom toward cursor
canvas.addEventListener("wheel", (e) => {
e.preventDefault();
const delta = -e.deltaY;
const zoomFactor = 1.1;
const mouse = screenToWorld(e.offsetX, e.offsetY);
if (delta > 0) {
view.zoom *= zoomFactor;
} else {
view.zoom /= zoomFactor;
}
view.offsetX = mouse.x - (e.offsetX / view.zoom);
view.offsetY = mouse.y - (e.offsetY / view.zoom);
redrawAll();
}, { passive: false });
// Undo with Ctrl+Z
document.addEventListener("keydown", (e) => {
if (e.ctrlKey && e.key === "z") {
if (currentPolygon.length > 0) {
currentPolygon.pop();
} else {
const type = document.getElementById("drawMode").value;
if (shapes[type].length > 0) {
shapes[type].pop();
}
}
redrawAll();
}
});
// --------- NEW: Load Levels from data/levels.json ---------
async function loadLevels() {
try {
const response = await fetch('data/levels.json');
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
loadedLevels = await response.json();
const levelSelect = document.getElementById('levelSelect');
levelSelect.innerHTML = ''; // Clear loading message
loadedLevels.forEach((level, idx) => {
const option = document.createElement('option');
option.value = idx;
option.textContent = level.name || `Level ${idx + 1}`;
levelSelect.appendChild(option);
});
} catch (err) {
alert('Failed to load levels.json: ' + err.message);
const levelSelect = document.getElementById('levelSelect');
levelSelect.innerHTML = '<option>Error loading levels</option>';
}
}
function loadSelectedLevel() {
const levelSelect = document.getElementById('levelSelect');
const idx = parseInt(levelSelect.value);
if (isNaN(idx) || !loadedLevels[idx]) {
alert('Please select a valid level');
return;
}
const level = loadedLevels[idx];
document.getElementById('levelName').value = level.name || '';
if (level.robots && level.robots.player && level.robots.player.position) {
shapes.robots.player.position = { ...level.robots.player.position };
} else {
shapes.robots.player.position = { x: 200, y: 200 };
}
shapes.waypoints = (level.waypoints || []).map(wp => ({
vertices: wp.vertices.map(v => ({ x: v.x, y: v.y })),
strokeColor: wp.strokeColor || "#0000FF",
fillColor: wp.fillColor || "#0000CC"
}));
shapes.obstacles = (level.obstacles || []).map(ob => ({
vertices: ob.vertices.map(v => ({ x: v.x, y: v.y })),
strokeColor: ob.strokeColor || "#999999",
fillColor: ob.fillColor || "#CCCCCC"
}));
currentPolygon = [];
redrawAll();
}
document.getElementById('loadLevelBtn').addEventListener('click', loadSelectedLevel);
// Load levels.json on page load
loadLevels();
// Initial draw
redrawAll();

240
game.js
View File

@ -2,11 +2,8 @@ import { Robot } from "./robot.js";
import { GameWorld } from "./gameworld.js";
import { lessons } from './data/lessons.js';
let mostRecentCode = ""; // The users code
let codeRanGood = false; // Your own function that returns true/false
let consoleText = ""; // What was printed
let currentLesson = 0;
let lessonComplete = false;
async function loadLessons() {
const response = await fetch('data/lessons.json');
@ -16,76 +13,19 @@ async function loadLessons() {
function showLesson(index) {
if (index < 0 || index >= lessons.length) return;
lessonComplete = false;
currentLesson = index;
const lesson = lessons[index];
loadLessonContent(lesson);
updateTabs(lessons, index);
if (lesson.map) {
console.log("Loading map for lesson:", lesson.map);
document.getElementById('gameCanvas').style.display = 'block';
for (let i = 0; i < gameWorld.levelData.length; i++) {
if (gameWorld.levelData[i].name === lesson.map) {
gameWorld.currentLevel = i;
console.log("Setting current level to:", i);
break;
}
}
resetGameWorld();
} else {
document.getElementById('gameCanvas').style.display = 'none';
}
document.getElementById('lesson-title').textContent = lesson.title;
document.getElementById('lesson-content').innerHTML = lesson.content;
document.getElementById('prev-lesson').disabled = index === 0;
document.getElementById('next-lesson').disabled = index === lessons.length - 1;
//console.log(isLessonDone(lesson.id));
console.log(isLessonDone(lesson.id));
updateLessonStatus();
PopulateObjectives(lesson.objectives); // Populate objectives for the lesson
}
function loadLessonContent(lesson) {
document.getElementById('lesson-title').textContent = lesson.title;
document.getElementById('lesson-content').innerHTML = lesson.content;
}
function updateTabs(lessons, currentIndex) {
let select = document.getElementById('lesson-select');
let select_robot = document.getElementById('robot-select');
select.innerHTML = ''; // Clear old options
select_robot.innerHTML = ''; // Clear old options
lessons.forEach((lesson, index) => {
const option = document.createElement('option');
option.value = index;
option.textContent = lesson.title || `Lesson ${index + 1}`;
if (lesson.level == "basics") {
select.appendChild(option);
} else {
select_robot.appendChild(option);
}
});
// Set current selected lesson
select.value = currentIndex;
select_robot.value = currentIndex;
// Handle user selection
select.addEventListener('change', () => {
const selectedIndex = Number(select.value);
console.log("Selected lesson index:", selectedIndex);
showLesson(selectedIndex);
});
select_robot.addEventListener('change', () => {
const selectedIndex = Number(select_robot.value);
console.log("Selected lesson index:", selectedIndex);
showLesson(selectedIndex);
});
}
document.getElementById('prev-lesson').addEventListener('click', () => {
showLesson(currentLesson - 1);
});
@ -93,55 +33,20 @@ document.getElementById('next-lesson').addEventListener('click', () => {
showLesson(currentLesson + 1);
});
function checkLessonDone() {
//consoleText = outputText; // Update console text
if (consoleText.includes("Error") || consoleText.includes("Exception") || consoleText.includes("PythonError")) {
console.log(consoleText);
codeRanGood = false;
} else {
codeRanGood = true;
}
console.log("codeRanGood ", codeRanGood);
function checkLessonDone(outputText) {
//checkCurrentStep(outputText);
const lesson = lessons[currentLesson];
const result = lesson.doneCondition({
code: mostRecentCode,
consoleText: consoleText,
codeRanGood: codeRanGood,
gameWorld: gameWorld
});
console.log(gameWorld.waypointsReached);
if (result.done) {
if (lesson.doneCondition && lesson.doneCondition(outputText)) {
markLessonDone(lesson.id);
}
console.log(result);
//if (result.progressArray) {
console.log("Progress: ", result.progressArray);
for (let i = 0; i < result.progressArray.length; i++) {
const objective = result.progressArray[i];
if (objective) {
toggleObjective(i, true); // Mark as completed
} else {
toggleObjective(i, false); // Mark as not completed
}
}
//}
if (result.hint) {
logToConsole("Hint: " + result.hint, false);
//console.log("Hint:", result.hint); // Or show it in your console UI
}
}
function markLessonDone(lessonId) {
if (lessonComplete) return; // Prevent marking multiple times
lessonComplete = true; // Set flag to prevent further marking
// Your logic here: e.g., store in localStorage or update UI
console.log(`Lesson ${lessonId} marked as done!`);
// For example:
localStorage.setItem(`lessonDone_${lessonId}`, 'true');
logToConsole("✅ Task Completed! ✅", false);
logToConsole("✅ Task Completed! ✅");
updateLessonStatus();
}
@ -163,31 +68,6 @@ function isLessonDone(lessonId) {
return localStorage.getItem(`lessonDone_${lessonId}`) === 'true';
}
let currentStepIndex = 0;
function checkCurrentStep(text) {
const lesson = lessons[currentLesson];
const step = lesson.steps[currentStepIndex];
const result = step.doneCondition(text);
if (result) {
currentStepIndex++;
renderSteps(); // Re-render to show the new step
}
}
function renderSteps() {
const lesson = lessons[currentLesson];
const container = document.getElementById("lesson-content");
container.innerHTML = "";
loadLessonContent(lesson); // Load the lesson content first
for (let i = 0; i <= currentStepIndex && i < lesson.steps.length; i++) {
const stepEl = document.createElement("div");
stepEl.innerHTML = lesson.steps[i].content;
container.appendChild(stepEl);
}
}
function clearLessonProgress() {
Object.keys(localStorage).forEach(key => {
if (key.startsWith('lessonDone_')) {
@ -199,47 +79,8 @@ function clearLessonProgress() {
}
let objectiveElements = []; // store checkbox + item div
const listContainer = document.getElementById("objectives-list");
function PopulateObjectives(objectives) {
listContainer.innerHTML = ""; // Clear the DOM
objectiveElements.length = 0; // Clear the stored references
objectives.forEach((text, index) => {
const item = document.createElement("div");
item.className = "objective";
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.id = "obj-" + index;
checkbox.disabled = true; // make it non-interactive
const label = document.createElement("label");
label.htmlFor = checkbox.id;
label.textContent = text;
item.appendChild(checkbox);
item.appendChild(label);
listContainer.appendChild(item);
objectiveElements.push({ checkbox, item }); // Store reference
});
}
function toggleObjective(index, completed = true) {
const obj = objectiveElements[index];
if (obj) {
obj.checkbox.checked = completed;
obj.item.classList.toggle("completed", completed);
}
}
//clearLessonProgress(); // Clear progress on load for testing
showLesson(0);
const consoleElement = document.getElementById("console");
const gameCanvas = document.getElementById("gameCanvas");
@ -272,7 +113,6 @@ function startPyodideWorker() {
switch (event.data.type) {
case "console":
logToConsole(event.data.data);
break;
case "error":
logToConsole(`<span style="color:red;">${event.data.message}</span>`);
@ -286,11 +126,6 @@ function startPyodideWorker() {
case "move":
move(event.data.data);
break;
case "execution_done":
console.log("Execution done");
document.getElementById('compile-button').disabled = false;
checkLessonDone();
break;
}
};
@ -310,10 +145,10 @@ function createInitialRobots() {
const maxLines = 64;
const logLines = [];
function logToConsole(text, checkLesson = true) {
function logToConsole(text) {
if (text.includes("Pyodide not initialized yet.")) return;
checkLessonDone(text);
const newLines = text.split('\n').map(line => line.trim()).filter(line => line !== "");
@ -331,30 +166,18 @@ function logToConsole(text, checkLesson = true) {
// Create and append separate divs for each line
logLines.forEach(lineText => {
const lineDiv = document.createElement('div');
lineDiv.innerHTML = lineText; // <-- render HTML tags here
lineDiv.style.maxWidth = "100%";
lineDiv.style.whiteSpace = "pre-wrap";
lineDiv.style.overflowWrap = "break-word";
lineDiv.style.wordWrap = "break-word";
lineDiv.textContent = lineText;
consoleElement.appendChild(lineDiv);
});
// Scroll to bottom
consoleElement.scrollTop = consoleElement.scrollHeight;
if (checkLesson && !text.includes("Welcome")) { // Don't check lesson completion for welcome message
consoleText = text; // Update console text
//checkLessonDone(text);
}
}
function clearConsole() {
logLines.length = 0; // Empty the logLines array
consoleElement.innerHTML = ""; // Clear the console DOM element
consoleText = "";
}
// ✅ Game Control Functions
@ -376,12 +199,6 @@ function togglePause() {
document.getElementById("pause-button").innerText = paused ? "Resume" : "Pause";
}
function resetGameWorld() {
robots = createInitialRobots();
gameWorld.reset(robots["player"]);
pyodideWorker.postMessage({ type: "interrupt" });
}
// ✅ Reset Function (Fixed)
function resetGame() {
// Terminate the worker
@ -404,8 +221,6 @@ function resetGame() {
document.getElementById("pause-button").innerText = "Pause";
logToConsole("Welcome to the game! Type your Python code in the editor and click 'Compile' to execute it.");
document.getElementById('compile-button').disabled = false;
}
const targetFPS = 30;
@ -429,18 +244,12 @@ function gameLoop(timestamp) {
gameWorld.update();
gameWorld.draw(ctx);
if (gameWorld.waypointsReachedChanged()) {
console.log("Waypoints reached:", gameWorld.waypointsReached);
checkLessonDone();
if (gameWorld.checkPlayerCompletedTask()) {
logToConsole("✅ Task Completed! ✅");
togglePause();
gameWorld.currentLevel++;
}
// if (gameWorld.checkPlayerCompletedTask()) {
// logToConsole("✅ Task Completed! ✅");
// togglePause();
// gameWorld.currentLevel++;
// }
pyodideWorker.postMessage({
type: "game_state",
state: gameWorld
@ -470,29 +279,18 @@ function updateSensorData() {
document.getElementById("compile-button").addEventListener("click", () => {
if (paused) return;
document.getElementById('compile-button').disabled = true;
clearConsole();
resetGameWorld();
// Use the Monaco Editor instance to get the code
let code = monacoEditor.getValue(); // Get text from the editor
//console.log(code);
console.log(code);
code = code.replace(/time\.sleep\(/g, "await time.sleep(");
code = code.replace(
/^([ \t]*)while True:\s*$/gm,
(_, indent) => `${indent}while True:\n${indent} await time.sleep(0.0001)`
);
console.log(code);
consoleElement.innerHTML = "";
pyodideWorker.postMessage({
type: "execute",
code: code
});
mostRecentCode = code;
logToConsole("Compiling your code...", false);
});
@ -590,18 +388,16 @@ function setupCanvas() {
}
// Call this function when the page loads
fetch('/data/levels.json')
.then(response => response.json())
.then(data => {
gameWorld.levelData = data;
setupCanvas();
resetGame(); // Initialize the game and robots
// Start game loop
gameLoop();
showLesson(0);
});

View File

@ -14,8 +14,6 @@ export class GameWorld {
this.currentLevel = 0;
this.waypoints = [];
this.prevWaypointsReached = [];
this.waypointsReached = [];
this.obstacles = [];
this.robots = [];
@ -30,8 +28,6 @@ export class GameWorld {
this.robots = []
this.obstacles = []
this.waypoints = [];
this.waypointsReached = [];
this.prevWaypointsReached = [];
Matter.World.clear(this.world); // Clear the world without resetting the engine
let level = this.levelData[this.currentLevel];
@ -55,10 +51,7 @@ export class GameWorld {
let obstacle = level.waypoints[i];
console.log("Adding waypoint:", obstacle);
this.addWaypoint(obstacle.vertices, obstacle.position, obstacle.strokeColor, obstacle.fillColor);
this.waypointsReached.push(false); // Initialize as not reached
}
this.prevWaypointsReached = [...this.waypointsReached];
console.log(level.waypointsReached)
// this.addObstacle([
// { x: -100, y: -100 }, // Vertex 1
@ -84,19 +77,7 @@ export class GameWorld {
this.robots[id].update(this);
}
for (let i = 0; i < this.waypoints.length; i++) {
if (this.waypointsReached[i]) {
} else {
let waypoint = this.waypoints[i];
let playerPos = this.robots[0].body.position;
let waypointBounds = waypoint.bounds;
if (Matter.Bounds.contains(waypointBounds, playerPos)) {
console.log("Player is inside the waypoint's bounding box.");
this.waypointsReached[i] = true; // Mark this waypoint as reached
}
}
}
//this.checkPlayerCompletedTask();
@ -105,131 +86,44 @@ export class GameWorld {
}
waypointsReached() {
return this.waypointsReached;
}
waypointsReachedChanged() {
// Check if waypointsReached has changed since the last update
let changed = false;
for (let i = 0; i < this.waypointsReached.length; i++) {
if (this.waypointsReached[i] !== this.prevWaypointsReached[i]) {
changed = true;
break;
}
}
// Update prevWaypointsReached to the current state
this.prevWaypointsReached = [...this.waypointsReached];
return changed;
}
// Needs to be updated to handle different win conditions
// checkPlayerCompletedTask() {
// let playerPos = this.robots[0].body.position;
// let waypointBounds = this.waypoints[0].bounds;
// if (Matter.Bounds.contains(waypointBounds, playerPos)) {
// console.log("Player is inside the waypoint's bounding box.");
// return true;
// }
// return false;
// }
checkPlayerCompletedTask() {
let playerPos = this.robots[0].body.position;
let waypointBounds = this.waypoints[0].bounds;
if (Matter.Bounds.contains(waypointBounds, playerPos)) {
console.log("Player is inside the waypoint's bounding box.");
return true;
}
return false;
}
addWaypoint(vertices, position = { x: 0, y: 0 }, strokeColor = "yellow", fillColor = "yellow") {
// Convert the polygon points into a Matter.js body
const sortedVertices = Matter.Vertices.clockwiseSort(vertices);
// Compute centroid
const centroid = this.getCentroid(sortedVertices);
// Create relative vertices centered around centroid
const relativeVertices = sortedVertices.map(v => ({
x: v.x - centroid.x,
y: v.y - centroid.y
}));
const body = Matter.Bodies.fromVertices(
centroid.x,
centroid.y,
[relativeVertices],
{
let body = Matter.Bodies.fromVertices(position.x, position.y, [vertices], {
isSensor: true,
isStatic: true,
label: "zone",
},
true
);
body.strokeColor = 'rgba(0, 0, 255, 0.1)';
body.fillColor = 'rgba(0, 0, 255, 0.1)';
label: "zone"
});
body.strokeColor = strokeColor;
body.fillColor = fillColor;
// Add body to world and store it
Matter.World.add(this.world, body);
this.waypoints.push(body);
}
getCentroid(vertices) {
let area = 0, cx = 0, cy = 0;
for (let i = 0; i < vertices.length; i++) {
const p1 = vertices[i];
const p2 = vertices[(i + 1) % vertices.length];
const cross = p1.x * p2.y - p2.x * p1.y;
area += cross;
cx += (p1.x + p2.x) * cross;
cy += (p1.y + p2.y) * cross;
}
area *= 0.5;
if (area === 0) return vertices[0]; // fallback to first point
cx /= (6 * area);
cy /= (6 * area);
return { x: cx, y: cy };
}
addObstacle(vertices, strokeColor = "black", fillColor = "gray") {
// Sort vertices clockwise (Matter requires this)
const sortedVertices = Matter.Vertices.clockwiseSort(vertices);
// Compute centroid
const centroid = this.getCentroid(sortedVertices);
// Create relative vertices centered around centroid
const relativeVertices = sortedVertices.map(v => ({
x: v.x - centroid.x,
y: v.y - centroid.y
}));
// Create the body with options to reduce auto corrections
const body = Matter.Bodies.fromVertices(
centroid.x,
centroid.y,
[relativeVertices],
{
isStatic: true,
// If your Matter.js supports these:
// removeCollinear: 0.01,
// minimumArea: 10
},
true // autoHull (convex decomposition) enabled
);
addObstacle(vertices, position = { x: 0, y: 0 }, strokeColor = "black", fillColor = "gray") {
// Convert the polygon points into a Matter.js body
let body = Matter.Bodies.fromVertices(position.x, position.y, [vertices], {
isStatic: true, // Obstacles shouldn't move
});
body.strokeColor = strokeColor;
body.fillColor = fillColor;
// Add body to world and store it
Matter.World.add(this.world, body);
this.obstacles.push(body);
}
addRobot(robot) {
console.log("added robot");
// Create the robot's Matter.js body
@ -273,29 +167,22 @@ export class GameWorld {
});
// Draw Waypoints
for (let w = 0; w < this.waypoints.length; w++) {
let body = this.waypoints[w];
this.waypoints.forEach(body => {
ctx.beginPath();
let vertices = body.vertices;
ctx.moveTo(vertices[0].x, vertices[0].y);
for (let i = 1; i < vertices.length; i++) {
ctx.lineTo(vertices[i].x, vertices[i].y);
}
ctx.fillStyle = body.fillColor;;
if (this.waypointsReached[w]) {
ctx.globalAlpha = 0.05; // Applies to all drawing
ctx.fillStyle = "green"; // Color for reached waypoints
ctx.strokeStyle = "rgba(0, 128, 0, 0.2)"; // green with 80% opacity
} else {
ctx.globalAlpha = 0.2; // Applies to all drawing
ctx.fillStyle = body.fillColor; // Default color for waypoints
ctx.strokeStyle = body.strokeColor;
}
ctx.closePath();
ctx.globalAlpha = 0.2; // Applies to all drawing
ctx.fill();
ctx.globalAlpha = 1.0; // Reset after if needed
ctx.stroke();
}
});
this.robots.forEach(robot => {
let body = robot.body; // Get the Matter.js body from the robot object

View File

@ -25,31 +25,9 @@
</div>
</header>
<!-- New Lesson Box / Instructions Area -->
<section id="lesson-box">
<div class="dropdown-row content-width">
<div class="dropdown-group">
<div class="dropdown-title">Basics</div>
<select id="lesson-select"></select>
</div>
<div class="dropdown-group">
<div class="dropdown-title">Robot</div>
<select id="robot-select"></select>
</div>
<div class="dropdown-group">
<div class="dropdown-title">Challenges</div>
<select id="challenge-select"></select>
</div>
</div>
<div class="content-width" style="display: flex; gap: 20px; align-items: flex-start;">
<!-- 📘 Lesson content area (3/4 width) -->
<div style="flex: 3;">
<div class="content-width">
<h2 id="lesson-title">Lesson Title</h2>
<p id="lesson-content">Lesson Content</p>
@ -62,18 +40,9 @@
<button id="next-lesson">Next →</button>
</div>
</div>
<!-- ✅ Objectives (1/4 width) -->
<aside style="flex: 1;">
<h2>Objectives</h2>
<div id="objectives-list">
<!-- Populated via JavaScript -->
</div>
</aside>
</div>
</section>
<!-- Main Content -->
<main>
<div class="container">

View File

@ -1,15 +1,12 @@
importScripts("https://cdn.jsdelivr.net/pyodide/v0.27.7/full/pyodide.js");
importScripts("https://cdn.jsdelivr.net/pyodide/v0.23.4/full/pyodide.js");
let sensorData = {}; // ✅ Store sensor values
let gameWorld = null;
async function initializePyodide() {
self.pyodide = await loadPyodide({
indexURL: "https://cdn.jsdelivr.net/pyodide/v0.27.7/full/"
indexURL: "https://cdn.jsdelivr.net/pyodide/v0.23.4/full/"
});
console.log("Pyodide loaded:", self.pyodide.version);
self.pyodide.globals.set("send_to_main", (event, data) => {
self.postMessage({ type: event, data: data });
@ -19,7 +16,7 @@ async function initializePyodide() {
// ✅ Expose sensor data to Python
self.pyodide.globals.set("get_sensor_data", (name) => {
if (gameWorld == null) {
if (gameWorld == null){
return null;
}
@ -31,7 +28,7 @@ async function initializePyodide() {
sensorData = sensorArray.map(sensor => ({
"type": sensor.type, // Individual sensor's type
"angle": sensor.angle, // Individual sensor's angle
"distance": Math.round(sensor.distance * 100) / 100, // Individual sensor's distance
"distance": sensor.distance, // Individual sensor's distance
"hitpoint": sensor.hitpoint // Whatever other attributes you need
}));
//console.log(sensorData["x"]);
@ -41,7 +38,7 @@ async function initializePyodide() {
self.pyodide.globals.set("get_robot_data", () => {
if (gameWorld == null) {
if (gameWorld == null){
return null;
}
let robot = gameWorld.robots[0];
@ -69,12 +66,6 @@ class RobotModule:
sensor_data = json.loads(get_sensor_data(name))
return sensor_data
def get_distance_left(self):
return self.get_sensors()[0]["distance"]
def get_distance_right(self):
return self.get_sensors()[1]["distance"]
def get_sensors(self):
return json.loads(get_sensor_data("sensors")) # Returns list of sensor dicts
@ -107,22 +98,12 @@ class RobotModule:
return magnitude
def move(self, speed):
if speed < -1:
speed = -1
elif speed > 1:
speed = 1
speed = speed/5000
send_to_main("move", speed)
def fire(self):
send_to_main("fire", None)
def turn(self, deg):
if deg < -1:
deg = -1
elif deg > 1:
deg = 1
deg = deg/150
send_to_main("turn", deg)
robot = RobotModule()
@ -148,8 +129,6 @@ async def async_sleep(seconds):
time.sleep = async_sleep # Monkey-patch time.sleep()
`);
self.postMessage({ type: "ready" }); // ✅ Notify main thread that Pyodide is ready
@ -157,11 +136,6 @@ time.sleep = async_sleep # ✅ Monkey-patch time.sleep()
initializePyodide();
// Add this function to trigger interrupts
function interruptExecution() {
interruptBuffer[0] = 2; // 2 is the magic number for KeyboardInterrupt
}
self.onmessage = async (event) => {
if (!self.pyodide) {
self.postMessage({ type: "error", message: "Pyodide not initialized yet." });
@ -184,6 +158,5 @@ self.onmessage = async (event) => {
} catch (error) {
self.postMessage({ type: "error", message: error.toString() });
}
self.postMessage({ type: "execution_done" });
}
};

View File

@ -30,53 +30,3 @@ while True:
else:
robot.turn(0)
time.sleep(0.1)
#Robot 1
import time
import robot
robot.move(1)
time.sleep(1.6)
robot.move(0)
robot.turn(1)
time.sleep(2.2)
robot.turn(0)
robot.move(1)
#Robot 2
import robot
import time
robot.move(1)
time.sleep(0.8)
robot.move(0.4)
robot.turn(1)
time.sleep(4.7)
robot.move(0)
robot.turn(0)
#Robot 3
import time
import robot
robot.move(1)
while True:
if robot.get_distance_left() < 58:
robot.turn(1)
robot.move(0.2)
elif robot.get_distance_right() < 58:
robot.turn(-1)
robot.move(0.2)
else:
robot.move(1)
robot.turn(0)
time.sleep(0.01)

114
style.css
View File

@ -9,38 +9,16 @@ html {
padding: 0;
height: 100%;
font-family: Arial, sans-serif;
background-color: #ffffff;
background-color: #fff;
display: flex;
flex-direction: column;
}
.objective {
margin: 10px 0;
display: flex;
align-items: center;
}
.objective label {
margin-left: 8px;
transition: color 0.3s;
}
.completed label {
color: green;
font-weight: bold;
text-decoration: line-through;
}
input[type="checkbox"] {
pointer-events: none; /* make it non-clickable */
}
/* ===== Header (top bar) ===== */
header {
background-color: #ffffff;
background-color: #f3f4f6;
/* light gray */
padding: 16px 0;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
@ -72,16 +50,6 @@ header p {
/* gray-600 */
}
code, pre {
font-family: Consolas, Menlo, Monaco, "Courier New", monospace;
background-color: inherit;
color: blue;
border: none;
padding: 0;
margin: 0;
}
.button-group {
display: flex;
gap: 12px;
@ -108,10 +76,6 @@ button {
background-color: #1d4ed8;
/* blue-700 */
}
#compile-button:disabled {
background-color: #bbbbbb;
/* blue-700 */
}
#pause-button {
background-color: #eab308;
@ -197,48 +161,6 @@ main {
}
.dropdown-row {
display: flex;
gap: 20px;
padding: 12px 0;
}
.dropdown-group {
flex: 1; /* Equal horizontal space */
display: flex;
flex-direction: column;
}
.dropdown-title {
font-weight: 600;
margin-bottom: 4px;
font-size: 14px;
color: #333;
}
.dropdown-group select {
width: 100%;
padding: 4px 8px;
font-size: 14px;
border-radius: 4px;
border: 1px solid #aaa;
background-color: white;
color: #333;
}
#lesson-box {
background: white;
border: 1px solid #ffffff;
border-top: none;
border-radius: 0 0 8px 8px;
padding-top: 0; /* prevents double padding below tabs */
margin-top: -1px; /* overlap the active tab */
}
/* Monaco editor - left half */
#monaco-editor {
@ -283,32 +205,16 @@ main {
font-size: 14px;
}
.container,
.right-side,
#console,
#console > div {
min-width: 0;
}
#console {
flex: 1;
overflow-y: auto;
white-space: pre-wrap;
overflow-wrap: break-word;
word-wrap: break-word;
border: 1px solid #d1d5db;
background: black;
color: white;
font-family: monospace;
font-family: monospace, monospace;
padding: 8px;
box-sizing: border-box;
}
#console > div {
max-width: 100%;
box-sizing: border-box;
overflow-wrap: break-word;
word-wrap: break-word;
white-space: pre-wrap;
overflow-y: auto;
border: 1px solid #d1d5db;
width: 100%;
}
/* alternate line colors */
@ -335,7 +241,7 @@ main {
}
#lesson-box {
background: #ffffff;
background: #f9f9f9;
padding: 8px 16px;
border-bottom: 1px solid #ddd;
font-family: sans-serif;
@ -359,9 +265,9 @@ main {
}
/* #lesson-box code {
#lesson-box code {
background: #eee;
padding: 2px 4px;
border-radius: 4px;
font-family: monospace;
} */
}