Haskelier
Haskelier

Reputation: 83

Accessing multiple data structures

I am writing a text-based adventure game in Haskell for experience after reading LYAH, but I need help writing a function in which two data structures (in this case two players) are accessed and another structure (another [attacked] player) is returned. Thanks!

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)

Upvotes: 0

Views: 71

Answers (1)

Boyd Stephen Smith Jr.
Boyd Stephen Smith Jr.

Reputation: 3202

Pattern matching or any of (many) other ways you can write a two-argument function? In addition you have various syntax that is only available to record types.

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

Please do research before posting on SO. The 3 "standard" beginner texts already explain this.

Upvotes: 3

Related Questions