我正在写一个猜卡游戏,这个游戏有3张目标牌,每次玩家选择3张牌作为他们的猜测。在那之后,玩家将获得3个整数反馈作为正确的牌,套装和等级的三倍,并返回一对下一个猜测和游戏状态
到现在为止,我已经定义了自己的卡片类型。代码如下所示
data Suit = Club | Diamond | Heart | Spade
deriving (Eq, Ord, Bounded, Enum, Show)
data Rank =
R2 | R3 | R4 | R5 | R6 | R7 | R8 | R9 | R10 |
Jack | Queen | King | Ace
deriving (Eq, Ord, Bounded, Enum, Show)
data Card = Card {suit::Suit, rank::Rank}
deriving (Eq, Bounded)
instance Ord Card where
compare (Card s1 r1) (Card s2 r2) =
let suitorder = compare s1 s2
in if suitorder == EQ then compare r1 r2 else suitorder
instance Enum Card where
fromEnum (Card s r) = (fromEnum s)*13 + (fromEnum r)
toEnum n = (Card s r)
where s = toEnum (n `div` 13)
r = toEnum (n `mod` 13)
instance Show Card where
show (Card s r) = show r ++ show s
type GameState = [[Card]] -- store the remaining possible cards
现在我需要根据问题的要求编写2个函数
initialGuess :: ([String],GameState)
不接受任何输入参数,并返回一对初始猜测和游戏状态
nextGuess :: ([String],GameState) -> (Int,Int,Int) -> ([String],GameState)
将一对先前的猜测和游戏状态,对该猜测的反馈以及一对下一个猜测和游戏状态作为输入。
现在我必须将[String]转换为我定义的[Card]类型,但我仍然坚持这种转换。
我当前的initialGuess显示在下面
initialGuess::([String], GameState)
initialGuess = let guess = [(Card Club R2),(Card Club R3),(Card Club R4)]
gs = FilterGameState
in (guess, gs)
..... -not complete yet
FilterGameState :: [[Card]]
FilterGameState = filter ([x,y,z]) decks
where decks = [[x,y,z] | x <- [minBound..maxBound] :: [Card],
y <- [minBound..maxBound] :: [Card],
z <- [minBound..maxBound] :: [Card]]
我仍然很难想出一种方法将initialGuess函数中的'guess'转换为字符串:(还有更多建议吗?
答案 0 :(得分:2)
您可以将Card定义为Read:
的实例data Suit = Club | Diamond | Heart | Spade
deriving (Eq, Ord, Bounded, Enum, Show, Read)
data Rank =
R2 | R3 | R4 | R5 | R6 | R7 | R8 | R9 | R10 |
Jack | Queen | King | Ace
deriving (Eq, Ord, Bounded, Enum, Show, Read)
data Card = Card {suit::Suit, rank::Rank}
deriving (Eq, Bounded)
instance Show Card where
show (Card s1 r1) = show s1 ++ " " ++ show r1
instance Read Card where
readsPrec i s = [(Card s1 r1, s'')
| (s1, s') <- readsPrec i s,
(r1, s'') <- readsPrec i s']
main = print $ (read "Club R3" :: Card)
(您将卡片表示为字符串的方式略有变化)。