Hacker News new | ask | show | jobs
by IanCal 3161 days ago
Interesting, you might want to look at the suggested code though, maybe play through with some beginners?

    function init(robot){
        robot.number = 0;
    }

    function loop(robot){
        robot.jump();
        if(robot.number++ % 2 == 0){
            robot.move(2);
        }
    }
This is in the second level.

Incrementing inside a check is awkward, as is just calling the variable 'number'. Perhaps something like

    function init(robot){
        robot.jump_next = true;
    }

    function loop(robot){
        if (robot.jump_next) {
            robot.jump()
            robot.jump_next = false;
        } else {
            robot.move(2);
            robot.jump_next = true;
        }
    }
3 comments

I think the readability to an inexperienced coder greatly improves just by moving the "robot.number++" outside the conditional and perhaps even changing it to "robot.number = robot.number + 1"

Though that is slightly different (since ++ will execute after the conditional is evaluated when following the lval but the change will make it run before)

Edit: on 2 seconds though... put that code AFTER the if statement and it would behave exactly as the example.

The first snippet calls robot.jump() every loop. The second doesn’t not.
True, although as someone else points out (contrary to what I thought) only the last runnable action is done.

If that wasn't the case, then swapping things around to be something more like "move_next_turn" would be clearer I think.

Very true, it is much easier to understand with a boolean, thanks!