Merl's Blog

Input?

Going from Python to Clojure has been difficult. I am certainly seeing benefits, I think my code is getting smaller. I mentioned threading, and functions/variables that exist for a tiny fraction of time.

I am remaking Tic Tac Toe in Clojure, I was struggling to get the player input.

I have received input from users before in C and in Python but not in Clojure. The way to do this is to use read-line.

My mission was for the player to look at the board and choose what number they wanted, but also for them to choose a number that is possible. After much tinkering I came to this conclusion.

(defn X? [bool]
  (if bool
    "X"
    "O"))

(defn replace-in-list [lst old-num xo]
    (map (fn [x]
      (if (= x old-num)
        Xo
        x))
     lst))

(defn update-board [grid xo]
   (loop []
     (println "Choose your position")
     (let [user-input (read-line) num (Integer/parseInt user-input)]
      (if (not-any? #{num} grid)
        (do (println "The value you entered is not possible silly. Please try again.") (recur))
        (replace-in-list grid num (X? xo)) ))))

Definitely not the cleanest of code. After completing this I took some time to do other tasks. Then I eventually came back to refactor this.

(defn X? [bool]
 (if bool
   "X"
   "O"))


(defn place-xo [grid old-num xo]
 (map
   #(if (= % old-num)
      xo
      %)
   grid))


(defn valid-move? [num grid]
 (not-any? #{num} grid))


(defn invalid-message []
 (println "The value you entered is not possible silly. Please try again."))


(defn get-move []
 (println "Choose your position")
 (let [user-input (read-line)
       move (Integer/parseInt user-input)]
   move))


(defn update-board [grid xo]
 (loop []
   (let [move (get-move)]
     (if (valid-move? move grid)
       (do (invalid-message) (recur))
       (place-xo grid move (X? xo))))))


It may still need some work but I was able to do a few things. I changed the name of replace-in-list to place-xo. I wanted to take out the print statements since they took up so much room, so the invalid message was a must as well as the get a move function. Getting the get-move function out was something I was pretty happy about because now the update board looks much nicer.

Still a ways to go for the whole project, and even refactoring this but I’m getting closer.

Best,

Merl