Skip to content

Commit

Permalink
fix: fix a bug in (combine) function
Browse files Browse the repository at this point in the history
(combine [[2] [0] [4] [4]]) was giving
[[2] [0] [8] [0]] instead of [[2] [8] [0] [0]]

(combine [[0] [0] [4] [4]] was giving
[[0] [8] [0] [0]] instead of [[8] [0] [0] [0]

(combine [[4] [4] [0] [4]]) was giving
[[8] [0] [4] [0]] instead of [[8] [4] [0] [0]]
  • Loading branch information
WarFox committed May 23, 2024
1 parent 613d478 commit e79933c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
11 changes: 6 additions & 5 deletions src/cljs_2048/board.cljs
Original file line number Diff line number Diff line change
Expand Up @@ -72,18 +72,19 @@
(into v (repeat fill-count [0]))))

(defn combine
"Combines two equal tiles into one in the vector v and fills remaining with zeroes"
"Combines two equal tiles into one in the vector v and fills remaining with zeroes.
v is a vector of vectors of single integer, for example [[2] [0] [4] [4]]
[0] means empty slot and all [0] should be trailing in the result."
[v]
(loop [[head & remaining] v
(loop [[head & remaining] (remove #(= [0] %) v) ;; Remove [0] tiles before reduction
acc []]
(cond
(empty? remaining)
(fill-zeroes (conj acc (if head head [0])) columns-count) ;; head can be nil

(= head (first remaining))
(let [sum (+ (first head) (first head))]
(when (pos? sum)
(re-frame/dispatch [::game-events/add-score sum]))
(let [sum (* 2 (first head))]
(re-frame/dispatch [::game-events/add-score sum])
(recur (rest remaining) (conj acc [sum])))

:else
Expand Down
12 changes: 12 additions & 0 deletions test/cljs_2048/board_test.cljs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,18 @@
(is (= (sut/combine [[1] [2] [3] [4]])
[[1] [2] [3] [4]]))

(is (= (sut/combine [[4] [4] [4] [4]])
[[8] [8] [0] [0]]))

(is (= (sut/combine [[2] [0] [4] [4]])
[[2] [8] [0] [0]]))

(is (= (sut/combine [[0] [0] [4] [4]])
[[8] [0] [0] [0]]))

(is (= (sut/combine [[4] [4] [0] [4]])
[[8] [4] [0] [0]]))

(is (= (sut/combine [[4] [2] [2] [0]])
[[4] [4] [0] [0]]))

Expand Down

0 comments on commit e79933c

Please sign in to comment.