Hey Reddit! I'm interviewing for a company that uses clojure, and as a test, thay asked me to develop a small game in Clojure to learn how it works and so they can see my code.
I've never coded in a functional language before, the only thing that I've used are some functional libs in NodeJs (like ramdaJS).
The game is fairly simple, just create a grid, and inside it create some robots that would be able to walk inside it (move from position [0 1] to [0 2]), without colliding with another robots or the outside of the grid. If I had to create that on an imperative language, it would be really easy, but I'm having some trouble in having the mindset on funcional programming and working with immutable data.
Here's what I worked this week after starting to learn clojure:
;; GRID
(defn create-tile [position]
{:position position
:content nil})
(defn create-grid [[size-x size-y]]
(mapv
(fn [x] (mapv (fn [y] (create-tile [x y])) (range size-y)))
(range size-x)))
(defn position-in-grid? [[pos-x pos-y] grid]
(and
(>= pos-x 0)
(>= pos-y 0)
(< pos-x (count grid))
(< pos-y (count (grid pos-x)))))
(defn validate-position [position grid]
(if (not (position-in-grid? position grid))
(throw (AssertionError. "Invalid position"))))
(defn place-content [position content grid]
(validate-position position grid)
(assoc grid (first position)
(assoc
(grid (first position))
(second position)
{:position position :content content})))
;; ROBOT
(defn create-robot [position direction]
{:type :robot
:position position
:direction direction})
(defn place-robot [robot grid]
(place-content (:position robot) robot grid))
(defn walk-robot [robot grid]
(place-content (:position robot) nil grid)
(let [new-pos (vec (map + (:position robot) (:direction robot)))]
(place-content
new-pos (assoc robot :position new-pos) grid)))
For now I just run the game on REPL, and later I'll create an app and everything. The main thing I'm having trouble is: how do I keep the "state" of the game? In an imperative language I would just create an object with the grid state and the robots, and update its values as needed. But here, do I need to create a new game state everytime I make a change?
So basically every function that is used to play the game (creating a robot, walking, etc.) would need to receive a current state, and return a new state with the changes made?
Thanks for the help!
EDIT:
Latest version