Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 | 1x 292x 292x 292x 292x 292x 292x 292x 292x 292x 292x 292x 10x 10x 292x 1x 1x 292x 1x 1x 1x 1x 1x 1x 1x 1x 292x 292x 7x 3x 3x 4x 4x 6x 4x 4x 4x 4x 4x 7x 292x 4x 4x 4x 4x 4x 4x 4x 4x 292x 10x 10x 10x 10x 10x 10x 2x 2x 2x 2x 10x 10x 292x 80x 80x 80x 646x 646x 50x 25x 646x 472x 391x 81x 81x 81x 472x 646x 80x 292x 80x 80x 80x 80x 80x 486x 486x 50x 25x 486x 312x 311x 310x 49x 49x 49x 312x 486x 80x 80x 80x 80x 292x 48x 48x 48x 48x 417x 417x 417x 144x 144x 273x 273x 273x 273x 417x 6843x 6843x 222x 111x 6843x 10x 10x 10x 6843x 417x 10x 10x 273x 417x 15x 15x 15x 417x 42x 42x 231x 231x 231x 231x 417x 9x 9x 9x 9x 9x 9x 9x 222x 417x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 417x 3x 3x 3x 3x 3x 3x 3x 417x 1x 1x 1x 1x 1x 1x 1x 417x 1x 1x 1x 1x 1x 210x 417x 3x 3x 3x 3x 3x 3x 210x 210x 210x 210x 210x 210x 210x 210x 210x 210x 210x 210x 210x 210x 210x 417x 80x 80x 80x 80x 80x 80x 80x 2x 2x 2x 4x 4x 3x 3x 3x 3x 1x 1x 4x 2x 2x 2x 2x 2x 2x 80x 80x 210x 210x 210x 210x 48x 6x 6x 6x 48x 48x 292x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 1x 1x 40x 48x 48x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 371x 371x 371x 371x 26x 26x 26x 371x 371x 371x 371x 371x 371x 371x 40x 360x 359x 360x 360x 7x 7x 7x 7x 7x 360x 352x 64x 64x 64x 64x 64x 64x 64x 64x 64x 352x 288x 288x 352x 360x 40x 3x 3x 3x 3x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 40x 5x 2x 2x 40x 40x 40x 40x 40x 40x 40x 40x 40x 292x | import { VirtualSpikeApi } from './spike-api';
export class PythonScriptRunner {
private api: VirtualSpikeApi;
private abortController: AbortController | null = null;
private isRunning = false;
public isPaused: boolean = false;
public currentLine: number = 0;
public stepDelayMs: number = 0;
private pausePromiseResolve: (() => void) | null = null;
constructor(api: VirtualSpikeApi) {
this.api = api;
}
public get active(): boolean {
return this.isRunning;
}
public pause(): void {
this.isPaused = true;
}
public resume(): void {
if (!this.isRunning) return;
this.isPaused = false;
if (this.pausePromiseResolve) {
const resolve = this.pausePromiseResolve;
this.pausePromiseResolve = null;
resolve();
}
}
public get isWaitingForStep(): boolean {
return this.pausePromiseResolve !== null;
}
public waitForPause(): Promise<number> {
if (this.isPaused && this.pausePromiseResolve) {
return Promise.resolve(this.currentLine);
}
return new Promise((resolve) => {
const check = setInterval(() => {
if (!this.isRunning || (this.isPaused && this.pausePromiseResolve)) {
clearInterval(check);
resolve(this.currentLine);
}
}, 5);
});
}
public step(): void {
if (!this.isRunning) return;
this.isPaused = true;
if (this.pausePromiseResolve) {
const resolve = this.pausePromiseResolve;
this.pausePromiseResolve = null;
resolve();
}
}
public abort(): void {
if (this.abortController) {
this.abortController.abort();
}
this.isRunning = false;
this.isPaused = false;
if (this.pausePromiseResolve) {
const resolve = this.pausePromiseResolve;
this.pausePromiseResolve = null;
resolve();
}
this.api.stopAllMotors();
}
public static findMatchingParen(str: string, openIndex: number): number {
let depth = 0;
let inQuote: string | null = null;
for (let i = openIndex; i < str.length; i++) {
const ch = str[i];
if ((ch === '"' || ch === "'") && (i === 0 || str[i - 1] !== '\\')) {
if (!inQuote) inQuote = ch;
else if (inQuote === ch) inQuote = null;
} else if (!inQuote) {
if (ch === '(') depth++;
else if (ch === ')') {
depth--;
if (depth === 0) return i;
}
}
}
return -1;
}
public static splitArguments(argsStr: string): string[] {
const result: string[] = [];
let depth = 0;
let inQuote: string | null = null;
let start = 0;
for (let i = 0; i < argsStr.length; i++) {
const ch = argsStr[i];
if ((ch === '"' || ch === "'") && (i === 0 || argsStr[i - 1] !== '\\')) {
if (!inQuote) inQuote = ch;
else if (inQuote === ch) inQuote = null;
} else if (!inQuote) {
if (ch === '(' || ch === '[' || ch === '{') depth++;
else if (ch === ')' || ch === ']' || ch === '}') depth--;
else if (ch === ',' && depth === 0) {
result.push(argsStr.substring(start, i).trim());
start = i + 1;
}
}
}
const last = argsStr.substring(start).trim();
if (last) result.push(last);
return result;
}
/**
* Transpiles a subset of Python into async JavaScript
*/
public static transpilePythonToJs(pyCode: string): string {
const lines = pyCode.split(/\r?\n/);
const outputLines: string[] = [];
const indentStack: number[] = [0];
for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
const rawLine = lines[lineIndex];
const lineNumber = lineIndex + 1;
// Skip empty lines or pure comments
if (!rawLine.trim() || rawLine.trim().startsWith('#')) {
continue;
}
// Calculate current indentation
const indent = rawLine.search(/\S|$/);
let line = rawLine.trim();
// Strip comments (respecting string literals)
let inQuote: string | null = null;
let commentIdx = -1;
for (let c = 0; c < line.length; c++) {
const char = line[c];
if ((char === '"' || char === "'") && (c === 0 || line[c - 1] !== '\\')) {
if (!inQuote) inQuote = char;
else if (inQuote === char) inQuote = null;
} else if (char === '#' && !inQuote) {
commentIdx = c;
break;
}
}
if (commentIdx !== -1) {
line = line.substring(0, commentIdx).trimEnd();
}
if (!line) continue;
// Handle closing braces when indent decreases
while (indentStack.length > 1 && indent < indentStack[indentStack.length - 1]) {
indentStack.pop();
outputLines.push(' '.repeat(indentStack[indentStack.length - 1]) + '}');
}
// Skip import statements
if (line.startsWith('import ') || line.startsWith('from ')) {
continue;
}
let transformed = line
.replace(/\bTrue\b/g, 'true')
.replace(/\bFalse\b/g, 'false')
.replace(/\bNone\b/g, 'null');
// Convert while loops
if (transformed.startsWith('while ') && transformed.endsWith(':')) {
let condition = transformed.slice(6, -1).trim();
condition = condition.replace(/\band\b/g, '&&').replace(/\bor\b/g, '||').replace(/\bnot\b/g, '!');
outputLines.push(' '.repeat(indent) + `await __traceLine(${lineNumber});`);
outputLines.push(' '.repeat(indent) + `while (${condition}) { await __traceLine(${lineNumber}); await __yield();`);
indentStack.push(indent + 2);
continue;
}
// Convert for i in range(...)
const forRangeMatch = transformed.match(/^for\s+([a-zA-Z0-9_]+)\s+in\s+range\((.*?)\)\s*:/);
if (forRangeMatch) {
const varName = forRangeMatch[1];
const rangeArgs = forRangeMatch[2].split(',').map((s) => s.trim());
let init = '0', end = '0', step = '1';
if (rangeArgs.length === 1) {
end = rangeArgs[0];
} else if (rangeArgs.length === 2) {
init = rangeArgs[0];
end = rangeArgs[1];
} else if (rangeArgs.length === 3) {
init = rangeArgs[0];
end = rangeArgs[1];
step = rangeArgs[2];
}
outputLines.push(' '.repeat(indent) + `await __traceLine(${lineNumber});`);
outputLines.push(' '.repeat(indent) + `for (let ${varName} = ${init}; ${varName} < ${end}; ${varName} += ${step}) { await __traceLine(${lineNumber}); await __yield();`);
indentStack.push(indent + 2);
continue;
}
// Convert if / elif / else
if (transformed.startsWith('if ') && transformed.endsWith(':')) {
let condition = transformed.slice(3, -1).trim();
condition = condition.replace(/\band\b/g, '&&').replace(/\bor\b/g, '||').replace(/\bnot\b/g, '!');
outputLines.push(' '.repeat(indent) + `await __traceLine(${lineNumber});`);
outputLines.push(' '.repeat(indent) + `if (${condition}) {`);
indentStack.push(indent + 2);
continue;
}
if (transformed.startsWith('elif ') && transformed.endsWith(':')) {
let condition = transformed.slice(5, -1).trim();
condition = condition.replace(/\band\b/g, '&&').replace(/\bor\b/g, '||').replace(/\bnot\b/g, '!');
// Close previous block if on same indent
if (indentStack.length > 1) indentStack.pop();
outputLines.push(' '.repeat(indent) + `} else if (await __traceLine(${lineNumber}), (${condition})) {`);
indentStack.push(indent + 2);
continue;
}
if (transformed === 'else:') {
if (indentStack.length > 1) indentStack.pop();
outputLines.push(' '.repeat(indent) + `} else {`);
indentStack.push(indent + 2);
continue;
}
// Convert Python ternary: var = val1 if cond else val2
const ternaryMatch = transformed.match(/^([a-zA-Z0-9_]+)\s*=\s*(.*?)\s+if\s+(.*?)\s+else\s+(.*)$/);
if (ternaryMatch) {
const varName = ternaryMatch[1];
const valTrue = ternaryMatch[2].trim();
let cond = ternaryMatch[3].trim().replace(/\band\b/g, '&&').replace(/\bor\b/g, '||').replace(/\bnot\b/g, '!');
const valFalse = ternaryMatch[4].trim();
transformed = `${varName} = (${cond}) ? (${valTrue}) : (${valFalse})`;
}
// Convert Python boolean & null literals
transformed = transformed
.replace(/\bTrue\b/g, 'true')
.replace(/\bFalse\b/g, 'false')
.replace(/\bNone\b/g, 'null');
// Auto-await asynchronous SPIKE methods
transformed = transformed.replace(/\b([a-zA-Z0-9_]+)\.move\(/g, 'await $1.move(');
transformed = transformed.replace(/\b([a-zA-Z0-9_]+)\.move_tank\(/g, 'await $1.move_tank(');
transformed = transformed.replace(/\b([a-zA-Z0-9_]+)\.run_for_degrees\(/g, 'await $1.run_for_degrees(');
transformed = transformed.replace(/\b([a-zA-Z0-9_]+)\.run_for_rotations\(/g, 'await $1.run_for_rotations(');
transformed = transformed.replace(/\b([a-zA-Z0-9_]+)\.run_for_seconds\(/g, 'await $1.run_for_seconds(');
transformed = transformed.replace(/\b([a-zA-Z0-9_]+)\.run_to_position\(/g, 'await $1.run_to_position(');
transformed = transformed.replace(/\bcontrol\.wait_for_seconds\(/g, 'wait_for_seconds(');
transformed = transformed.replace(/\bwait_for_seconds\(/g, 'await wait_for_seconds(');
transformed = transformed.replace(/\btime\.sleep\(/g, 'await wait_for_seconds(');
// Transform method calls with keyword arguments into options objects
// e.g. .start(steering=int(steering), speed=BASE_SPEED) -> .start({ steering: int(steering), speed: BASE_SPEED })
// e.g. .run_for_seconds(5, speed=50) -> .run_for_seconds(5, { speed: 50 })
// e.g. .move(10, 'cm', steering=20, speed=50) -> .move(10, 'cm', { steering: 20, speed: 50 })
const methodCallRegex = /\.([a-zA-Z_]\w*)\(/g;
let match: RegExpExecArray | null;
while ((match = methodCallRegex.exec(transformed)) !== null) {
const parenOpen = match.index + match[0].length - 1;
const parenClose = PythonScriptRunner.findMatchingParen(transformed, parenOpen);
if (parenClose !== -1) {
const argsStr = transformed.substring(parenOpen + 1, parenClose);
const args = PythonScriptRunner.splitArguments(argsStr);
const hasKwargs = args.some((a) => /^[a-zA-Z_]\w*\s*=/.test(a));
if (hasKwargs) {
const positional: string[] = [];
const props: string[] = [];
for (const arg of args) {
const eqIdx = arg.indexOf('=');
if (eqIdx !== -1) {
const k = arg.substring(0, eqIdx).trim();
const v = arg.substring(eqIdx + 1).trim();
props.push(`${k}: ${v}`);
} else {
positional.push(arg);
}
}
const newArgs = [...positional, `{ ${props.join(', ')} }`].join(', ');
const before = transformed.substring(0, parenOpen + 1);
const after = transformed.substring(parenClose);
transformed = `${before}${newArgs}${after}`;
methodCallRegex.lastIndex = parenOpen + 1 + newArgs.length + 1;
}
}
}
// Handle simple print
transformed = transformed.replace(/\bprint\((.*?)\)/g, 'console.log($1)');
outputLines.push(' '.repeat(indent) + `await __traceLine(${lineNumber});`);
outputLines.push(' '.repeat(indent) + transformed + ';');
}
// Close any remaining open braces
while (indentStack.length > 1) {
indentStack.pop();
outputLines.push(' '.repeat(indentStack[indentStack.length - 1]) + '}');
}
return outputLines.join('\n');
}
/**
* Run a SPIKE Python script asynchronously
*/
public async execute(
pyCode: string,
onLog?: (msg: string) => void,
onLine?: (line: number) => void,
startPaused: boolean = false
): Promise<void> {
this.abortController = new AbortController();
this.isRunning = true;
this.isPaused = startPaused;
this.currentLine = 0;
this.pausePromiseResolve = null;
const signal = this.abortController.signal;
// Build execution context environment
const self = this;
const PrimeHub = () => this.api.createPrimeHub();
const Motor = (port: any) => this.api.createMotor(port);
const MotorPair = (l?: any, r?: any) => this.api.createMotorPair(l, r);
const ColorSensor = (port: any = 'C') => this.api.createColorSensor(port);
const DistanceSensor = () => this.api.createDistanceSensor();
const Timer = function () {
return self.api.createTimer();
};
const wait_for_seconds = async (sec: number) => {
await this.api.wait(sec);
};
const time = {
sleep: async (sec: number) => {
await this.api.wait(sec);
},
};
const control = {
Timer: () => this.api.createTimer(),
wait_for_seconds,
};
const spike = {
PrimeHub,
Motor,
MotorPair,
ColorSensor,
DistanceSensor,
Timer: () => this.api.createTimer(),
control,
};
// Pre-instantiated default hardware instances for beginner and Word Block scripts
const hub = PrimeHub();
const motors = MotorPair('A', 'B');
const motor_a = Motor('A');
const motor_b = Motor('B');
const motor_c = Motor('C');
const motor_d = Motor('D');
const motor_e = Motor('E');
const motor_f = Motor('F');
// Python built-in functions
const int = (v: any) => Math.trunc(Number(v)) || 0;
const float = (v: any) => Number(v) || 0;
const round = (v: any, d = 0) => {
const f = Math.pow(10, d);
return Math.round(Number(v) * f) / f;
};
const abs = (v: any) => Math.abs(Number(v));
const min = (...args: any[]) => Math.min(...(Array.isArray(args[0]) ? args[0] : args));
const max = (...args: any[]) => Math.max(...(Array.isArray(args[0]) ? args[0] : args));
const len = (v: any) => (v && typeof v.length === 'number' ? v.length : 0);
const str = (v: any) => String(v);
const __yield = async () => {
if (signal.aborted) throw new Error('Aborted');
await new Promise<void>((resolve) => {
const timer = setTimeout(resolve, 0);
const abortHandler = () => {
clearTimeout(timer);
resolve();
};
if (signal.aborted) {
abortHandler();
} else {
signal.addEventListener('abort', abortHandler, { once: true });
}
});
if (signal.aborted) throw new Error('Aborted');
};
const __traceLine = async (lineNum: number) => {
if (signal.aborted) throw new Error('Aborted');
this.currentLine = lineNum;
onLine?.(lineNum);
if (this.isPaused) {
await new Promise<void>((resolve) => {
this.pausePromiseResolve = resolve;
});
this.pausePromiseResolve = null;
if (signal.aborted) throw new Error('Aborted');
} else {
if (this.stepDelayMs > 0) {
await new Promise<void>((resolve) => {
const timer = setTimeout(resolve, this.stepDelayMs);
const abortHandler = () => {
clearTimeout(timer);
resolve();
};
if (signal.aborted) {
abortHandler();
} else {
signal.addEventListener('abort', abortHandler, { once: true });
}
});
if (signal.aborted) throw new Error('Aborted');
} else {
await __yield();
}
}
};
const consoleLog = (...args: any[]) => {
const msg = args.map((a) => (typeof a === 'object' && a !== null ? JSON.stringify(a) : String(a))).join(' ');
if (onLog) onLog(msg);
console.log(`[Robot Python]:`, ...args);
};
const jsCode = PythonScriptRunner.transpilePythonToJs(pyCode);
try {
// Execute within async function scope
const fn = new Function(
'PrimeHub',
'Motor',
'MotorPair',
'ColorSensor',
'DistanceSensor',
'Timer',
'wait_for_seconds',
'time',
'spike',
'control',
'hub',
'motors',
'motor_a',
'motor_b',
'motor_c',
'motor_d',
'motor_e',
'motor_f',
'int',
'float',
'round',
'abs',
'min',
'max',
'len',
'str',
'__yield',
'__traceLine',
'console',
`return (async () => {\n${jsCode}\n})();`
);
await fn(
PrimeHub,
Motor,
MotorPair,
ColorSensor,
DistanceSensor,
Timer,
wait_for_seconds,
time,
spike,
control,
hub,
motors,
motor_a,
motor_b,
motor_c,
motor_d,
motor_e,
motor_f,
int,
float,
round,
abs,
min,
max,
len,
str,
__yield,
__traceLine,
{ log: consoleLog }
);
} catch (err: any) {
if (err.message !== 'Aborted' && err.message !== 'Simulation execution stopped by user') {
throw err;
}
} finally {
this.api.stopAllMotors();
this.isRunning = false;
this.isPaused = false;
this.currentLine = 0;
this.pausePromiseResolve = null;
this.abortController = null;
}
}
}
|