about summary refs log tree commit diff
path: root/src/Xanthous/App/Autocommands.hs
diff options
context:
space:
mode:
Diffstat (limited to 'src/Xanthous/App/Autocommands.hs')
-rw-r--r--src/Xanthous/App/Autocommands.hs44
1 files changed, 44 insertions, 0 deletions
diff --git a/src/Xanthous/App/Autocommands.hs b/src/Xanthous/App/Autocommands.hs
new file mode 100644
index 000000000000..e8d94ce741fd
--- /dev/null
+++ b/src/Xanthous/App/Autocommands.hs
@@ -0,0 +1,44 @@
+--------------------------------------------------------------------------------
+module Xanthous.App.Autocommands
+  ( runAutocommand
+  , autoStep
+  ) where
+--------------------------------------------------------------------------------
+import Xanthous.Prelude
+--------------------------------------------------------------------------------
+import Control.Concurrent (threadDelay)
+--------------------------------------------------------------------------------
+import Xanthous.App.Common
+import Xanthous.App.Time
+import Xanthous.Data
+import Xanthous.Data.App
+import Xanthous.Entities.Character (speed)
+import Xanthous.Game.State
+--------------------------------------------------------------------------------
+
+autoStep :: Autocommand -> AppM ()
+autoStep (AutoMove dir) = do
+  newPos <- uses characterPosition $ move dir
+  collisionAt newPos >>= \case
+    Nothing -> do
+      characterPosition .= newPos
+      stepGameBy =<< uses (character . speed) (|*| 1)
+      describeEntitiesAt newPos
+    Just _ -> cancelAutocommand
+
+--------------------------------------------------------------------------------
+
+autocommandIntervalμs :: Int
+autocommandIntervalμs = 1000 * 50 -- 50 ms
+
+runAutocommand :: Autocommand -> AppM ()
+runAutocommand ac = do
+  env <- ask
+  tid <- liftIO . async $ runReaderT go env
+  autocommand .= ActiveAutocommand ac tid
+  where
+    go = everyμs autocommandIntervalμs $ sendEvent AutoContinue
+
+-- | Perform 'act' every μs microseconds forever
+everyμs :: MonadIO m => Int -> m () -> m ()
+everyμs μs act = act >> liftIO (threadDelay μs) >> everyμs μs act