我正在阅读LYAH后在Haskell写一个基于文本的冒险游戏,但我需要帮助编写一个函数,其中访问两个数据结构(在这种情况下是两个玩家)和另一个结构(另一个[攻击]玩家)被退回。谢谢!
data Player = Player { name :: String
, hp :: Int
, atk :: Int
, def :: Int
, spd :: Int
} deriving (Show, Eq)
data Qstat = Qstat Int Int Int Int
lv :: Qstat
lv = Qstat 1 1 1 1
describe :: Player -> String
describe (Player {name = n, hp = h, atk = a, def = d, spd = s})
= "Name: " ++ n
++ ", HP: " ++ (show h)
++ ", ATK: " ++ (show a)
++ ", DEF: " ++ (show d)
++ ", SPD: " ++ (show s)
promote :: Qstat -> Player -> Player
promote (Qstat w x y z) (Player {name = n, hp = h, atk = a, def = d, spd = s})
= Player n (h + w) (a + x) (d + y) (s + z)
gets :: Player -> Qstat
gets (Player {name = n, hp = h, atk = a, def = d, spd = s})
= Qstat n h a d s
attack :: Player -> Player -> Player
attack = --how can I access the stats of both players (preferably without do notation)
答案 0 :(得分:3)
模式匹配或任何(很多)其他方法可以编写双参数函数?此外,您还有各种语法,仅适用于记录类型。
attack :: Player -> Player -> Player
attack aggressor defender = victim { hp = max 0 $ hp victim - dmg }
where
aQual = atk aggressor + spd aggressor
dQual = def defender + spd defender
(victor, victim) = case compare aQual dQual of
LT -> (defender, aggressor)
_ -> (aggressor, defendor)
dmg = max 1 $ atk victor - def victim
请在发布SO之前进行研究。 3个“标准”初学者文本已经解释了这一点。