Skip to content

Commit

Permalink
Probability distributions working
Browse files Browse the repository at this point in the history
  • Loading branch information
mthvedt committed Sep 22, 2011
1 parent 29f28ce commit 083418e
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
29 changes: 29 additions & 0 deletions src/battleship/ai.clj
@@ -0,0 +1,29 @@
(ns battleship.ai
(:use battleship.core))

; A Monte Carlo solver for Battleship.

; An infinite sequence of random boards
(def infinite-boards
(repeatedly #(place-all-pieces (newboard))))

; 1 if we might want to shoot that square, 0 otherwise
(defn is-target [square]
(if (and (not (nil? (:piece square)))
(= :unstruck (:state square)))
1 0))

; Gets the (not normalized) distribution of targetable squares
; in a (finite) boardseq.
(defn get-distribution [boardseq]
(reduce (fn [running-count board]
(map (fn [running-count-row row]
(map + running-count-row
(map #(if (is-target %) 1 0) row)))
running-count board))
(repeat (repeat 0.0)) boardseq))

#_(defn get-normalized-probability-distribution [boardseq]
(let [magnitude (apply #(apply + %) boardseq)]
(map #(map / (float %) magnitude)
(get-distribution boardseq))))
10 changes: 8 additions & 2 deletions src/battleship/game.clj
Expand Up @@ -35,6 +35,10 @@
(range (int \A) (int \K)) (:board dboard))
[top-bottom-border])))

; good for debugging
(defn print-board [board]
(dorun (map println (get-board-strs (DecoratedBoard. board nil nil) true))))

(defn print-message [dboard is-friendly]
nil)

Expand Down Expand Up @@ -93,14 +97,15 @@
(println
"Welcome to Battleship. Input some coordinates to fire, or 'Q' to quit.")
(loop [game (newgame)]
(printgame game)
(if (game-won? game)
(let [winner (get-winner game)]
(if (= winner 1)
(println "***YOU WIN!***")
(println "***YOU LOSE!***"))
nil)
(flush)
nil) ; returning nil not neccesary, but clarifies the code
(do
(printgame game)
(print "Fire: ")
(flush)
(let [input-line (read-line)
Expand All @@ -110,6 +115,7 @@
(= \Q letter)
(do
(println "Be seeing you...")
(flush)
nil)
(or (nil? letter) (nil? number))
(do
Expand Down

0 comments on commit 083418e

Please sign in to comment.