Skip to content

Instantly share code, notes, and snippets.

@ujjwalt
Last active September 20, 2015 10:59
Show Gist options
  • Save ujjwalt/17b1fd21016031e381ab to your computer and use it in GitHub Desktop.
Save ujjwalt/17b1fd21016031e381ab to your computer and use it in GitHub Desktop.
Snakes and Ladders. #FnConf15
(def cells 30) ; Number of cells on the board
; Map of snakes swallowing you at the key and shitting you out at the value
(def snakes {27 1
21 9
19 7
17 4})
; Map of ladders bottom to top cell
(def ladders {3 22
5 8
11 26
20 29})
(def num-of-players 2) ; Number of players in the game
(def initial-state (vec (repeat num-of-players 1))) ; Initialize the state of the game
; Calculate the new position based on whether the user has reached the end
(defn calc-pos
[moves pos]
(if (> (+ moves pos) cells)
pos
(+ moves pos)))
; Calculate the new state of the game
(defn calc-state
[state turn new-pos]
(assoc state turn (or (snakes new-pos) (ladders new-pos) new-pos)))
; Roll the dice and move player with turn those many positions
(defn roll-the-dice
[state turn]
(let [new-pos (calc-pos (inc (rand-int 6)) (state turn))]
(println state (inc turn) new-pos) ; State, Current turn, New position
(if (= new-pos cells)
(str "Player " (inc turn) " won!")
(recur (calc-state state turn new-pos) (mod (inc turn) num-of-players)))))
; Start the game
(defn -main
[]
(roll-the-dice initial-state 0))
@ujjwalt
Copy link
Author

ujjwalt commented Sep 20, 2015

Snakes and Ladders

This is the first Clojure program I've ever written by myself. A code review would be highly appreciated.
The board is based on the image from the slides
Snakes and Ladders board

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment