我正在写一个Cardguess游戏,用户设置答案并让PC猜测。对于我的项目,输入卡号为2.
然后,我需要编写cardguess算法。 我创建了卡模块。
data Suit = Club | Diamond | Heart | Spade
deriving (Eq, Ord, Bounded, Enum)
suitchars = "CDHS"
data Rank =
R2 | R3 | R4 | R5 | R6 | R7 | R8 | R9 | R10 |
Jack | Queen | King | Ace
deriving (Eq, Ord, Bounded, Enum)
rankchars = "23456789TJQKA"
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)
我的策略是将Suit和Rank分成两部分。最初的猜测可能是Card Club R5
,Card Heart Jack
然后我将得到反馈,并且根据它,我会尝试nextGuess
,所以到目前为止,直到得到正确的答案。
我写了initialGuess
函数。
我把剩余的卡片放在GameState
。
initialGuess :: Int -> ([Card], GameState)
initialGuess card_number
| card_number == 2 = ((Card Club R5):(Card Heart J),cardDeck)
现在,我需要编写nextGuess
代码。
nextGuess :: ([Card],GameState) -> (Int,Int,Int,Int,Int) ->([Card],GameState)
(Int,Int,Int,Int,Int)
是反馈值。
我如何表示第一个参数([Card],GameState)
,这意味着之前的猜测卡和之前的GameState
。
答案 0 :(得分:1)
由于我不理解你的问题,而且你是初学者,我会在你的帖子的其他一些方面挑剔。
你有
initialGuess card_number
| card_number == 2 = ((Card Club R5):(Card Heart J),cardDeck)
接受您现在只需要initialGuess 2
工作,您的列表语法错误。你的意思是
initialGuess card_number
| card_number == 2 = (Card Club R5 : Card Heart J : [], cardDeck)
或
initialGuess card_number
| card_number == 2 = ([Card Club R5, Card Heart J], cardDeck)
他们的意思相同,但后者更清楚。
你有
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
如果您import Data.Monoid
,您可以更简单地将其写为
instance Ord Card where
compare (Card s1 r1) (Card s2 r2) = compare s1 s2 `mappend` compare r1 r2
但更好的方法是将其遗漏并要求编译器为您编写代码:
data Card = Card {suit::Suit, rank::Rank}
deriving (Eq, Ord, Bounded)
生成的Ord
实例根据您的需要使用词典排序。
答案 1 :(得分:1)
这里很难读懂你的想法,但也许你想要这样的东西:
startGuessing guesses state = do
feedBack <- readFeedback
let (newGuess, newState) = nextGuess (guesses, state) feedback
startGuessing (guesses ++ newGuess) newState
main = do
let (guesses, state) = initialGuess 2
startGuessing guesses state