Game loop using the State monad in JavaScript

Dimitris Papadimitriou
2 min readOct 26, 2020

github repo : https://github.com/dimitris-papadimitriou-chr/FunctionalJsWithCategories/blob/master/monads/state-example-1/demo.js

This is a short article on how to create a game loop using the State monad. Unfortunately i am not going to cover the theory of State monad in this article but hopefully i would do this in a subsequent article.

using the State we can pass a state along with a value. We are going to use this to build a simple loop. It’s a simple string parsing algorithm. This simple game is an haskell example and goes like this :


Passes a string of dictionary {a,b,c}
Game is to produce a number from the string.
By default the game is off, a C toggles the
game on and off. A 'a' gives +1 and a b gives -1.
E.g
'ab' = 0
'ca' = 1
'cabca' = 0

the implementation is as follows

the idea is that we pattern match on the array

  1. if is empty we return the State monad as it is. and the computation reached the end
  2. if is not Empty we parse the String into a new State where we can access the previous state s and increase/decrease it appropriately if its a or b respectively. Then pass the rest of the string to the playGamefunction recursively. This playGame(xs) will return the state for the rest of the game which we bind to the state for the current character in order to return the overall state.

Run This

— — — — — — — — — — — — — — — — — — — — — — — —

Excerpt from :Functional Programming in Javascript

Functional Programming in Javascript

--

--