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.

78 lines
3.1KB

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