3

Clojureを学ぶ練習として、スパイダーソリティアプレーヤーを書こうとしています。カードの配り方を考えています。

私は(stackoverflowの助けを借りて)2つの標準デッキから104枚のカードのシャッフルされたシーケンスを作成しました。各カードは、

(defstruct card :rank :suit :face-up)

Spiderのタブローは次のように表されます。

(defstruct tableau :stacks :complete)

ここで、:stacksはカードベクトルのベクトルであり、そのうち4枚は表向きに5枚、表向きに1枚、6枚は表向きに4枚、表向きに1枚、合計54枚のカードを含みます。完成したエースキングのセットの(最初は)空のベクトル(たとえば、印刷目的ではキングハートとして表されます)。undealtデッキの残りはrefに保存する必要があります

(def deck (ref seq))

ゲーム中、タブローには次のようなものが含まれる場合があります。

(struct-map tableau
  :stacks [[AH 2C KS ...]
           [6D QH JS ...]
           ...
           ]
  :complete [KC KS])

ここで、「AH」は{:rank:ace:suit:hearts:face-upfalse}などを含むカードです。

スタックを処理して残りを参照に保存する関数を作成するにはどうすればよいですか?

4

2 に答える 2

2

上記の答えを研究した後に私が思いついた解決策は次のとおりです。私はまだそれを改良していることに注意してください、そして改善のための提案、特により慣用的なClojureの使用を歓迎します。また、これらの関数はいくつかの個別のファイルで定義されており、必ずしも示されている順序で表示されるとは限らないことに注意してください(違いが生じる場合)。

(def suits [:clubs :diamonds :hearts :spades])
(def suit-names
  {:clubs "C" :diamonds "D"
   :hearts "H" :spades "S"})

(def ranks
  (reduce into (replicate 2
    [:ace :two :three :four :five :six :seven :eight :nine :ten :jack :queen :king])))
(def rank-names
  {:ace "A" :two "2"
   :three "3" :four "4"
   :five "5" :six "6"
   :seven "7" :eight "8"
   :nine "9" :ten "T"
   :jack "J" :queen "Q"
   :king "K"})

(defn card-name
  [card show-face-down]
  (let
    [rank (rank-names (:rank card))
     suit (suit-names (:suit card))
     face-down (:face-down card)]
    (if
      face-down
      (if
        show-face-down
        (.toLowerCase (str rank suit))
        "XX")
      (str rank suit))))

(defn suit-seq
  "Return 4 suits:
  if number-of-suits == 1: :clubs :clubs :clubs :clubs
  if number-of-suits == 2: :clubs :diamonds :clubs :diamonds
  if number-of-suits == 4: :clubs :diamonds :hearts :spades."
  [number-of-suits]
  (take 4 (cycle (take number-of-suits suits))))

(defstruct card :rank :suit :face-down)

(defn unshuffled-deck
  "Create an unshuffled deck containing all cards from the number of suits specified."
  [number-of-suits]
  (for
    [rank ranks suit (suit-seq number-of-suits)]
    (struct card rank suit true)))

(defn shuffled-deck
  "Create a shuffled deck containing all cards from the number of suits specified."
  [number-of-suits]
  (shuffle (unshuffled-deck number-of-suits)))

(defn deal-one-stack
  "Deals a stack of n cards and returns a vector containing the new stack and the rest of the deck."
  [n deck]
  (loop
    [stack []
     current n
     rest-deck deck]
    (if (<= current 0)
      (vector
        (vec
          (reverse
            (conj
              (rest stack)
              (let
                [{rank :rank suit :suit} (first stack)]
                (struct card rank suit false)))))
        rest-deck)
      (recur (conj stack (first rest-deck)) (dec current) (rest rest-deck)))))

(def current-deck (ref (shuffled-deck 4)))

(defn deal-initial-tableau
  "Deals the initial tableau and returns it. Sets the @deck to the remainder of the deck after dealing."
  []
  (dosync
    (loop
      [stacks []
       current 10
       rest-deck @current-deck]
      (if (<= current 0)
        (let [t (struct tableau (reverse stacks) [])
              r rest-deck]
          (ref-set current-deck r)
          t)
        (let
          [n (if (<= current 4) 6 5)
           [s r] (deal-one-stack n rest-deck)]
          (recur (vec (conj stacks s)) (dec current) r))))))

(defstruct tableau :stacks :complete)

(defn pretty-print-tableau
  [tableau show-face-down]
  (let
    [{stacks :stacks complete :complete} tableau]
    (apply str
      (for
        [row (range 0 6)]
        (str
          (apply str
            (for
              [stack stacks]
              (let
                [card (nth stack row nil)]
                (str
                  (if
                    (nil? card)
                    "  "
                    (card-name card show-face-down)) " "))))
          \newline)))))
于 2010-04-26T11:15:08.190 に答える
0

chunks特定のシーケンスからそれぞれアイテムのベクトルを取得する関数とsize、それらのチャンクを前面から削除する別の関数を作成できます。

;; note the built-in assumption that s contains enough items;
;; if it doesn't, one chunk less then requested will be produced
(defn take-chunks [chunks size s]
  (map vec (partition size (take (* chunks size) s))))

;; as above, no effort is made to handle short sequences in some special way;
;; for a short input sequence, an empty output sequence will be returned
(defn drop-chunks [chunks size s]
  (drop (* chunks size) s))

次に、両方を実行する関数を追加します(との後split-atにモデル化split-with):

(defn split-chunks [chunks size s]
  [(take-chunks chunks size s)
   (drop-chunks chunks size s)])

各カードが最初{:face-up false}にあると仮定すると、次の関数を使用して、スタックの最後のカードをめくることができます。

(defn turn-last-card [stack]
  (update-in stack [(dec (count stack)) :face-up] not))

次に、指定されたデッキから初期スタック/チャンクを処理する関数:

(defn deal-initial-stacks [deck]
  (dosync
    (let [[short-stacks remaining] (split-chunks 6 5 deck)
          [long-stacks remaining] (split-chunks 4 6 remaining)]
      [remaining
       (vec (map turn-last-card
                 (concat short-stacks long-stacks)))])))

戻り値は、最初の要素がデッキの残りの部分であり、2番目の要素が初期スタックのベクトルであるダブルトンベクトルです。

次に、これをトランザクションで使用して、参照を考慮に入れます。

(dosync (let [[new-deck stacks] (deal-initial-stacks @deck-ref)]
          (ref-set deck-ref new-deck)
          stacks))

さらに良いことに、ゲームの状態全体を単一のRefまたはAtomに保持し、ref-setからalter/に切り替えswap!ます(この例ではRefを使用し、代わりにアトムを使用するようにdosync切り替えます):alterswap!

;; the empty vector is for the stacks
(def game-state-ref (ref [(get-initial-deck) []]))

;; deal-initial-stacks only takes a deck as an argument,
;; but the fn passed to alter will receive a vector of [deck stacks];
;; the (% 0) bit extracts the first item of the vector,
;; that is, the deck; you could instead change the arguments
;; vector of deal-initial-stacks to [[deck _]] and pass the
;; modified deal-initial-stacks to alter without wrapping in a #(...)
(dosync (alter game-state-ref #(deal-initial-stacks (% 0))))

免責事項:これはどれもテストの注目を少しも受けていません(私はそれがうまくいくはずだと思いますが、私が見逃したかもしれない愚かなタイプミスを法として)。でも、それはあなたの練習なので、テスト/研磨の部分はあなたに任せてもいいと思います。:-)

于 2010-04-24T19:44:11.717 に答える