<< first < prev 1 2 3 4 5 6 7 8 9 next > last >> Walking Around...
Walking Around in our World

Ok, now that we can see our world, let's write some code that lets us walk around in it. The function walk-direction (not in the functional style) takes a direction and lets us walk there:

(defn walk-direction [direction]
  (let [next (first (filter (fn [x] (= direction (first x)))
                            (rest (location game-map))))]
    (cond next (do (def location (nth next 2)) (look))
          :else '(you cannot go that way -))))

The special command let allows us to create the local variable next, which we set to the path descriptor for the direction the player wants to walk in - rest just chops the first item off of a list. If the user types in a bogus direction, next will be (). The cond command is like a chain of if-then commands in Lisp: Each row in a cond has a value to check and an action to do. In this case, if the next location is not nil, it will def the player's location to the third item (the one at index 2) in the path descriptor, which holds the symbol describing the new direction, then gives the user a look of the new place. If the next location is nil, it falls through to the next line and admonishes the user. Let's try it:

(walk-direction 'west)
user=> (walk-direction 'west)
(you are in a beautiful garden -
there is a well in front of you -
there is a door going east from here -
you see a frog on the floor -
you see a chain on the floor -)

Little Wizard In Clojure, nil and the empty list ("()") are not the same, this is different from Common Lisp.


Now, we were able to simplify our description functions by creating a look command that is easy for our player to type. Similarly, it would be nice to adjust the walk-direction command so that it doesn't have an annoying quote mark in the command that the player has to type in. But, as we have learned, when the compiler reads a form in Code Mode, it will read all its parameters in Code Mode, unless a quote tells it not to. Is there anything we can do to tell the compiler that west is just a piece of data without the quote?

<< first < prev 1 2 3 4 5 6 7 8 9 next > last >> Walking Around...