Created
April 29, 2012 13:35
-
-
Save mistercam/2550477 to your computer and use it in GitHub Desktop.
Functions to execute specific moves on the Reversi board
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn flip [board piece move direction] | |
"Returns a new board with results of playing the specified move and piece" | |
(if (flippable? board piece move direction) | |
(loop [b board m (vec (map + move direction))] ; bind board to b so we can use it in recur | |
(let [r (m 0) | |
c (m 1) | |
p ((board r) c)] | |
(if (= p piece) | |
b ; we've come to a piece the same colour as the active piece, so we're done flipping. Return the modified board. | |
(recur (assoc b r (assoc (b r) c piece)) (vec (map + m direction)))))) ; more flipping to be done, so flip and recur. | |
board)) ; move+piece won't cause a flip, so just return the board | |
(defn place-piece [board piece move] | |
"Returns a new board that results from playing the specified piece and move." | |
(if (move-valid? board piece move) | |
(let [r (move 0) c (move 1)] | |
((comp | |
#(assoc % r (assoc (% r) c piece)) | |
#(flip % piece move (directions :N )) | |
#(flip % piece move (directions :NE )) | |
#(flip % piece move (directions :E )) | |
#(flip % piece move (directions :SE )) | |
#(flip % piece move (directions :S )) | |
#(flip % piece move (directions :SW )) | |
#(flip % piece move (directions :W )) | |
#(flip % piece move (directions :NW ))) | |
board)))) ; the move and piece were not valid, so just return the board unchanged | |
;; An alternative version of place-piece | |
(defn place-piece-alt [board piece move] | |
"Returns a new board that results from playing the specified piece and move." | |
(if (move-valid? board piece move) | |
(let [r (move 0) c (move 1) b (atom board)] | |
(swap! b #(assoc % r (assoc (% r) c piece))) | |
(swap! b #(flip % piece move (directions :N ))) | |
(swap! b #(flip % piece move (directions :NE ))) | |
(swap! b #(flip % piece move (directions :E ))) | |
(swap! b #(flip % piece move (directions :SE ))) | |
(swap! b #(flip % piece move (directions :S ))) | |
(swap! b #(flip % piece move (directions :SW ))) | |
(swap! b #(flip % piece move (directions :W ))) | |
(swap! b #(flip % piece move (directions :NW )))) | |
board)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment