Hacker News new | past | comments | ask | show | jobs | submit login


There's a small thinking shift between writing a game in an imperative style and writing it in a functional style. In particular, it's smaller, I think, for games than for other kinds of applications.

In a typical game, you have a global state - a series of objects describing the properties of the game world at a certain time. You continuously update these objects, based on what input you receive from the user, and then present those changes to him, by way of video and audio rendering.

In pseudoC it would look like this :

gameState s; int time = 0;

int main() { load_resources();

   while(!game_exit()) {

        time = time + 1;

   return 0;

Switching to a functional language, a way of thinking about the game flow I've found useful is this :

The main loop becomes a function of two parameters : the current game state and the current inputs. From these it computes the next state. After the current simulation tick has passed, the next game state become the current one, whatever video and audio you have is updated and new inputs are gathered. It would look like this :

int main() { game_loop(load_resources(),init_inputs(),0); }

gameState game_loop(gameState currentState, gameInput inputs, int game_time) { render_video(currentState); render_audio(currentState);

     game_loop(next_state(currentState,inputs),new_inputs(),game_time + 1);

Yeah, in C it will blow your stack, but functional languages have to deal with recursion much more often, and what you see there will be optimised away to a loop and be executed in constant space.

Other things to note are that you see the state passed explicitly between functions (no relying on it inherently existing as a global) and that the shift is from modifing an object as the game progresses, to creating a new object to represent the new state of the world, and discarding the old one.

Languages, be it lisp, haskell, calm, scala, f# or python, java, c, c# (used as functional languages) are relatively easy to learn. What's hard is adapting your thinking to the strengths and limitations imposed by them.

Hope this helped.

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact