<h2 id="intro">Intro</h2>
<p>I was tasked to write kragii worms in the game and informed that they’re small (10cm / 4 inches) long worms that burrow in ground and are drawn to farming fields and people. They’re dangerous and might eat harvest or people.</p>
<p>Special events build on top of the new system I explained in <a href="https://hackerpublicradio.org/eps.php?id=2733">episode 2733</a>. They are read from same API as regular news and need same <code>ToJSON</code>, <code>FromJSON</code>, <code>ToDto</code> and <code>FromDto</code> instances as regular news (for translating them data transfer objects and then into JSON for sending to client).</p>
<h2 id="loading">Loading</h2>
<p>Starting from the API interface, the first real difference is when JSON stored into database is turned into <code>NewsArticle</code>. Two cases, where special news have available options added to them and regular news are left unchanged. These options tell player what choices they have when dealing with the situation and evaluated every time special event is loaded, because situation might have changed since special event got stored into database and available options might have changed.</p>
<pre><code>addOptions (key, article) = case article of
                                Special news -&gt;
                                    (key, Special $ availableOptions news)
                                _ -&gt;
                                    (key, article)

availableOptions :: SpecialNews -&gt; SpecialNews
availableOptions x =
    case x of
        KragiiWorms event _ choice -&gt;
            KragiiWorms event (eventOptions event) choice</code></pre>
<p><code>eventOptions</code> is one of the events defined in <code>SpecialEvent</code> type class that specifies two functions every special event has to have. <code>eventOptions</code> lists what options the event has currently available and <code>resolveEvent</code> resolves the event according to choice user might have made (hence <code>Maybe</code> in it).</p>
<p>Type class is parametrized with three types (imaginatively named to <code>a</code>, <code>b</code> and <code>c</code>). First is data type that holds information about special event (where it’s happening and to who for example), second one is one that tells all possible choices player has and third one lists various results that might occur when resolving the event. In this example they’re <code>KragiiWormsEvent</code>, <code>KragiiWormsChoice</code> and <code>KragiiResults</code>.</p>
<pre><code>data KragiiWormsEvent = KragiiWormsEvent
    { kragiiWormsPlanetId   :: Key Planet
    , kragiiWormsPlanetName :: Text
    , kragiiWormsSystemId   :: Key StarSystem
    , kragiiWormsSystemName :: Text
    , kragiiWormsDate       :: Int
    }

data KragiiWormsChoice =
    EvadeWorms
    | AttackWorms
    | TameWorms

data KragiiResults =
    WormsStillPresent
    | WormsRemoved
    | WormsTamed
    | CropsDestroyed (RawResource Biological)
    | FarmersInjured</code></pre>
<p>Definition of the <code>SpecialEvent</code> type class is shown below. Type signature of <code>resolveEvent</code> is gnarly because it’s reading and writing database.</p>
<pre><code>class SpecialEvent a b c | a -&gt; b, a -&gt; c where
    eventOptions :: a -&gt; [UserOption b]
    resolveEvent :: ( PersistQueryRead backend, PersistQueryWrite backend
                    , MonadIO m, BaseBackend backend ~ SqlBackend ) =&gt;
                    (Key News, a) -&gt; Maybe b -&gt; ReaderT backend m (Maybe EventRemoval, [c])</code></pre>
<p>One more piece we need is <code>UserOption</code>. This records options in a format that is useful in the client side. Each option player has are given title and explanation that are shown on UI.</p>
<pre><code>data UserOption a =
    UserOption { userOptionTitle :: Text
               , userOptionExplanation :: [Text]
               , userOptionChoice :: a
               }</code></pre>
<p>Current implementation of <code>eventOptions</code> doesn’t allow database access, but I’m planning on adding that at the point where I need it. Example doesn’t show all different options, as they all have same structure. Only first option in the list is shown:</p>
<pre><code>eventOptions _ = [ UserOption { userOptionTitle = &quot;Avoid the worms&quot;
                              , userOptionExplanation = [ &quot;Keep using fields, while avoiding the worms and hope they&#39;ll eventually leave.&quot;
                                                        , &quot;50 units of biologicals lost&quot;
                                                        , &quot;25% chance of worms leaving&quot;
                                                        ]
                              , userOptionChoice = EvadeWorms
                            }
                   , ...
                   ]</code></pre>
<h2 id="making-choice">Making choice</h2>
<p><code>putApiMessageIdR</code> handles updating news with <code>HTTP PUT</code> messages. First steps is to check that caller has autenticated and retrieve id of their faction. News article that is transferred in body as JSON is parsed and checked for type. Updating regular news articles isn’t supported and is signaled with <code>HTTP 403</code> status code. One more check to perform is to check that news article being edited actually belong to the faction player is member of. If that’s not the case <code>HTTP 404</code> message is returned.</p>
<p>If we got this far, news article is updated with the content sent by client (that also contains possible choice made by user). There’s no check that type of news article doesn’t change or that the option selected doesn’t change (I need to add these at later point). In the end, list of all messages is returned back to the client.</p>
<pre><code>putApiMessageIdR :: Key News -&gt; Handler Value
putApiMessageIdR mId = do
    (_, _, fId) &lt;- apiRequireFaction
    msg &lt;- requireJsonBody
    let article = fromDto msg
    _ &lt;- if isSpecialEvent article
            then do
                loadedMessages &lt;- runDB $ selectList [ NewsId ==. mId
                                                     , NewsFactionId ==. fId ] [ Asc NewsDate ]
                if length loadedMessages == 0
                    then apiNotFound
                    else runDB $ update mId [ NewsContent =. (toStrict $ encodeToLazyText article) ]
            else apiForbidden &quot;unsupported article type&quot;
    loadAllMessages fId</code></pre>
<h2 id="resolving-event">Resolving event</h2>
<p>Special event occured, user made (or did not) a choice. Now it’s time to simulate what happens. Below is <code>resolveEvent</code> for kragii attack.</p>
<pre><code>resolveEvent keyEventPair (Just choice) =
    runWriterT . runMaybeT $
        case choice of
                EvadeWorms -&gt;
                    chooseToAvoid keyEventPair

                AttackWorms -&gt;
                    chooseToAttack keyEventPair

                TameWorms -&gt;
                    chooseToTame keyEventPair

resolveEvent keyEventPair Nothing =
    runWriterT . runMaybeT $ noChoice keyEventPair</code></pre>
<p><code>runWriterT</code> and <code>runMaybeT</code> are used as code being called uses monad transformers to add some extra handling. <code>WriterT</code> adds ability to record data (<code>KragiiResult</code> in this case) and <code>MaybeT</code> adds ability to stop computation early if one of the steps return <code>Nothing</code> value.</p>
<p>Let’s walk through what happens when user has chosen to avoid kragii worms and keep working only part of the fields. First step is to load faction information. If faction couldn’t be found, we abort. Next amount of biological matter consumed and how much is left is calculated. Again, if calculation isn’t possible, we’ll abort. This step reaches into database and updates amount of biological matter stored by the faction (again, possibility to stop early). Final step is to check if kragii leave or not (again, chance of abort).</p>
<pre><code>chooseToAvoid :: ( MonadIO m, PersistQueryWrite backend
                 , BaseBackend backend ~ SqlBackend ) =&gt;
                 (Key News, KragiiWormsEvent)
                 -&gt; MaybeT (WriterT [KragiiResults] (ReaderT backend m)) EventRemoval
chooseToAvoid (_, event) = do
    faction &lt;- getFaction event
    (cost, bioLeft) &lt;- calculateNewBio (RawResource 50) (entityVal faction)
    _ &lt;- destroyCrops faction cost bioLeft
    removeNews $ PercentileChance 25</code></pre>
<p>Loading faction has several step. Id is stored in the event is used to load planet. Planet might or might have an owner faction, depending on if it has been settled. This faction id is used to load faction data. Loading might fail if corresponding record has been removed from database and planet might not be settled at the given time. Any of these cases will result <code>Nothing</code> be returned and whole event resolution being aborted. I’m starting to really like that I don’t have to write separate <code>if</code> statements to take care of these special cases.</p>
<pre><code>getFaction :: ( MonadIO m, PersistStoreRead backend
              , BaseBackend backend ~ SqlBackend ) =&gt;
              KragiiWormsEvent
              -&gt; MaybeT (WriterT [KragiiResults] (ReaderT backend m)) (Entity Faction)
getFaction event = MaybeT $ do
    planet &lt;- lift $ get $ kragiiWormsPlanetId event
    let owner = join $ fmap planetOwnerId planet
    res &lt;- lift $ mapM getEntity owner
    return $ join res</code></pre>
<p>Amount of biological matter in store is stored in faction information. If it’s zero or less, <code>Nothing</code> is returned as there’s nothing to do really. In other cases, amount of biological matter left is calculated and result returned in form of <code>( cost, biological matter left )</code>. I’m carrying around the cost, as it’s later needed for reporting how much matter was removed.</p>
<pre><code>calculateNewBio :: Monad m =&gt;
                RawResource Biological -&gt; Faction
                -&gt; MaybeT (WriterT [KragiiResults] m) ((RawResource Biological), (RawResource Biological))
calculateNewBio cost faction = MaybeT $ do
    let currentBio = factionBiologicals faction
    return $ if currentBio &gt; 0
                then Just $ ( cost
                            , RawResource $ max 0 (currentBio - unRawResource cost))
                else Nothing</code></pre>
<p><code>destroyCrops</code> updates database with new amount of biological matter in store for the faction and records amount of destruction in <code>CropsDestroyed</code>. <code>tell</code> requires that we have <code>Writer</code> at our disposal and makes recording information nice and easy.</p>
<pre><code>destroyCrops :: ( MonadIO m, PersistQueryWrite backend, BaseBackend backend ~ SqlBackend ) =&gt;
                Entity Faction -&gt; RawResource Biological
                -&gt; RawResource Biological -&gt; MaybeT (WriterT [KragiiResults] (ReaderT backend m)) ()
destroyCrops faction cost bioLeft = MaybeT $ do
    _ &lt;- lift $ updateWhere [ FactionId ==. entityKey faction ]
                            [ FactionBiologicals =. unRawResource bioLeft ]
    tell [ CropsDestroyed cost ]
    return $ Just ()</code></pre>
<p>Final step is to roll a percentile die against given odds and see what happens. In case of <code>Success</code>, we record that worms were removed and value of function will be <code>Just RemoveOriginalEvent</code>. If we didn’t beat the odds, <code>WormsStillPresent</code> gets recorded and value of function is <code>Just KeepOriginalEvent</code>. Return value will then be used later to mark special event handled.</p>
<pre><code>removeNews :: ( PersistStoreWrite backend, MonadIO m, BaseBackend backend ~ SqlBackend ) =&gt;
              PercentileChance -&gt; MaybeT (WriterT [KragiiResults] (ReaderT backend m)) EventRemoval
removeNews odds = MaybeT $ do
res &lt;- liftIO $ roll odds
    case res of
        Success -&gt; do
            _ &lt;- tell [ WormsRemoved ]
            return $ Just RemoveOriginalEvent
        Failure -&gt; do
            _ &lt;- tell [ WormsStillPresent ]
            return $ Just KeepOriginalEvent</code></pre>
<p>So result of this whole matter is:</p>
<pre><code>( [KragiiResults], Maybe EventRemoval )</code></pre>
<p>and whole lot of database activity.</p>
<h2 id="handling-events-during-simulation">Handling events during simulation</h2>
<p>Pieces are now in place, time to put things in motion. When handling special events for a faction, first step is to load all unhandled ones and then call <code>handleSpecialEvent</code> for each of them.</p>
<pre><code>handleFactionEvents :: (BaseBackend backend ~ SqlBackend
                       , PersistStoreWrite backend, PersistQueryRead backend
                       , PersistQueryWrite backend, MonadIO m) =&gt;
                       Time -&gt; Entity Faction -&gt; ReaderT backend m [Key News]
handleFactionEvents date faction = do
    loadedMessages &lt;- selectList [ NewsFactionId ==. (entityKey faction)
                                 , NewsSpecialEvent ==. UnhandledSpecialEvent ] [ Desc NewsDate ]
    let specials = mapMaybe extractSpecialNews $ parseNewsEntities loadedMessages
    mapM (handleSpecialEvent (entityKey faction) date) specials</code></pre>
<p><code>resolveEvent</code> resolves event based on choice user maybe made (this is what we explored earlier in the episode). Depending on the result of <code>resolveEvent</code>, event gets marked to handled and dismissed. In any case, a news article spelling out what happend is created and saved.</p>
<pre><code>handleSpecialEvent :: (PersistQueryWrite backend, MonadIO m
                      , BaseBackend backend ~ SqlBackend) =&gt;
                      Key Faction -&gt; Time -&gt; (Key News, SpecialNews) -&gt; ReaderT backend m (Key News)
handleSpecialEvent fId date (nId, (KragiiWorms event _ choice)) = do
    (removal, results) &lt;- resolveEvent (nId, event) choice
    _ &lt;- when (removal /= Just KeepOriginalEvent) $
                    updateWhere [ NewsId ==. nId ]
                                [ NewsSpecialEvent =. HandledSpecialEvent
                                , NewsDismissed =. True ]
    insert $ report fId date event choice results</code></pre>
<p>Result article creation is abstracted by <code>ResultReport</code> type class. It has single function <code>report</code> that takes parameters: database key of the faction the event concerns of, current time, special event that was processed, choice that was made and list of records telling what happened during resolution. It will return <code>News</code> that is ready to be saved into database.</p>
<pre><code>class ResultsReport a b c | a -&gt; b, a -&gt; c where
report :: Key Faction -&gt; Time -&gt; a -&gt; Maybe b -&gt; [c] -&gt; News</code></pre>
<ul>
<li>quite long and verbose instance</li>
<li>essentially take event, choice and results and build a string explaining what actually happened</li>
<li>&lt;&gt; is monoid operation for combining things, here used for text</li>
</ul>
<p>Instance declaration is pretty long, because there’s many different cases to account for and by definition they’re all pretty verbose. I have included it in its entirity below, as it might be interesting to glance over and see different kinds of combinations that resolution might create.</p>
<pre><code>instance ResultsReport KragiiWormsEvent KragiiWormsChoice KragiiResults where
    report fId date event choice results =
        let
            content = KragiiNews { kragiiNewsPlanetId = kragiiWormsPlanetId event
                                 , kragiiNewsPlanetName = kragiiWormsPlanetName event
                                 , kragiiNewsSystemId = kragiiWormsSystemId event
                                 , kragiiNewsSystemName = kragiiWormsSystemName event
                                 , kragiiNewsExplanation = repText
                                 , kragiiNewsDate = timeCurrentTime date
                                 }
        in
            mkNews fId date $ KragiiResolution content
        where
            repText = header choice &lt;&gt; &quot; &quot; &lt;&gt; removed choice (WormsRemoved `elem` results) &lt;&gt; &quot; &quot; &lt;&gt; injury &lt;&gt; &quot; &quot; &lt;&gt; destruction &lt;&gt; &quot; &quot;

            header (Just EvadeWorms) = &quot;Local farmers had chosen to work on their fields, while avoiding the kragii worms.&quot;
            header (Just AttackWorms) = &quot;Local farmers had decided to attack the worms with chemicals and burning.&quot;
            header (Just TameWorms) = &quot;Decision to try and tame the kragii had been taken.&quot;
            header Nothing = &quot;No decision what to do about worms had been taken.&quot;

            removed (Just EvadeWorms) True = &quot;After some time, there has been no new kragii sightings and it seems that the threat is now over.&quot;
            removed (Just AttackWorms) True = &quot;Attacks seem to have worked and there has been no new kragii sightings.&quot;
            removed (Just TameWorms) True = &quot;Kragii has been tamed and put into use of improving soil quality.&quot;
            removed Nothing True = &quot;Despite farmers doing nothing at all about the situation, kragii worms disappeared eventually.&quot;
            removed (Just EvadeWorms) False = &quot;Kragii are still present on the planet and hamper farming operations considerability.&quot;
            removed (Just AttackWorms) False = &quot;Despite the best efforts of farmers, kragii threat is still present.&quot;
            removed (Just TameWorms) False = &quot;Taming of the worms was much harder than anticipated and they remain wild.&quot;
            removed Nothing False = &quot;While farmers were debating best course of action, kragii reigned free and destroyed crops.&quot;

            injury = if FarmersInjured `elem` results
                        then &quot;Some of the personnel involved in the event were seriously injured.&quot;
                        else &quot;There are no known reports of personnel injuries.&quot;

            totalDestroyed = mconcat $ map (x -&gt; case x of
                                                    CropsDestroyed n -&gt; n
                                                    _ -&gt; mempty) results
            destruction = if totalDestroyed &gt; RawResource 0
                            then &quot;In the end, &quot; &lt;&gt; pack (show (unRawResource totalDestroyed)) &lt;&gt; &quot; units of harvest was destroyed.&quot;
                            else &quot;Despite of all this, no harvest was destroyed.&quot;</code></pre>
<p>While there are still pieces left that need a bit work or are completely missing, the overall structure is in place. While this one took quite a bit of work to get working, I’m hoping that the next special event will be a lot easier to implement. Thanks for listening the episode.</p>
<p>Easiest way to catch me nowdays is either via email or on fediverse where I’m Tuula@mastodon.social</p>
