-
-
Save mvcds/bf662bdd5b5add7ec3303f24b25593a2 to your computer and use it in GitHub Desktop.
Clojure meetup #115
This file contains hidden or 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
(ns chess.core | |
(:require | |
[clojure.set]) | |
) | |
(def pieces #{ \K \Q \N \B \R }) | |
(def row-mapping | |
{\1 1 \2 2 \3 3 \4 4 \5 5 \6 6 \7 7 \8 8} | |
) | |
(def column-mapping | |
{\a 1 \b 2 \c 3 \d 4 \e 5 \f 6 \g 7 \h 8} | |
) | |
(def board [[\R \N \B \Q \K \B \N \R] | |
[\P \P \P \P \P \P \P \P] | |
(vec (repeat 8 nil)) | |
(vec (repeat 8 nil)) | |
(vec (repeat 8 nil)) | |
(vec (repeat 8 nil)) | |
(vec (repeat 8 nil)) | |
[\P \P \P \P \P \P \P \P] | |
[\R \N \B \K \Q \B \N \R]]) | |
(defn print-board | |
[board] | |
(println board)) | |
(require '[clojure.set :as set]) | |
(defn find-in-column | |
"get the position of the piece in the column" | |
[board column piece] | |
(loop [rows board | |
row-index 1 | |
] | |
(if (> row-index 8) | |
nil | |
(let [row (first rows) | |
square (get row column)] | |
(if (= square piece) | |
[column row-index] | |
(recur (rest board) (inc row-index))))))) | |
(defn remove-piece [board [column row]] | |
(assoc-in board [(dec row) (dec column)] nil)) | |
(defn add-piece [board [column row] piece] | |
(assoc-in board [(dec row) (dec column)] piece) | |
) | |
(defn rocade-short [board] | |
(-> board | |
(remove-piece [8 1]) | |
(add-piece [6 1] \R) | |
(remove-piece [5 1]) | |
(add-piece [7 1] \K) | |
)) | |
(defn evaluate-move | |
[board move] | |
(if (= move "o-o") (rocade-short board)) | |
(let [charset (set move) | |
piece (first (clojure.set/intersection charset pieces)) | |
is-pawn-move (nil? piece) | |
column (column-mapping | |
(if is-pawn-move | |
(first move))) | |
row (row-mapping | |
(if is-pawn-move | |
(second move))) | |
coordinate (find-in-column board column (or piece \P)) | |
] | |
; (println 'piece piece) | |
; [piece column row] | |
(-> board | |
(remove-piece coordinate) | |
(add-piece [column row] (or piece \P))) | |
)) | |
(defn pprint-board [board] | |
(doseq [row board] | |
(doseq [elem row] | |
(print (or elem " "))) | |
(println))) | |
(defn repl | |
[] | |
(loop [state board] | |
(print "Move?") | |
(flush) | |
(let [x (read-line) ] | |
(if (= x "exit") (println "bye") (do | |
(evaluate-move state x) | |
(pprint-board state) | |
(recur state))) | |
))) | |
(repl) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment