Crab.ask() (Idea)

From 8x9craft
Jump to: navigation, search

Enable writing programs that depend on user input.

It would pause script execution waiting for owner's chat message and return that message after receiving it.

Right now you'd have to do something along the lines of:

function run(name, number) {
    crab.say('Hey ' + name '! You got a ' + (number > 10 ? 'gel' : 'tasty') + ' banana after putting it in a microwave for ' + number + ' seconds!');
}

const STATE = {
    initial: 0,
    waitForANumber: 1,
    waitForAName: 2,
    run: 3
}

var state = STATE.initial;
var number;
var name;
cran.onChatMessage(msg => {
    switch (state) {
        case STATE.waitForANumber:
            number = msg;
            crab.say('Give a name:');
            state = STATE.waitForAName;
            break;
        case STATE.waitForAName:
            name = msg;
            state = STATE.run;
            run(name, number);
            break;
    }
});
crab.say('Give a number:');
state = STATE.waitForANumber;
crab.handleEvents();

It would be better to enable imperative-style programming while still being able to wait for user input, like that:

// same as crab.onChatMessage(msg => { /* set this to some variable and interrupt handling events */ }); crab.say(something); crab.handleEvents();
var number = crab.ask('Give a number:');
var name = crab.ask('Give a name:');
crab.say('Hey ' + name '! You got a ' + (number > 10 ? 'gel' : 'tasty') + ' banana after putting it in a microwave for ' + number + ' seconds!');

And maybe give an option for timeout after n seconds:

var number;
var tries = 3;

while (tries) {
    // crab.ask(msg: String, timeout: Number): String | undefined
    // returns player's input from chat, or undefined after timeout seconds of no response.
    number = crab.ask('Give a number:', 5); // wait 5 seconds before giving up
    if (typeof number != 'undefined') break;
    --tries;
    if (tries > 0) crab.say('Hey, give me a number in the next ' + (tries * 5) + ' seconds please! ');
}

if (typeof number != 'undefined') {
    // Do the rest
}

Or to run a callback after n seconds:

function getRandomIntInclusive(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

// crab.ask(msg: String, timeout: Number, callback: Function): any
// returns a String input by the player in chat, or value that a callback returned after timeout seconds of no response from the player
var number = crab.ask('Give a number:', 5, () => {
    var n = getRandomIntInclusive(5, 9);
    crab.say('I got tired of waiting, I chose a number for you: ' + n);
    return n;
}); // wait 5 seconds and set a default value if there was no input from the player

See also