new, minimalist layout

master
Jake 2025-06-24 13:21:04 +08:00
parent 2dfdbab898
commit 92b2b12f92
8 changed files with 563 additions and 82 deletions

View File

@ -9,6 +9,34 @@
} }
} }
}, },
"waypoints": [
{
"position": {
"x": 420,
"y": 200
},
"vertices": [
{
"x": -50,
"y": -50
},
{
"x": 50,
"y": -50
},
{
"x": 50,
"y": 50
},
{
"x": -50,
"y": 50
}
],
"strokeColor": "#0000FF",
"fillColor": "#0000CC"
}
],
"obstacles": [ "obstacles": [
{ {
"vertices": [ "vertices": [
@ -30,7 +58,7 @@
} }
], ],
"position": { "position": {
"x": 400, "x": 800,
"y": 300 "y": 300
}, },
"strokeColor": "#999999", "strokeColor": "#999999",
@ -39,26 +67,171 @@
{ {
"vertices": [ "vertices": [
{ {
"x": 300, "x": -10,
"y": 380 "y": -10
}, },
{ {
"x": 420, "x": 1010,
"y": 380 "y": -10
}, },
{ {
"x": 350, "x": 1010,
"y": 550 "y": 10
}, },
{ {
"x": 280, "x": -10,
"y": 420 "y": 10
} }
], ],
"position": { "position": {
"x": 400, "x": 500,
"y": 0
},
"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": 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": 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"
}
]
},
{
"name": "Level 2",
"robots": {
"player": {
"position": {
"x": 200,
"y": 200
}
}
},
"waypoints": [
{
"position": {
"x": 220,
"y": 500
},
"vertices": [
{
"x": -50,
"y": -50 "y": -50
}, },
{
"x": 50,
"y": -50
},
{
"x": 50,
"y": 50
},
{
"x": -50,
"y": 50
}
],
"strokeColor": "#000099",
"fillColor": "#0000CC"
}
],
"obstacles": [
{
"vertices": [
{
"x": -100,
"y": -100
},
{
"x": 100,
"y": -100
},
{
"x": 100,
"y": 100
},
{
"x": -100,
"y": 100
}
],
"position": {
"x": 200,
"y": 300
},
"strokeColor": "#999999", "strokeColor": "#999999",
"fillColor": "#CCCCCC" "fillColor": "#CCCCCC"
}, },

42
game.js
View File

@ -61,12 +61,42 @@ function createInitialRobots() {
} }
// ✅ Function to log messages to console // ✅ Function to log messages to console
const maxLines = 64;
const logLines = [];
function logToConsole(text) { function logToConsole(text) {
//console.log(text.replace("<b>", "").replace("</b>", "")); if (text.includes("Pyodide not initialized yet.")) return;
consoleElement.innerHTML += text.replace(/\n/g, "<br>") + "<br>";
const newLines = text.split('\n').map(line => line.trim()).filter(line => line !== "");
// Add new lines to the array
logLines.push(...newLines);
// Keep only the last maxLines entries
if (logLines.length > maxLines) {
logLines.splice(0, logLines.length - maxLines);
}
// Clear console
consoleElement.innerHTML = "";
// Create and append separate divs for each line
logLines.forEach(lineText => {
const lineDiv = document.createElement('div');
lineDiv.textContent = lineText;
consoleElement.appendChild(lineDiv);
});
// Scroll to bottom
consoleElement.scrollTop = consoleElement.scrollHeight; consoleElement.scrollTop = consoleElement.scrollHeight;
} }
function clearConsole() {
logLines.length = 0; // Empty the logLines array
consoleElement.innerHTML = ""; // Clear the console DOM element
}
// ✅ Game Control Functions // ✅ Game Control Functions
function fire() { function fire() {
logToConsole("<b>🔥 Gun Fired! 🔥</b>"); logToConsole("<b>🔥 Gun Fired! 🔥</b>");
@ -90,6 +120,7 @@ function togglePause() {
function resetGame() { function resetGame() {
// Terminate the worker // Terminate the worker
pyodideWorker.terminate(); pyodideWorker.terminate();
clearConsole();
// Restart the worker and rebind event listener // Restart the worker and rebind event listener
pyodideWorker = startPyodideWorker(); pyodideWorker = startPyodideWorker();
@ -105,6 +136,8 @@ function resetGame() {
// Unpause the game if it was paused // Unpause the game if it was paused
paused = false; paused = false;
document.getElementById("pause-button").innerText = "Pause"; document.getElementById("pause-button").innerText = "Pause";
logToConsole("Welcome to the game! Type your Python code in the editor and click 'Compile' to execute it.");
} }
const targetFPS = 30; const targetFPS = 30;
@ -128,6 +161,11 @@ function gameLoop(timestamp) {
gameWorld.update(); gameWorld.update();
gameWorld.draw(ctx); gameWorld.draw(ctx);
if (gameWorld.checkPlayerCompletedTask()){
logToConsole("<b>🏁 Task Completed! 🏁</b>");
togglePause();
gameWorld.currentLevel++;
}
pyodideWorker.postMessage({ pyodideWorker.postMessage({
type: "game_state", type: "game_state",

View File

@ -11,7 +11,9 @@ export class GameWorld {
let ground = Matter.Bodies.rectangle(400, 600, 800, 50, { isStatic: true }); let ground = Matter.Bodies.rectangle(400, 600, 800, 50, { isStatic: true });
Matter.World.add(this.world, ground); Matter.World.add(this.world, ground);
this.levelData = null; this.levelData = null;
this.currentLevel = 0;
this.waypoints = [];
this.obstacles = []; this.obstacles = [];
this.robots = []; this.robots = [];
@ -25,9 +27,10 @@ export class GameWorld {
reset(player = null) { reset(player = null) {
this.robots = [] this.robots = []
this.obstacles = [] this.obstacles = []
this.waypoints = [];
Matter.World.clear(this.world); // Clear the world without resetting the engine Matter.World.clear(this.world); // Clear the world without resetting the engine
let level = this.levelData[0]; let level = this.levelData[this.currentLevel];
if (player) { if (player) {
console.log("Resetting player position to:", level.robots["player"]["position"]); console.log("Resetting player position to:", level.robots["player"]["position"]);
@ -41,7 +44,13 @@ export class GameWorld {
for (let i = 0; i < level.obstacles.length; i++) { for (let i = 0; i < level.obstacles.length; i++) {
let obstacle = level.obstacles[i]; let obstacle = level.obstacles[i];
this.addObstacle(obstacle.vertices, obstacle.position); this.addObstacle(obstacle.vertices, obstacle.position, obstacle.strokeColor, obstacle.fillColor);
}
for (let i = 0; i < level.waypoints.length; i++) {
let obstacle = level.waypoints[i];
console.log("Adding waypoint:", obstacle);
this.addWaypoint(obstacle.vertices, obstacle.position, obstacle.strokeColor, obstacle.fillColor);
} }
// this.addObstacle([ // this.addObstacle([
@ -68,17 +77,48 @@ export class GameWorld {
this.robots[id].update(this); this.robots[id].update(this);
} }
//this.checkPlayerCompletedTask();
Matter.Engine.update(this.engine); Matter.Engine.update(this.engine);
} }
addObstacle(vertices, position = { x: 0, y: 0 }) { // 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;
}
addWaypoint(vertices, position = { x: 0, y: 0 }, strokeColor = "yellow", fillColor = "yellow") {
// Convert the polygon points into a Matter.js body
let body = Matter.Bodies.fromVertices(position.x, position.y, [vertices], {
isSensor: true,
isStatic: true,
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);
}
addObstacle(vertices, position = { x: 0, y: 0 }, strokeColor = "black", fillColor = "gray") {
// Convert the polygon points into a Matter.js body // Convert the polygon points into a Matter.js body
let body = Matter.Bodies.fromVertices(position.x, position.y, [vertices], { let body = Matter.Bodies.fromVertices(position.x, position.y, [vertices], {
isStatic: true, // Obstacles shouldn't move isStatic: true, // Obstacles shouldn't move
}); });
body.strokeColor = strokeColor;
body.fillColor = fillColor;
// Add body to world and store it // Add body to world and store it
Matter.World.add(this.world, body); Matter.World.add(this.world, body);
this.obstacles.push(body); this.obstacles.push(body);
@ -118,7 +158,29 @@ export class GameWorld {
for (let i = 1; i < vertices.length; i++) { for (let i = 1; i < vertices.length; i++) {
ctx.lineTo(vertices[i].x, vertices[i].y); ctx.lineTo(vertices[i].x, vertices[i].y);
} }
ctx.fillStyle = body.fillColor;;
ctx.strokeStyle = body.strokeColor;
ctx.closePath(); ctx.closePath();
ctx.fill();
ctx.stroke();
});
// Draw Waypoints
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;;
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(); ctx.stroke();
}); });
@ -145,6 +207,8 @@ export class GameWorld {
let startPoint = { x: startX, y: startY }; let startPoint = { x: startX, y: startY };
let endPoint = { x: endX, y: endY }; let endPoint = { x: endX, y: endY };
ignoreBodies.push(...this.waypoints); // Add all obstacles to the ignore list
// Get all bodies in the world // Get all bodies in the world
let allBodies = Matter.Composite.allBodies(this.engine.world); let allBodies = Matter.Composite.allBodies(this.engine.world);

View File

@ -2,81 +2,221 @@
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Pyodide Real-Time Python Execution with Console</title> <title>Learn CircuitPython</title>
<script src="https://cdn.jsdelivr.net/pyodide/v0.23.4/full/pyodide.js"></script> <script src="https://cdn.jsdelivr.net/pyodide/v0.23.4/full/pyodide.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.19.0/matter.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.19.0/matter.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/monaco-editor@0.39.0/min/vs/loader.js"></script> <script src="https://cdn.jsdelivr.net/npm/monaco-editor@0.39.0/min/vs/loader.js"></script>
<style> <style>
/* Use a grid layout for the entire page */ /* Reset & base */
body { * {
box-sizing: border-box;
}
body,
html {
margin: 0; margin: 0;
display: grid; padding: 0;
grid-template-columns: 1fr 1fr; /* Two equal columns */
grid-template-rows: auto 2fr 1fr; /* Header, main content, and console sections */
height: 100vh; /* Full viewport height */
font-family: Arial, sans-serif;
}
h1 {
grid-column: span 2; /* Header spans both columns */
text-align: center;
margin: 10px 0;
}
#monaco-editor {
grid-column: 1; /* Left column */
grid-row: 2 / span 2; /* Takes full left side */
border: 1px solid #ccc;
height: 100%; /* Fill available space */
}
#gameCanvas {
grid-column: 2; /* Right column */
grid-row: 2; /* Top two-thirds */
width: 100%;
height: 100%; /* Canvas stretches to fill the grid cell */
border: 1px solid black;
}
#console {
grid-column: 2; /* Right column */
grid-row: 3; /* Bottom one-third */
background-color: black;
color: white;
font-family: monospace;
padding: 10px;
overflow-y: auto;
border: 1px solid #ccc;
height: 100%; height: 100%;
font-family: Arial, sans-serif;
background-color: #fff;
display: grid;
grid-template-rows: auto 1fr auto;
grid-template-columns: 1fr;
min-height: 100vh;
}
/* ===== Header (top bar) ===== */
header {
background-color: #f3f4f6;
/* light gray */
padding: 16px 0;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
.header-inner {
max-width: 960px;
margin: 0 auto;
padding: 0 16px;
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 16px;
}
header h1 {
font-size: 1.5rem;
font-weight: bold;
margin: 0 0 4px 0;
color: #1f2937;
/* gray-800 */
}
header p {
margin: 0;
font-size: 0.875rem;
color: #4b5563;
/* gray-600 */
}
.button-group {
display: flex;
gap: 12px;
flex-wrap: wrap;
} }
button { button {
margin: 10px; cursor: pointer;
border: none;
border-radius: 6px;
padding: 8px 16px;
font-weight: 600;
color: white;
box-shadow: 0 2px 4px rgb(0 0 0 / 0.1);
transition: background-color 0.3s ease;
}
#compile-button {
background-color: #2563eb;
/* blue-600 */
}
#compile-button:hover {
background-color: #1d4ed8;
/* blue-700 */
}
#pause-button {
background-color: #eab308;
/* yellow-500 */
color: #000;
}
#pause-button:hover {
background-color: #ca8a04;
/* yellow-600 */
color: #000;
}
#reset-button {
background-color: #dc2626;
/* red-600 */
}
#reset-button:hover {
background-color: #b91c1c;
/* red-700 */
}
/* ===== Main Content ===== */
main {
display: flex;
justify-content: center;
padding: 16px;
background: #f9fafb;
}
.container {
width: 75vw;
/* about 12.5% margin on each side */
max-width: 1200px;
height: 800px;
display: flex;
gap: 20px;
background: white;
}
/* Monaco editor - left half */
#monaco-editor {
flex: 1;
border: 1px solid #d1d5db;
/* gray-300 */
height: 100%;
}
/* Right side: canvas + console */
.right-side {
flex: 1;
display: flex;
flex-direction: column;
gap: 12px;
height: 100%;
}
/* Canvas - top 2/3 */
#gameCanvas {
flex: 2;
border: 1px solid black;
width: 100%;
background: white;
}
#console {
flex: 1;
background: black;
color: white;
font-family: monospace, monospace;
padding: 8px;
overflow-y: auto;
border: 1px solid #d1d5db;
width: 100%;
}
/* alternate line colors */
#console > div:nth-child(odd) {
background-color: #222;
}
#console > div:nth-child(even) {
background-color: #111;
}
/* Responsive for smaller screens */
@media (max-width: 900px) {
.container {
flex-direction: column;
width: 95vw;
height: auto;
}
#monaco-editor,
.right-side {
height: 400px;
}
} }
</style> </style>
</head> </head>
<body> <body>
<h1>Real-Time Python Execution</h1> <!-- Top Bar with Heading and Buttons -->
<header>
<!-- Monaco Editor --> <div class="header-inner">
<div id="monaco-editor"></div> <div>
<h1>Learn CircuitPython</h1>
<!-- Game Canvas --> <p>Write code, simulate physics, and see instant output</p>
<canvas id="gameCanvas"></canvas> </div>
<div class="button-group">
<!-- Console Output --> <button id="compile-button">Compile & Run</button>
<div id="console"></div>
<!-- Buttons -->
<div style="grid-column: span 2; text-align: center;">
<button id="compile-button">Compile and Run</button>
<button id="pause-button">Pause</button> <button id="pause-button">Pause</button>
<button id="reset-button">Reset</button> <button id="reset-button">Reset</button>
</div> </div>
</div>
</header>
<!-- Main Content -->
<main>
<div class="container">
<div id="monaco-editor"></div>
<div class="right-side">
<canvas id="gameCanvas"></canvas>
<div id="console"></div>
</div>
</div>
</main>
<script type="module"> <script type="module">
import { initializeMonaco } from './game.js'; import { initializeMonaco } from './game.js';

View File

@ -10,3 +10,23 @@ while True:
else: else:
robot.turn(0) robot.turn(0)
time.sleep(0.1) time.sleep(0.1)
import robot
import time
robot.move(0.00006)
while True:
left = robot.get_sensors()[0]["distance"]
right = robot.get_sensors()[1]["distance"]
print(str(int(left)) + "\t" + str(int(right)))
if left < 55:
robot.turn(0.01)
elif right < 55:
robot.turn(-0.01)
else:
robot.turn(0)
time.sleep(0.1)

View File

@ -132,7 +132,7 @@ export class Robot {
} }
draw_sensors(ctx) { draw_sensors(ctx) {
ctx.fillStyle = "yellow"; ctx.fillStyle = "green";
this.sensors.forEach(sensor => { this.sensors.forEach(sensor => {
const radians = ((this.angle + sensor.angleOffset) * Math.PI) / 180; const radians = ((this.angle + sensor.angleOffset) * Math.PI) / 180;
const sensorX = this.body.position.x + Math.cos(radians) * 15; const sensorX = this.body.position.x + Math.cos(radians) * 15;

View File

@ -102,7 +102,7 @@ export class RaycastSensor extends Sensor {
} }
ctx.strokeStyle = "yellow"; ctx.strokeStyle = "green";
ctx.beginPath(); ctx.beginPath();
ctx.lineWidth = 2; ctx.lineWidth = 2;
ctx.moveTo(this.startX, this.startY); ctx.moveTo(this.startX, this.startY);

46
style.css Normal file
View File

@ -0,0 +1,46 @@
/* Use a grid layout for the entire page */
body {
margin: 0;
display: grid;
grid-template-columns: 1fr 1fr; /* Two equal columns */
grid-template-rows: auto 2fr 1fr; /* Header, main content, and console sections */
height: 100vh; /* Full viewport height */
font-family: Arial, sans-serif;
}
h1 {
grid-column: span 2; /* Header spans both columns */
text-align: center;
margin: 10px 0;
}
#monaco-editor {
grid-column: 1; /* Left column */
grid-row: 2 / span 2; /* Takes full left side */
border: 1px solid #ccc;
height: 100%; /* Fill available space */
}
#gameCanvas {
grid-column: 2; /* Right column */
grid-row: 2; /* Top two-thirds */
width: 100%;
height: 100%; /* Canvas stretches to fill the grid cell */
border: 1px solid black;
}
#console {
grid-column: 2; /* Right column */
grid-row: 3; /* Bottom one-third */
background-color: black;
color: white;
font-family: monospace;
padding: 10px;
overflow-y: auto;
border: 1px solid #ccc;
height: 100%;
}
button {
margin: 10px;
}