File size: 1,620 Bytes
b09157d | 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 | // Commands may span several WASI writes. Await animations before acknowledging
// stdout so scanf cannot accept the next turn while a pawn is still walking.
export function createInteractionProtocol({ mode, start, move, finish, robot, output }) {
let pending = '';
async function line(text) {
const value = text.trim();
let match;
if (mode === 'tic-tac-toe') {
if (value === 'tictactoe start') return start();
if ((match = /^tictactoe play ([12]) ([1-9])$/.exec(value))) return move(Number(match[1]), Number(match[2]));
if ((match = /^tictactoe result ([012])$/.exec(value))) return finish(Number(match[1]));
if (value.startsWith('tictactoe')) throw new Error('Invalid Tic Tac Toe command. Check the exercise message formats.');
} else if ((match = /^robot (microduck|reachy) ([a-z0-9_]+)$/.exec(value))) {
const allowed = { microduck: ['excited', 'sad', 'mock'], reachy: ['proud1', 'reprimand1'] };
if (!allowed[match[1]].includes(match[2])) throw new Error('Unknown exercise emotion. Check the exercise message formats.');
return robot(match[1], match[2]);
} else if (value.startsWith('robot ')) throw new Error('Invalid robot command. Check the exercise message formats.');
await output(text);
}
return {
async write(text) {
pending += text;
let n;
while ((n = pending.indexOf('\n')) >= 0) {
const record = pending.slice(0, n + 1); pending = pending.slice(n + 1);
await line(record);
}
},
async flush() { if (pending) { const record = pending; pending = ''; await line(record); } },
};
}
|