Clojure - 从矢量中删除项目以表示从卡片处理

时间:2013-03-23 07:49:01

标签: clojure

我有一个向量矢量,我用来代表一副牌:

[["A" "D"] ["K" "H"] ["K" "C"] ["K" "S"] ["K" "D"] ["Q" "H"] ["Q" "C"] ["Q" "S"]
 ["Q" "D"] ["J" "H"] ["J" "C"] ["J" "S"] ["J" "D"] ["T" "H"] ["T" "C"] ["T" "S"]
 ["T" "D"] ["9" "H"] ["9" "C"] ["9" "S"] ["9" "D"] ["8" "H"] ["8" "C"] ["8" "S"]
 ["8" "D"] ["7" "H"] ["7" "C"] ["7" "S"] ["7" "D"] ["6" "H"] ["6" "C"] ["6" "S"]
 ["6" "D"] ["5" "H"] ["5" "C"] ["5" "S"] ["5" "D"] ["4" "H"] ["4" "C"] ["4" "S"]
 ["4" "D"] ["3" "H"] ["3" "C"] ["3" "S"] ["3" "D"] ["2" "H"] ["2" "C"] ["2" "S"]
 ["2" "D"]]

在某些时候,我想"交易"一些卡片,并从卡座上取下那些卡片。

如果您想告诉我使用seq并且实际上我的原始版本是一系列向量,那也没关系,所以对我来说这两种方式都没有关系。

我知道我可能想要创建一个原子"剩余甲板"并从此seq或向量中删除项目。

我打算开源这个,这是代码的相关部分:

(def suits ["H" "C" "S" "D"])
(def ranks ["A" "K" "Q" "J" "T" "9" "8" "7" "6" "5" "4" "3" "2"])

(def deck (for [x ranks
                y suits]
            [x y]))


;; alternative deck that creates vector:

(def deck2 (vec (for [x ranks
                y suits]
            [x y])))

;;Another way to do it: While it's fine if I have a sequence of string pairs, I'd rather use vectors of vectors because I think destructuring will work better plus I think it'll be consistent across the program. 

(def deck3 (for [x ranks
                y suits]
            (str x y)))


(def hand [(rand-nth deck) (rand-nth deck)])

(def full-hand (concat board hand))

看起来我可以通过使用一些.indexOf函数并将其抛入一个原子来连接subvecs但是我不能帮助但是认为这是hacky并且Lisp应该能够比这更好。我真的无法在任何地方找到任何有用的信息。我知道删除和过滤,但那些似乎没有做任何事情,但抛出错误。


编辑:为什么选择downvote?我只是在交易牌后尝试更新牌组。

因此,如果我代表一个较小的套牌:

[["A" "D"] ["K" "H"] ["K" "C"] ["K" "S"] ["K" "D"] ["Q" "H"] ["Q" "C"] ["Q" "S"]]

然后更新后(例如:玩家是交易[" Q"" S"] [" Q"" C"] ,剩下的套牌应该是这样的:

[["A" "D"] ["K" "H"] ["K" "C"] ["K" "S"] ["K" "D"] ["Q" "H"]]

因此在交易剩余时间内没有共用手牌或重复牌。

2 个答案:

答案 0 :(得分:2)

我不确定我是否理解你的问题,但无论我收集了什么,我都会将套牌代表一个包裹在原子中的套牌,每一手牌都会更新原子。

(def suits ["H" "C" "S" "D"])
(def ranks ["A" "K" "Q" "J" "T" "9" "8" "7" "6" "5" "4" "3" "2"])

(def deck (atom  (->> (for [x ranks
                            y suits]
                        [x y])
                      (into #{}))))

(defn hand []
  (-> (rand-int (count @deck))
      (drop @deck)
      (first)))

(defn play-hand []
  (swap! deck clojure.set/difference #{(hand)}))

(play-hand)

答案 1 :(得分:1)

我知道这已经接受了答案,但你确信你想在这里介绍州吗?我会考虑将deck作为参数传递给hand等。当你想要并行交易时会发生什么?