Hacker News new | ask | show | jobs
by zatkin 3863 days ago
Everything is great, simple, and easy to understand, and then I get to that Snake example and the code is nearly unreadable.
1 comments

The Snake code is more complex than it needs to be -- example: defining directions as constants from 1 to 4 and then using IF on the direction, instead of defining directions as offsets in the coordinates. But simpler code would not be that much simpler -- Forth just takes getting used to, and I guess the step up to a whole game was too steep. Add some smaller exercises first? Like Sokoban?

(Generally the main thing that'd make Forth more readable is local variables in place of stack manipulations.)

If you really insist on having an enum for your directions, what you could do is something like this: (assuming 2s complement and TRUE being ~0)

    : DIREQ DIRECTION @ = ;
    : DELTA DIREQ SWAP DIREQ NEGATE + ;
    : MOVE-SNAKE-HEAD
      LEFT RIGHT DELTA SNAKE-X-HEAD +!
      UP DOWN DELTA SNAKE-Y-HEAD +! ;
It's an open question whether this approach is any better but I think it looks a bit more Forthlike, insofar as I have any grasp of what that is.

I think having offsets would make more sense - e.g., suppose your playfield is 80 units wide, then you'd have left and right as -1 and +1, and up and down as -80 and +80 (which I assume is what you mean).