diff --git a/AStar.hs b/AStar.hs
new file mode 100644
--- /dev/null
+++ b/AStar.hs
@@ -0,0 +1,17 @@
+module AStar where
+
+import           Data.Graph.AStar
+
+import           Data.Hashable
+
+import qualified Data.HashSet     as HS
+
+-- find all min-length paths
+aStarAll :: (Hashable a, Ord a, Ord c, Num c) =>
+         (a -> HS.HashSet a) -> (a -> c) -> (a -> Bool) -> a -> [[a]]
+aStarAll graph heur goal start = go Nothing HS.empty where
+    go optLen exclude = case aStar graph' dist heur goal start of
+            Just path@(first:_) | maybe True (length path ==) optLen -> path : go (Just $ length path) (HS.insert first exclude)
+            _ -> []
+        where graph' v = graph v `HS.difference` exclude
+    dist = const $ const 1
diff --git a/Board.hs b/Board.hs
new file mode 100644
--- /dev/null
+++ b/Board.hs
@@ -0,0 +1,639 @@
+{-# LANGUAGE LambdaCase #-}
+
+module Board where
+
+import           Control.Monad.Random
+import           Control.Monad.Writer
+import           Data.Bifunctor
+import           Data.Function         (on)
+import           Data.Functor          (($>))
+import           Data.Functor.Identity
+import           Data.Maybe
+import           Safe
+
+import qualified Data.HashSet          as HS
+import qualified Data.Map.Strict       as M
+import qualified Data.Set              as S
+
+import qualified BoardConf             as BC
+import qualified Pos                   as P
+import qualified Power                 as Pow
+import qualified RollFrom              as RF
+
+import           AStar
+import           Creature
+import           Exit
+import           Group
+import           Item
+import           Rand
+import           Wall
+
+w,h :: Int
+w = 5
+h = 5
+
+inBounds :: P.Pos -> Bool
+inBounds (P.Pos x y) = 0 <= x && x < w && 0 <= y && y < h
+
+inBoundsW :: P.WPos -> Bool
+inBoundsW = all inBounds . P.adjPoss
+
+poss :: S.Set P.Pos
+poss = S.fromList [ P.Pos x y | x <- [0..w-1], y <- [0..h-1] ]
+
+wPoss :: S.Set P.WPos
+wPoss = S.fromList [ wp | p <- S.toList poss, up <- [True,False], let wp = P.WPos p up, all inBounds $ P.adjPoss wp ]
+
+boundaryWPoss :: S.Set P.WPos
+boundaryWPoss = S.fromList $
+     [ P.WPos (P.Pos x y) True | x <- [0..w-1], y <- [-1,h-1] ]
+     <> [ P.WPos (P.Pos x y) False | x <- [-1,w-1], y <- [0..h-1] ]
+
+isBoundaryWPos :: P.WPos -> Bool
+isBoundaryWPos (P.WPos (P.Pos _ y) True)  = y `elem` [-1,h-1]
+isBoundaryWPos (P.WPos (P.Pos x _) False) = x `elem` [-1,w-1]
+
+treasuresPerBoard :: Int
+treasuresPerBoard = 5
+
+-- XXX If all active, status line is 58 long -- watch out with renaming!
+data Status = Dazzled | Smoke | Haste | Ghost | Foresight deriving (Eq, Ord, Show)
+
+type Tagged = S.Set P.WPos
+
+data Board = Board
+    { visible    :: S.Set P.Pos
+    , unrevealed :: S.Set P.Pos
+    , creatures  :: M.Map P.Pos Creature
+    , items      :: M.Map P.Pos Item
+    , walls      :: M.Map P.WPos Wall
+    , exits      :: M.Map P.WPos Exit
+    , powers     :: M.Map P.Pos Pow.Power
+    , treasures  :: Int
+    , timer      :: Int
+    , possItems  :: [Item]
+    , safe       :: Bool
+    , statuses   :: M.Map Status Int
+    , expected   :: M.Map P.Pos (Maybe Creature)
+    , tagged     :: Tagged
+    , diffs      :: BC.BoardConfDiffs
+    , conf       :: BC.BoardConf
+    }
+
+new :: BC.BoardConf -> Board
+new = Board S.empty poss M.empty M.empty M.empty initBoundary M.empty treasuresPerBoard 0 [] True M.empty M.empty S.empty M.empty where
+     initBoundary = M.fromSet (const UnseenBoundary) boundaryWPoss
+
+empty :: Board
+empty = new BC.emptyBoardConf
+
+modVisible :: (S.Set P.Pos -> S.Set P.Pos) -> Board -> Board
+modVisible f bd = bd { visible = f $ visible bd }
+setVisible :: S.Set P.Pos -> Board -> Board
+setVisible = modVisible . const
+
+modUnrevealed :: (S.Set P.Pos -> S.Set P.Pos) -> Board -> Board
+modUnrevealed f bd = bd { unrevealed = f $ unrevealed bd }
+setUnrevealed :: S.Set P.Pos -> Board -> Board
+setUnrevealed = modUnrevealed . const
+
+modCreatures :: (M.Map P.Pos Creature -> M.Map P.Pos Creature) -> Board -> Board
+modCreatures f bd = bd { creatures = f $ creatures bd }
+
+modItems :: (M.Map P.Pos Item -> M.Map P.Pos Item) -> Board -> Board
+modItems f bd = bd { items = f $ items bd }
+
+modWalls :: (M.Map P.WPos Wall -> M.Map P.WPos Wall) -> Board -> Board
+modWalls f bd = bd { walls = f $ walls bd }
+
+modExits :: (M.Map P.WPos Exit -> M.Map P.WPos Exit) -> Board -> Board
+modExits f bd = bd { exits = f $ exits bd }
+
+modPowers :: (M.Map P.Pos Pow.Power -> M.Map P.Pos Pow.Power) -> Board -> Board
+modPowers f bd = bd { powers = f $ powers bd }
+
+modTreasures, modTimer :: (Int -> Int) -> Board -> Board
+modTreasures f bd = bd { treasures = f $ treasures bd }
+modTimer f bd = bd { timer = f $ timer bd }
+setTimer :: Int -> Board -> Board
+setTimer = modTimer . const
+
+setSafe :: Bool -> Board -> Board
+setSafe s bd = bd { safe = s }
+
+modStatuses :: (M.Map Status Int -> M.Map Status Int) -> Board -> Board
+modStatuses f bd = bd { statuses = f $ statuses bd }
+
+modExpected :: (M.Map P.Pos (Maybe Creature) -> M.Map P.Pos (Maybe Creature)) -> Board -> Board
+modExpected f bd = bd { expected = f $ expected bd }
+setExpected :: M.Map P.Pos (Maybe Creature) -> Board -> Board
+setExpected = modExpected . const
+
+modTagged :: (Tagged -> Tagged) -> Board -> Board
+modTagged f bd = bd { tagged = f $ tagged bd }
+
+modConf :: (BC.BoardConf -> BC.BoardConf) -> Board -> Board
+modConf f bd = bd { conf = f $ conf bd }
+
+wPosVisible :: S.Set P.Pos -> P.WPos -> Bool
+wPosVisible vis wp = any (`S.member` vis) $ P.adjPoss wp
+
+visibleWPoss, invisibleWPoss :: Tagged -> S.Set P.Pos -> S.Set P.WPos
+visibleWPoss tags vis = tags `S.union` S.filter (wPosVisible vis) wPoss
+invisibleWPoss tags vis = S.filter (not . wPosVisible vis) wPoss S.\\ tags
+
+invisible :: Board -> S.Set P.Pos
+invisible bd = poss S.\\ visible bd
+
+onSpawnTreasure :: Board -> Board
+onSpawnTreasure bd = (if treasures bd > 1 then setUnrevealed poss else id)
+    $ modTreasures (+ (-1)) bd
+
+setPlayerDead :: Board -> Board
+setPlayerDead = modCreatures . M.map $ \case
+    Player -> DeadPlayer
+    c      -> c
+
+treasureAt :: Board -> P.Pos -> Item
+treasureAt bd (P.Pos x y)
+    | treasures bd == 1 = Gem
+    | 2*x > w = treasureAt bd (P.Pos (w-1-x) y)
+    | 2*y > h = treasureAt bd (P.Pos x (h-1-y))
+treasureAt _ (P.Pos 2 2) = Junk
+treasureAt _ (P.Pos 1 1) = Potion
+treasureAt _ (P.Pos 0 2) = MiniPotion
+treasureAt bd (P.Pos 1 0) | Just i <- headMay $ possItems bd = i
+treasureAt bd (P.Pos 0 y) | Just i <- possItems bd `atMay` (y+1) = i
+treasureAt bd (P.Pos 2 0) = treasureAt bd $ P.Pos 0 2
+treasureAt _ _ = ScoreTreasure
+
+setFov :: Bool -> Board -> Rand StdGen Board
+setFov hasKey bd0 = setSafe False <$> iter bd0 where
+    iter bd =
+        let oldVis = visible bd
+            newVis = fov bd
+            oldWVis = visibleWPoss (tagged bd) oldVis
+            newWVis = visibleWPoss (tagged bd) newVis
+        in if newVis == oldVis
+        then seeBoundary hasKey $ destroyInvisStuffs bd
+        else do
+            bd' <- destroyInvisStuffs . updateVis . destroyInvisWalls . updateVis <$>
+                createAtW (newWVis S.\\ oldWVis) bd
+            newVis' <- shuffle . S.toList $ visible bd' S.\\ oldVis
+            let newInvis' = S.toList $ oldVis S.\\ visible bd'
+            bd'' <- revealVis <$> (expectAtMaybe newInvis' =<< createAt newVis' bd')
+            -- created orbs may lead to new vision, so need to iterate
+            iter bd''
+    destroyInvisWalls, destroyInvisStuffs :: Board -> Board
+    destroyInvisStuffs bd = modCreatures delPInvis . modItems delPInvis $ bd where
+        delPInvis :: M.Map P.Pos a -> M.Map P.Pos a
+        delPInvis = (M.\\ M.fromSet (const ()) (invisible bd))
+    destroyInvisWalls bd = modWalls delWPInvis bd where
+        delWPInvis :: M.Map P.WPos a -> M.Map P.WPos a
+        delWPInvis = (M.\\ M.fromSet (const ()) (invisibleWPoss (tagged bd) (visible bd)))
+    expectAtMaybe
+        | expectant bd0 = expectAt
+        | otherwise = const pure
+    createAt :: [P.Pos] -> Board -> Rand StdGen Board
+    createAt = flip $ foldM createP
+    createAtW :: S.Set P.WPos -> Board -> Rand StdGen Board
+    createAtW = flip $ foldM createW
+    bc = conf bd0
+    createP :: Board -> P.Pos -> Rand StdGen Board
+    createW :: Board -> P.WPos -> Rand StdGen Board
+    createP bd p = modExpected (M.delete p) <$> createP' (modUnrevealed (S.delete p) bd) p
+    createP' bd p
+        | S.null (unrevealed bd) && treasures bd > 0 =
+            pure . onSpawnTreasure . modItems (M.insert p $ treasureAt bd p) $ bd
+        | safe bd = pure bd
+        | p `M.member` creatures bd = pure bd
+        | expectant bd = pure $ case expected bd M.!? p of
+            Just (Just c) -> modCreatures (M.insert p c) bd
+            _             -> bd
+        | otherwise =
+            maybe bd (($ bd) . modCreatures . M.insert p) <$> RF.roll (BC.creatureRoll bc)
+    createW bd wp =
+        maybe bd (($ bd) . modWalls . M.insert wp) <$> RF.roll (BC.wallRoll bc)
+    revealVis bd
+        -- | Needed when all poss revealed on spawning treasure
+        | S.null (unrevealed bd) && treasures bd > 0 = setUnrevealed (poss `S.difference` visible bd) bd
+        -- | Needed only when we created a treasure
+        | otherwise = modUnrevealed (`S.difference` visible bd) bd
+
+seeBoundary :: Bool -> Board -> Rand StdGen Board
+seeBoundary hasKey bd = do
+    v <- newVisBdd
+    pure $ modExits (flip (foldr set) v) bd
+    where
+    newVisBdd = shuffle . S.toList . S.filter (wPosVisible $ visible bd) .
+             S.filter ((== Just UnseenBoundary) . (exits bd M.!?)) $ boundaryWPoss
+    set :: P.WPos -> M.Map P.WPos Exit -> M.Map P.WPos Exit
+    set wp exs = M.insert wp ex exs where
+        ex | S.null . S.delete wp $ S.filter (sameWall wp) unseen =
+                case S.toList $ S.filter (not . sameWall wp) unseen of
+                    [] -> Exit
+                    wp':_ | hasKey && all (sameWall wp') (S.delete wp unseen) -> KeyExit
+                    _ -> SeenBoundary
+            | otherwise = SeenBoundary
+        unseen = S.filter ((== Just UnseenBoundary) . (exs M.!?)) boundaryWPoss
+        sameWall = (==) `on` P.exitDir
+
+
+fov, playerFov :: Board -> S.Set P.Pos
+fov bd = addOrbFovs plFov plFov where
+    plFov = fovs $ playerPoss bd <> cameraPoss bd
+    fovs = S.unions . map (fovAt bd)
+    addOrbFovs :: S.Set P.Pos -> S.Set P.Pos -> S.Set P.Pos
+    addOrbFovs v news
+        | S.null news = v
+        | otherwise = let
+            orbPoss = [ p | (p, i) <- M.assocs $ M.restrictKeys (items bd) news, isOrb i ]
+            orbFovs = fovs orbPoss
+            isOrb (ItemInvItem Orb) = True
+            isOrb (RollingOrb _ _)  = True
+            isOrb _                 = False
+        in addOrbFovs (v `S.union` orbFovs) (orbFovs S.\\ v)
+playerFov bd = S.unions . map (fovAt bd) $ playerPoss bd
+
+
+playerPoss :: Board -> [ P.Pos ]
+playerPoss bd = [ p | (p,Player) <- M.assocs $ creatures bd ]
+
+cameraPoss :: Board -> [ P.Pos ]
+cameraPoss bd = [ p | (p, ItemInvItem (Camera _)) <- M.assocs $ items bd ]
+
+fovAt :: Board -> P.Pos -> S.Set P.Pos
+fovAt bd base = S.filter inRange $ poss S.\\ blocked where
+    blocked = S.unions [ wallCone (short wl) base wp
+        | (wp,wl) <- M.assocs $ walls bd, wl `notElem` [Window, BrokenWindow]
+        ] where
+        short Pillar           = True
+        short (UmbrellaWall _) = True
+        short _                = False
+    inRange
+        | Just r <- sightRadius = (<= r*r) . ((smokeFac*smokeFac)*) . P.distSquared base
+        | otherwise = const True
+        where
+        sightRadius = minimumMay $ mapMaybe rad (M.assocs (statuses bd))
+        rad (Dazzled,_) = Just 0
+        rad (Smoke,n)   = Just $ max 0 (maxSmoke - n) + smokeFac
+        rad _           = Nothing
+
+wallCone :: Bool -> P.Pos -> P.WPos -> S.Set P.Pos
+wallCone short base wp = (poss `S.intersection`) $ (base +^) `S.map` wallCone' (neg base +^ wp) where
+    wallCone' (P.WPos p False) = flipPos `S.map` wallCone' (P.WPos (flipPos p) True)
+    wallCone' (P.WPos (P.Pos x y) True)
+        | x < 0 = (\(P.Pos x' y') -> P.Pos (-x') y') `S.map` wallCone' (P.WPos (P.Pos (-x) y) True)
+        | y < 0 = (\(P.Pos x' y') -> P.Pos x' (-y')) `S.map` wallCone' (P.WPos (P.Pos x (-y-1)) True)
+        | otherwise =
+            S.fromList [ P.Pos x' y'
+                | x' <- [-w..w], y' <- [y+1..h]
+                , ineq x' y'
+                ] where
+        -- (y+1/2)/(x-w/2) <= y'/x' <= (y+1/2)/(x+w/2)
+        ineq x' y' | short = abs (x'*(8*y+4) - 8*y'*x) <= 3*y' -- w = 3/4
+            | otherwise    = abs (x'*(2*y+1) - 2*y'*x) <= y' -- w = 1
+    flipPos (P.Pos x y) = P.Pos y x
+
+smokeFac, maxSmoke :: Int
+smokeFac = 4
+maxSmoke = 20
+
+updateVis :: Board -> Board
+updateVis bd = setVisible (fov bd) bd
+
+data Move = Move {mvCreature :: Creature, mvFrom :: P.Pos, mvDir :: P.Dir}
+
+data Alert
+    = AlertMoveCreature Creature P.Pos P.Dir
+    | AlertMoveItem Item P.Pos P.Dir
+    | AlertUseItem Item P.Pos P.Dir
+    | AlertHighlight (S.Set P.Pos) (S.Set P.WPos)
+data Transition = Transition { transBase :: Board, transAlerts :: [Alert] }
+
+data MoveResults = MoveResults
+    { damage     :: Sum Int
+    , exitings   :: [P.WPos]
+    , alerts     :: [Alert]
+    , someAction :: Any
+    }
+instance Semigroup MoveResults where
+    MoveResults a b c d <> MoveResults a' b' c' d' = MoveResults (a<>a') (b<>b') (c<>c') (d<>d')
+instance Monoid MoveResults where
+    mempty = MoveResults mempty mempty mempty mempty
+action :: MoveResults
+action = mempty { someAction = Any True }
+
+movePlayers :: P.Dir -> Board -> Writer MoveResults Board
+movePlayers dir bd = foldM (flip $ tryMoveCreature dir) bd (playerPoss bd)
+
+throughWall :: Board -> Creature -> Maybe Wall -> Bool
+throughWall _ _ Nothing                     = True
+throughWall _ GhostMonster _                = True
+throughWall bd Player _ | ghostly bd        = True
+throughWall _ Player (Just Hedge)           = True
+throughWall _ (InflatedBalloon _) (Just _)  = False
+throughWall _ _ (Just BrokenWindow)         = True
+throughWall _ _ _                           = False
+
+creatureCanMove :: Board -> Creature -> P.Pos -> P.Dir -> Bool
+creatureCanMove bd c p dir =
+    let p' = P.dirPos dir +^ p
+        wp = P.wposInDir p dir
+    in inBounds p' && (c == Player || M.notMember p' (creatures bd)) && throughWall bd c (walls bd M.!? wp)
+
+creatureCanTryMove :: Board -> Creature -> P.Pos -> P.Dir -> Bool
+creatureCanTryMove bd c p dir =
+    let p' = P.dirPos dir +^ p
+        wp = P.wposInDir p dir
+    in and
+        [ inBounds p'
+        , creatures bd M.!? p' `elem` [Nothing, Just Player]
+        , throughWall bd c $ walls bd M.!? wp
+        , c /= SmartMonster || p' `S.member` playerFov bd
+        ]
+
+exitInDir :: Board -> P.Pos -> P.Dir -> Bool
+exitInDir bd p d = exits bd M.!? P.wposInDir p d `elem` [Just Exit, Just KeyExit]
+
+enterAt :: P.WPos -> Board -> Board
+enterAt wp@(P.WPos (P.Pos x y) _) = modVisible (S.insert p') . modCreatures (M.insert p' Player) . modExits (M.insert wp Entrance) where
+    p' = P.Pos (max 0 x) (max 0 y)
+
+oppositeWPos :: P.WPos -> P.WPos
+oppositeWPos (P.WPos (P.Pos x y) True)  = P.WPos (P.Pos x (h-2-y)) True
+oppositeWPos (P.WPos (P.Pos x y) False) = P.WPos (P.Pos (w-2-x) y) False
+
+tryMoveCreature :: P.Dir -> P.Pos -> Board -> Writer MoveResults Board
+tryMoveCreature dir p bd
+    | Just Player <- creatures bd M.!? p
+    , not $ ghostly bd
+    , let wp = P.wposInDir p dir
+    , Just wl <- walls bd M.!? wp
+    , Just cost <- wallDestructionCost wl
+    = do
+        tell $ action { damage = Sum cost }
+        pure . modTagged (S.delete wp) . modWalls (M.update damageWall wp) $ bd
+    | Just c <- creatures bd M.!? p, creatureCanMove bd c p dir = do
+        let p' = P.dirPos dir +^ p
+        bd' <- case creatures bd M.!? p' of
+            Just (InflatedBalloon _) | c == Player ->
+                tryMoveCreature dir p' bd
+            _ -> pure bd
+        let creatureDestroyed = maybe False isMonster $ creatures bd' M.!? p'
+            throughPainful = c == Player && not (ghostly bd) &&
+                (walls bd M.!? P.wposInDir p dir) `elem` [Just Hedge, Just BrokenWindow]
+            dmg = sum $ [2 | creatureDestroyed] <> [1 | throughPainful]
+            modMove = modCreatures $ M.insert p' c . M.delete p
+            modBalloon
+                | Just (InflatedBalloon charges) <- creatures bd' M.!? p'
+                , charges > 0
+                , p' `M.notMember` items bd'
+                = modItems . M.insert p' . ItemInvItem $ Balloon charges
+                | otherwise = id
+        tell $ action { damage = Sum dmg, alerts = move c }
+        pure . modBalloon . modMove $ bd'
+    | Just Player <- creatures bd M.!? p, exitInDir bd p dir = do
+        tell $ action { exitings = [P.wposInDir p dir], alerts = move Player }
+        pure $  modCreatures (M.delete p) bd
+    | otherwise = pure bd
+    where
+    move c = [AlertMoveCreature c p dir]
+    damageWall = \case
+        ThickHedge -> Just Hedge
+        Window     -> Just BrokenWindow
+        _          -> Nothing
+
+collectItems :: Board -> Writer [Item] Board
+collectItems bd
+    | p:_ <- playerPoss bd
+    = collectItemsAt p bd
+    | otherwise = pure bd
+
+collectItemsAt :: P.Pos -> Board -> Writer [Item] Board
+collectItemsAt p bd
+    | Just item <- items bd M.!? p = let
+        takeUmbrella
+            | UmbrellaHandle d <- item =
+                let wp' = P.wposInDir p d
+                in modTagged (S.delete wp') . modWalls (M.delete wp')
+            | otherwise = id
+        getItem
+            | UmbrellaHandle d <- item = P.wposInDir p d `M.member` walls bd
+            | otherwise = True
+        in do
+            when getItem $ tell [item]
+            pure . modItems (M.delete p) . takeUmbrella $ bd
+    | otherwise = pure bd
+
+grabItem :: P.Dir -> Board -> Writer [Item] Board
+grabItem d bd
+    | p:_ <- playerPoss bd
+    = collectItemsAt (p +^ P.dirPos d) bd
+    | otherwise = pure bd
+
+
+findPathDir, chaseDir :: Creature -> Board -> P.Pos -> P.Pos -> Rand StdGen (Maybe P.Dir)
+findPathDir c bd from goal = do
+    let firsts = headMay `mapMaybe` aStarAll graph (P.sqDist goal) (== goal) from
+        dirs = (P.posDir . (+^ neg from)) `mapMaybe` firsts
+    randElem dirs
+    where
+    graph :: P.Pos -> HS.HashSet P.Pos
+    graph p = HS.fromList [ p +^ P.dirPos d | d <- P.dirs,  creatureCanTryMove bd c p d ]
+chaseDir c bd from goal =
+    let diff = from +^ neg goal
+        ok = creatureCanTryMove bd c from
+        dirs = filter ok <$> P.dirsTowardsZero diff
+    in headMay . concat <$> mapM shuffle dirs
+
+npcs :: Board -> M.Map P.Pos Creature
+npcs = M.filter (/= Player) . creatures
+
+incStatus :: Status -> Int -> Board -> Board
+incStatus st n = modStatuses $ M.alter f st where
+    f (Just n') = Just $ n + n'
+    f _         = Just n
+hasted,isHasteRound,ghostly,expectant :: Board -> Bool
+hasted = M.member Haste . statuses
+ghostly = M.member Ghost . statuses
+expectant = M.member Foresight . statuses
+isHasteRound bd
+    | Just n <- statuses bd M.!? Haste = n `mod` 2 == 1
+    | otherwise = False
+
+beginExpect :: Board -> Rand StdGen Board
+beginExpect bd
+    | expectant bd = pure bd
+    | otherwise = (expectAt . S.toList $ invisible bd) bd
+
+expectAt :: [P.Pos] -> Board -> Rand StdGen Board
+expectAt ps bd0 = foldM expectP bd0 ps
+    where
+    expectP bd p = ($ bd) . modExpected . M.insert p <$> RF.roll (BC.creatureRoll $ conf bd0)
+
+npcsAct :: Board -> WriterT [Alert] (Rand StdGen) Board
+npcsAct bd0
+    | isHasteRound bd0 = pure bd0
+    | otherwise = do
+    actors <- lift . shuffle . M.toList $ npcs bd0
+    foldM npcAct bd0 actors
+    where
+    npcAct :: Board -> (P.Pos, Creature) -> WriterT [Alert] (Rand StdGen) Board
+    npcAct bd (p,c)
+        | ppos:_ <- playerPoss bd =
+            (forceRand =<< lift (pathAlg c c bd p ppos)) >>= \case
+                Just dir ->
+                    mapWriterT (pure . runIdentity . (second alerts <$>)) $ tryMoveCreature dir p bd
+                _ -> pure bd
+        | otherwise = pure bd
+        where
+        -- Force non-calm monsters to move randomly when next to player
+        forceRand :: Maybe P.Dir -> WriterT [Alert] (Rand StdGen) (Maybe P.Dir)
+        forceRand md | c `elem` [ CalmMonster, GhostMonster ] = pure md
+        forceRand (Just dir) | not (creatureCanMove bd c p dir) = randAvailableDir
+        forceRand Nothing | c == SmartMonster = randAvailableDir
+        forceRand md = pure md
+        randAvailableDir = lift . randElem $
+            filter (\d -> creatureCanMove bd c p d && creatureCanTryMove bd c p d) P.dirs
+
+    pathAlg BasicMonster = chaseDir
+    pathAlg CalmMonster  = chaseDir
+    pathAlg GhostMonster = chaseDir
+    pathAlg SmartMonster = findPathDir
+    pathAlg ChaseMonster = findPathDir
+    pathAlg _            = \_ _ _ _ -> pure Nothing
+
+tryUseInvItem :: InvItem -> P.Dir -> Board -> WriterT [Alert] Maybe Board
+tryUseInvItem e d bd
+    | p:_ <- playerPoss bd = do
+        tell [AlertUseItem (ItemInvItem e) p d]
+        let wp = P.wposInDir p d
+        lift . guard $ canUseOnWall e || (walls bd M.!? wp) `elem` [Nothing, Just BrokenWindow]
+        let p' = p +^ P.dirPos d
+        lift . guard $ inBounds p'
+        case e of
+            Cloak -> pure $ modWalls (M.insert wp $ CloakWall d 1) bd
+            Umbrella -> do
+                guard . M.notMember p' $ items bd
+                let wp' = P.wposInDir p' d
+                guard $ inBoundsW wp'
+                guard $ (walls bd M.!? wp') `elem` [Nothing, Just BrokenWindow]
+                let addUmbrellaWall = modWalls (M.insert wp' $ UmbrellaWall d)
+                if p' `M.member` creatures bd
+                    then do
+                        let (bd', mr) = runWriter $ tryMoveCreature d p' bd
+                        guard . getAny $ someAction mr
+                        pure $ addUmbrellaWall bd'
+                    else pure . modItems (M.insert p' $ UmbrellaHandle d) . addUmbrellaWall $ bd
+            Balloon charges -> let inflate = modCreatures (M.insert p' (InflatedBalloon $ charges - 1))
+                in if p' `M.member` creatures bd
+                    then do
+                        let (bd', mr) = runWriter $ tryMoveCreature d p' bd
+                        guard . getAny $ someAction mr
+                        pure $ inflate bd'
+                    else pure $ inflate bd
+            Orb -> ($ bd) <$> dropItem p' (RollingOrb d True)
+            Flash ->
+                let flashPoss = wallCone True p wp
+                    flashWPoss = wp `S.insert` invisibleWPoss S.empty (poss S.\\ flashPoss)
+                    delPoss = flip (foldr M.delete) flashPoss
+                    delWPoss = flip (foldr M.delete) flashWPoss
+                    delWPossS = flip (foldr S.delete) flashWPoss
+                    reveal, destroyTreasure :: Board -> Board
+                    reveal = destroyTreasure
+                        . modUnrevealed (`S.difference` flashPoss)
+                        . modVisible (`S.union` flashPoss)
+                    -- | Pretend we created and immediately destroyed a treasure
+                    destroyTreasure bd' | null (unrevealed bd') = onSpawnTreasure bd'
+                        | otherwise = bd'
+                in tell [AlertHighlight flashPoss flashWPoss] $>
+                    (reveal . modItems delPoss . modCreatures delPoss . modTagged delWPossS $ modWalls delWPoss bd)
+            Tent -> do
+                guard . M.notMember p' $ creatures bd
+                pure .
+                    modWalls (flip (foldr (M.alter (Just . fromMaybe TentWall))) (filter inBoundsW $ P.wposInDir p' <$> P.dirs))
+                    . modCreatures (M.delete p . M.insert p' Player) $ bd
+            Spraypaint _ -> do
+                guard $ wp `M.member` walls bd
+                pure $ modTagged (S.insert wp) bd
+            _ -> ($ bd) <$> dropItem p' (ItemInvItem e)
+    | otherwise = lift Nothing
+    where
+    dropItem p i = do
+            guard . M.notMember p $ items bd
+            guard . M.notMember p $ creatures bd
+            pure $ modItems (M.insert p i)
+    canUseOnWall Flash          = True
+    canUseOnWall (Spraypaint _) = True
+    canUseOnWall _              = False
+
+doPhysics :: Board -> Writer [Alert] Board
+doPhysics bd0
+    | isHasteRound bd0
+    = pure $ modStatuses (decayStatuses True) bd0
+    | otherwise
+    = modStatuses (decayStatuses False)
+    . modItems decayCameras
+    . decayCloaks
+    . tickTimer
+    <$> rollOrbs bd0
+    where
+    decayCloaks bd = foldr decayCloakWall bd . M.assocs . M.filter isCloakWall $ walls bd
+    isCloakWall (CloakWall _ _) = True
+    isCloakWall _               = False
+    decayCloakWall :: (P.WPos, Wall) -> Board -> Board
+    decayCloakWall (wp, CloakWall d n)
+        | n > 0 = modWalls . M.insert wp $ CloakWall d (n-1)
+        | otherwise = modTagged (S.delete wp)
+            . modWalls (M.delete wp)
+            . modItems (M.insert (P.posInDir wp d) $ ItemInvItem Cloak)
+    decayCloakWall _ = id
+    decayCameras = M.mapMaybe $ \case
+        ItemInvItem (Camera n) | n > 0 -> Just . ItemInvItem . Camera $ n-1
+            | otherwise -> Nothing
+        i -> Just i
+    decayStatuses hasteOnly = M.filter (>0) . M.mapWithKey decay where
+        decay Haste n = n-1
+        decay _ n | hasteOnly = n
+        decay _ n = n-1
+    rollOrbs bd = foldM rollOrb bd (M.assocs $ items bd) where
+        rollOrb :: Board -> (P.Pos, Item) -> Writer [Alert] Board
+        rollOrb bd' (p, RollingOrb dir True)
+            = pure $ modItems (M.insert p (RollingOrb dir False)) bd'
+        rollOrb bd' (p, orb@(RollingOrb dir False))
+            | let p' = p +^ P.dirPos dir
+            , inBounds p'
+            , p' `M.notMember` items bd'
+            , P.wposInDir p dir `M.notMember` walls bd'
+            = tell [AlertMoveItem orb p dir] $> modItems (M.delete p . M.insert p' orb) bd'
+            | otherwise
+            = pure $ modItems (M.insert p (ItemInvItem Orb)) bd'
+        rollOrb bd' _ = pure bd'
+    tickTimer = rollOver . modTimer (+1) where
+        rollOver bd | timer bd >= turnsPerSide
+            = modConf (BC.modRolls decSides decSides) . setTimer 0 $ bd
+        rollOver bd = bd
+        decSides = RF.modSides (+ (-1))
+        turnsPerSide = 8
+
+addPower :: Bool -> Board -> Board
+addPower overUsable bd
+    | p:_ <- playerPoss bd = modPowers (M.alter (add p) p) bd
+    | otherwise = bd
+    where
+    add p Nothing    = Just . Pow.upgrade $ Pow.new (typeAt p) overUsable
+    add _ (Just pow) = Just $ Pow.upgrade pow
+    typeAt (P.Pos x y)
+        | 2*x > w = typeAt (P.Pos (w-1-x) y)
+        | 2*y > h = typeAt (P.Pos x (h-1-y))
+    typeAt (P.Pos 0 0) = Pow.Smoke
+    typeAt (P.Pos 0 1) = Pow.Dazzle
+    typeAt (P.Pos 0 2) = Pow.Teleport
+    typeAt (P.Pos 1 0) = Pow.Ghost
+    typeAt (P.Pos 1 1) = Pow.Heal
+    typeAt (P.Pos 1 2) = Pow.Haste
+    typeAt (P.Pos 2 0) = Pow.Teleport
+    typeAt (P.Pos 2 1) = Pow.Foresight
+    typeAt (P.Pos 2 2) = Pow.Undo
+    typeAt _ = Pow.Heal -- impossible
diff --git a/BoardConf.hs b/BoardConf.hs
new file mode 100644
--- /dev/null
+++ b/BoardConf.hs
@@ -0,0 +1,83 @@
+{-# LANGUAGE TupleSections #-}
+
+module BoardConf where
+
+import           Control.Monad.Random
+import qualified Data.Map.Strict      as M
+import           Data.Maybe
+
+import           Creature
+import           Rand
+import           Wall
+
+import qualified Pos                  as P
+import qualified RollFrom             as RF
+
+data BoardConf = BoardConf
+    { level        :: Int
+    , creatureRoll :: RF.RollFrom Creature
+    , wallRoll     :: RF.RollFrom Wall
+    }
+emptyBoardConf :: BoardConf
+emptyBoardConf = BoardConf 0 RF.empty RF.empty
+
+modRolls :: (RF.RollFrom Creature -> RF.RollFrom Creature)
+    -> (RF.RollFrom Wall -> RF.RollFrom Wall)
+    -> BoardConf -> BoardConf
+modRolls f f' bc = bc
+    { creatureRoll = f $ creatureRoll bc
+    , wallRoll = f' $ wallRoll bc
+    }
+
+-- XXX: ugly manual polymorphism ahead
+data Diffable = DiffableCreature Creature | DiffableWall Wall
+data RollFromDiff a
+    = Add a
+    | Swap a a
+
+type BoardConfDiffs = M.Map P.Dir [RollFromDiff Diffable]
+apply :: BoardConfDiffs -> P.Dir -> BoardConf -> BoardConf
+apply bcd d = flip (foldr apply') (fromMaybe [] $ bcd M.!? d) where
+    apply' (Add (DiffableCreature c)) = modC $ applyRFD (Add c)
+    apply' (Swap (DiffableCreature c) (DiffableCreature c')) = modC $ applyRFD (Swap c c')
+    apply' (Add (DiffableWall w)) = modW $ applyRFD (Add w)
+    apply' (Swap (DiffableWall w) (DiffableWall w')) = modW $ applyRFD (Swap w w')
+    apply' _ = id
+    applyRFD :: (Eq a, Ord a) => RollFromDiff a -> RF.RollFrom a -> RF.RollFrom a
+    applyRFD (Add a)     = RF.add a
+    applyRFD (Swap a a') = RF.swap a a'
+    modC f bc = bc { creatureRoll = f $ creatureRoll bc }
+    modW f bc = bc { wallRoll = f $ wallRoll bc }
+
+genDiffs :: BoardConf -> Rand StdGen BoardConfDiffs
+genDiffs bc = (M.fromList <$>) . forM P.dirs $ \d -> (d,) <$> genDiffDir d where
+    genDiffDir P.DUp    = sequence [ addCreature, swapCreature ]
+    genDiffDir P.DRight = sequence [ addCreature, swapWall ]
+    genDiffDir P.DDown  = sequence [ addWall, swapWall ]
+    genDiffDir P.DLeft  = sequence [ addWall, swapCreature ]
+    addCreature = pure . Add $ DiffableCreature BasicMonster
+    addWall = pure . Add . DiffableWall $ if level bc == 1 then Hedge else BasicWall
+    swapCreature = do
+        swapOut <- randElem . filter upgradableCreature $ RF.vals (creatureRoll bc)
+        case swapOut of
+            Nothing -> addCreature
+            Just c -> Swap (DiffableCreature c) . DiffableCreature <$> upgradeCreature c
+    creatureUpgrades BasicMonster = [CalmMonster, ChaseMonster]
+    creatureUpgrades CalmMonster  = [GhostMonster]
+    creatureUpgrades ChaseMonster = [SmartMonster]
+    creatureUpgrades _            = []
+    upgradableCreature = not . null . creatureUpgrades
+    upgradeCreature = randElemUnsafe . creatureUpgrades
+    swapWall = do
+        swapOut <- randElem . filter upgradableWall $ RF.vals (wallRoll bc)
+        case swapOut of
+            Nothing -> addWall
+            Just c  -> Swap (DiffableWall c) . DiffableWall <$> upgradeWall c
+    wallUpgrades Hedge = [ThickHedge]
+    wallUpgrades BasicWall
+        | level bc == 2 = [Pillar]
+        | otherwise = [Window]
+    wallUpgrades Window = [BrokenWindow]
+    wallUpgrades _ = []
+    upgradableWall = not . null . wallUpgrades
+    upgradeWall = randElemUnsafe . wallUpgrades
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,5 @@
+# Revision history for fearOfView
+
+## 0.1.0.0 -- YYYY-mm-dd
+
+* First release.
diff --git a/COPYING b/COPYING
new file mode 100644
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,661 @@
+                    GNU AFFERO GENERAL PUBLIC LICENSE
+                       Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+our General Public Licenses are intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+  A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate.  Many developers of free software are heartened and
+encouraged by the resulting cooperation.  However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+  The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community.  It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server.  Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+  An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals.  This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU Affero General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Remote Network Interaction; Use with the GNU General Public License.
+
+  Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software.  This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero General Public License from time to time.  Such new versions
+will be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU Affero General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU Affero General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU Affero General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source.  For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code.  There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU AGPL, see
+<http://www.gnu.org/licenses/>.
diff --git a/CPos.hs b/CPos.hs
new file mode 100644
--- /dev/null
+++ b/CPos.hs
@@ -0,0 +1,9 @@
+module CPos where
+
+-- | curses convention (y increases downwards)
+data CPos = CPos { x :: Int, y :: Int } deriving (Eq, Ord)
+instance Semigroup CPos where
+    CPos x1 y1 <> CPos x2 y2 = CPos (x1+x2) (y1+y2)
+instance Monoid CPos where
+    mempty = CPos 0 0
+
diff --git a/CStyle.hs b/CStyle.hs
new file mode 100644
--- /dev/null
+++ b/CStyle.hs
@@ -0,0 +1,32 @@
+module CStyle where
+
+import qualified UI.HSCurses.Curses as C
+
+type ColPair = Int
+white,red,green,yellow,blue,magenta,cyan,black :: ColPair
+white = 0
+red = 1
+green = 2
+yellow = 3
+blue = 4
+magenta = 5
+cyan = 6
+black = 7
+
+onBlue, onRed, onYellow :: ColPair -> ColPair
+onBlue = (+8) . (`mod` 8)
+onRed = (+16) . (`mod` 8)
+onYellow = (+24) . (`mod` 8)
+
+data CStyle = CStyle { cstyleCol :: ColPair, cstyleAttr :: C.Attr }
+a0, aBold :: C.Attr
+a0 = C.attr0
+aBold = C.setBold a0 True
+style0, styleBold :: CStyle
+style0 = CStyle 0 a0
+styleBold = CStyle 0 aBold
+
+data Glyph = Glyph { glyphChar :: Char, glyphStyle :: CStyle }
+
+modColour :: (ColPair -> ColPair) -> Glyph -> Glyph
+modColour f (Glyph c (CStyle col a)) = Glyph c (CStyle (f col) a)
diff --git a/Command.hs b/Command.hs
new file mode 100644
--- /dev/null
+++ b/Command.hs
@@ -0,0 +1,16 @@
+module Command where
+
+import qualified Inventory as I
+import qualified Pos       as P
+
+data Command
+    = Dir P.Dir
+    | UseInv I.Slot
+    | UsePower
+    | Accept
+    | SkipTutorial
+    | DebugAddPower | DebugAddJunk | DebugAddItems | DebugExit
+    | ToggleAscii
+    | Refresh | Redraw | Suspend | Clear
+    | Quit | ForceQuit
+    deriving (Eq, Ord, Show, Read)
diff --git a/Creature.hs b/Creature.hs
new file mode 100644
--- /dev/null
+++ b/Creature.hs
@@ -0,0 +1,22 @@
+module Creature where
+
+data Creature
+    = Player
+    | DeadPlayer
+    | SmartMonster
+    | GhostMonster
+    | ChaseMonster
+    | CalmMonster
+    | BasicMonster
+    | InflatedBalloon Int
+    deriving (Eq, Ord)
+
+isMonster :: Creature -> Bool
+isMonster Player              = False
+isMonster DeadPlayer          = False
+isMonster (InflatedBalloon _) = False
+isMonster SmartMonster        = True
+isMonster GhostMonster        = True
+isMonster ChaseMonster        = True
+isMonster CalmMonster         = True
+isMonster BasicMonster        = True
diff --git a/CursesDraw.hs b/CursesDraw.hs
new file mode 100644
--- /dev/null
+++ b/CursesDraw.hs
@@ -0,0 +1,575 @@
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE LambdaCase       #-}
+{-# LANGUAGE TupleSections    #-}
+
+module CursesDraw where
+
+import           Control.Concurrent  (threadDelay)
+import           Control.Monad.State
+import           Data.Bifunctor
+import           Data.Function       (on)
+import           Data.List           (foldl', intersperse, minimumBy)
+import           Data.Maybe
+import           Safe
+
+import qualified Data.Map.Strict     as M
+import qualified Data.Set            as S
+
+import           Creature
+import           CStyle
+import           Equipment
+import           Exit
+import           Group
+import           Item
+import           Wall
+
+import qualified Board               as B
+import qualified BoardConf           as BC
+import qualified CPos                as CP
+import qualified CursesUI            as CU
+import qualified Game                as G
+import qualified Highscore           as HS
+import qualified HighscoreFile       as HSF
+import qualified Inventory           as I
+import qualified Pos                 as P
+import qualified Power               as Pow
+import qualified RollFrom            as RF
+import qualified Tutorial            as T
+
+scrW,scrH :: Int
+scrW = 60
+scrH = 20
+
+-- Can draw on board at CPos x y for x < w and y < h
+w,h :: Int
+w = B.w * 3 + 1
+h = B.h * 2 + 1
+
+invItemGlyph :: InvItem -> Glyph
+invItemGlyph e = Glyph c $ CStyle cyan aBold where
+    c = case e of
+        Orb          -> 'o'
+        Cloak        -> '['
+        Umbrella     -> '/'
+        Balloon _    -> '&'
+        Flash        -> '='
+        Camera _     -> ')'
+        Tent         -> 'A'
+        Spraypaint _ -> ':'
+
+drawStyledStrs :: CU.Window -> CP.CPos -> [(String, CStyle)] -> CU.UIM ()
+drawStyledStrs win (CP.CPos x0 y) = void . (`runStateT` x0) . mapM draw where
+    draw (s,style) = do
+        x <- get
+        lift $ CU.drawStr win style (CP.CPos x y) s
+        put $ x + length s
+
+twoCharNum :: Int -> String
+twoCharNum n | 0 <= n && n < 10 = ' ' : show n
+    | otherwise = take 2 $ show n
+
+drawStatus :: G.Game -> CU.UIM ()
+drawStatus (G.Game { G.life = life, G.maxLife = maxLife, G.score = score, G.level = level, G.round = rnd, G.junk = junk, G.equipment = equipment, G.board = B.Board { B.statuses = statuses } }) = do
+    let win = CU.StatusWin
+    unless (M.null statuses) $ drawStyledStrs win (CP.CPos 0 0) statusStrs
+    drawStyledStrs win (CP.CPos 0 1) numStrs
+    where
+    -- XXX: keep in sync with magic numbers in highlightTut
+    numStrs =
+        [ ("Life: ", style0)
+        , (twoCharNum life, lifeStyle)
+        , ("/", style0)
+        , (show maxLife, if maxLife == G.initLife then style0 else equipStyle Charm)
+        , ("   Score: ", style0)
+        , (twoCharNum score <> "/" <> show G.maxScore, style0)
+        , ("~", scoreStyle)
+        , ("   Level: " <> twoCharNum rnd <> ":", style0)
+        , (showLevel level, levelStyle level)
+        ] <> if junk == 0 && S.null equipment then [] else
+        [ ("   Junk: ", style0)
+        , (twoCharNum junk <> "/" <> show (S.size equipment + 2), style0)
+        , ("%", junkStyle)
+        ]
+    lifeStyle = case life of
+        n | n <= 0 -> CStyle (onRed black) aBold
+        1          -> CStyle red aBold
+        2          -> CStyle red a0
+        3          -> CStyle yellow aBold
+        4          -> CStyle yellow a0
+        5          -> style0
+        6          -> CStyle green a0
+        _          -> CStyle green aBold
+    statusStrs = intersperse ("   ", style0)
+        [ (show (fst status) <> " " <> twoCharNum (snd status), statStyle status)
+        | status <- M.assocs statuses ]
+    statStyle (B.Dazzled,_) = CStyle cyan aBold
+    statStyle (B.Ghost,_) = style0
+    statStyle (B.Smoke,_) = CStyle blue aBold
+    statStyle (B.Haste,n) = CStyle (if n `mod` 2 == 1 then red else yellow) aBold
+    statStyle (B.Foresight,_) = styleBold
+
+exitChar :: P.Dir -> Char
+exitChar = \case
+    P.DUp    -> '^'
+    P.DDown  -> 'v'
+    P.DRight -> '>'
+    P.DLeft  -> '<'
+
+drawBoard :: B.Board -> CU.UIM ()
+drawBoard = drawAlertedBoard . baseAlerted
+
+data AlertedBoard = AlertedBoard
+    { base          :: B.Board
+    , creatureMoves :: M.Map P.WPos Creature
+    , itemMoves     :: M.Map P.WPos Item
+    , itemUses      :: M.Map P.WPos Item
+    , highlightPs   :: S.Set P.Pos
+    , highlightWPs  :: S.Set P.WPos
+    }
+baseAlerted :: B.Board -> AlertedBoard
+baseAlerted bd = AlertedBoard bd M.empty M.empty M.empty S.empty S.empty
+
+drawTrans :: B.Transition -> CU.UIM ()
+drawTrans (B.Transition bd0 alerts) =
+    let alerted = foldl' applyAlert (baseAlerted bd0) alerts
+    in do
+        drawAlertedBoard alerted
+        CU.wRefresh CU.BoardWin
+        CU.wErase CU.BoardWin
+        liftIO (threadDelay 50000)
+    where
+    applyAlert alerted (B.AlertMoveCreature c p d) =
+        alerted { creatureMoves = M.insert (P.wposInDir p d) c $ creatureMoves alerted
+        , base = B.modCreatures (M.delete p) $ base alerted
+        }
+    applyAlert alerted (B.AlertMoveItem i p d) =
+        alerted { itemMoves = M.insert (P.wposInDir p d) i $ itemMoves alerted
+        , base = B.modItems (M.delete p) $ base alerted
+        }
+    applyAlert alerted (B.AlertUseItem i p d) =
+        alerted { itemUses = M.insert (P.wposInDir p d) i $ itemUses alerted
+        , base = B.modItems (M.delete p) $ base alerted
+        }
+    applyAlert alerted (B.AlertHighlight ps wps) =
+        alerted { highlightPs = ps `S.union` highlightPs alerted
+        , highlightWPs = wps `S.union` highlightWPs alerted
+        }
+
+char,bold,dim :: Char -> Glyph
+char c = Glyph c style0
+bold c = Glyph c styleBold
+dim c = Glyph c $ CStyle (onBlue white) a0
+
+levelStyle :: Int -> CStyle
+levelStyle 1 = CStyle green a0
+levelStyle 2 = CStyle white aBold
+levelStyle 3 = CStyle yellow aBold
+levelStyle _ = style0
+
+showLevel :: Int -> String
+showLevel l | l > 0 = (['A'..] !! (l-1)):""
+showLevel _ = "-"
+
+scoreStyle, junkStyle :: CStyle
+scoreStyle = CStyle yellow a0
+junkStyle = CStyle blue aBold
+
+creatureGlyph :: Creature -> Glyph
+creatureGlyph Player          = bold '@'
+creatureGlyph DeadPlayer      = Glyph '@' $ CStyle (onRed black) aBold
+creatureGlyph BasicMonster    = Glyph 'm' $ CStyle yellow a0
+creatureGlyph CalmMonster     = Glyph 'p' $ CStyle blue aBold
+creatureGlyph ChaseMonster    = Glyph 'c' $ CStyle yellow aBold
+creatureGlyph GhostMonster    = Glyph 'g' $ CStyle white aBold
+creatureGlyph SmartMonster    = Glyph 's' $ CStyle red aBold
+creatureGlyph (InflatedBalloon charges) = Glyph '0' . CStyle magenta $ if charges > 0 then aBold else a0
+
+itemGlyph :: Item -> Glyph
+itemGlyph Gem           = Glyph '*' $ CStyle green aBold
+itemGlyph Potion           = Glyph '!' $ CStyle green aBold
+itemGlyph MiniPotion           = Glyph '!' $ CStyle green a0
+itemGlyph ScoreTreasure      = Glyph '~' scoreStyle
+itemGlyph Junk      = Glyph '%' junkStyle
+itemGlyph (UmbrellaHandle d)           = Glyph (if d `elem` [P.DUp, P.DDown] then '|' else '-') $ CStyle magenta aBold
+itemGlyph CameraBoxed           = Glyph ')' $ CStyle cyan a0
+itemGlyph (RollingOrb _ _)           = Glyph 'o' $ CStyle cyan a0
+itemGlyph (ItemInvItem e) = invItemGlyph e
+
+wallGlyphVert :: Wall -> Glyph
+wallGlyphVert = \case
+    BasicWall -> bold wallchar
+    Pillar -> char '|'
+    Hedge -> Glyph wallchar $ CStyle green aBold
+    ThickHedge -> Glyph '║' $ CStyle green a0
+    Window -> Glyph wallchar $ CStyle cyan a0
+    BrokenWindow -> Glyph ';' $ CStyle cyan a0
+    (CloakWall _ _) -> Glyph wallchar $ CStyle cyan aBold
+    (UmbrellaWall d) -> Glyph (if d == P.DRight then '>' else '<') $ CStyle magenta aBold
+    TentWall -> Glyph wallchar $ CStyle red aBold
+    where wallchar = '│'
+
+wallGlyphHoriz :: Wall -> (Glyph,Glyph)
+wallGlyphHoriz = \case
+    Pillar               -> (char '-', char '-')
+    (UmbrellaWall P.DUp) -> (umb '/', umb '\\')
+    (UmbrellaWall _)     -> (umb '\\', umb '/')
+    BasicWall            -> doublet $ bold wallchar
+    Hedge                -> doublet . Glyph wallchar $ CStyle green aBold
+    ThickHedge           -> doublet . Glyph '═' $ CStyle green a0
+    Window               -> doublet . Glyph wallchar $ CStyle cyan a0
+    BrokenWindow         -> (Glyph '.' $ CStyle cyan a0 , Glyph ',' $ CStyle cyan a0)
+    (CloakWall _ _)      -> doublet . Glyph wallchar $ CStyle cyan aBold
+    TentWall -> doublet . Glyph wallchar $ CStyle red aBold
+    where
+    wallchar = '─'
+    umb c = Glyph c $ CStyle magenta aBold
+    doublet gl = (gl,gl)
+
+exitGlyphVert :: CStyle -> P.WPos -> Exit -> Glyph
+exitGlyphVert st wp = \case
+    Exit           -> bold $ exitChar (P.exitDir wp)
+    KeyExit        -> Glyph (exitChar (P.exitDir wp)) $ equipStyle Key
+    Entrance       -> char 'x'
+    UnseenBoundary -> char '.'
+    SeenBoundary   -> Glyph '│' st
+
+exitGlyphHoriz :: CStyle -> P.WPos -> Exit -> (Glyph,Glyph)
+exitGlyphHoriz st wp = \case
+    Exit           -> (bold $ exitChar (P.exitDir wp), Glyph '─' st)
+    KeyExit        -> (Glyph (exitChar (P.exitDir wp)) $ equipStyle Key, Glyph '─' st)
+    Entrance       -> (char 'x', Glyph '─' st)
+    UnseenBoundary -> doublet $ char '.'
+    SeenBoundary   -> doublet $ Glyph '─' st
+    where doublet gl = (gl,gl)
+
+-- positions in board window
+posCPosL, posCPosR, posIntCPos :: P.Pos -> CP.CPos
+posCPosL (P.Pos x y) = CP.CPos (3*(x+1) - 2) $ 2*(B.h - y) - 1
+posCPosR = (CP.CPos 1 0 <>) . posCPosL
+posIntCPos p = posCPosL p <> CP.CPos 2 (-1)
+wposCPos, wposCPosR :: P.WPos -> CP.CPos
+wposCPos (P.WPos p up) = posCPosL p <> if up then CP.CPos 0 (-1) else CP.CPos 2 0
+wposCPosR = (CP.CPos 1 0 <>) . wposCPos
+
+drawAlertedBoard :: AlertedBoard -> CU.UIM ()
+drawAlertedBoard AlertedBoard{ base = bd, creatureMoves = cmvs, itemMoves = imvs, itemUses = iuses, highlightPs = hps, highlightWPs = hwps } =
+    let wallsV :: M.Map P.WPos Glyph
+        wallsH :: M.Map P.WPos (Maybe Glyph,Maybe Glyph)
+        wallsV = highlightV `M.union` mvingV `M.union` wObscuredV `M.union` bdWallsV `M.union` borderV
+        wallsH = highlightH `M.union` mvingH `M.union` wObscuredH `M.union` bdWallsH `M.union` borderH
+        cells, items, creatures, obscured, powers :: M.Map P.Pos (Maybe Glyph,Maybe Glyph)
+        layer = M.unionWith $ \(l,r) (l',r') -> (l `mplus` l', r `mplus` r')
+        cells = highlightCells `layer` obscured `layer` creatures `layer` items `layer` powers
+        filterV = M.filterWithKey $ const . not . P.up
+        filterH = M.filterWithKey $ const . P.up
+        filterSV = S.filter $ not . P.up
+        filterSH = S.filter P.up
+        glyphsV f m = M.mapWithKey f $ filterV m
+        glyphsH f m = M.mapWithKey ((bimap Just Just .) . f) $ filterH m
+        borderV = glyphsV (exitGlyphVert levBoundSt) $ B.exits bd
+        borderH = glyphsH (exitGlyphHoriz levBoundSt) $ B.exits bd
+        bdWallsV = glyphsV (const wallGlyphVert) $ B.walls bd
+        bdWallsH = glyphsH (const wallGlyphHoriz) $ B.walls bd
+        levBoundSt = levelStyle . BC.level $ B.conf bd
+        items = M.mapWithKey itemGlyphs $ B.items bd
+        itemGlyphs p i = (Nothing,) . Just . powerBG p $ itemGlyph i
+        biGlyph gl = (Just gl, Just gl)
+        powerBG :: P.Pos -> Glyph -> Glyph
+        powerBG p
+            | Just pow <- B.powers bd M.!? p, Pow.charges pow > 0 = modColour onRed
+            -- | Just pow <- B.powers bd M.!? p, Pow.overUsable pow = modColour onYellow
+            | otherwise = id
+        powers = (Nothing,) . Just . powerGlyph <$> B.powers bd
+        powerGlyph pow = Glyph '"' $ case True of
+            _ | Pow.charges pow > 0 -> CStyle red aBold
+            _ | Pow.overUsable pow  -> equipStyle Siphon
+            _                       -> style0
+        creatures = (,Nothing) . Just . creatureGlyph' <$> B.creatures bd
+        creatureGlyph' Player = Glyph '@' $ CStyle col a where
+            col | B.isHasteRound bd = red
+                | B.hasted bd = yellow
+                | otherwise = white
+            a   | B.ghostly bd = a0
+                | otherwise = aBold
+        creatureGlyph' c = creatureGlyph c
+        obscured = M.fromSet (\p -> (Just . dim $ expectChar p,) . Just . powerBG p . dim $ obsChar p) $ B.poss S.\\ B.visible bd where
+            expectChar p
+                | B.expectant bd
+                , Just (Just c) <- B.expected bd M.!? p = glyphChar $ creatureGlyph' c
+                | otherwise = ' '
+            obsChar p
+                | p `S.member` B.unrevealed bd = expectedTreasureChar p
+                | otherwise = ' '
+            expectedTreasureChar = glyphChar . itemGlyph . B.treasureAt bd
+        wObscuredV = M.fromSet (const $ dim ' ') . filterSV $ obscuredWPoss
+        wObscuredH = M.fromSet (const . biGlyph $ dim ' ') . filterSH $ obscuredWPoss
+        obscuredWPoss = B.invisibleWPoss (B.tagged bd) (B.visible bd)
+        mvingV = M.map creatureGlyph' (filterV cmvs) `M.union` M.map itemGlyph (filterV $ imvs `M.union` iuses)
+        mvingH = M.map ((,Nothing) . Just . creatureGlyph') (filterH cmvs)
+            `M.union` M.map ((Nothing,) . Just . itemGlyph) (filterH imvs)
+            `M.union` M.map ((,Nothing) . Just . itemGlyph) (filterH iuses)
+        highlightCells = M.fromSet (const . biGlyph $ bold '#') hps
+        highlightV = M.fromSet (const $ bold '#') $ filterSV hwps
+        highlightH = M.fromSet (const . biGlyph $ bold '#') $ filterSH hwps
+
+        -- Positions with wall-intersection to top-right
+        intersections :: M.Map P.Pos Glyph
+        intersections = iHighlighted `M.union` iObscured `M.union` iWalls
+        iWalls = M.map (Glyph '·') . M.unionsWith pref $ M.fromList <$>
+            [ [ (p,i), (p <> if up then P.Pos (-1) 0 else P.Pos 0 (-1),i) ]
+            | (P.WPos p up, Just i) <- M.toList $
+                M.map wallI (B.walls bd) `M.union` M.map (const $ Just exitCol) (B.exits bd) ]
+            where
+            wallI BasicWall        = Just $ CStyle white aBold
+            wallI Hedge            = Just $ CStyle green aBold
+            wallI ThickHedge       = Just $ CStyle green a0
+            wallI Pillar           = Nothing
+            wallI Window           = Nothing
+            wallI BrokenWindow     = Nothing
+            wallI (UmbrellaWall _) = Nothing
+            wallI (CloakWall _ _)  = Just $ CStyle cyan aBold
+            wallI TentWall         = Just $ CStyle red aBold
+            exitCol = levBoundSt
+            pref a b = minimumBy (compare `on` cstyleCol) [a,b] -- white < green < magenta
+        iObscured = M.fromSet (const $ dim ' ') $ S.filter (\p -> P.x p < B.w-1 && P.y p < B.h-1 &&
+             and [ p' `S.member` M.keysSet obscured || not (B.inBounds p')
+                 | p' <- (p +^) <$> [ P.Pos x y | x <- [0,1], y <- [0,1] ] ]) B.poss
+        iHighlighted = M.fromSet (const $ bold '#') $ S.filter (\p -> P.x p < B.w-1 && P.y p < B.h-1 &&
+             and [ p' `S.member` hps
+                 | p' <- (p +^) <$> [ P.Pos x y | x <- [0,1], y <- [0,1] ] ]) B.poss
+
+        horizCPosMap :: M.Map P.Pos (Maybe Glyph, Maybe Glyph) -> M.Map CP.CPos Glyph
+        horizCPosMap m = M.mapMaybe fst (M.mapKeys posCPosL m) `M.union` M.mapMaybe snd (M.mapKeys posCPosR m)
+        horizWCPosMap :: M.Map P.WPos (Maybe Glyph, Maybe Glyph) -> M.Map CP.CPos Glyph
+        horizWCPosMap m = M.mapMaybe fst (M.mapKeys wposCPos m) `M.union` M.mapMaybe snd (M.mapKeys wposCPosR m)
+
+        glyphs :: M.Map CP.CPos Glyph
+        glyphs = M.unions
+            [ horizCPosMap cells
+            , M.mapKeys wposCPos wallsV
+            , horizWCPosMap wallsH
+            , M.mapKeys posIntCPos intersections
+            ]
+    in do
+        sequence_ $ M.mapWithKey (CU.drawGlyph CU.BoardWin) glyphs
+
+drawInv :: Maybe I.Slot -> Int -> Bool -> I.Inventory -> Maybe Pow.Power -> CU.UIM ()
+drawInv sel preserve highlightEmpty (I.Inventory inv) pow = do
+    let win = CU.InvWin
+    let str x y st = CU.drawStr win st (CP.CPos x y)
+    str 0 0 styleBold "Inventory:"
+    sequence_ $
+        [ do
+            str 0 slot style (show slot)
+            case me of
+                Nothing -> pure ()
+                Just e -> do
+                    CU.drawGlyph win (CP.CPos 2 slot) (invItemGlyph e)
+                    str 4 slot style $ show e
+        | slot <- I.slots
+        , let me = inv M.!? slot
+        , let style = CStyle col attr where
+                col | slot <= preserve = yellow
+                    | highlightEmpty && isNothing me = red
+                    | otherwise = white
+                attr | sel == Just slot = aBold
+                    | otherwise = a0
+        ] <>
+        [ str 0 (length I.slots + 2) style $ "0 \" " <> show tp <> " " <> show charges <> "/" <> show maxCharges
+        | Pow.Power tp charges maxCharges overUsable <- maybeToList pow
+        , let style | overUsable && charges == 0 = equipStyle Siphon
+                | otherwise = CStyle red $ if charges > 0 then aBold else a0
+        ]
+
+equipStyle :: Equipment -> CStyle
+equipStyle Bag      = CStyle yellow a0
+equipStyle Charm    = CStyle green aBold
+equipStyle GrabHand = CStyle red a0
+equipStyle Key      = CStyle blue aBold
+equipStyle Siphon   = CStyle yellow aBold
+
+drawEquip :: S.Set Equipment -> CU.UIM ()
+drawEquip es | S.null es = pure ()
+drawEquip es = do
+    let win = CU.EquipWin
+    let str x y st = CU.drawStr win st (CP.CPos x y)
+    str 0 0 styleBold "Equipment:"
+    forM_ (zip [1..] (S.toList es)) $ \(y,e) ->
+        str 0 y (equipStyle e) $ show e
+
+drawMessage :: G.Game -> CU.UIM ()
+drawMessage game = do
+    let win = CU.MessageWin
+        (text,style) = case G.playState game of
+            G.Dead            -> ("You died with " <> show (G.score game) <>
+                " points on level " <> show (G.round game) <>
+                ":" <> showLevel (G.level game) <> ".  [Space]", styleBold)
+            G.Won             -> ("Congratulations, you win!  [Space]", styleBold)
+            G.Tutorialising b -> (T.text b <> "  [Spc/T]", CStyle magenta aBold)
+            _                 -> ("", style0)
+    CU.drawStr win style (CP.CPos 0 0) text
+
+drawLevelInfo :: B.Board -> CU.UIM ()
+drawLevelInfo bd = do
+    drawRoll 0 (BC.creatureRoll bc) G.initCreatureSides creatureGlyph
+    drawRoll 1 (BC.wallRoll bc) G.initWallSides wallGlyphVert
+    drawDiffsLine 2
+    where
+    win = CU.LevelInfoWin
+    nullGlyph = char '-'
+    drawRoll :: Int -> RF.RollFrom a -> Int -> (a -> Glyph) -> CU.UIM ()
+    drawRoll m roll initSides f = sequence_ $
+        [ CU.drawGlyph win (CP.CPos n m) $ maybe nullGlyph f (RF.vals roll `atMay` n)
+        | n <- [0 .. RF.sides roll - 1]
+        ] <> [ CU.drawGlyph win (CP.CPos initSides m) $ char ']' ]
+    bc = B.conf bd
+    diffs = B.diffs bd
+    drawDiffsLine y = CU.drawStr win style0 (CP.CPos 0 y) introStr >> sequence_
+        [ do
+            draw b . char' $ exitChar dir
+            draw (b+1) (char ':')
+            forM (zip [0..] rdfs) (\(x,rdf) -> draw (b+3+x) $ rdfGlyph rdf)
+        | (n,dir) <- zip [0..] P.dirs
+        , dir `elem` possibleExitDirs
+        , let b = length introStr + 8*n
+        , let char'
+                | dir `elem` exitDirs = bold
+                | dir `elem` keyExitDirs = \c -> Glyph c $ equipStyle Key
+                | otherwise = char
+        , Just rdfs <- [diffs M.!? dir]
+        ]
+        where
+        introStr = "On exit:  "
+        draw x = CU.drawGlyph win (CP.CPos x y)
+        rdfGlyph (BC.Add (BC.DiffableCreature c))    = creatureGlyph c
+        rdfGlyph (BC.Swap _ (BC.DiffableCreature c)) = creatureGlyph c
+        rdfGlyph (BC.Add (BC.DiffableWall wl))       = wallGlyphVert wl
+        rdfGlyph (BC.Swap _ (BC.DiffableWall wl))    = wallGlyphVert wl
+        exitsWith ex = P.exitDir <$> M.keys (M.filter (== ex) (B.exits bd))
+        exitDirs = exitsWith Exit
+        keyExitDirs = exitsWith KeyExit
+        possibleExitDirs = exitDirs <> keyExitDirs <> exitsWith UnseenBoundary
+
+data HSInfo
+    = HSRank Int
+    | HSAlive
+    | HSDead
+    | HSWon
+
+drawMainScreen :: G.Game -> CU.UIM ()
+drawMainScreen game = do
+    let win = CU.MainWin
+        curHs = twiddle $ G.highscore Nothing game where
+            twiddle hs = hs { HS.maxLevel = 0, HS.maxRound = HS.maxRound hs + 1 }
+        centre style y s
+            | y >= scrH = pure ()
+            | otherwise = CU.drawStr win style (CP.CPos ((scrW - length s) `div` 2) y) s
+        drawTitle = sequence_ [ drawStyledStrs win (CP.CPos titleX y) s
+            | (y,s) <-
+                [ (0, [ ("·──·──·──·", bdSt), ("     ", bgSt) ])
+                , (1, [ ("│", bdSt), (" Fe@r of", styleBold)
+                    , ("│", bdSt), ("View ", bgSt) ])
+                , (2, [ ("·──·  ·──·", bdSt), ("     ", bgSt) ])
+                ]
+            ] where
+            titleX = (scrW - length "| Fe@r of|View") `div` 2
+            bdSt = CStyle yellow aBold
+            bgSt = CStyle (onBlue white) aBold
+        wonStyle = CStyle magenta aBold
+
+    ascii <- gets CU.asciiOnly
+
+    let drawHS :: Bool -> Int -> HSInfo -> HS.Highscore -> CU.UIM ()
+        drawHS showName y info hs =
+            drawStyledStrs win (CP.CPos (scoreX showName) y) $
+            (case info of
+                HSRank rank -> [(twoCharNum rank, styleBold)]
+                HSAlive     -> [(" @", styleBold)]
+                HSDead      -> [(" ",style0), ("@", CStyle (onRed white) aBold)]
+                HSWon       -> [(" ",style0), ("@", wonStyle)]
+            ) <>
+            [ ("   ", style0)
+            ] <>
+            [ (take 8 (fromMaybe "[anon]" (HS.name hs) <> repeat ' ') <> "  ", CStyle cyan aBold)
+            | showName
+            ] <>
+            [ (twoCharNum (HS.score hs) <> "~",
+                if HS.score hs == G.maxScore then wonStyle else scoreStyle)
+            , ("  ", style0)
+            , (twoCharNum (HS.maxRound hs) <> ":", style0)
+            , let lev = HS.maxLevel hs in (showLevel lev, levelStyle lev)
+            ] <>
+            [ ("  ", style0) ] <>
+            [ (take 1 $ show e, equipStyle e) | e <- S.toList $ HS.equipment hs ]
+        scoreX showName = min ((scrW - l) `div` 2) (scrW - l - 1 - aKeyL)
+            where l = sum $ [length "99   99~  99:C"]
+                    <> [11 | showName] <> [2 + length allEquipment]
+        additionalKeys =
+            [ " More keys:" ]
+            <> [ "T: Hints" | T.TMeta `S.notMember` G.unseenBeats game ]
+            <> [ "-: " <> "ASCII " <> (if ascii then "[x]" else "[ ]")
+               , "Q: Exit" ]
+        aKeyL = maximum $ length <$> additionalKeys
+
+    let keysLine y = centre style0 y "Keys: cursors / WASD / HJKL; 0-9"
+
+    drawTitle
+    if HS.maxRound curHs > 1
+        then do
+            centre styleBold 3 "Game in progress:"
+            drawHS False 4 HSAlive curHs
+            centre styleBold 6 "Press Space to continue"
+        else case G.prevHS game of
+                Just prev -> do
+                    centre style0 3 "Last game:"
+                    let info | HS.score prev >= G.maxScore = HSWon
+                            | otherwise = HSDead
+                    drawHS False 4 info prev
+                    centre styleBold 6 "Press Space to start new game"
+                Nothing -> centre styleBold 4 "Press Space to start"
+    keysLine 7
+
+    hss <- liftIO HSF.get
+    unless (null hss) $ do
+        let someNamed = any (isJust . HS.name) hss
+        drawStyledStrs win (CP.CPos (scoreX someNamed - 1) 9) $
+            [ ("Rank ", styleBold) ] <>
+            [ ("  Name    ", CStyle cyan aBold) | someNamed ] <>
+            [ ("Score ", scoreStyle)
+            , ("Level ", style0)
+            , ("Equip", style0) ]
+        sequence_ [ drawHS someNamed (10+i) (HSRank $ 1+i) hs | (i,hs) <- zip [0..] hss ]
+
+    sequence_ [ CU.drawStr win
+            (CStyle (onBlue white) $ if n == 0 then aBold else a0)
+            (CP.CPos (scrW - 2 - aKeyL) $ 10 + n) . take aKeyL $ s <> repeat ' '
+        | (s,n) <- zip additionalKeys [0..]
+        ]
+
+tutBox :: T.Beat -> Maybe (CP.CPos, [Glyph])
+tutBox = tutBox' where
+    tutBox' (T.Movement p) = Just (boardOffset <> posCPosL p, [creatureGlyph Player])
+    tutBox' (T.Trapped p) = Just (boardOffset <> posCPosL p, [creatureGlyph Player])
+    tutBox' (T.SeeMonster p c) = Just (boardOffset <> posCPosL p, [creatureGlyph c])
+    tutBox' (T.SeeExit wp) = Just (boardOffset <> wposCPos wp, [bold . exitChar $ P.exitDir wp])
+    tutBox' (T.SeeItem p i) = Just (boardOffset <> posCPosR p, [itemGlyph i])
+    tutBox' (T.SeePotion p) = Just (boardOffset <> posCPosR p, [itemGlyph Potion])
+    tutBox' (T.SeeMiniPotion p) = Just (boardOffset <> posCPosR p, [itemGlyph MiniPotion])
+    tutBox' (T.SeeScore p) = Just (boardOffset <> posCPosR p, [itemGlyph ScoreTreasure])
+    tutBox' (T.SeeJunk p) = Just (boardOffset <> posCPosR p, [itemGlyph Junk])
+    tutBox' (T.SeeGem p) = Just (boardOffset <> posCPosR p, [itemGlyph Gem])
+    tutBox' T.CollectItem = Just (invOffset <> CP.CPos 0 1, [char '1'])
+    tutBox' T.CollectGem = Just (invOffset <> CP.CPos 0 10, [Glyph '0' $ CStyle red aBold])
+    tutBox' T.CollectScore = Just (statusOffset <> CP.CPos 20 0, (char <$> (" 1/" <> show G.maxScore)) <> [Glyph '~' scoreStyle])
+    tutBox' (T.Hurt l ml) = Just (statusOffset <> CP.CPos 6 0, char <$> twoCharNum l <> "/" <> show ml)
+    tutBox' T.Timer = Just (levelInfoOffset <> CP.CPos (G.initCreatureSides - 4) 0, char <$> "-  ]")
+    tutBox' T.SecondRound = Just (levelInfoOffset <> CP.CPos 0 2, char <$> "On exit:")
+    tutBox' _                  = Nothing
+    boardOffset = CP.CPos 1 3
+    invOffset = CP.CPos (1+w+2) 3
+    statusOffset = CP.CPos 0 1
+    afterBoard = 3 + max h (3 + length I.slots)
+    levelInfoOffset = CP.CPos 1 (1 + afterBoard)
+
+highlightTut :: T.Beat -> CU.UIM ()
+highlightTut = maybe (pure ()) (uncurry CU.drawHighlightBoxChars) . tutBox
diff --git a/CursesUI.hs b/CursesUI.hs
new file mode 100644
--- /dev/null
+++ b/CursesUI.hs
@@ -0,0 +1,167 @@
+{-# LANGUAGE CPP        #-}
+{-# LANGUAGE LambdaCase #-}
+
+module CursesUI where
+
+import           Control.Exception.Safe
+import           Control.Monad.State
+import           Data.Char              (chr)
+import           Foreign.Ptr
+
+import qualified Data.Map.Strict        as M
+import qualified UI.HSCurses.Curses     as C
+
+import           CStyle
+
+import qualified CPos                   as CP
+import qualified KeyBindings            as KB
+
+data Window
+    = MainWin
+    | StatusWin
+    | BoardWin
+    | InvWin
+    | EquipWin
+    | LevelInfoWin
+    | MessageWin
+    | TutorialWin
+    deriving (Eq,Ord,Enum,Bounded)
+allWindows :: [Window]
+allWindows = [minBound..maxBound]
+
+data UIState = UIState
+    { dispCPairs    :: [C.Pair]
+    , uiKeyBindings :: KB.KeyBindings
+    , windows       :: M.Map Window C.Window
+    , asciiOnly     :: Bool
+    }
+type UIM = StateT UIState IO
+nullUIState :: UIState
+nullUIState = UIState [] [] M.empty False
+
+insWin :: Window -> C.Window -> UIM ()
+insWin w cw = do
+    modify $ \s -> s {windows = M.insert w cw $ windows s}
+    wsetBkgrnd w
+
+getWin :: Window -> UIM C.Window
+getWin w = gets $ M.findWithDefault nullPtr w . windows
+
+getBindings :: UIM KB.KeyBindings
+getBindings = gets $ (<> KB.defaultBindings) . uiKeyBindings
+
+charify :: C.Key -> Maybe Char
+charify key = case key of
+    C.KeyChar ch   -> Just ch
+    C.KeyBackspace -> Just '\b'
+    C.KeyLeft      -> Just '←'
+    C.KeyRight     -> Just '→'
+    C.KeyDown      -> Just '↓'
+    C.KeyUp        -> Just '↑'
+    _              -> Nothing
+
+handleEsc :: C.Key -> IO C.Key
+handleEsc k@(C.KeyChar '\ESC') = do
+    C.timeout 100
+    cch <- C.getch
+    C.timeout (-1)
+    pure $ if cch == -1 then k
+        else C.KeyChar $ chr $ fromIntegral cch+128
+handleEsc k = pure k
+
+-- From Curses.CursesHelper:
+-- | Converts a list of 'Curses.Color' pairs (foreground color and
+--   background color) into the curses representation 'Curses.Pair'.
+colorsToPairs :: [(C.Color, C.Color)] -> IO [C.Pair]
+colorsToPairs cs = do
+    p <- C.colorPairs
+    let nColors = length cs
+        blackWhite = p < nColors
+    if blackWhite then pure $ replicate nColors $ C.Pair 0
+        -- print ("Terminal does not support enough colors. Number of " <>
+        --          " colors requested: " <> show nColors <>
+        --          ". Number of colors supported: " <> show p)
+    else mapM toPairs (zip [1..] cs)
+    where toPairs (n, (fg, bg)) = do
+            let p = C.Pair n
+            C.initPair p fg bg
+            pure p
+
+setBkgrnd :: UIM ()
+setBkgrnd = do
+    cpairs <- gets dispCPairs
+    liftIO . C.bkgrndSet a0 $ cpairs !! white
+    liftIO $ C.erase >> C.refresh
+
+wsetBkgrnd :: Window -> UIM ()
+-- >= hscurses-1.5.1 required for C.wbkgrndSet
+#if MIN_VERSION_hscurses(1,5,1)
+wsetBkgrnd w = do
+    cpairs <- gets dispCPairs
+    cw <- getWin w
+    liftIO . C.wbkgrndSet cw a0 $ cpairs !! white
+    liftIO $ C.werase cw >> C.wRefresh cw
+#else
+wsetBkgrnd _ = pure ()
+#endif
+
+wSetStyle :: Window -> CStyle -> UIM ()
+wSetStyle w (CStyle col attr) = do
+    cpairs <- gets dispCPairs
+    cw <- getWin w
+    liftIO $ C.wAttrSet cw (attr, cpairs!!col)
+withStyle :: Window -> CStyle -> (UIM a -> UIM a)
+withStyle w style m = wSetStyle w style >> (m <* wSetStyle w style0)
+
+subCharAscii :: Bool -> Char -> Char
+subCharAscii True = \case
+    '·' -> '+'
+    '┌' -> '+'
+    '┐' -> '+'
+    '└' -> '+'
+    '┘' -> '+'
+    '│' -> '|'
+    '║' -> '}'
+    '─' -> '-'
+    '═' -> '='
+    c   -> c
+subCharAscii False = id
+
+drawHighlightBoxChars :: CP.CPos -> [Glyph] -> UIM ()
+drawHighlightBoxChars (CP.CPos x y) gls = do
+    -- hscurses doesn't expose mvwin, so manually recreate the window in the
+    -- right position:
+    wnoutRefresh TutorialWin
+    liftIO . C.delWin =<< getWin TutorialWin
+    let w = 2 + length gls
+    insWin TutorialWin =<< liftIO (C.newWin 3 w (y-1) (x-1))
+    ascii <- gets asciiOnly
+    withStyle TutorialWin (CStyle magenta aBold) $ liftIO . drawBorder ascii (3,w) =<< getWin TutorialWin
+    sequence_ [ drawGlyph TutorialWin (CP.CPos (1+n) 1) gl | (gl,n) <- zip gls [0..] ]
+    where
+    -- Draw border manually rather than using C.wBorder:
+    -- default border characters are ugly on e.g. windows PuTTY,
+    -- and trying to set C.Border to use box-drawing chars doesn't work.
+    drawBorder :: Bool -> (Int,Int) -> C.Window -> IO ()
+    drawBorder ascii (h,w) cw = do
+        let add yy xx = C.mvWAddStr cw yy xx . (subCharAscii ascii <$>)
+        add 0 0 $ '┌':replicate (w-2) '─' <> "┐"
+        sequence_ [ add y' 0 "│" >> add y' (w-1) "│"
+            | y' <- [1..h-2] ]
+        -- |This throws an error due to moving cursor out of the window
+        add (h-1) 0 ('└':replicate (w-2) '─' <> "┘")
+            `catchIO` (\_ -> pure ())
+
+drawStr :: Window -> CStyle -> CP.CPos -> String -> UIM ()
+drawStr w style (CP.CPos x y) s = do
+    ascii <- gets asciiOnly
+    cw <- getWin w
+    withStyle w style . liftIO $ C.mvWAddStr cw y x (subCharAscii ascii <$> s)
+
+drawGlyph :: Window -> CP.CPos -> Glyph -> UIM ()
+drawGlyph w p (Glyph ch style) = drawStr w style p $ ch:""
+
+wErase, wRefresh, wnoutRefresh :: Window -> UIM ()
+wErase w = liftIO . C.werase =<< getWin w
+wRefresh w = liftIO . C.wRefresh =<< getWin w
+wnoutRefresh w = liftIO . C.wnoutRefresh =<< getWin w
diff --git a/CursesUIMInstance.hs b/CursesUIMInstance.hs
new file mode 100644
--- /dev/null
+++ b/CursesUIMInstance.hs
@@ -0,0 +1,106 @@
+{-# OPTIONS_GHC -fno-warn-orphans #-}
+
+{-# LANGUAGE FlexibleContexts  #-}
+{-# LANGUAGE FlexibleInstances #-}
+{-# LANGUAGE TupleSections     #-}
+
+module CursesUIMInstance where
+
+import           Control.Monad.State
+import           Data.List                ((\\))
+import           Data.Maybe
+
+import qualified UI.HSCurses.Curses       as C
+import qualified UI.HSCurses.CursesHelper as CH
+
+import           CStyle
+import           CursesUI
+
+import qualified Command                  as Cmd
+import qualified CPos                     as CP
+import qualified CursesDraw               as CD
+import qualified Game                     as G
+import qualified Inventory                as I
+import qualified UIMonad                  as UIM
+
+instance UIM.UIMonad UIM where
+    runUI m = evalStateT m nullUIState
+    initUI = do
+        _ <- liftIO $ CH.start >> C.cursSet C.CursorInvisible
+        cpairs <- liftIO . colorsToPairs $
+            concat [ (,c) <$> cols
+                | let cols =
+                        [ CH.white, CH.red, CH.green, CH.yellow
+                        , CH.blue, CH.magenta, CH.cyan, CH.black]
+                , c <- [CH.black,CH.blue,CH.red,CH.yellow]
+                ]
+        modify $ \s -> s {dispCPairs = cpairs}
+        setBkgrnd
+        insWin StatusWin =<< liftIO (C.newWin 2 CD.scrW 0 0)
+        insWin BoardWin =<< liftIO (C.newWin CD.h (CD.w+1) 3 1)
+        insWin InvWin =<< liftIO (C.newWin (3 + length I.slots) 20 3 (1+CD.w+3))
+        insWin EquipWin =<< liftIO (C.newWin (3 + length I.slots) 15 3 (1+CD.w+3+20))
+        let afterBoard = 3 + max CD.h (3 + length I.slots)
+        insWin LevelInfoWin =<< liftIO (C.newWin 3 CD.scrW (1 + afterBoard) 1)
+        insWin MessageWin =<< liftIO (C.newWin 1 CD.scrW (1 + 3 + 1 + afterBoard) 0)
+        insWin MainWin =<< liftIO (C.newWin CD.scrH CD.scrW 0 0)
+        insWin TutorialWin =<< liftIO (C.newWin 3 3 0 50)
+        pure True
+    endUI = liftIO CH.end
+    draw game = unlessSmall $ do
+        drawState
+        forM_ (allWindows \\ stateWins) wnoutRefresh
+        forM_ stateWins wnoutRefresh
+        liftIO C.update
+        forM_ stateWins wErase
+        where
+        st = G.playState game
+        stateWins = case st of
+            G.RoundEnded      -> [MainWin]
+            G.Tutorialising b | isJust (CD.tutBox b) -> gameWindows <> [TutorialWin]
+            _                 -> gameWindows
+        gameWindows = allWindows \\ [MainWin,TutorialWin]
+        drawState = case st of
+            G.RoundEnded -> CD.drawMainScreen game
+            _ -> do
+                let bd = G.board game
+                forM_ (reverse $ G.transitions game) CD.drawTrans
+                CD.drawBoard bd
+                CD.drawInv (G.selectedSlot game) (G.preserveSlots game) (G.canGrab game) (G.inventory game) (G.powerOn game)
+                CD.drawEquip $ G.equipment game
+                CD.drawStatus game
+                CD.drawLevelInfo bd
+                CD.drawMessage game
+                case st of
+                    G.Tutorialising b -> CD.highlightTut b
+                    _                 -> pure ()
+        unlessSmall m = do
+            (h,w) <- liftIO C.scrSize
+            if h < CD.scrH || w < CD.scrW then
+                let s = "Terminal too small!"
+                in if w < length s || h < 1 then pure ()
+                else do
+                    liftIO $ C.erase >> C.refresh
+                    drawStr StatusWin style0 (CP.CPos 0 0) s
+                    wRefresh StatusWin
+            else m
+    suspend = do
+        liftIO $ CH.suspend >> C.resetParams
+        UIM.redraw
+    redraw = liftIO $ C.endWin >> C.refresh
+    setAsciiOnly a = modify $ \s -> s { asciiOnly = a }
+    toggleAsciiOnly = modify $ \s -> s { asciiOnly = not (asciiOnly s) }
+
+    setUIBinding ch cmd = modify $ \s -> s { uiKeyBindings = (ch,cmd) : uiKeyBindings s }
+
+    getChRaw = (charify <$>) $ liftIO $ CH.getKey (pure ()) >>= handleEsc
+    getInput = do
+        let userResizeCode = 1337  -- XXX: chosen not to conflict with HSCurses codes
+        key <- liftIO $ CH.getKey (C.ungetCh userResizeCode) >>= handleEsc
+        if key == C.KeyUnknown userResizeCode
+            then do
+                _ <- liftIO C.scrSize
+                pure [Cmd.Redraw]
+            else case charify key of
+                Just ch -> maybeToList . lookup ch <$> getBindings
+                _       -> pure []
diff --git a/Equipment.hs b/Equipment.hs
new file mode 100644
--- /dev/null
+++ b/Equipment.hs
@@ -0,0 +1,16 @@
+module Equipment where
+
+data Equipment
+    = Bag
+    | Charm
+    | GrabHand
+    | Key
+    | Siphon
+    deriving (Eq, Ord, Show, Enum, Bounded)
+
+allEquipment :: [Equipment]
+allEquipment = [minBound..maxBound]
+
+equipmentStr :: Equipment -> String
+equipmentStr GrabHand = "Grab hand"
+equipmentStr e        = show e
diff --git a/Exit.hs b/Exit.hs
new file mode 100644
--- /dev/null
+++ b/Exit.hs
@@ -0,0 +1,10 @@
+module Exit where
+
+data Exit
+    = Exit
+    | KeyExit
+    | Entrance
+    | UnseenBoundary
+    | SeenBoundary
+    deriving (Eq,Ord)
+
diff --git a/Game.hs b/Game.hs
new file mode 100644
--- /dev/null
+++ b/Game.hs
@@ -0,0 +1,457 @@
+{-# LANGUAGE CPP                   #-}
+{-# LANGUAGE FlexibleContexts      #-}
+{-# LANGUAGE FlexibleInstances     #-}
+{-# LANGUAGE LambdaCase            #-}
+{-# LANGUAGE MultiParamTypeClasses #-}
+
+module Game where
+
+import           Prelude               hiding (round)
+
+import           Control.Monad.Random
+import           Control.Monad.State
+import           Control.Monad.Writer
+import           Data.Functor
+import           Data.Functor.Identity
+import           Data.Maybe
+
+import qualified Data.IntMap.Strict    as IM
+import qualified Data.Map.Strict       as M
+import qualified Data.Set              as S
+
+import           Creature
+import           Equipment
+import           Exit
+import           Group
+import           Item
+import           Rand
+import           Wall
+
+import qualified Board                 as B
+import qualified BoardConf             as BC
+import qualified Command               as C
+import qualified Highscore             as HS
+import qualified Inventory             as I
+import qualified Pos                   as P
+import qualified Power                 as Pow
+import qualified RollFrom              as RF
+import qualified Tutorial              as T
+
+data Game = Game
+    { board        :: B.Board
+    , transitions  :: [ B.Transition ]
+    , inventory    :: I.Inventory
+    , equipment    :: S.Set Equipment
+    , selectedSlot :: Maybe I.Slot
+    , score        :: Int
+    , life         :: Int
+    , maxLife      :: Int
+    , junk         :: Int
+    , level        :: Int
+    , round        :: Int
+    , roundItems   :: [Item]
+    , levels       :: IM.IntMap BC.BoardConf
+    , prev         :: Maybe Game
+    , unseenBeats  :: S.Set T.Type
+    , prevHS       :: Maybe HS.Highscore
+    , gen          :: StdGen
+    }
+
+maxLevel, maxScore, initLife, charmBonus :: Int
+maxLevel = 3
+maxScore = 25
+initLife = 5
+charmBonus = 1
+
+initCreatureSides, initWallSides :: Int
+initCreatureSides = 36
+initWallSides = 30
+
+baseLevels :: IM.IntMap BC.BoardConf
+baseLevels = IM.fromList
+    [ (1, BC.BoardConf 1
+        (RF.RollFrom initCreatureSides $ replicate 5 BasicMonster)
+        (RF.RollFrom initWallSides $ replicate 6 Hedge))
+    , (2, BC.BoardConf 2
+        (RF.RollFrom initCreatureSides $ replicate 5 BasicMonster)
+        (RF.RollFrom initWallSides $ replicate 6 BasicWall <> [Pillar]))
+    , (3, BC.BoardConf 3
+        (RF.RollFrom initCreatureSides $ replicate 5 BasicMonster)
+        (RF.RollFrom initWallSides $ replicate 6 BasicWall <> [Window, Window]))
+    ]
+
+new :: MonadIO m => m Game
+new = do
+    g <- initStdGen
+    pure $ Game { board = B.empty, transitions = [], inventory = I.empty, equipment = S.empty, selectedSlot = Nothing, score = 0, life = 0, maxLife = 0, junk = 0, level = 0, round = 0, roundItems = [], levels = baseLevels, prev = Nothing, unseenBeats = S.fromList T.allTypes, prevHS = Nothing, gen = g }
+
+modBoard :: (B.Board -> B.Board) -> Game -> Game
+modBoard f game = game { board = f $ board game }
+setBoard :: B.Board -> Game -> Game
+setBoard = modBoard . const
+
+modScore, modLife, modMaxLife, modJunk, modLevel, modRound :: (Int -> Int) -> Game -> Game
+modScore f game = game { score = f $ score game }
+modLife f game = game { life = f $ life game }
+modMaxLife f game = game { maxLife = f $ maxLife game }
+modJunk f game = game { junk = f $ junk game }
+modLevel f game = game { level = f $ level game }
+modRound f game = game { round = f $ round game }
+setScore, setLife, setMaxLife, setJunk, setLevel, setRound :: Int -> Game -> Game
+setScore = modScore . const
+setLife = modLife . const
+setMaxLife = modMaxLife . const
+setJunk = modJunk . const
+setLevel = modLevel . const
+setRound = modRound . const
+
+setRoundItems :: [Item] -> Game -> Game
+setRoundItems is game = game { roundItems = is }
+
+modLevels :: (IM.IntMap BC.BoardConf -> IM.IntMap BC.BoardConf) -> Game -> Game
+modLevels f game = game { levels = f $ levels game }
+
+modPrev :: (Maybe Game -> Maybe Game) -> Game -> Game
+modPrev f game = game { prev = f $ prev game }
+setPrev :: Maybe Game -> Game -> Game
+setPrev = modPrev . const
+
+modLifeWithMax, modScoreWithMax :: (Int -> Int) -> Game -> Game
+modLifeWithMax f game = modLife (min (maxLife game) . f) game
+modScoreWithMax f = modScore $ min maxScore . f
+
+modTransitions :: ([B.Transition] -> [B.Transition]) -> Game -> Game
+modTransitions f game = game { transitions = f $ transitions game }
+setTransitions :: [B.Transition] -> Game -> Game
+setTransitions = modTransitions . const
+pushTransition :: B.Transition -> Game -> Game
+pushTransition = modTransitions . (:)
+
+setSelectedSlot :: Maybe I.Slot -> Game -> Game
+setSelectedSlot slot game = game { selectedSlot = slot }
+
+modInventory :: (I.Inventory -> I.Inventory) -> Game -> Game
+modInventory f game = game { inventory = f $ inventory game }
+setInventory :: I.Inventory -> Game -> Game
+setInventory = modInventory . const
+
+modEquipment :: (S.Set Equipment -> S.Set Equipment) -> Game -> Game
+modEquipment f game = game { equipment = f $ equipment game }
+setEquipment :: S.Set Equipment -> Game -> Game
+setEquipment = modEquipment . const
+
+modUnseenBeats :: (S.Set T.Type -> S.Set T.Type) -> Game -> Game
+modUnseenBeats f game = game { unseenBeats = f $ unseenBeats game }
+setUnseenBeats :: S.Set T.Type -> Game -> Game
+setUnseenBeats = modUnseenBeats . const
+
+setPrevHS :: Maybe HS.Highscore -> Game -> Game
+setPrevHS mhs game = game { prevHS = mhs }
+
+hasEquip :: Equipment -> Game -> Bool
+hasEquip e = (e `S.member`) . equipment
+
+preserveSlots :: Game -> Int
+preserveSlots game
+    | hasEquip Bag game = 1
+    | otherwise = 0
+
+canGrab :: Game -> Bool
+canGrab = hasEquip GrabHand
+
+highscore :: Maybe HS.Username -> Game -> HS.Highscore
+highscore name game = HS.Highscore
+    { HS.score = score game
+    , HS.maxRound = round game
+    , HS.maxLevel = fix0 $ level game
+    , HS.equipment = equipment game
+    , HS.name = name
+    }
+    where
+    fix0 0 = 3
+    fix0 n = n
+
+type T m = StateT Game m
+
+runT :: MonadIO m => T m a -> m a
+runT m = evalStateT m =<< new
+
+nullGen :: StdGen
+nullGen = mkStdGen 0
+
+evalR :: MonadState Game m => Rand StdGen a -> m a
+evalR m = do
+    game <- get
+    let (a,g) = runRand m $ gen game
+    put $ game {gen = g}
+    pure a
+
+modifyR :: MonadState Game m => (Game -> Rand StdGen Game) -> m ()
+modifyR f = do
+    game <- get
+    let (game',g) = runRand (f game) $ gen game
+    put $ game' {gen = g}
+
+modBoardM :: Monad m => (B.Board -> m B.Board) -> Game -> m Game
+modBoardM f game =  (`setBoard` game) <$> f (board game)
+
+initGame, nextRound :: (MonadState Game m, MonadIO m) => m ()
+initGame = do
+    beats <- gets unseenBeats
+    hs <- gets $ highscore Nothing
+    put =<< new
+    let mhs = if HS.maxRound hs > 0 then Just hs else Nothing
+    modify $ setPrevHS mhs . setUnseenBeats beats
+nextRound = do
+    modify . modInventory . I.clearAllBut =<< gets preserveSlots
+    modify $ modRound (+1) . setLevel 1 . setPrev Nothing
+    charmed <- gets $ hasEquip Charm
+    let l = initLife + if charmed then charmBonus else 0
+    modify $ setLife l . setMaxLife l
+    modify . setRoundItems =<< evalR (take 3 <$> shuffle findableTreasures)
+    enterNewBoard True =<< evalR (randMemberUnsafe B.boundaryWPoss)
+    endTurn
+
+enterNewBoard :: MonadState Game m => Bool -> P.WPos -> m ()
+enterNewBoard doRecharge e = do
+    powers <- gets $ (if doRecharge then M.map Pow.recharge else id) . B.powers . board
+    bc <- gets currentLevelBC
+    diffs <- evalR $ BC.genDiffs bc
+    is <- gets roundItems
+    modify . setBoard $ (B.enterAt e $ B.new bc) { B.powers = powers, B.diffs = diffs, B.possItems = is}
+    setFov
+    where
+    currentLevelBC game = fromMaybe BC.emptyBoardConf . (IM.!? level game) $ levels game
+
+
+setFov :: MonadState Game m => m ()
+setFov = modifyR . modBoardM . B.setFov =<< gets (hasEquip Key)
+
+addJunk :: MonadState Game m => m ()
+addJunk = do
+    modify (modJunk (+1))
+    (gets enough >>=) . flip when $ do
+        modify $ setJunk 0
+        es <- gets equipment
+        evalR (randMember (S.fromList allEquipment S.\\ es)) >>= \case
+            Nothing -> modify $ modScoreWithMax (+1)
+            Just e  -> do
+                modify . modEquipment $ S.insert e
+                onAdd e
+    where
+    enough g = junk g > S.size (equipment g) + 1
+    onAdd Charm = modify $ modMaxLife (+charmBonus)
+    onAdd Siphon = modify . modBoard $ B.modPowers (M.map $ Pow.setOverUsable True)
+    onAdd _     = pure ()
+
+collect :: MonadState Game m => [Item] -> m ()
+collect = mapM_ collect' where
+    collect' Gem                = modify . modBoard . B.addPower =<< gets (hasEquip Siphon)
+    collect' ScoreTreasure           = modify $ modScoreWithMax (+1)
+    collect' Potion           = modify $ modLifeWithMax (+4)
+    collect' MiniPotion           = modify $ modLifeWithMax (+2)
+    collect' Junk             = addJunk
+    collect' (UmbrellaHandle _) = collect' (ItemInvItem Umbrella)
+    collect' CameraBoxed        = modify . modInventory $ snd . I.add (Camera initCameraCharge)
+    collect' (RollingOrb _ _)   = collect' (ItemInvItem Orb)
+    collect' (ItemInvItem (Camera 0))      = pure ()
+    collect' (ItemInvItem e)      = modify . modInventory $ snd . I.add e
+
+clearTrans :: MonadState Game m => m ()
+clearTrans = modify $ setTransitions []
+
+modBoardTellM :: MonadState Game m => (B.Board -> WriterT a m B.Board) -> m a
+modBoardTellM f = do
+    (bd,a) <- runWriterT . f =<< gets board
+    modify (setBoard bd) $> a
+modBoardTell :: MonadState Game m => (B.Board -> Writer a B.Board) -> m a
+modBoardTell = modBoardTellM . (mapWriterT (pure . runIdentity) .)
+
+exitLevel :: MonadState Game m => P.WPos -> m ()
+exitLevel exitPos = do
+    endLevel $ P.exitDir exitPos
+    lev <- gets level
+    when (lev <= maxLevel) $
+        enterNewBoard False $ B.oppositeWPos exitPos
+    where
+    endLevel :: MonadState Game m => P.Dir -> m ()
+    endLevel dir = do
+        diffs <- gets $ B.diffs . board
+        lev <- gets level
+        modify . modLevels $ IM.adjust (BC.apply diffs dir) lev
+        modify (modLevel $ (`mod` 4) . (+1))
+
+movePlayer :: MonadState Game m => P.Dir -> m ()
+movePlayer dir = do
+    bd <- gets board
+    mr <- modBoardTell $ B.movePlayers dir
+    when (getAny . B.someAction $ mr) $ do
+        modify $ modLifeWithMax (+ (-(getSum $ B.damage mr)))
+        showAlerts bd $ B.alerts mr
+        envAct
+        mapM_ exitLevel $ B.exitings mr
+        endTurn
+
+showAlerts :: MonadState Game m => B.Board -> [B.Alert] -> m ()
+showAlerts bd alerts = unless (null alerts) $ modify . pushTransition $ B.Transition bd alerts
+
+useInvSlotInDir :: MonadState Game m => I.Slot -> P.Dir -> m ()
+useInvSlotInDir slot dir =
+    gets ((M.!? slot) . I.invItems . inventory) >>= \case
+        Nothing -> (gets canGrab >>=) . flip when $ do
+            is <- modBoardTell (B.grabItem dir)
+            unless (null is) $ collect is >> envAct >> endTurn
+        Just e -> do
+            bd <- gets board
+            case runWriterT $ B.tryUseInvItem e dir bd of
+                Nothing -> pure ()
+                Just (bd', alerts) -> do
+                    showAlerts bd alerts
+                    modify $ setBoard bd'
+                    modify . modInventory . I.modInvItems $ useUp slot
+                    envAct
+                    endTurn
+    where
+    useUp :: I.Slot -> M.Map I.Slot InvItem -> M.Map I.Slot InvItem
+    useUp s inv
+        | Just (Spraypaint n) <- inv M.!? s
+            , n > 1 = M.insert s (Spraypaint $ n-1) inv
+        | otherwise = M.delete s inv
+
+
+envAct :: MonadState Game m => m ()
+envAct = do
+    bd <- gets board
+    modBoardTellM (mapWriterT evalR . B.npcsAct) >>= showAlerts bd
+    bd' <- gets board
+    modBoardTell B.doPhysics >>= showAlerts bd'
+    collect =<< modBoardTell B.collectItems
+    setFov
+    -- | collect again, in case vision spawned something on our loc
+    collect =<< modBoardTell B.collectItems
+
+undoTurns :: Int
+undoTurns = 5
+
+endTurn :: MonadState Game m => m ()
+endTurn = do
+    undoCharges <- gets $ maybe 0 Pow.activatableTimes . (M.!? undoPos) . B.powers . board
+    modify . eraseBefore $ undoTurns * undoCharges
+    modify . setPrev . Just =<< get
+    gets ((<=0) . life) >>= flip when (modify $ modBoard B.setPlayerDead)
+    where
+    eraseBefore n | n <= 0 = setPrev Nothing
+    eraseBefore n = modPrev (eraseBefore (n-1) <$>)
+    undoPos = P.Pos 2 2
+
+powerOn :: Game -> Maybe Pow.Power
+powerOn game | let bd = board game, p:_ <- B.playerPoss bd = B.powers bd M.!? p
+powerOn _ = Nothing
+
+activatePower :: MonadState Game m => m ()
+activatePower = do
+    bd <- gets board
+    case True of
+        _ | p:_ <- B.playerPoss bd
+          , Just pow <- B.powers bd M.!? p
+          , Pow.activatable pow
+          -> do
+              when (Pow.tp pow == Pow.Foresight) . modifyR $ modBoardM B.beginExpect
+              -- |XXX: Be careful of the subtle interaction with the undo power
+              -- when changing this.
+              modify $ modBoard (B.modPowers $ M.alter (Pow.deplete =<<) p) . doPower (Pow.tp pow) p
+              unless (Pow.tp pow == Pow.Undo) envAct
+              endTurn
+        _ -> pure ()
+    where
+    doPower Pow.Heal _ = modLifeWithMax (+2)
+    doPower Pow.Smoke _ = modBoard $ B.incStatus B.Smoke (B.maxSmoke + 1)
+    doPower Pow.Haste _ = modBoard $ B.incStatus B.Haste 8
+    doPower Pow.Dazzle _ = modBoard $ B.incStatus B.Dazzled 5
+    doPower Pow.Ghost _ = modBoard $ B.incStatus B.Ghost 6
+    doPower Pow.Foresight _ = modBoard $ B.incStatus B.Foresight 11
+    doPower Pow.Teleport p = modBoard $ B.setSafe True . B.modCreatures (M.delete p . M.insert (centre +^ centre +^ neg p) Player)
+    doPower Pow.Undo _ = \game -> let (game',trans) = runWriter $ prevTurn undoTurns game in game' { transitions = reverse trans } where
+        prevTurn :: Int -> Game -> Writer [B.Transition] Game
+        prevTurn n g | n < 0 = pure g
+        prevTurn n g = maybe (pure g) ((tell [B.Transition (board g) []] >>) . prevTurn (n-1)) $ prev g
+    centre = P.Pos 2 2
+
+data PlayState = Playing | Dead | RoundEnded | Won | Tutorialising T.Beat deriving Eq
+playState :: Game -> PlayState
+playState game
+    | level game == 0 = RoundEnded
+    | life game <= 0 = Dead
+    | score game >= maxScore = Won
+    | Just b <- S.lookupMin $ triggeredBeats game = Tutorialising b
+    | otherwise = Playing
+
+doCommand :: (MonadState Game m, MonadIO m) => C.Command -> m ()
+doCommand c = gets playState >>= \case
+    Dead -> case c of
+        C.Accept -> initGame
+        _        -> pure ()
+    Won -> case c of
+        C.Accept -> initGame
+        _        -> pure ()
+    RoundEnded -> case c of
+        C.Accept -> nextRound
+        C.SkipTutorial -> modify (setUnseenBeats $ S.fromList T.allTypes) >> nextRound
+        _        -> pure ()
+    Tutorialising b -> case c of
+        C.Accept       -> modify . modUnseenBeats . S.delete $ T.tp b
+        C.SkipTutorial -> modify $ setUnseenBeats S.empty
+        _              -> pure ()
+    Playing -> case c of
+        C.Dir dir -> do
+            gets selectedSlot >>= \case
+                Nothing -> movePlayer dir
+                Just slot -> do
+                    modify $ setSelectedSlot Nothing
+                    useInvSlotInDir slot dir
+        C.UseInv slot -> do
+            gets selectedSlot >>= modify . \case
+                Just s | s == slot -> setSelectedSlot Nothing
+                Just s' -> modInventory (I.swap slot s') . setSelectedSlot Nothing
+                Nothing -> setSelectedSlot $ Just slot
+        C.UsePower -> activatePower
+#ifdef DEBUG
+        C.DebugAddPower -> modify . modBoard . B.addPower =<< gets (hasEquip Siphon)
+        C.DebugAddJunk -> addJunk
+        C.DebugAddItems -> collect findableTreasures
+        C.DebugExit -> exitLevel =<< evalR (randElemUnsafe $ S.toList B.boundaryWPoss)
+#endif
+        _ -> pure ()
+
+triggeredBeats :: Game -> S.Set T.Beat
+triggeredBeats game = S.unions . S.map triggered $ unseenBeats game where
+    triggered T.TMeta = S.singleton T.Meta
+    triggered T.TMeta2 = S.singleton T.Meta2
+    triggered T.TMovement | p:_ <- B.playerPoss bd = S.singleton $ T.Movement p
+    triggered T.TTrapped | p:_ <- B.playerPoss bd
+        , all (trappedDir p) P.dirs
+        , any ((`M.member` B.walls bd) . P.wposInDir p) P.dirs
+        = S.singleton $ T.Trapped p
+    triggered T.TSeeMonster = uncurry T.SeeMonster `S.map` (S.fromList . M.assocs . M.filter isMonster $ B.creatures bd)
+    triggered T.TSeeExit = T.SeeExit `S.map` M.keysSet (M.filter (== Exit) $ B.exits bd)
+    triggered T.TSeeItem = uncurry T.SeeItem `S.map` (S.fromList . M.assocs . M.filter (`notElem` [Potion, MiniPotion, ScoreTreasure, Junk, Gem]) $ B.items bd)
+    triggered T.TSeePotion = T.SeePotion `S.map` M.keysSet (M.filter (== Potion) $ B.items bd)
+    triggered T.TSeeMiniPotion = T.SeeMiniPotion `S.map` M.keysSet (M.filter (== MiniPotion) $ B.items bd)
+    triggered T.TSeeScore = T.SeeScore `S.map` M.keysSet (M.filter (== ScoreTreasure) $ B.items bd)
+    triggered T.TSeeJunk = T.SeeJunk `S.map` M.keysSet (M.filter (== Junk) $ B.items bd)
+    triggered T.TSeeGem = T.SeeGem `S.map` M.keysSet (M.filter (== Gem) $ B.items bd)
+    triggered T.THurt | life game < maxLife game = sng $ T.Hurt (life game) (maxLife game)
+    triggered T.TCollectItem | 1 `M.member` I.invItems (inventory game) = sng T.CollectItem
+    triggered T.TCollectItem2 | 1 `M.member` I.invItems (inventory game) = sng T.CollectItem2
+    triggered T.TCollectGem | p:_ <- B.playerPoss bd, p `M.member` B.powers bd = sng T.CollectGem
+    triggered T.TCollectScore | score game == 1 = sng T.CollectScore
+    triggered T.TTimer | (RF.sides . BC.creatureRoll $ B.conf bd) < initCreatureSides - 2 = sng T.Timer
+    triggered T.TSecondRound | round game > 1 = sng T.SecondRound
+    triggered T.TTutEnd | S.size (unseenBeats game) == 1 = sng T.TutEnd
+    triggered _ = S.empty
+    trappedDir p dir = or [ not $ B.inBounds p'
+        , p' `M.member` B.creatures bd
+        , P.wposInDir p dir `M.member` B.walls bd ]
+        where p' = p +^ P.dirPos dir
+    sng = S.singleton
+    bd = board game
diff --git a/GameName.hs b/GameName.hs
new file mode 100644
--- /dev/null
+++ b/GameName.hs
@@ -0,0 +1,4 @@
+module GameName where
+
+gameName :: String
+gameName = "fearOfView"
diff --git a/Group.hs b/Group.hs
new file mode 100644
--- /dev/null
+++ b/Group.hs
@@ -0,0 +1,14 @@
+{-# LANGUAGE FlexibleInstances     #-}
+{-# LANGUAGE MultiParamTypeClasses #-}
+
+module Group where
+
+class Monoid g => Grp g where
+    neg :: g -> g
+    zero :: g
+    zero = mempty
+
+class Action a b where
+    (+^) :: a -> b -> b
+instance Monoid m => Action m m where
+    (+^) = mappend
diff --git a/Highscore.hs b/Highscore.hs
new file mode 100644
--- /dev/null
+++ b/Highscore.hs
@@ -0,0 +1,32 @@
+module Highscore where
+
+import           Data.Function (on)
+import           Data.List     (sort)
+
+import qualified Data.Set      as S
+
+import           Equipment
+
+type Username = String
+
+data Highscore = Highscore
+    { score     :: Int
+    , maxRound  :: Int
+    , maxLevel  :: Int
+    , name      :: Maybe Username
+    , equipment :: S.Set Equipment
+    } deriving Eq
+
+instance Ord Highscore where
+    (<=) = (<=) `on` (\hs -> (-score hs, maxRound hs, maxLevel hs))
+
+type Highscores = [Highscore]
+
+maxHighscores :: Int
+maxHighscores = 10
+
+add :: Highscore -> Highscores -> Highscores
+add hs = take maxHighscores . sort . (hs:)
+
+empty :: Highscores
+empty = []
diff --git a/HighscoreFile.hs b/HighscoreFile.hs
new file mode 100644
--- /dev/null
+++ b/HighscoreFile.hs
@@ -0,0 +1,31 @@
+module HighscoreFile where
+
+import           Codec.Serialise
+import           Control.Exception.Safe
+import           Control.Monad
+import           Data.Either
+import           System.Directory
+import           System.FileLock        (SharedExclusive (..), withFileLock)
+import           System.FilePath        ((</>))
+
+import           GameName
+import qualified Highscore              as HS
+import           Serialise              ()
+
+getPath :: IO FilePath
+getPath = do
+    dir <- getXdgDirectory XdgData gameName
+    createDirectoryIfMissing True dir
+    pure $ dir </> "highscores"
+
+add :: HS.Highscore -> IO ()
+add hs = do
+    path <- getPath
+    withFileLock (path<>".lock") Exclusive $ \_ -> do
+        hss <- (fromRight HS.empty <$>) . tryAny $ readFileDeserialise path
+        void . tryAny . writeFileSerialise path $ HS.add hs hss
+
+get :: IO HS.Highscores
+get = do
+    path <- getPath
+    (fromRight HS.empty <$>) . tryAny . withFileLock (path<>".lock") Shared $ \_ -> readFileDeserialise path
diff --git a/Inventory.hs b/Inventory.hs
new file mode 100644
--- /dev/null
+++ b/Inventory.hs
@@ -0,0 +1,38 @@
+{-# LANGUAGE LambdaCase #-}
+
+module Inventory where
+
+import           Data.List       ((\\))
+import qualified Data.Map.Strict as M
+import           Safe
+
+import           Item
+
+type Slot = Int
+newtype Inventory = Inventory { invItems :: M.Map Slot InvItem }
+
+empty :: Inventory
+empty = Inventory M.empty
+
+null :: Inventory -> Bool
+null (Inventory inv) = M.null inv
+
+modInvItems :: (M.Map Slot InvItem -> M.Map Slot InvItem) -> Inventory -> Inventory
+modInvItems f inv = inv { invItems = f $ invItems inv }
+
+slots :: [Slot]
+slots = [1..8]
+
+swap :: Slot -> Slot -> Inventory -> Inventory
+swap n m = modInvItems . M.mapKeys $ \case
+    k | k == n -> m
+    k | k == m -> n
+    k          -> k
+
+add :: InvItem -> Inventory -> (Bool,Inventory)
+add e (Inventory inv)
+    | Just n <- headMay $ slots \\ M.keys inv = (True, Inventory $ M.insert n e inv)
+    | otherwise = (False, Inventory inv)
+
+clearAllBut :: Int -> Inventory -> Inventory
+clearAllBut n = modInvItems $ M.fromList . zip [1..] . (snd <$>) . take n . M.toList
diff --git a/Item.hs b/Item.hs
new file mode 100644
--- /dev/null
+++ b/Item.hs
@@ -0,0 +1,43 @@
+module Item where
+
+import qualified Pos as P
+
+data Item
+    = Gem
+    | ScoreTreasure
+    | Junk
+    | UmbrellaHandle P.Dir
+    | CameraBoxed
+    | Potion
+    | MiniPotion
+    | RollingOrb { orbRollDir :: P.Dir, orbJustDropped :: Bool }
+    | ItemInvItem InvItem
+    deriving (Eq, Ord)
+
+data InvItem
+    = Cloak
+    | Orb
+    | Umbrella
+    | Balloon Int
+    | Flash
+    | Camera Int
+    | Tent
+    | Spraypaint Int
+    deriving (Eq, Ord, Show, Read)
+
+initCameraCharge, initBalloonCharges, initSpraypaintCharges :: Int
+initCameraCharge = 10
+initBalloonCharges = 3
+initSpraypaintCharges = 5
+
+findableTreasures :: [Item]
+findableTreasures =
+    [ ItemInvItem Cloak
+    , ItemInvItem Orb
+    , ItemInvItem Umbrella
+    , ItemInvItem (Balloon initBalloonCharges)
+    , ItemInvItem Flash
+    , ItemInvItem Tent
+    , ItemInvItem (Spraypaint initSpraypaintCharges)
+    , CameraBoxed
+    ]
diff --git a/KeyBindings.hs b/KeyBindings.hs
new file mode 100644
--- /dev/null
+++ b/KeyBindings.hs
@@ -0,0 +1,115 @@
+module KeyBindings (KeyBindings, defaultBindings, findBindings, findBinding, showKey,
+    showKeyChar, showKeyFriendly, showKeyFriendlyShort, dvorakViBindings) where
+
+import           Data.Bits  (xor)
+import           Data.Char
+import           Data.List
+import           Data.Maybe
+
+import qualified Command    as C
+import qualified Inventory  as I
+import qualified Pos        as P
+
+type KeyBindings = [ (Char,C.Command) ]
+
+ctrl, unctrl, meta, unmeta :: Char -> Char
+ctrl = toEnum . xor 64 . fromEnum
+meta = toEnum . xor 128 . fromEnum
+unctrl = ctrl
+unmeta = meta
+
+lowerToo :: KeyBindings -> KeyBindings
+lowerToo = concatMap addLower
+    where addLower b@(c, cmd) = [ b, (toLower c, cmd) ]
+
+quitBindings, qwertyViBindings, wasdBindings, dvorakViBindings, cursorBindings, actionBindings, basicBindings, defaultBindings :: KeyBindings
+quitBindings = lowerToo
+    [ ('Q', C.Quit)
+    , (ctrl '[', C.Quit)
+    , (ctrl 'C', C.Quit) ]
+
+qwertyViBindings = lowerToo
+    [ ('H', C.Dir P.DLeft)
+    , ('J', C.Dir P.DDown)
+    , ('K', C.Dir P.DUp)
+    , ('L', C.Dir P.DRight)
+    ]
+
+dvorakViBindings =
+    [ ('h', C.Dir P.DLeft)
+    , ('t', C.Dir P.DDown)
+    , ('n', C.Dir P.DUp)
+    , ('s', C.Dir P.DRight)
+    ]
+
+wasdBindings = lowerToo
+    [ ('W', C.Dir P.DLeft)
+    , ('S', C.Dir P.DDown)
+    , ('W', C.Dir P.DUp)
+    , ('D', C.Dir P.DRight)
+    ]
+
+cursorBindings =
+    [ ('←', C.Dir P.DLeft)
+    , ('↓', C.Dir P.DDown)
+    , ('↑', C.Dir P.DUp)
+    , ('→', C.Dir P.DRight)
+    ]
+
+actionBindings = [ (chr $ ord '1' + (slot-1), C.UseInv slot) | slot <- I.slots ]
+    <> [ ('0', C.UsePower) ]
+
+basicBindings =
+    [ (' ', C.Accept)
+    , ('\r', C.Accept)
+    , ('\n', C.Accept)
+    , ('\f', C.Redraw)
+    , (ctrl 'Z', C.Suspend)
+    , ('t', C.SkipTutorial)
+    , ('T', C.SkipTutorial)
+    , ('-', C.ToggleAscii)
+    ]
+
+debugBindings :: KeyBindings
+debugBindings =
+    [ ('P', C.DebugAddPower)
+    , ('J', C.DebugAddJunk)
+    , ('I', C.DebugAddItems)
+    , ('E', C.DebugExit)
+    ]
+
+defaultBindings = quitBindings <> debugBindings <> wasdBindings <> qwertyViBindings <> cursorBindings <> actionBindings <> basicBindings
+
+findBindings :: KeyBindings -> C.Command -> [Char]
+findBindings bdgs cmd = nub
+    $ [ ch | (ch,cmd') <- bdgs, cmd'==cmd ]
+
+findBinding :: KeyBindings -> C.Command -> Maybe Char
+findBinding = (listToMaybe.) . findBindings
+
+showKey :: Char -> String
+showKey ch
+    | isAscii (unmeta ch) = 'M':'-':showKey (unmeta ch)
+    | isPrint ch = [ch]
+    | isPrint (unctrl ch) = '^':[unctrl ch]
+    | otherwise = "[?]"
+
+showKeyFriendly, showKeyFriendlyShort :: Char -> String
+showKeyFriendly ' '  = "space"
+showKeyFriendly '\r' = "return"
+showKeyFriendly '\n' = "newline"
+showKeyFriendly '\t' = "tab"
+showKeyFriendly '\b' = "bksp"
+showKeyFriendly ch   = showKey ch
+
+showKeyFriendlyShort '\r' = "ret"
+showKeyFriendlyShort '\t' = "tab"
+showKeyFriendlyShort '\b' = "bksp"
+showKeyFriendlyShort ch   = showKey ch
+
+showKeyChar :: Char -> Char
+showKeyChar ch
+    | isAscii (unmeta ch) = '['
+    | isPrint ch = ch
+    | isPrint (unctrl ch) = '^'
+    | otherwise = '?'
diff --git a/Main.hs b/Main.hs
new file mode 100644
--- /dev/null
+++ b/Main.hs
@@ -0,0 +1,109 @@
+{-# LANGUAGE CPP                 #-}
+{-# LANGUAGE LambdaCase          #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+
+module Main where
+
+import           Codec.Serialise
+import           Control.Exception.Safe
+import           Control.Monad.Except
+import           Control.Monad.State
+import           Safe
+import           System.Console.GetOpt
+import           System.Directory
+import           System.Environment
+import           System.Exit
+import           System.FilePath        ((</>))
+
+import           CursesUIMInstance      ()
+import           GameName
+import           KeyBindings            (dvorakViBindings)
+import           Serialise              ()
+
+import qualified Command                as Cmd
+import qualified CursesUI               as CU
+import qualified Game                   as G
+import qualified Highscore              as HS
+import qualified HighscoreFile          as HSF
+import qualified UIMonad                as UIM
+
+version :: String
+version = CURRENT_PACKAGE_VERSION
+
+data Opt
+    = StatePath FilePath
+    | Username HS.Username
+    | AsciiOnly
+    | Dvorak
+    | Help
+    | Version
+    deriving (Eq, Ord, Show)
+
+options :: [OptDescr Opt]
+options =
+    [ Option ['s'] ["statefile"] (ReqArg StatePath "PATH") "Path to game state file"
+    , Option ['n'] ["username"] (ReqArg Username "NAME") "Optional username for highscores"
+    , Option ['a'] ["ascii"] (NoArg AsciiOnly) "Draw only ASCII characters"
+    , Option ['d'] ["dvorak"] (NoArg Dvorak) "Use dvorak roguelike keys (htns)"
+    , Option ['h'] ["help"] (NoArg Help) "Show usage information"
+    , Option ['v'] ["version"] (NoArg Version) "Show version information"
+    ]
+
+usage :: String
+usage = usageInfo header options
+    where header = "Usage: " <> gameName <> " [OPTION...]"
+
+parseArgs :: [String] -> IO ([Opt],[String])
+parseArgs argv =
+    case getOpt Permute options argv of
+        (o,n,[])   -> return (o,n)
+        (_,_,errs) -> ioError (userError (concat errs ++ usage))
+
+main :: IO ()
+main = do
+    (opts,_) <- parseArgs =<< getArgs
+    when (Help `elem` opts) $ putStr usage >> exitSuccess
+    when (Version `elem` opts) $ putStrLn version >> exitSuccess
+    statePath <- case headMay [ path | StatePath path <- opts ] of
+        Just path -> pure path
+        Nothing -> do
+            dataDir <- getXdgDirectory XdgData gameName
+            createDirectoryIfMissing True dataDir
+            pure $ dataDir </> "gamestate"
+    let ascii = AsciiOnly `elem` opts
+    let dvorak = Dvorak `elem` opts
+    let username = headMay [ name | Username name <- opts ]
+    let doCUI :: CU.UIM () -> IO ()
+        doCUI m = void (UIM.doUI m) `catch` (\QuitException -> exitSuccess)
+    doCUI . G.runT $ do
+        lift $ UIM.setAsciiOnly ascii
+        when dvorak . lift $ sequence_ [ UIM.setUIBinding ch cmd | (ch,cmd) <- dvorakViBindings ]
+        liftIO (tryAny $ readFileDeserialise statePath) >>= \case
+            Right game -> put game
+            Left _     -> G.initGame
+        let mainLoop :: UIM.UIMonad uiM => G.T uiM ()
+            mainLoop = do
+                liftIO . writeFileSerialise statePath =<< get
+                lift . UIM.draw =<< get
+                G.clearTrans
+                playSt <- gets G.playState
+                let after = do
+                        playSt' <- gets G.playState
+                        when (playSt == G.Playing && playSt' `elem` [G.Dead, G.Won]) $
+                            liftIO . HSF.add =<< gets (G.highscore username)
+                        mainLoop
+                runExceptT (mapM_ processCommand =<< (lift . lift) UIM.getInput) >>=
+                    either pure (const after)
+        mainLoop
+
+
+data QuitException = QuitException deriving Show
+instance Exception QuitException
+
+processCommand :: UIM.UIMonad uiM => Cmd.Command -> ExceptT () (G.T uiM) ()
+processCommand Cmd.Quit        = throw QuitException
+processCommand Cmd.ForceQuit   = throw QuitException
+processCommand Cmd.ToggleAscii = lift . lift $ UIM.toggleAsciiOnly
+processCommand Cmd.Redraw      = lift . lift $ UIM.redraw
+processCommand Cmd.Suspend     = lift . lift $ UIM.suspend
+processCommand cmd             = lift $ G.doCommand cmd
diff --git a/Pos.hs b/Pos.hs
new file mode 100644
--- /dev/null
+++ b/Pos.hs
@@ -0,0 +1,100 @@
+{-# LANGUAGE DeriveGeneric         #-}
+{-# LANGUAGE MultiParamTypeClasses #-}
+
+module Pos where
+
+import           Data.Hashable
+import           GHC.Generics
+
+import           Group
+
+-- | y increases upwards
+data Pos = Pos {x :: Int, y :: Int} deriving (Eq, Ord, Show, Read, Generic)
+instance Hashable Pos
+instance Semigroup Pos where
+    Pos x1 y1 <> Pos x2 y2 = Pos (x1+x2) (y1+y2)
+instance Monoid Pos where
+    mempty = Pos 0 0
+
+instance Grp Pos where
+    neg (Pos x' y') = Pos (-x') (-y')
+    zero = Pos 0 0
+
+-- | manhatten metric
+sqDist :: Pos -> Pos -> Int
+sqDist p p' = let Pos x' y' = p +^ neg p' in abs x' + abs y'
+
+-- | euclidean metric, squared
+distSquared :: Pos -> Pos -> Int
+distSquared p p' = let Pos x' y' = p +^ neg p' in x'*x' + y'*y'
+
+-- up or right
+data WPos = WPos {pos :: Pos, up :: Bool} deriving (Eq, Ord)
+
+instance Action Pos WPos where
+    p +^ WPos p' up' = WPos (p <> p') up'
+
+data Dir = DUp | DRight | DDown | DLeft deriving (Eq, Ord, Read, Show)
+dirs :: [Dir]
+dirs = [DUp, DRight, DDown, DLeft]
+
+dirPos :: Dir -> Pos
+dirPos DUp    = Pos 0 1
+dirPos DRight = Pos 1 0
+dirPos DDown  = Pos 0 (-1)
+dirPos DLeft  = Pos (-1) 0
+
+posDir :: Pos -> Maybe Dir
+posDir (Pos 0 1)    = Just DUp
+posDir (Pos 1 0)    = Just DRight
+posDir (Pos 0 (-1)) = Just DDown
+posDir (Pos (-1) 0) = Just DLeft
+posDir _            = Nothing
+
+negDir, flipDirV, flipDirH, flipDirDiag :: Dir -> Dir
+negDir = flipDirH . flipDirV
+flipDirV DUp   = DDown
+flipDirV DDown = DUp
+flipDirV d     = d
+flipDirH DRight = DLeft
+flipDirH DLeft  = DRight
+flipDirH d      = d
+flipDirDiag DUp    = DRight
+flipDirDiag DRight = DUp
+flipDirDiag DLeft  = DDown
+flipDirDiag DDown  = DLeft
+
+wposInDir :: Pos -> Dir -> WPos
+wposInDir p dir =
+    let p' = dirPos dir +^ p
+    in case dir of
+        DUp    -> WPos p True
+        DRight -> WPos p False
+        DDown  -> WPos p' True
+        DLeft  -> WPos p' False
+
+posInDir :: WPos -> Dir -> Pos
+posInDir (WPos p up') d
+    | (up' && d == DUp) || (not up' && d == DRight) = p +^ dirPos d
+    | otherwise = p
+
+adjPoss :: WPos -> [Pos]
+adjPoss (WPos p up') = [p, p +^ dirPos (if up' then DUp else DRight)]
+
+dirsTowardsZero :: Pos -> [[Dir]]
+dirsTowardsZero (Pos x' y')
+    | x' < 0 = (flipDirH <$>) <$> dirsTowardsZero (Pos (-x') y')
+    | y' < 0 = (flipDirV <$>) <$> dirsTowardsZero (Pos x' (-y'))
+    | x' < y' = (flipDirDiag <$>) <$> dirsTowardsZero (Pos y' x')
+    | x' == y' = [[DDown,DLeft],[DUp,DRight]]
+    | x' > y' = [[DLeft]] <> (if y'>0 then [[DDown],[DUp]] else [[DDown,DUp]]) <> [[DRight]]
+    | otherwise = [[]]
+
+exitDir :: WPos -> Dir
+exitDir (WPos (Pos _ y') True)
+    | y' <= 0 = DDown
+    | otherwise = DUp
+exitDir (WPos (Pos x' _) False)
+    | x' <= 0 = DLeft
+    | otherwise = DRight
+
diff --git a/Power.hs b/Power.hs
new file mode 100644
--- /dev/null
+++ b/Power.hs
@@ -0,0 +1,47 @@
+module Power where
+
+-- XXX: If adding a power with a longer name, check still fits in inventory
+-- window when we have >= 10 charges.
+data PowerType
+    = Heal
+    | Dazzle
+    | Smoke
+    | Haste
+    | Teleport
+    | Undo
+    | Ghost
+    | Foresight
+    deriving (Eq, Ord, Show)
+
+data Power = Power
+    { tp         :: PowerType
+    , charges    :: Int
+    , maxCharges :: Int
+    , overUsable :: Bool
+    }
+
+setOverUsable :: Bool -> Power -> Power
+setOverUsable b pow = pow { overUsable = b }
+
+new :: PowerType -> Bool -> Power
+new tp' = Power tp' 0 0
+
+activatable :: Power -> Bool
+activatable pow = charges pow > 0 || overUsable pow
+
+activatableTimes :: Power -> Int
+activatableTimes pow
+    | overUsable pow = charges pow + maxCharges pow
+    | otherwise = charges pow
+
+upgrade, recharge :: Power -> Power
+upgrade pow =
+    -- |Capped at 99 so will fit in inventory window
+    pow { maxCharges = min 99 $ maxCharges pow + 1, charges = min 99 $ charges pow + 1 }
+recharge pow = pow {charges = maxCharges pow}
+
+deplete :: Power -> Maybe Power
+deplete pow
+    | charges pow > 0 = Just $ pow { charges = charges pow - 1 }
+    | maxCharges pow > 1 = Just $ pow { maxCharges = maxCharges pow - 1 }
+    | otherwise = Nothing
diff --git a/README.md b/README.md
new file mode 100644
--- /dev/null
+++ b/README.md
@@ -0,0 +1,14 @@
+# Fear of View
+A terminal broughlike game about manipulating vision.
+
+Released under the AGPL, version 3 or later. See LICENSE.
+
+![Screenshot](fov-shot.png "Screenshot")
+
+## Building
+Dependencies:
+* GHC and cabal: package `cabal-install` on Debian, `dev-haskell/cabal` on Gentoo, etc.
+* ncurses
+
+Run with `cabal run`.
+Install with `cabal install`.
diff --git a/Rand.hs b/Rand.hs
new file mode 100644
--- /dev/null
+++ b/Rand.hs
@@ -0,0 +1,24 @@
+module Rand where
+
+import           Control.Monad.Random
+
+import qualified Data.Set             as S
+
+-- | Argument must be non-empty
+randElemUnsafe :: [a] -> Rand StdGen a
+randElemUnsafe as = (as!!) <$> getRandomR (0, length as - 1)
+
+randElem :: [a] -> Rand StdGen (Maybe a)
+randElem [] = pure Nothing
+randElem as = Just <$> randElemUnsafe as
+
+-- | Argument must be non-empty
+randMemberUnsafe :: S.Set a -> Rand StdGen a
+randMemberUnsafe s = (S.toList s !!) <$> getRandomR (0,S.size s - 1)
+
+randMember :: S.Set a -> Rand StdGen (Maybe a)
+randMember s | S.null s = pure Nothing
+randMember s = Just <$> randMemberUnsafe s
+
+shuffle :: [a] -> Rand StdGen [a]
+shuffle = liftRand . uniformShuffleList
diff --git a/RollFrom.hs b/RollFrom.hs
new file mode 100644
--- /dev/null
+++ b/RollFrom.hs
@@ -0,0 +1,26 @@
+module RollFrom where
+
+import           Control.Monad.Random
+import           Data.List
+import           Safe
+
+data RollFrom a = RollFrom { sides :: Int, vals :: [a] }
+
+empty :: (Eq a, Ord a) => RollFrom a
+empty = RollFrom 0 []
+
+modVals :: (Eq a, Ord a) => ([a] -> [a]) -> RollFrom a -> RollFrom a
+modVals f from = from { vals = f $ vals from }
+modSides :: (Int -> Int) -> RollFrom a -> RollFrom a
+modSides f from = from { sides = f $ sides from }
+
+roll :: (Eq a, Ord a) => RollFrom a -> Rand StdGen (Maybe a)
+roll from = do
+    n <- getRandomR (0, sides from - 1)
+    pure $ vals from `atMay` n
+
+add :: (Eq a, Ord a) => a -> RollFrom a -> RollFrom a
+add a = modVals $ sort . (a :)
+
+swap :: (Eq a, Ord a) => a -> a -> RollFrom a -> RollFrom a
+swap a a' = add a' . modVals (delete a)
diff --git a/Serialise.hs b/Serialise.hs
new file mode 100644
--- /dev/null
+++ b/Serialise.hs
@@ -0,0 +1,85 @@
+{-# OPTIONS_GHC -fno-warn-orphans #-}
+
+{-# LANGUAGE DeriveGeneric      #-}
+{-# LANGUAGE StandaloneDeriving #-}
+
+module Serialise where
+
+import           Codec.Serialise
+import           GHC.Generics
+import           System.Random.Internal
+import           System.Random.SplitMix
+
+import           Creature
+import           Equipment
+import           Exit
+import           Item
+import           Power
+import           Wall
+
+import qualified Board                  as B
+import qualified BoardConf              as BC
+import qualified Game                   as G
+import qualified Highscore              as HS
+import qualified Inventory              as I
+import qualified Pos                    as P
+import qualified RollFrom               as RF
+import qualified Tutorial               as T
+
+instance Serialise P.Pos
+deriving instance Generic P.WPos
+instance Serialise P.WPos
+deriving instance Generic P.Dir
+instance Serialise P.Dir
+deriving instance Generic Creature
+instance Serialise Creature
+deriving instance Generic Item
+instance Serialise Item
+deriving instance Generic Equipment
+instance Serialise Equipment
+deriving instance Generic Wall
+instance Serialise Wall
+deriving instance Generic Exit
+instance Serialise Exit
+deriving instance Generic PowerType
+instance Serialise PowerType
+deriving instance Generic Power
+instance Serialise Power
+deriving instance Generic a => Generic (RF.RollFrom a)
+instance (Generic a, Serialise a) => Serialise (RF.RollFrom a)
+deriving instance Generic BC.BoardConf
+instance Serialise BC.BoardConf
+deriving instance Generic BC.Diffable
+instance Serialise BC.Diffable
+deriving instance Generic a => Generic (BC.RollFromDiff a)
+instance (Generic a, Serialise a) => Serialise (BC.RollFromDiff a)
+deriving instance Generic B.Status
+instance Serialise B.Status
+deriving instance Generic B.Board
+instance Serialise B.Board
+deriving instance Generic B.Alert
+instance Serialise B.Alert
+deriving instance Generic B.Transition
+instance Serialise B.Transition
+deriving instance Generic InvItem
+instance Serialise InvItem
+deriving instance Generic I.Inventory
+instance Serialise I.Inventory
+
+deriving instance Generic T.Type
+instance Serialise T.Type
+deriving instance Generic T.Beat
+instance Serialise T.Beat
+
+instance Serialise SMGen where
+    encode = encode . show
+    decode = read <$> decode
+
+deriving instance Generic StdGen
+instance Serialise StdGen
+
+deriving instance Generic G.Game
+instance Serialise G.Game
+
+deriving instance Generic HS.Highscore
+instance Serialise HS.Highscore
diff --git a/Tutorial.hs b/Tutorial.hs
new file mode 100644
--- /dev/null
+++ b/Tutorial.hs
@@ -0,0 +1,123 @@
+module Tutorial where
+
+import           Creature
+import           Item
+
+import qualified Pos      as P
+
+data Beat
+    = Meta
+    | Meta2
+    | Movement P.Pos
+    | Trapped P.Pos
+    | Hurt Int Int
+    | CollectItem
+    | CollectItem2
+    | CollectGem
+    | CollectScore
+    | SeeMonster P.Pos Creature
+    | SeeItem P.Pos Item
+    | SeePotion P.Pos
+    | SeeMiniPotion P.Pos
+    | SeeScore P.Pos
+    | SeeJunk P.Pos
+    | SeeGem P.Pos
+    | SeeExit P.WPos
+    | Timer
+    | SecondRound
+    | TutEnd
+    deriving (Eq, Ord)
+
+data Type
+    = TMeta
+    | TMeta2
+    | TMovement
+    | TTrapped
+    | TSeeMonster
+    | TSeeExit
+    | TSeeItem
+    | TSeePotion
+    | TSeeMiniPotion
+    | TSeeScore
+    | TSeeJunk
+    | TSeeGem
+    | TCollectItem
+    | TCollectItem2
+    | TCollectGem
+    | TCollectScore
+    | THurt
+    | TTimer
+    | TSecondRound
+    | TTutEnd
+    deriving (Eq, Ord, Enum, Bounded, Show)
+
+tp :: Beat -> Type
+tp Meta              = TMeta
+tp Meta2             = TMeta2
+tp (Movement _)      = TMovement
+tp (Trapped _)       = TTrapped
+tp (SeeMonster _ _)  = TSeeMonster
+tp (SeeExit _)       = TSeeExit
+tp (SeeItem _ _)     = TSeeItem
+tp (SeePotion _)     = TSeePotion
+tp (SeeMiniPotion _) = TSeeMiniPotion
+tp (SeeScore _)      = TSeeScore
+tp (SeeJunk _)       = TSeeJunk
+tp (SeeGem _)        = TSeeGem
+tp CollectItem       = TCollectItem
+tp CollectItem2      = TCollectItem2
+tp CollectGem        = TCollectGem
+tp CollectScore      = TCollectScore
+tp (Hurt _ _)        = THurt
+tp Timer             = TTimer
+tp SecondRound       = TSecondRound
+tp TutEnd            = TTutEnd
+
+allTypes :: [Type]
+allTypes = [minBound..maxBound]
+
+text :: Beat -> String
+text = text' . tp
+    where
+     -- Not longer than this (with scrW = 60 and appending "  [Spc/T]")
+     -- "##################################################"
+    text' TMeta =
+        "Welcome. Press space, or T to disable game hints."
+    text' TMeta2 =
+        "These hints are just hints. Experiment to learn."
+    text' TMovement =
+        "Move using cursors / WASD / HJKL."
+    text' TTrapped =
+        "Trapped! You can't rest, but can walk into a wall."
+    text' TSeeMonster =
+        "That's something you'd rather not see..."
+    text' TSeeExit =
+        "You found the way out of here, at last."
+    text' TSeeItem =
+        "Why are things always in the last place you look?"
+    text' TSeePotion =
+        "That looks very refreshing."
+    text' TSeeMiniPotion =
+        "That looks quite refreshing."
+    text' TSeeScore =
+        "This is just what you're looking for."
+    text' TSeeJunk =
+        "A load of junk. Maybe you could salvage something."
+    text' TSeeGem =
+        "That looks powerful."
+    text' TCollectItem =
+        "An item! Hit 1 then a direction to try to use it;"
+    text' TCollectItem2 =
+        "experiment to learn how to use each kind of item."
+    text' TCollectGem =
+        "Press 0 to activate the power here."
+    text' TCollectScore =
+        "Enough of these, and you can get out of here!"
+    text' THurt =
+        "That hurt! Watch where you walk."
+    text' TTimer =
+        "It gets more dangerous here the longer you stay."
+    text' TSecondRound =
+        "Levels get harder based on which way you leave."
+    text' TTutEnd =
+        "That was the last hint. You're on your own now."
diff --git a/UIMonad.hs b/UIMonad.hs
new file mode 100644
--- /dev/null
+++ b/UIMonad.hs
@@ -0,0 +1,26 @@
+module UIMonad where
+
+import           Control.Exception.Safe
+import           Control.Monad.IO.Class
+
+import qualified Command                as Cmd
+import qualified Game                   as G
+
+class (Applicative m, MonadIO m, MonadMask m) => UIMonad m where
+    runUI :: m a -> IO a
+    initUI :: m Bool
+    endUI :: m ()
+    draw :: G.Game -> m ()
+    getInput :: m [ Cmd.Command ]
+    getChRaw :: m ( Maybe Char )
+    suspend, redraw :: m ()
+
+    setAsciiOnly :: Bool -> m ()
+    toggleAsciiOnly :: m ()
+
+    setUIBinding :: Char -> Cmd.Command -> m ()
+
+    doUI :: m a -> IO (Maybe a)
+    doUI m = runUI $ do
+        ok <- initUI
+        if ok then Just <$> m `finally` endUI else pure Nothing
diff --git a/Wall.hs b/Wall.hs
new file mode 100644
--- /dev/null
+++ b/Wall.hs
@@ -0,0 +1,24 @@
+module Wall where
+
+import qualified Pos as P
+
+data Wall
+    = BasicWall
+    | Pillar
+    | Hedge
+    | ThickHedge
+    | Window
+    | BrokenWindow
+    | CloakWall P.Dir Int
+    | UmbrellaWall P.Dir
+    | TentWall
+    deriving (Eq, Ord)
+
+wallDestructionCost :: Wall -> Maybe Int
+wallDestructionCost Hedge            = Nothing
+wallDestructionCost BrokenWindow     = Nothing
+wallDestructionCost (CloakWall _ _)  = Nothing
+wallDestructionCost Window           = Just 0
+wallDestructionCost TentWall         = Just 0
+wallDestructionCost (UmbrellaWall _) = Just 0
+wallDestructionCost _                = Just 1
diff --git a/fearOfView.cabal b/fearOfView.cabal
new file mode 100644
--- /dev/null
+++ b/fearOfView.cabal
@@ -0,0 +1,81 @@
+cabal-version:      2.2
+name:               fearOfView
+version:            0.1.0.0
+license:            AGPL-3.0-or-later
+license-file:       COPYING
+maintainer:         mbays@sdf.org
+author:             mbays
+homepage:           https://mbays.sdf.org/fov/
+synopsis:           A terminal broughlike game about manipulating vision 
+description:
+    A constrained roguelike ("broughlike") game played on a 5x5 grid of cells
+    which are regenerated when out of view. Designed for colour terminals,
+    using the ncurses library.
+category:           Game
+extra-source-files: CHANGELOG.md README.md fov-shot.png
+
+source-repository head
+    type: git
+    location: https://thegonz.net/~fov/fearOfView.git
+
+flag debug
+    description: Enable debug keys
+    default:     False
+    manual:      True
+
+executable fearOfView
+    main-is:           Main.hs
+    pkgconfig-depends: ncursesw
+    other-modules:
+        AStar
+        Board
+        BoardConf
+        Command
+        Creature
+        CPos
+        CStyle
+        CursesDraw
+        CursesUI
+        CursesUIMInstance
+        Equipment
+        Exit
+        Inventory
+        Game
+        GameName
+        Group
+        Highscore
+        HighscoreFile
+        Item
+        KeyBindings
+        Pos
+        Power
+        Rand
+        RollFrom
+        UIMonad
+        Serialise
+        Tutorial
+        Wall
+
+    default-language:  Haskell2010
+    ghc-options:       -Wall
+    build-depends:
+        base >=4.3 && <5,
+        mtl >=2.2 && <2.4,
+        safe >=0.3.18 && <0.4,
+        containers >=0.4 && <0.9,
+        directory >=1.2.3.0 && <1.4,
+        filepath >=1.0 && <2.1,
+        safe-exceptions >=0.1 && <0.2,
+        hscurses >=1.4 && <1.6,
+        MonadRandom >=0.6 && <0.7,
+        splitmix >=0.1 && <0.2,
+        random >=1.3 && <1.4,
+        serialise >=0.2 && <0.3,
+        bytestring >=0.10 && <0.13,
+        hashable >=1.4 && <1.5,
+        unordered-containers >=0.2 && <0.3,
+        astar >=0.3 && <0.4,
+        filelock >=0.1 && <0.2
+
+    if flag(debug)
+        cpp-options: -DDEBUG
diff --git a/fov-shot.png b/fov-shot.png
new file mode 100644
Binary files /dev/null and b/fov-shot.png differ
