-
-
Save anonymous/e31bbacc1c60155187b2 to your computer and use it in GitHub Desktop.
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
mines.field=> (print-field (gen-field 10 10 25)) | |
124X31 | |
1XXXX21111 | |
25X643X11X | |
1XXX2X2111 | |
13X5421 11 | |
12XX1 1X | |
1221 11 | |
111 1221 | |
1X21 2XX1 | |
12X1 2X31 | |
nil | |
=============== field.clj =============== | |
(ns mines.field) | |
;; Coordinate | |
(defrecord Coord [x y]) | |
;; Field with width, height and a set of Coords for bombs. | |
(defrecord Field [w h bombs]) | |
(defn gen-field | |
"Generates a field." | |
[w h bomb_count] | |
(loop [bombs #{} bombs_left bomb_count] | |
(if (> bombs_left 0) | |
(recur (conj bombs (Coord. (rand-int w) (rand-int h))) (dec bombs_left)) | |
(Field. w h bombs)))) | |
(defn bomb? | |
"Tests for a bomb on a cell." | |
[{:keys [bombs] :as field} coord] | |
(bombs coord)) | |
(defn valid-coord? | |
"Tests if a coordinate is valid." | |
[{:keys [w h] :as field} {:keys [x y] :as coord}] | |
(and (>= x 0) (>= y 0) (< x w) (< y h))) | |
(defn neighbour-coords | |
"Generates the coordinates of neighbour cells." | |
[field {:keys [x y] :as coord}] | |
(filter #(valid-coord? field %) [ | |
(Coord. (dec x) (dec y)) | |
(Coord. x (dec y)) | |
(Coord. (inc x) (dec y)) | |
(Coord. (dec x) y) | |
(Coord. (inc x) y) | |
(Coord. (dec x) (inc y)) | |
(Coord. x (inc y)) | |
(Coord. (inc x) (inc y))])) | |
(defn bomb-count | |
"Returns the bomb count of a cell." | |
[field coord] | |
(count (filter #(bomb? field %) (neighbour-coords field coord)))) | |
(defn print-cell | |
"Prints a cell." | |
[field coord] | |
(print (if (bomb? field coord) | |
"\033[1;31mX\033[0m" | |
(let [bc (bomb-count field coord)] | |
(if (= bc 0) " " bc))))) | |
(defn print-field | |
"Prints a field." | |
[{:keys [w h] :as field}] | |
(doseq [x (range w)] | |
(dorun (map #(print-cell field (Coord. x %)) (range h))) | |
(println))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment