Haskell- War 纸牌游戏

Haskell- War card Game

我正在尝试编写的规则之一是:

When the two players play cards of equal rank, this triggers a “war”. Each player sets down three cards, and then flips one more card. Whoever wins between these last two flipped cards gets to take all the cards in the round, including the 3 cards that were set down by each player. If those flipped cards match again, another war is triggered, which is resolved in the same way.

我可以在我的代码中实现第一轮 war,但是我遇到的问题是当两个玩家拿到同一张牌时开始第二轮 war再次。我遇到的问题是当第二轮 war 开始时,两名玩家将第一轮 war 的牌搁置一旁,第二轮 war 的所有牌都由谁拿到第二个 war 和第一个 war。 我不知道如何让我的 war 函数存储第一轮卡片,正如您在我的 otherwise 中看到的那样,我只是丢弃了第一轮的卡片。

war :: ([Int], [Int]) -> ([Int], [Int])
war (x:xs,y:ys)
 | head(drop 3 xs) > head(drop 3 (ys))  = (drop 4 (xs) ++ player1Pot (x:xs) ++ player2Pot (y:ys), drop 4 (ys))
 | head(drop 3 xs) < head(drop 3 (ys))  = (drop 4 (xs), drop 4 (ys) ++ player2Pot (y:ys) ++ player1Pot (x:xs))
 | otherwise  = war (drop 4 (xs),drop 4 (ys))

standardRound :: ([Int], [Int]) -> ([Int], [Int])
standardRound ([],y:ys) = ([],y:ys)
standardRound (x:xs,[]) = (x:xs,[])
standardRound (x:xs,y:ys)
 | x > y            = (xs ++ [y] ++ [x], ys)
 | y > x            = (xs, ys ++ [x] ++ [y])
 | otherwise        = war (x:xs,y:ys)

war 函数添加另一个参数。

war :: ([Int],[Int]) -> ([Int],[Int]) -> ([Int],[Int])
war (px,py) (x,y) = let
  [(xp',(xc:xr)),(yp',(yc:yr))] = map (splitAt 3) [x,y]
  in case xc `compare` yc of
    GT -> (xr ++ px ++ xp' ++ [xc] ++ py ++ yp' ++ [yc], yr)
    LT -> (xr, yr ++ py ++ yp' ++ [yc] ++ px ++ xp' ++ [xc])
    EQ -> war (px ++ xp' ++ [xc], py ++ yp' ++ [yc]) (xr,yr)

standardRound 函数的调用中:第一个参数应该是 ([],[]),在递归调用中它应该是卡片列表。

您可以使用 let ... in 提取元组的值

| otherwise = let (newxs,newys) = war (drop 4 xs, drop 4 ys) in
              (take 3 xs ++ newxs, take 3 ys ++ newys)

以便您可以返回修改后的版本。随心所欲地在之前或之后添加掉落的卡片。