ClojureScript+React/Om clone of 2048
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
2.7KB

  1. (ns ttfe.board)
  2. (defn move-right [board]
  3. (mapv (fn [line]
  4. (let [numbers (filter #(not= % nil) line)
  5. crunched-numbers (loop [acc [] line (reverse numbers) i 0]
  6. (if (>= i (count numbers))
  7. acc
  8. (if (= (nth line i) (nth line (inc i) nil))
  9. (recur (conj acc (* 2 (nth line i)))
  10. line
  11. (+ i 2))
  12. (recur (conj acc (nth line i))
  13. line
  14. (inc i)))))]
  15. (vec (concat (repeat (- (count line) (count crunched-numbers))
  16. nil)
  17. (reverse crunched-numbers)))))
  18. board))
  19. (defn move-left [board]
  20. (mapv (fn [line]
  21. (let [numbers (filter #(not= % nil) line)
  22. crunched-numbers (loop [acc [] line numbers i 0]
  23. (if (>= i (count numbers))
  24. acc
  25. (if (= (nth line i) (nth line (inc i) nil))
  26. (recur (conj acc (* 2 (nth line i)))
  27. line
  28. (+ i 2))
  29. (recur (conj acc (nth line i))
  30. line
  31. (inc i)))))]
  32. (vec (concat crunched-numbers
  33. (repeat (- (count line) (count crunched-numbers))
  34. nil)))))
  35. board))
  36. (defn rotate-cw [board]
  37. (apply mapv (fn [a b c d] [a b c d]) (vec (reverse board))))
  38. (defn rotate-ccw [board]
  39. (vec (reverse (apply mapv (fn [a b c d] [a b c d]) board))))
  40. (defn move-up [board]
  41. (rotate-ccw (move-right (rotate-cw board))))
  42. (defn move-down [board]
  43. (rotate-ccw (move-left (rotate-cw board))))
  44. (defn find-empty-tiles [board]
  45. (reduce (fn [acc row-n]
  46. (let [row (nth board row-n)]
  47. (concat acc (reduce (fn [col-acc col-n]
  48. (let [tile (nth row col-n)]
  49. (if (nil? tile)
  50. (conj col-acc [row-n col-n])
  51. col-acc)))
  52. '()
  53. (range (count row))))))
  54. '()
  55. (range (count board))))
  56. (defn add-tile [board]
  57. (let [[rand-row rand-col] (rand-nth (find-empty-tiles board))]
  58. (update-in board [rand-row rand-col] (fn [_] 2))))