-- Hoogle documentation, generated by Haddock
-- See Hoogle, http://www.haskell.org/hoogle/


-- | A game engine library for tactical squad ASCII roguelike dungeon crawlers
--   
--   LambdaHack is a Haskell game engine library for ASCII roguelike games
--   of arbitrary theme, size and complexity, with optional tactical squad
--   combat. It's packaged together with a sample dungeon crawler in
--   fantasy setting that can be tried out in the browser at
--   <a>http://lambdahack.github.io</a>. (It runs fastest on Chrome.
--   Keyboard commands and savefiles are supported only on recent enough
--   versions of browsers. Mouse should work everywhere.)
--   
--   Please see the changelog file for recent improvements and the issue
--   tracker for short-term plans. Long term goals include multiplayer
--   tactical squad combat, in-game content creation, auto-balancing and
--   persistent content modification based on player behaviour.
--   Contributions are welcome.
--   
--   Games known to use the LambdaHack library:
--   
--   <ul>
--   <li>Allure of the Stars, a near-future Sci-Fi game,
--   <a>http://hackage.haskell.org/package/Allure</a></li>
--   <li>Space Privateers, an adventure game set in far future,
--   <a>http://hackage.haskell.org/package/SpacePrivateers</a></li>
--   </ul>
--   
--   Note: All modules in this library are kept visible, to let games
--   override and reuse them. OTOH, to reflect that some modules are
--   implementation details relative to others, the source code adheres to
--   the following convention. If a module has the same name as a
--   directory, the module is the exclusive interface to the directory. No
--   references to the modules in the directory are allowed except from the
--   interface module. This policy is only binding when developing the
--   library --- library users are free to access any modules, since the
--   library authors are in no position to guess their particular needs.
--   
--   This is a workaround .cabal file, flattened to eliminated internal
--   libraries until generating haddocks for them is fixed. The original
--   .cabal file is stored in the github repo.
@package LambdaHack
@version 0.9.5.0


-- | Custom Prelude, compatible across many GHC versions.
module Game.LambdaHack.Core.Prelude

-- | Append two lists, i.e.,
--   
--   <pre>
--   [x1, ..., xm] ++ [y1, ..., yn] == [x1, ..., xm, y1, ..., yn]
--   [x1, ..., xm] ++ [y1, ...] == [x1, ..., xm, y1, ...]
--   </pre>
--   
--   If the first list is not finite, the result is the first list.
(++) :: [a] -> [a] -> [a]
infixr 5 ++

-- | The value of <tt>seq a b</tt> is bottom if <tt>a</tt> is bottom, and
--   otherwise equal to <tt>b</tt>. In other words, it evaluates the first
--   argument <tt>a</tt> to weak head normal form (WHNF). <tt>seq</tt> is
--   usually introduced to improve performance by avoiding unneeded
--   laziness.
--   
--   A note on evaluation order: the expression <tt>seq a b</tt> does
--   <i>not</i> guarantee that <tt>a</tt> will be evaluated before
--   <tt>b</tt>. The only guarantee given by <tt>seq</tt> is that the both
--   <tt>a</tt> and <tt>b</tt> will be evaluated before <tt>seq</tt>
--   returns a value. In particular, this means that <tt>b</tt> may be
--   evaluated before <tt>a</tt>. If you need to guarantee a specific order
--   of evaluation, you must use the function <tt>pseq</tt> from the
--   "parallel" package.
seq :: a -> b -> b
infixr 0 `seq`

-- | <i>O(n)</i>. <a>filter</a>, applied to a predicate and a list, returns
--   the list of those elements that satisfy the predicate; i.e.,
--   
--   <pre>
--   filter p xs = [ x | x &lt;- xs, p x]
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; filter odd [1, 2, 3]
--   [1,3]
--   </pre>
filter :: (a -> Bool) -> [a] -> [a]

-- | <i>O(min(m,n))</i>. <a>zip</a> takes two lists and returns a list of
--   corresponding pairs.
--   
--   <pre>
--   zip [1, 2] ['a', 'b'] = [(1, 'a'), (2, 'b')]
--   </pre>
--   
--   If one input list is short, excess elements of the longer list are
--   discarded:
--   
--   <pre>
--   zip [1] ['a', 'b'] = [(1, 'a')]
--   zip [1, 2] ['a'] = [(1, 'a')]
--   </pre>
--   
--   <a>zip</a> is right-lazy:
--   
--   <pre>
--   zip [] _|_ = []
--   zip _|_ [] = _|_
--   </pre>
--   
--   <a>zip</a> is capable of list fusion, but it is restricted to its
--   first list argument and its resulting list.
zip :: [a] -> [b] -> [(a, b)]

-- | The <a>print</a> function outputs a value of any printable type to the
--   standard output device. Printable types are those that are instances
--   of class <a>Show</a>; <a>print</a> converts values to strings for
--   output using the <a>show</a> operation and adds a newline.
--   
--   For example, a program to print the first 20 integers and their powers
--   of 2 could be written as:
--   
--   <pre>
--   main = print ([(n, 2^n) | n &lt;- [0..19]])
--   </pre>
print :: Show a => a -> IO ()

-- | Extract the first component of a pair.
fst :: (a, b) -> a

-- | Extract the second component of a pair.
snd :: (a, b) -> b

-- | <a>otherwise</a> is defined as the value <a>True</a>. It helps to make
--   guards more readable. eg.
--   
--   <pre>
--   f x | x &lt; 0     = ...
--       | otherwise = ...
--   </pre>
otherwise :: Bool

-- | <i>O(n)</i>. <a>map</a> <tt>f xs</tt> is the list obtained by applying
--   <tt>f</tt> to each element of <tt>xs</tt>, i.e.,
--   
--   <pre>
--   map f [x1, x2, ..., xn] == [f x1, f x2, ..., f xn]
--   map f [x1, x2, ...] == [f x1, f x2, ...]
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; map (+1) [1, 2, 3]
--   </pre>
map :: (a -> b) -> [a] -> [b]

-- | Application operator. This operator is redundant, since ordinary
--   application <tt>(f x)</tt> means the same as <tt>(f <a>$</a> x)</tt>.
--   However, <a>$</a> has low, right-associative binding precedence, so it
--   sometimes allows parentheses to be omitted; for example:
--   
--   <pre>
--   f $ g $ h x  =  f (g (h x))
--   </pre>
--   
--   It is also useful in higher-order situations, such as <tt><a>map</a>
--   (<a>$</a> 0) xs</tt>, or <tt><a>zipWith</a> (<a>$</a>) fs xs</tt>.
--   
--   Note that <tt>(<a>$</a>)</tt> is levity-polymorphic in its result
--   type, so that <tt>foo <a>$</a> True</tt> where <tt>foo :: Bool -&gt;
--   Int#</tt> is well-typed.
($) :: forall (r :: RuntimeRep) a (b :: TYPE r). (a -> b) -> a -> b
infixr 0 $

-- | general coercion from integral types
fromIntegral :: (Integral a, Num b) => a -> b

-- | general coercion to fractional types
realToFrac :: (Real a, Fractional b) => a -> b

-- | The <a>Bounded</a> class is used to name the upper and lower limits of
--   a type. <a>Ord</a> is not a superclass of <a>Bounded</a> since types
--   that are not totally ordered may also have upper and lower bounds.
--   
--   The <a>Bounded</a> class may be derived for any enumeration type;
--   <a>minBound</a> is the first constructor listed in the <tt>data</tt>
--   declaration and <a>maxBound</a> is the last. <a>Bounded</a> may also
--   be derived for single-constructor datatypes whose constituent types
--   are in <a>Bounded</a>.
class Bounded a
minBound :: Bounded a => a
maxBound :: Bounded a => a

-- | Class <a>Enum</a> defines operations on sequentially ordered types.
--   
--   The <tt>enumFrom</tt>... methods are used in Haskell's translation of
--   arithmetic sequences.
--   
--   Instances of <a>Enum</a> may be derived for any enumeration type
--   (types whose constructors have no fields). The nullary constructors
--   are assumed to be numbered left-to-right by <a>fromEnum</a> from
--   <tt>0</tt> through <tt>n-1</tt>. See Chapter 10 of the <i>Haskell
--   Report</i> for more details.
--   
--   For any type that is an instance of class <a>Bounded</a> as well as
--   <a>Enum</a>, the following should hold:
--   
--   <ul>
--   <li>The calls <tt><a>succ</a> <a>maxBound</a></tt> and <tt><a>pred</a>
--   <a>minBound</a></tt> should result in a runtime error.</li>
--   <li><a>fromEnum</a> and <a>toEnum</a> should give a runtime error if
--   the result value is not representable in the result type. For example,
--   <tt><a>toEnum</a> 7 :: <a>Bool</a></tt> is an error.</li>
--   <li><a>enumFrom</a> and <a>enumFromThen</a> should be defined with an
--   implicit bound, thus:</li>
--   </ul>
--   
--   <pre>
--   enumFrom     x   = enumFromTo     x maxBound
--   enumFromThen x y = enumFromThenTo x y bound
--     where
--       bound | fromEnum y &gt;= fromEnum x = maxBound
--             | otherwise                = minBound
--   </pre>
class Enum a

-- | the successor of a value. For numeric types, <a>succ</a> adds 1.
succ :: Enum a => a -> a

-- | the predecessor of a value. For numeric types, <a>pred</a> subtracts
--   1.
pred :: Enum a => a -> a

-- | Convert from an <a>Int</a>.
toEnum :: Enum a => Int -> a

-- | Convert to an <a>Int</a>. It is implementation-dependent what
--   <a>fromEnum</a> returns when applied to a value that is too large to
--   fit in an <a>Int</a>.
fromEnum :: Enum a => a -> Int

-- | Used in Haskell's translation of <tt>[n..]</tt> with <tt>[n..] =
--   enumFrom n</tt>, a possible implementation being <tt>enumFrom n = n :
--   enumFrom (succ n)</tt>. For example:
--   
--   <ul>
--   <li><pre>enumFrom 4 :: [Integer] = [4,5,6,7,...]</pre></li>
--   <li><pre>enumFrom 6 :: [Int] = [6,7,8,9,...,maxBound ::
--   Int]</pre></li>
--   </ul>
enumFrom :: Enum a => a -> [a]

-- | Used in Haskell's translation of <tt>[n,n'..]</tt> with <tt>[n,n'..] =
--   enumFromThen n n'</tt>, a possible implementation being
--   <tt>enumFromThen n n' = n : n' : worker (f x) (f x n')</tt>,
--   <tt>worker s v = v : worker s (s v)</tt>, <tt>x = fromEnum n' -
--   fromEnum n</tt> and <tt>f n y | n &gt; 0 = f (n - 1) (succ y) | n &lt;
--   0 = f (n + 1) (pred y) | otherwise = y</tt> For example:
--   
--   <ul>
--   <li><pre>enumFromThen 4 6 :: [Integer] = [4,6,8,10...]</pre></li>
--   <li><pre>enumFromThen 6 2 :: [Int] = [6,2,-2,-6,...,minBound ::
--   Int]</pre></li>
--   </ul>
enumFromThen :: Enum a => a -> a -> [a]

-- | Used in Haskell's translation of <tt>[n..m]</tt> with <tt>[n..m] =
--   enumFromTo n m</tt>, a possible implementation being <tt>enumFromTo n
--   m | n &lt;= m = n : enumFromTo (succ n) m | otherwise = []</tt>. For
--   example:
--   
--   <ul>
--   <li><pre>enumFromTo 6 10 :: [Int] = [6,7,8,9,10]</pre></li>
--   <li><pre>enumFromTo 42 1 :: [Integer] = []</pre></li>
--   </ul>
enumFromTo :: Enum a => a -> a -> [a]

-- | Used in Haskell's translation of <tt>[n,n'..m]</tt> with <tt>[n,n'..m]
--   = enumFromThenTo n n' m</tt>, a possible implementation being
--   <tt>enumFromThenTo n n' m = worker (f x) (c x) n m</tt>, <tt>x =
--   fromEnum n' - fromEnum n</tt>, <tt>c x = bool (&gt;=) (<a>(x</a>
--   0)</tt> <tt>f n y | n &gt; 0 = f (n - 1) (succ y) | n &lt; 0 = f (n +
--   1) (pred y) | otherwise = y</tt> and <tt>worker s c v m | c v m = v :
--   worker s c (s v) m | otherwise = []</tt> For example:
--   
--   <ul>
--   <li><pre>enumFromThenTo 4 2 -6 :: [Integer] =
--   [4,2,0,-2,-4,-6]</pre></li>
--   <li><pre>enumFromThenTo 6 8 2 :: [Int] = []</pre></li>
--   </ul>
enumFromThenTo :: Enum a => a -> a -> a -> [a]

-- | The <a>Eq</a> class defines equality (<a>==</a>) and inequality
--   (<a>/=</a>). All the basic datatypes exported by the <a>Prelude</a>
--   are instances of <a>Eq</a>, and <a>Eq</a> may be derived for any
--   datatype whose constituents are also instances of <a>Eq</a>.
--   
--   The Haskell Report defines no laws for <a>Eq</a>. However, <a>==</a>
--   is customarily expected to implement an equivalence relationship where
--   two values comparing equal are indistinguishable by "public"
--   functions, with a "public" function being one not allowing to see
--   implementation details. For example, for a type representing
--   non-normalised natural numbers modulo 100, a "public" function doesn't
--   make the difference between 1 and 201. It is expected to have the
--   following properties:
--   
--   <ul>
--   <li><i><b>Reflexivity</b></i> <tt>x == x</tt> = <a>True</a></li>
--   <li><i><b>Symmetry</b></i> <tt>x == y</tt> = <tt>y == x</tt></li>
--   <li><i><b>Transitivity</b></i> if <tt>x == y &amp;&amp; y == z</tt> =
--   <a>True</a>, then <tt>x == z</tt> = <a>True</a></li>
--   <li><i><b>Substitutivity</b></i> if <tt>x == y</tt> = <a>True</a> and
--   <tt>f</tt> is a "public" function whose return type is an instance of
--   <a>Eq</a>, then <tt>f x == f y</tt> = <a>True</a></li>
--   <li><i><b>Negation</b></i> <tt>x /= y</tt> = <tt>not (x ==
--   y)</tt></li>
--   </ul>
--   
--   Minimal complete definition: either <a>==</a> or <a>/=</a>.
class Eq a
(==) :: Eq a => a -> a -> Bool
(/=) :: Eq a => a -> a -> Bool
infix 4 ==
infix 4 /=

-- | Trigonometric and hyperbolic functions and related functions.
--   
--   The Haskell Report defines no laws for <a>Floating</a>. However,
--   <tt>(<a>+</a>)</tt>, <tt>(<a>*</a>)</tt> and <a>exp</a> are
--   customarily expected to define an exponential field and have the
--   following properties:
--   
--   <ul>
--   <li><tt>exp (a + b)</tt> = <tt>exp a * exp b</tt></li>
--   <li><tt>exp (fromInteger 0)</tt> = <tt>fromInteger 1</tt></li>
--   </ul>
class Fractional a => Floating a
pi :: Floating a => a
exp :: Floating a => a -> a
log :: Floating a => a -> a
sqrt :: Floating a => a -> a
(**) :: Floating a => a -> a -> a
logBase :: Floating a => a -> a -> a
sin :: Floating a => a -> a
cos :: Floating a => a -> a
tan :: Floating a => a -> a
asin :: Floating a => a -> a
acos :: Floating a => a -> a
atan :: Floating a => a -> a
sinh :: Floating a => a -> a
cosh :: Floating a => a -> a
tanh :: Floating a => a -> a
asinh :: Floating a => a -> a
acosh :: Floating a => a -> a
atanh :: Floating a => a -> a
infixr 8 **

-- | Fractional numbers, supporting real division.
--   
--   The Haskell Report defines no laws for <a>Fractional</a>. However,
--   <tt>(<a>+</a>)</tt> and <tt>(<a>*</a>)</tt> are customarily expected
--   to define a division ring and have the following properties:
--   
--   <ul>
--   <li><i><b><a>recip</a> gives the multiplicative inverse</b></i> <tt>x
--   * recip x</tt> = <tt>recip x * x</tt> = <tt>fromInteger 1</tt></li>
--   </ul>
--   
--   Note that it <i>isn't</i> customarily expected that a type instance of
--   <a>Fractional</a> implement a field. However, all instances in
--   <tt>base</tt> do.
class Num a => Fractional a

-- | Fractional division.
(/) :: Fractional a => a -> a -> a

-- | Reciprocal fraction.
recip :: Fractional a => a -> a

-- | Conversion from a <a>Rational</a> (that is <tt><a>Ratio</a>
--   <a>Integer</a></tt>). A floating literal stands for an application of
--   <a>fromRational</a> to a value of type <a>Rational</a>, so such
--   literals have type <tt>(<a>Fractional</a> a) =&gt; a</tt>.
fromRational :: Fractional a => Rational -> a
infixl 7 /

-- | Integral numbers, supporting integer division.
--   
--   The Haskell Report defines no laws for <a>Integral</a>. However,
--   <a>Integral</a> instances are customarily expected to define a
--   Euclidean domain and have the following properties for the
--   <a>div</a>/<a>mod</a> and <a>quot</a>/<a>rem</a> pairs, given suitable
--   Euclidean functions <tt>f</tt> and <tt>g</tt>:
--   
--   <ul>
--   <li><tt>x</tt> = <tt>y * quot x y + rem x y</tt> with <tt>rem x y</tt>
--   = <tt>fromInteger 0</tt> or <tt>g (rem x y)</tt> &lt; <tt>g
--   y</tt></li>
--   <li><tt>x</tt> = <tt>y * div x y + mod x y</tt> with <tt>mod x y</tt>
--   = <tt>fromInteger 0</tt> or <tt>f (mod x y)</tt> &lt; <tt>f
--   y</tt></li>
--   </ul>
--   
--   An example of a suitable Euclidean function, for <a>Integer</a>'s
--   instance, is <a>abs</a>.
class (Real a, Enum a) => Integral a

-- | integer division truncated toward zero
quot :: Integral a => a -> a -> a

-- | integer remainder, satisfying
--   
--   <pre>
--   (x `quot` y)*y + (x `rem` y) == x
--   </pre>
rem :: Integral a => a -> a -> a

-- | integer division truncated toward negative infinity
div :: Integral a => a -> a -> a

-- | integer modulus, satisfying
--   
--   <pre>
--   (x `div` y)*y + (x `mod` y) == x
--   </pre>
mod :: Integral a => a -> a -> a

-- | simultaneous <a>quot</a> and <a>rem</a>
quotRem :: Integral a => a -> a -> (a, a)

-- | simultaneous <a>div</a> and <a>mod</a>
divMod :: Integral a => a -> a -> (a, a)

-- | conversion to <a>Integer</a>
toInteger :: Integral a => a -> Integer
infixl 7 `quot`
infixl 7 `rem`
infixl 7 `div`
infixl 7 `mod`

-- | The <a>Monad</a> class defines the basic operations over a
--   <i>monad</i>, a concept from a branch of mathematics known as
--   <i>category theory</i>. From the perspective of a Haskell programmer,
--   however, it is best to think of a monad as an <i>abstract datatype</i>
--   of actions. Haskell's <tt>do</tt> expressions provide a convenient
--   syntax for writing monadic expressions.
--   
--   Instances of <a>Monad</a> should satisfy the following:
--   
--   <ul>
--   <li><i>Left identity</i> <tt><a>return</a> a <a>&gt;&gt;=</a> k = k
--   a</tt></li>
--   <li><i>Right identity</i> <tt>m <a>&gt;&gt;=</a> <a>return</a> =
--   m</tt></li>
--   <li><i>Associativity</i> <tt>m <a>&gt;&gt;=</a> (\x -&gt; k x
--   <a>&gt;&gt;=</a> h) = (m <a>&gt;&gt;=</a> k) <a>&gt;&gt;=</a>
--   h</tt></li>
--   </ul>
--   
--   Furthermore, the <a>Monad</a> and <a>Applicative</a> operations should
--   relate as follows:
--   
--   <ul>
--   <li><pre><a>pure</a> = <a>return</a></pre></li>
--   <li><pre>(<a>&lt;*&gt;</a>) = <a>ap</a></pre></li>
--   </ul>
--   
--   The above laws imply:
--   
--   <ul>
--   <li><pre><a>fmap</a> f xs = xs <a>&gt;&gt;=</a> <a>return</a> .
--   f</pre></li>
--   <li><pre>(<a>&gt;&gt;</a>) = (<a>*&gt;</a>)</pre></li>
--   </ul>
--   
--   and that <a>pure</a> and (<a>&lt;*&gt;</a>) satisfy the applicative
--   functor laws.
--   
--   The instances of <a>Monad</a> for lists, <a>Maybe</a> and <a>IO</a>
--   defined in the <a>Prelude</a> satisfy these laws.
class Applicative m => Monad (m :: Type -> Type)

-- | Sequentially compose two actions, passing any value produced by the
--   first as an argument to the second.
(>>=) :: Monad m => m a -> (a -> m b) -> m b

-- | Sequentially compose two actions, discarding any value produced by the
--   first, like sequencing operators (such as the semicolon) in imperative
--   languages.
(>>) :: Monad m => m a -> m b -> m b

-- | Inject a value into the monadic type.
return :: Monad m => a -> m a
infixl 1 >>=
infixl 1 >>

-- | A type <tt>f</tt> is a Functor if it provides a function <tt>fmap</tt>
--   which, given any types <tt>a</tt> and <tt>b</tt> lets you apply any
--   function from <tt>(a -&gt; b)</tt> to turn an <tt>f a</tt> into an
--   <tt>f b</tt>, preserving the structure of <tt>f</tt>. Furthermore
--   <tt>f</tt> needs to adhere to the following:
--   
--   <ul>
--   <li><i>Identity</i> <tt><a>fmap</a> <a>id</a> == <a>id</a></tt></li>
--   <li><i>Composition</i> <tt><a>fmap</a> (f . g) == <a>fmap</a> f .
--   <a>fmap</a> g</tt></li>
--   </ul>
--   
--   Note, that the second law follows from the free theorem of the type
--   <a>fmap</a> and the first law, so you need only check that the former
--   condition holds.
class Functor (f :: Type -> Type)
fmap :: Functor f => (a -> b) -> f a -> f b

-- | Replace all locations in the input with the same value. The default
--   definition is <tt><a>fmap</a> . <a>const</a></tt>, but this may be
--   overridden with a more efficient version.
(<$) :: Functor f => a -> f b -> f a
infixl 4 <$

-- | Basic numeric class.
--   
--   The Haskell Report defines no laws for <a>Num</a>. However,
--   <tt>(<a>+</a>)</tt> and <tt>(<a>*</a>)</tt> are customarily expected
--   to define a ring and have the following properties:
--   
--   <ul>
--   <li><i><b>Associativity of <tt>(<a>+</a>)</tt></b></i> <tt>(x + y) +
--   z</tt> = <tt>x + (y + z)</tt></li>
--   <li><i><b>Commutativity of <tt>(<a>+</a>)</tt></b></i> <tt>x + y</tt>
--   = <tt>y + x</tt></li>
--   <li><i><b><tt><a>fromInteger</a> 0</tt> is the additive
--   identity</b></i> <tt>x + fromInteger 0</tt> = <tt>x</tt></li>
--   <li><i><b><a>negate</a> gives the additive inverse</b></i> <tt>x +
--   negate x</tt> = <tt>fromInteger 0</tt></li>
--   <li><i><b>Associativity of <tt>(<a>*</a>)</tt></b></i> <tt>(x * y) *
--   z</tt> = <tt>x * (y * z)</tt></li>
--   <li><i><b><tt><a>fromInteger</a> 1</tt> is the multiplicative
--   identity</b></i> <tt>x * fromInteger 1</tt> = <tt>x</tt> and
--   <tt>fromInteger 1 * x</tt> = <tt>x</tt></li>
--   <li><i><b>Distributivity of <tt>(<a>*</a>)</tt> with respect to
--   <tt>(<a>+</a>)</tt></b></i> <tt>a * (b + c)</tt> = <tt>(a * b) + (a *
--   c)</tt> and <tt>(b + c) * a</tt> = <tt>(b * a) + (c * a)</tt></li>
--   </ul>
--   
--   Note that it <i>isn't</i> customarily expected that a type instance of
--   both <a>Num</a> and <a>Ord</a> implement an ordered ring. Indeed, in
--   <tt>base</tt> only <a>Integer</a> and <a>Rational</a> do.
class Num a
(+) :: Num a => a -> a -> a
(-) :: Num a => a -> a -> a
(*) :: Num a => a -> a -> a

-- | Unary negation.
negate :: Num a => a -> a

-- | Absolute value.
abs :: Num a => a -> a

-- | Sign of a number. The functions <a>abs</a> and <a>signum</a> should
--   satisfy the law:
--   
--   <pre>
--   abs x * signum x == x
--   </pre>
--   
--   For real numbers, the <a>signum</a> is either <tt>-1</tt> (negative),
--   <tt>0</tt> (zero) or <tt>1</tt> (positive).
signum :: Num a => a -> a

-- | Conversion from an <a>Integer</a>. An integer literal represents the
--   application of the function <a>fromInteger</a> to the appropriate
--   value of type <a>Integer</a>, so such literals have type
--   <tt>(<a>Num</a> a) =&gt; a</tt>.
fromInteger :: Num a => Integer -> a
infixl 6 +
infixl 7 *
infixl 6 -

-- | The <a>Ord</a> class is used for totally ordered datatypes.
--   
--   Instances of <a>Ord</a> can be derived for any user-defined datatype
--   whose constituent types are in <a>Ord</a>. The declared order of the
--   constructors in the data declaration determines the ordering in
--   derived <a>Ord</a> instances. The <a>Ordering</a> datatype allows a
--   single comparison to determine the precise ordering of two objects.
--   
--   The Haskell Report defines no laws for <a>Ord</a>. However,
--   <a>&lt;=</a> is customarily expected to implement a non-strict partial
--   order and have the following properties:
--   
--   <ul>
--   <li><i><b>Transitivity</b></i> if <tt>x &lt;= y &amp;&amp; y &lt;=
--   z</tt> = <a>True</a>, then <tt>x &lt;= z</tt> = <a>True</a></li>
--   <li><i><b>Reflexivity</b></i> <tt>x &lt;= x</tt> = <a>True</a></li>
--   <li><i><b>Antisymmetry</b></i> if <tt>x &lt;= y &amp;&amp; y &lt;=
--   x</tt> = <a>True</a>, then <tt>x == y</tt> = <a>True</a></li>
--   </ul>
--   
--   Note that the following operator interactions are expected to hold:
--   
--   <ol>
--   <li><tt>x &gt;= y</tt> = <tt>y &lt;= x</tt></li>
--   <li><tt>x &lt; y</tt> = <tt>x &lt;= y &amp;&amp; x /= y</tt></li>
--   <li><tt>x &gt; y</tt> = <tt>y &lt; x</tt></li>
--   <li><tt>x &lt; y</tt> = <tt>compare x y == LT</tt></li>
--   <li><tt>x &gt; y</tt> = <tt>compare x y == GT</tt></li>
--   <li><tt>x == y</tt> = <tt>compare x y == EQ</tt></li>
--   <li><tt>min x y == if x &lt;= y then x else y</tt> = <a>True</a></li>
--   <li><tt>max x y == if x &gt;= y then x else y</tt> = <a>True</a></li>
--   </ol>
--   
--   Minimal complete definition: either <a>compare</a> or <a>&lt;=</a>.
--   Using <a>compare</a> can be more efficient for complex types.
class Eq a => Ord a
compare :: Ord a => a -> a -> Ordering
(<) :: Ord a => a -> a -> Bool
(<=) :: Ord a => a -> a -> Bool
(>) :: Ord a => a -> a -> Bool
(>=) :: Ord a => a -> a -> Bool
max :: Ord a => a -> a -> a
min :: Ord a => a -> a -> a
infix 4 >=
infix 4 >
infix 4 <=
infix 4 <

-- | Parsing of <a>String</a>s, producing values.
--   
--   Derived instances of <a>Read</a> make the following assumptions, which
--   derived instances of <a>Show</a> obey:
--   
--   <ul>
--   <li>If the constructor is defined to be an infix operator, then the
--   derived <a>Read</a> instance will parse only infix applications of the
--   constructor (not the prefix form).</li>
--   <li>Associativity is not used to reduce the occurrence of parentheses,
--   although precedence may be.</li>
--   <li>If the constructor is defined using record syntax, the derived
--   <a>Read</a> will parse only the record-syntax form, and furthermore,
--   the fields must be given in the same order as the original
--   declaration.</li>
--   <li>The derived <a>Read</a> instance allows arbitrary Haskell
--   whitespace between tokens of the input string. Extra parentheses are
--   also allowed.</li>
--   </ul>
--   
--   For example, given the declarations
--   
--   <pre>
--   infixr 5 :^:
--   data Tree a =  Leaf a  |  Tree a :^: Tree a
--   </pre>
--   
--   the derived instance of <a>Read</a> in Haskell 2010 is equivalent to
--   
--   <pre>
--   instance (Read a) =&gt; Read (Tree a) where
--   
--           readsPrec d r =  readParen (d &gt; app_prec)
--                            (\r -&gt; [(Leaf m,t) |
--                                    ("Leaf",s) &lt;- lex r,
--                                    (m,t) &lt;- readsPrec (app_prec+1) s]) r
--   
--                         ++ readParen (d &gt; up_prec)
--                            (\r -&gt; [(u:^:v,w) |
--                                    (u,s) &lt;- readsPrec (up_prec+1) r,
--                                    (":^:",t) &lt;- lex s,
--                                    (v,w) &lt;- readsPrec (up_prec+1) t]) r
--   
--             where app_prec = 10
--                   up_prec = 5
--   </pre>
--   
--   Note that right-associativity of <tt>:^:</tt> is unused.
--   
--   The derived instance in GHC is equivalent to
--   
--   <pre>
--   instance (Read a) =&gt; Read (Tree a) where
--   
--           readPrec = parens $ (prec app_prec $ do
--                                    Ident "Leaf" &lt;- lexP
--                                    m &lt;- step readPrec
--                                    return (Leaf m))
--   
--                        +++ (prec up_prec $ do
--                                    u &lt;- step readPrec
--                                    Symbol ":^:" &lt;- lexP
--                                    v &lt;- step readPrec
--                                    return (u :^: v))
--   
--             where app_prec = 10
--                   up_prec = 5
--   
--           readListPrec = readListPrecDefault
--   </pre>
--   
--   Why do both <a>readsPrec</a> and <a>readPrec</a> exist, and why does
--   GHC opt to implement <a>readPrec</a> in derived <a>Read</a> instances
--   instead of <a>readsPrec</a>? The reason is that <a>readsPrec</a> is
--   based on the <a>ReadS</a> type, and although <a>ReadS</a> is mentioned
--   in the Haskell 2010 Report, it is not a very efficient parser data
--   structure.
--   
--   <a>readPrec</a>, on the other hand, is based on a much more efficient
--   <a>ReadPrec</a> datatype (a.k.a "new-style parsers"), but its
--   definition relies on the use of the <tt>RankNTypes</tt> language
--   extension. Therefore, <a>readPrec</a> (and its cousin,
--   <a>readListPrec</a>) are marked as GHC-only. Nevertheless, it is
--   recommended to use <a>readPrec</a> instead of <a>readsPrec</a>
--   whenever possible for the efficiency improvements it brings.
--   
--   As mentioned above, derived <a>Read</a> instances in GHC will
--   implement <a>readPrec</a> instead of <a>readsPrec</a>. The default
--   implementations of <a>readsPrec</a> (and its cousin, <a>readList</a>)
--   will simply use <a>readPrec</a> under the hood. If you are writing a
--   <a>Read</a> instance by hand, it is recommended to write it like so:
--   
--   <pre>
--   instance <a>Read</a> T where
--     <a>readPrec</a>     = ...
--     <a>readListPrec</a> = <a>readListPrecDefault</a>
--   </pre>
class Read a

-- | attempts to parse a value from the front of the string, returning a
--   list of (parsed value, remaining string) pairs. If there is no
--   successful parse, the returned list is empty.
--   
--   Derived instances of <a>Read</a> and <a>Show</a> satisfy the
--   following:
--   
--   <ul>
--   <li><tt>(x,"")</tt> is an element of <tt>(<a>readsPrec</a> d
--   (<a>showsPrec</a> d x ""))</tt>.</li>
--   </ul>
--   
--   That is, <a>readsPrec</a> parses the string produced by
--   <a>showsPrec</a>, and delivers the value that <a>showsPrec</a> started
--   with.
readsPrec :: Read a => Int -> ReadS a

-- | The method <a>readList</a> is provided to allow the programmer to give
--   a specialised way of parsing lists of values. For example, this is
--   used by the predefined <a>Read</a> instance of the <a>Char</a> type,
--   where values of type <a>String</a> should be are expected to use
--   double quotes, rather than square brackets.
readList :: Read a => ReadS [a]
class (Num a, Ord a) => Real a

-- | the rational equivalent of its real argument with full precision
toRational :: Real a => a -> Rational

-- | Efficient, machine-independent access to the components of a
--   floating-point number.
class (RealFrac a, Floating a) => RealFloat a

-- | a constant function, returning the radix of the representation (often
--   <tt>2</tt>)
floatRadix :: RealFloat a => a -> Integer

-- | a constant function, returning the number of digits of
--   <a>floatRadix</a> in the significand
floatDigits :: RealFloat a => a -> Int

-- | a constant function, returning the lowest and highest values the
--   exponent may assume
floatRange :: RealFloat a => a -> (Int, Int)

-- | The function <a>decodeFloat</a> applied to a real floating-point
--   number returns the significand expressed as an <a>Integer</a> and an
--   appropriately scaled exponent (an <a>Int</a>). If
--   <tt><a>decodeFloat</a> x</tt> yields <tt>(m,n)</tt>, then <tt>x</tt>
--   is equal in value to <tt>m*b^^n</tt>, where <tt>b</tt> is the
--   floating-point radix, and furthermore, either <tt>m</tt> and
--   <tt>n</tt> are both zero or else <tt>b^(d-1) &lt;= <a>abs</a> m &lt;
--   b^d</tt>, where <tt>d</tt> is the value of <tt><a>floatDigits</a>
--   x</tt>. In particular, <tt><a>decodeFloat</a> 0 = (0,0)</tt>. If the
--   type contains a negative zero, also <tt><a>decodeFloat</a> (-0.0) =
--   (0,0)</tt>. <i>The result of</i> <tt><a>decodeFloat</a> x</tt> <i>is
--   unspecified if either of</i> <tt><a>isNaN</a> x</tt> <i>or</i>
--   <tt><a>isInfinite</a> x</tt> <i>is</i> <a>True</a>.
decodeFloat :: RealFloat a => a -> (Integer, Int)

-- | <a>encodeFloat</a> performs the inverse of <a>decodeFloat</a> in the
--   sense that for finite <tt>x</tt> with the exception of <tt>-0.0</tt>,
--   <tt><a>uncurry</a> <a>encodeFloat</a> (<a>decodeFloat</a> x) = x</tt>.
--   <tt><a>encodeFloat</a> m n</tt> is one of the two closest
--   representable floating-point numbers to <tt>m*b^^n</tt> (or
--   <tt>±Infinity</tt> if overflow occurs); usually the closer, but if
--   <tt>m</tt> contains too many bits, the result may be rounded in the
--   wrong direction.
encodeFloat :: RealFloat a => Integer -> Int -> a

-- | <a>exponent</a> corresponds to the second component of
--   <a>decodeFloat</a>. <tt><a>exponent</a> 0 = 0</tt> and for finite
--   nonzero <tt>x</tt>, <tt><a>exponent</a> x = snd (<a>decodeFloat</a> x)
--   + <a>floatDigits</a> x</tt>. If <tt>x</tt> is a finite floating-point
--   number, it is equal in value to <tt><a>significand</a> x * b ^^
--   <a>exponent</a> x</tt>, where <tt>b</tt> is the floating-point radix.
--   The behaviour is unspecified on infinite or <tt>NaN</tt> values.
exponent :: RealFloat a => a -> Int

-- | The first component of <a>decodeFloat</a>, scaled to lie in the open
--   interval (<tt>-1</tt>,<tt>1</tt>), either <tt>0.0</tt> or of absolute
--   value <tt>&gt;= 1/b</tt>, where <tt>b</tt> is the floating-point
--   radix. The behaviour is unspecified on infinite or <tt>NaN</tt>
--   values.
significand :: RealFloat a => a -> a

-- | multiplies a floating-point number by an integer power of the radix
scaleFloat :: RealFloat a => Int -> a -> a

-- | <a>True</a> if the argument is an IEEE "not-a-number" (NaN) value
isNaN :: RealFloat a => a -> Bool

-- | <a>True</a> if the argument is an IEEE infinity or negative infinity
isInfinite :: RealFloat a => a -> Bool

-- | <a>True</a> if the argument is too small to be represented in
--   normalized format
isDenormalized :: RealFloat a => a -> Bool

-- | <a>True</a> if the argument is an IEEE negative zero
isNegativeZero :: RealFloat a => a -> Bool

-- | <a>True</a> if the argument is an IEEE floating point number
isIEEE :: RealFloat a => a -> Bool

-- | a version of arctangent taking two real floating-point arguments. For
--   real floating <tt>x</tt> and <tt>y</tt>, <tt><a>atan2</a> y x</tt>
--   computes the angle (from the positive x-axis) of the vector from the
--   origin to the point <tt>(x,y)</tt>. <tt><a>atan2</a> y x</tt> returns
--   a value in the range [<tt>-pi</tt>, <tt>pi</tt>]. It follows the
--   Common Lisp semantics for the origin when signed zeroes are supported.
--   <tt><a>atan2</a> y 1</tt>, with <tt>y</tt> in a type that is
--   <a>RealFloat</a>, should return the same value as <tt><a>atan</a>
--   y</tt>. A default definition of <a>atan2</a> is provided, but
--   implementors can provide a more accurate implementation.
atan2 :: RealFloat a => a -> a -> a

-- | Extracting components of fractions.
class (Real a, Fractional a) => RealFrac a

-- | The function <a>properFraction</a> takes a real fractional number
--   <tt>x</tt> and returns a pair <tt>(n,f)</tt> such that <tt>x =
--   n+f</tt>, and:
--   
--   <ul>
--   <li><tt>n</tt> is an integral number with the same sign as <tt>x</tt>;
--   and</li>
--   <li><tt>f</tt> is a fraction with the same type and sign as
--   <tt>x</tt>, and with absolute value less than <tt>1</tt>.</li>
--   </ul>
--   
--   The default definitions of the <a>ceiling</a>, <a>floor</a>,
--   <a>truncate</a> and <a>round</a> functions are in terms of
--   <a>properFraction</a>.
properFraction :: (RealFrac a, Integral b) => a -> (b, a)

-- | <tt><a>truncate</a> x</tt> returns the integer nearest <tt>x</tt>
--   between zero and <tt>x</tt>
truncate :: (RealFrac a, Integral b) => a -> b

-- | <tt><a>round</a> x</tt> returns the nearest integer to <tt>x</tt>; the
--   even integer if <tt>x</tt> is equidistant between two integers
round :: (RealFrac a, Integral b) => a -> b

-- | <tt><a>ceiling</a> x</tt> returns the least integer not less than
--   <tt>x</tt>
ceiling :: (RealFrac a, Integral b) => a -> b

-- | <tt><a>floor</a> x</tt> returns the greatest integer not greater than
--   <tt>x</tt>
floor :: (RealFrac a, Integral b) => a -> b

-- | Conversion of values to readable <a>String</a>s.
--   
--   Derived instances of <a>Show</a> have the following properties, which
--   are compatible with derived instances of <a>Read</a>:
--   
--   <ul>
--   <li>The result of <a>show</a> is a syntactically correct Haskell
--   expression containing only constants, given the fixity declarations in
--   force at the point where the type is declared. It contains only the
--   constructor names defined in the data type, parentheses, and spaces.
--   When labelled constructor fields are used, braces, commas, field
--   names, and equal signs are also used.</li>
--   <li>If the constructor is defined to be an infix operator, then
--   <a>showsPrec</a> will produce infix applications of the
--   constructor.</li>
--   <li>the representation will be enclosed in parentheses if the
--   precedence of the top-level constructor in <tt>x</tt> is less than
--   <tt>d</tt> (associativity is ignored). Thus, if <tt>d</tt> is
--   <tt>0</tt> then the result is never surrounded in parentheses; if
--   <tt>d</tt> is <tt>11</tt> it is always surrounded in parentheses,
--   unless it is an atomic expression.</li>
--   <li>If the constructor is defined using record syntax, then
--   <a>show</a> will produce the record-syntax form, with the fields given
--   in the same order as the original declaration.</li>
--   </ul>
--   
--   For example, given the declarations
--   
--   <pre>
--   infixr 5 :^:
--   data Tree a =  Leaf a  |  Tree a :^: Tree a
--   </pre>
--   
--   the derived instance of <a>Show</a> is equivalent to
--   
--   <pre>
--   instance (Show a) =&gt; Show (Tree a) where
--   
--          showsPrec d (Leaf m) = showParen (d &gt; app_prec) $
--               showString "Leaf " . showsPrec (app_prec+1) m
--            where app_prec = 10
--   
--          showsPrec d (u :^: v) = showParen (d &gt; up_prec) $
--               showsPrec (up_prec+1) u .
--               showString " :^: "      .
--               showsPrec (up_prec+1) v
--            where up_prec = 5
--   </pre>
--   
--   Note that right-associativity of <tt>:^:</tt> is ignored. For example,
--   
--   <ul>
--   <li><tt><a>show</a> (Leaf 1 :^: Leaf 2 :^: Leaf 3)</tt> produces the
--   string <tt>"Leaf 1 :^: (Leaf 2 :^: Leaf 3)"</tt>.</li>
--   </ul>
class Show a

-- | Convert a value to a readable <a>String</a>.
--   
--   <a>showsPrec</a> should satisfy the law
--   
--   <pre>
--   showsPrec d x r ++ s  ==  showsPrec d x (r ++ s)
--   </pre>
--   
--   Derived instances of <a>Read</a> and <a>Show</a> satisfy the
--   following:
--   
--   <ul>
--   <li><tt>(x,"")</tt> is an element of <tt>(<a>readsPrec</a> d
--   (<a>showsPrec</a> d x ""))</tt>.</li>
--   </ul>
--   
--   That is, <a>readsPrec</a> parses the string produced by
--   <a>showsPrec</a>, and delivers the value that <a>showsPrec</a> started
--   with.
showsPrec :: Show a => Int -> a -> ShowS

-- | A specialised variant of <a>showsPrec</a>, using precedence context
--   zero, and returning an ordinary <a>String</a>.
show :: Show a => a -> String

-- | The method <a>showList</a> is provided to allow the programmer to give
--   a specialised way of showing lists of values. For example, this is
--   used by the predefined <a>Show</a> instance of the <a>Char</a> type,
--   where values of type <a>String</a> should be shown in double quotes,
--   rather than between square brackets.
showList :: Show a => [a] -> ShowS

-- | When a value is bound in <tt>do</tt>-notation, the pattern on the left
--   hand side of <tt>&lt;-</tt> might not match. In this case, this class
--   provides a function to recover.
--   
--   A <a>Monad</a> without a <a>MonadFail</a> instance may only be used in
--   conjunction with pattern that always match, such as newtypes, tuples,
--   data types with only a single data constructor, and irrefutable
--   patterns (<tt>~pat</tt>).
--   
--   Instances of <a>MonadFail</a> should satisfy the following law:
--   <tt>fail s</tt> should be a left zero for <a>&gt;&gt;=</a>,
--   
--   <pre>
--   fail s &gt;&gt;= f  =  fail s
--   </pre>
--   
--   If your <a>Monad</a> is also <a>MonadPlus</a>, a popular definition is
--   
--   <pre>
--   fail _ = mzero
--   </pre>
class Monad m => MonadFail (m :: Type -> Type)
fail :: MonadFail m => String -> m a

-- | A functor with application, providing operations to
--   
--   <ul>
--   <li>embed pure expressions (<a>pure</a>), and</li>
--   <li>sequence computations and combine their results (<a>&lt;*&gt;</a>
--   and <a>liftA2</a>).</li>
--   </ul>
--   
--   A minimal complete definition must include implementations of
--   <a>pure</a> and of either <a>&lt;*&gt;</a> or <a>liftA2</a>. If it
--   defines both, then they must behave the same as their default
--   definitions:
--   
--   <pre>
--   (<a>&lt;*&gt;</a>) = <a>liftA2</a> <a>id</a>
--   </pre>
--   
--   <pre>
--   <a>liftA2</a> f x y = f <a>&lt;$&gt;</a> x <a>&lt;*&gt;</a> y
--   </pre>
--   
--   Further, any definition must satisfy the following:
--   
--   <ul>
--   <li><i>Identity</i> <pre><a>pure</a> <a>id</a> <a>&lt;*&gt;</a> v =
--   v</pre></li>
--   <li><i>Composition</i> <pre><a>pure</a> (.) <a>&lt;*&gt;</a> u
--   <a>&lt;*&gt;</a> v <a>&lt;*&gt;</a> w = u <a>&lt;*&gt;</a> (v
--   <a>&lt;*&gt;</a> w)</pre></li>
--   <li><i>Homomorphism</i> <pre><a>pure</a> f <a>&lt;*&gt;</a>
--   <a>pure</a> x = <a>pure</a> (f x)</pre></li>
--   <li><i>Interchange</i> <pre>u <a>&lt;*&gt;</a> <a>pure</a> y =
--   <a>pure</a> (<a>$</a> y) <a>&lt;*&gt;</a> u</pre></li>
--   </ul>
--   
--   The other methods have the following default definitions, which may be
--   overridden with equivalent specialized implementations:
--   
--   <ul>
--   <li><pre>u <a>*&gt;</a> v = (<a>id</a> <a>&lt;$</a> u)
--   <a>&lt;*&gt;</a> v</pre></li>
--   <li><pre>u <a>&lt;*</a> v = <a>liftA2</a> <a>const</a> u v</pre></li>
--   </ul>
--   
--   As a consequence of these laws, the <a>Functor</a> instance for
--   <tt>f</tt> will satisfy
--   
--   <ul>
--   <li><pre><a>fmap</a> f x = <a>pure</a> f <a>&lt;*&gt;</a> x</pre></li>
--   </ul>
--   
--   It may be useful to note that supposing
--   
--   <pre>
--   forall x y. p (q x y) = f x . g y
--   </pre>
--   
--   it follows from the above that
--   
--   <pre>
--   <a>liftA2</a> p (<a>liftA2</a> q u v) = <a>liftA2</a> f u . <a>liftA2</a> g v
--   </pre>
--   
--   If <tt>f</tt> is also a <a>Monad</a>, it should satisfy
--   
--   <ul>
--   <li><pre><a>pure</a> = <a>return</a></pre></li>
--   <li><pre>(<a>&lt;*&gt;</a>) = <a>ap</a></pre></li>
--   <li><pre>(<a>*&gt;</a>) = (<a>&gt;&gt;</a>)</pre></li>
--   </ul>
--   
--   (which implies that <a>pure</a> and <a>&lt;*&gt;</a> satisfy the
--   applicative functor laws).
class Functor f => Applicative (f :: Type -> Type)

-- | Lift a value.
pure :: Applicative f => a -> f a

-- | Sequential application.
--   
--   A few functors support an implementation of <a>&lt;*&gt;</a> that is
--   more efficient than the default one.
(<*>) :: Applicative f => f (a -> b) -> f a -> f b

-- | Sequence actions, discarding the value of the first argument.
(*>) :: Applicative f => f a -> f b -> f b

-- | Sequence actions, discarding the value of the second argument.
(<*) :: Applicative f => f a -> f b -> f a
infixl 4 <*>
infixl 4 *>
infixl 4 <*

-- | Data structures that can be folded.
--   
--   For example, given a data type
--   
--   <pre>
--   data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)
--   </pre>
--   
--   a suitable instance would be
--   
--   <pre>
--   instance Foldable Tree where
--      foldMap f Empty = mempty
--      foldMap f (Leaf x) = f x
--      foldMap f (Node l k r) = foldMap f l `mappend` f k `mappend` foldMap f r
--   </pre>
--   
--   This is suitable even for abstract types, as the monoid is assumed to
--   satisfy the monoid laws. Alternatively, one could define
--   <tt>foldr</tt>:
--   
--   <pre>
--   instance Foldable Tree where
--      foldr f z Empty = z
--      foldr f z (Leaf x) = f x z
--      foldr f z (Node l k r) = foldr f (f k (foldr f z r)) l
--   </pre>
--   
--   <tt>Foldable</tt> instances are expected to satisfy the following
--   laws:
--   
--   <pre>
--   foldr f z t = appEndo (foldMap (Endo . f) t ) z
--   </pre>
--   
--   <pre>
--   foldl f z t = appEndo (getDual (foldMap (Dual . Endo . flip f) t)) z
--   </pre>
--   
--   <pre>
--   fold = foldMap id
--   </pre>
--   
--   <pre>
--   length = getSum . foldMap (Sum . const  1)
--   </pre>
--   
--   <tt>sum</tt>, <tt>product</tt>, <tt>maximum</tt>, and <tt>minimum</tt>
--   should all be essentially equivalent to <tt>foldMap</tt> forms, such
--   as
--   
--   <pre>
--   sum = getSum . foldMap Sum
--   </pre>
--   
--   but may be less defined.
--   
--   If the type is also a <a>Functor</a> instance, it should satisfy
--   
--   <pre>
--   foldMap f = fold . fmap f
--   </pre>
--   
--   which implies that
--   
--   <pre>
--   foldMap f . fmap g = foldMap (f . g)
--   </pre>
class Foldable (t :: Type -> Type)

-- | Map each element of the structure to a monoid, and combine the
--   results.
foldMap :: (Foldable t, Monoid m) => (a -> m) -> t a -> m

-- | Right-associative fold of a structure.
--   
--   In the case of lists, <a>foldr</a>, when applied to a binary operator,
--   a starting value (typically the right-identity of the operator), and a
--   list, reduces the list using the binary operator, from right to left:
--   
--   <pre>
--   foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...)
--   </pre>
--   
--   Note that, since the head of the resulting expression is produced by
--   an application of the operator to the first element of the list,
--   <a>foldr</a> can produce a terminating expression from an infinite
--   list.
--   
--   For a general <a>Foldable</a> structure this should be semantically
--   identical to,
--   
--   <pre>
--   foldr f z = <a>foldr</a> f z . <a>toList</a>
--   </pre>
foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b

-- | Left-associative fold of a structure.
--   
--   In the case of lists, <a>foldl</a>, when applied to a binary operator,
--   a starting value (typically the left-identity of the operator), and a
--   list, reduces the list using the binary operator, from left to right:
--   
--   <pre>
--   foldl f z [x1, x2, ..., xn] == (...((z `f` x1) `f` x2) `f`...) `f` xn
--   </pre>
--   
--   Note that to produce the outermost application of the operator the
--   entire input list must be traversed. This means that <a>foldl'</a>
--   will diverge if given an infinite list.
--   
--   Also note that if you want an efficient left-fold, you probably want
--   to use <a>foldl'</a> instead of <a>foldl</a>. The reason for this is
--   that latter does not force the "inner" results (e.g. <tt>z `f` x1</tt>
--   in the above example) before applying them to the operator (e.g. to
--   <tt>(`f` x2)</tt>). This results in a thunk chain <tt>O(n)</tt>
--   elements long, which then must be evaluated from the outside-in.
--   
--   For a general <a>Foldable</a> structure this should be semantically
--   identical to,
--   
--   <pre>
--   foldl f z = <a>foldl</a> f z . <a>toList</a>
--   </pre>
foldl :: Foldable t => (b -> a -> b) -> b -> t a -> b

-- | A variant of <a>foldr</a> that has no base case, and thus may only be
--   applied to non-empty structures.
--   
--   <pre>
--   <a>foldr1</a> f = <a>foldr1</a> f . <a>toList</a>
--   </pre>
foldr1 :: Foldable t => (a -> a -> a) -> t a -> a

-- | A variant of <a>foldl</a> that has no base case, and thus may only be
--   applied to non-empty structures.
--   
--   <pre>
--   <a>foldl1</a> f = <a>foldl1</a> f . <a>toList</a>
--   </pre>
foldl1 :: Foldable t => (a -> a -> a) -> t a -> a

-- | Does the element occur in the structure?
elem :: (Foldable t, Eq a) => a -> t a -> Bool

-- | The largest element of a non-empty structure.
maximum :: (Foldable t, Ord a) => t a -> a

-- | The least element of a non-empty structure.
minimum :: (Foldable t, Ord a) => t a -> a

-- | The <a>product</a> function computes the product of the numbers of a
--   structure.
product :: (Foldable t, Num a) => t a -> a
infix 4 `elem`

-- | Functors representing data structures that can be traversed from left
--   to right.
--   
--   A definition of <a>traverse</a> must satisfy the following laws:
--   
--   <ul>
--   <li><i>Naturality</i> <tt>t . <a>traverse</a> f = <a>traverse</a> (t .
--   f)</tt> for every applicative transformation <tt>t</tt></li>
--   <li><i>Identity</i> <tt><a>traverse</a> <a>Identity</a> =
--   <a>Identity</a></tt></li>
--   <li><i>Composition</i> <tt><a>traverse</a> (<a>Compose</a> .
--   <a>fmap</a> g . f) = <a>Compose</a> . <a>fmap</a> (<a>traverse</a> g)
--   . <a>traverse</a> f</tt></li>
--   </ul>
--   
--   A definition of <a>sequenceA</a> must satisfy the following laws:
--   
--   <ul>
--   <li><i>Naturality</i> <tt>t . <a>sequenceA</a> = <a>sequenceA</a> .
--   <a>fmap</a> t</tt> for every applicative transformation
--   <tt>t</tt></li>
--   <li><i>Identity</i> <tt><a>sequenceA</a> . <a>fmap</a> <a>Identity</a>
--   = <a>Identity</a></tt></li>
--   <li><i>Composition</i> <tt><a>sequenceA</a> . <a>fmap</a>
--   <a>Compose</a> = <a>Compose</a> . <a>fmap</a> <a>sequenceA</a> .
--   <a>sequenceA</a></tt></li>
--   </ul>
--   
--   where an <i>applicative transformation</i> is a function
--   
--   <pre>
--   t :: (Applicative f, Applicative g) =&gt; f a -&gt; g a
--   </pre>
--   
--   preserving the <a>Applicative</a> operations, i.e.
--   
--   <pre>
--   t (<a>pure</a> x) = <a>pure</a> x
--   t (f <a>&lt;*&gt;</a> x) = t f <a>&lt;*&gt;</a> t x
--   </pre>
--   
--   and the identity functor <a>Identity</a> and composition functors
--   <a>Compose</a> are from <a>Data.Functor.Identity</a> and
--   <a>Data.Functor.Compose</a>.
--   
--   (The naturality law is implied by parametricity.)
--   
--   Instances are similar to <a>Functor</a>, e.g. given a data type
--   
--   <pre>
--   data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)
--   </pre>
--   
--   a suitable instance would be
--   
--   <pre>
--   instance Traversable Tree where
--      traverse f Empty = pure Empty
--      traverse f (Leaf x) = Leaf &lt;$&gt; f x
--      traverse f (Node l k r) = Node &lt;$&gt; traverse f l &lt;*&gt; f k &lt;*&gt; traverse f r
--   </pre>
--   
--   This is suitable even for abstract types, as the laws for
--   <a>&lt;*&gt;</a> imply a form of associativity.
--   
--   The superclass instances should satisfy the following:
--   
--   <ul>
--   <li>In the <a>Functor</a> instance, <a>fmap</a> should be equivalent
--   to traversal with the identity applicative functor
--   (<a>fmapDefault</a>).</li>
--   <li>In the <a>Foldable</a> instance, <a>foldMap</a> should be
--   equivalent to traversal with a constant applicative functor
--   (<a>foldMapDefault</a>).</li>
--   </ul>
class (Functor t, Foldable t) => Traversable (t :: Type -> Type)

-- | Map each element of a structure to an action, evaluate these actions
--   from left to right, and collect the results. For a version that
--   ignores the results see <a>traverse_</a>.
traverse :: (Traversable t, Applicative f) => (a -> f b) -> t a -> f (t b)

-- | Evaluate each action in the structure from left to right, and collect
--   the results. For a version that ignores the results see
--   <a>sequenceA_</a>.
sequenceA :: (Traversable t, Applicative f) => t (f a) -> f (t a)

-- | Map each element of a structure to a monadic action, evaluate these
--   actions from left to right, and collect the results. For a version
--   that ignores the results see <a>mapM_</a>.
mapM :: (Traversable t, Monad m) => (a -> m b) -> t a -> m (t b)

-- | Evaluate each monadic action in the structure from left to right, and
--   collect the results. For a version that ignores the results see
--   <a>sequence_</a>.
sequence :: (Traversable t, Monad m) => t (m a) -> m (t a)

-- | The class of semigroups (types with an associative binary operation).
--   
--   Instances should satisfy the following:
--   
--   <ul>
--   <li><i>Associativity</i> <tt>x <a>&lt;&gt;</a> (y <a>&lt;&gt;</a> z) =
--   (x <a>&lt;&gt;</a> y) <a>&lt;&gt;</a> z</tt></li>
--   </ul>
class Semigroup a

-- | The class of monoids (types with an associative binary operation that
--   has an identity). Instances should satisfy the following:
--   
--   <ul>
--   <li><i>Right identity</i> <tt>x <a>&lt;&gt;</a> <a>mempty</a> =
--   x</tt></li>
--   <li><i>Left identity</i> <tt><a>mempty</a> <a>&lt;&gt;</a> x =
--   x</tt></li>
--   <li><i>Associativity</i> <tt>x <a>&lt;&gt;</a> (y <a>&lt;&gt;</a> z) =
--   (x <a>&lt;&gt;</a> y) <a>&lt;&gt;</a> z</tt> (<a>Semigroup</a>
--   law)</li>
--   <li><i>Concatenation</i> <tt><a>mconcat</a> = <a>foldr</a>
--   (<a>&lt;&gt;</a>) <a>mempty</a></tt></li>
--   </ul>
--   
--   The method names refer to the monoid of lists under concatenation, but
--   there are many other instances.
--   
--   Some types can be viewed as a monoid in more than one way, e.g. both
--   addition and multiplication on numbers. In such cases we often define
--   <tt>newtype</tt>s and make those instances of <a>Monoid</a>, e.g.
--   <a>Sum</a> and <a>Product</a>.
--   
--   <b>NOTE</b>: <a>Semigroup</a> is a superclass of <a>Monoid</a> since
--   <i>base-4.11.0.0</i>.
class Semigroup a => Monoid a

-- | Identity of <a>mappend</a>
mempty :: Monoid a => a

-- | An associative operation
--   
--   <b>NOTE</b>: This method is redundant and has the default
--   implementation <tt><a>mappend</a> = (<a>&lt;&gt;</a>)</tt> since
--   <i>base-4.11.0.0</i>.
mappend :: Monoid a => a -> a -> a

-- | Fold a list using the monoid.
--   
--   For most types, the default definition for <a>mconcat</a> will be
--   used, but the function is included in the class definition so that an
--   optimized version can be provided for specific types.
mconcat :: Monoid a => [a] -> a
data Bool
False :: Bool
True :: Bool

-- | The character type <a>Char</a> is an enumeration whose values
--   represent Unicode (or equivalently ISO/IEC 10646) code points (i.e.
--   characters, see <a>http://www.unicode.org/</a> for details). This set
--   extends the ISO 8859-1 (Latin-1) character set (the first 256
--   characters), which is itself an extension of the ASCII character set
--   (the first 128 characters). A character literal in Haskell has type
--   <a>Char</a>.
--   
--   To convert a <a>Char</a> to or from the corresponding <a>Int</a> value
--   defined by Unicode, use <a>toEnum</a> and <a>fromEnum</a> from the
--   <a>Enum</a> class respectively (or equivalently <a>ord</a> and
--   <a>chr</a>).
data Char

-- | Double-precision floating point numbers. It is desirable that this
--   type be at least equal in range and precision to the IEEE
--   double-precision type.
data Double

-- | Single-precision floating point numbers. It is desirable that this
--   type be at least equal in range and precision to the IEEE
--   single-precision type.
data Float

-- | A fixed-precision integer type with at least the range <tt>[-2^29 ..
--   2^29-1]</tt>. The exact range for a given implementation can be
--   determined by using <a>minBound</a> and <a>maxBound</a> from the
--   <a>Bounded</a> class.
data Int

-- | Invariant: <a>Jn#</a> and <a>Jp#</a> are used iff value doesn't fit in
--   <a>S#</a>
--   
--   Useful properties resulting from the invariants:
--   
--   <ul>
--   <li><pre>abs (<a>S#</a> _) &lt;= abs (<a>Jp#</a> _)</pre></li>
--   <li><pre>abs (<a>S#</a> _) &lt; abs (<a>Jn#</a> _)</pre></li>
--   </ul>
data Integer

-- | The <a>Maybe</a> type encapsulates an optional value. A value of type
--   <tt><a>Maybe</a> a</tt> either contains a value of type <tt>a</tt>
--   (represented as <tt><a>Just</a> a</tt>), or it is empty (represented
--   as <a>Nothing</a>). Using <a>Maybe</a> is a good way to deal with
--   errors or exceptional cases without resorting to drastic measures such
--   as <a>error</a>.
--   
--   The <a>Maybe</a> type is also a monad. It is a simple kind of error
--   monad, where all errors are represented by <a>Nothing</a>. A richer
--   error monad can be built using the <a>Either</a> type.
data Maybe a
Nothing :: Maybe a
Just :: a -> Maybe a
data Ordering
LT :: Ordering
EQ :: Ordering
GT :: Ordering

-- | Arbitrary-precision rational numbers, represented as a ratio of two
--   <a>Integer</a> values. A rational number may be constructed using the
--   <a>%</a> operator.
type Rational = Ratio Integer

-- | A value of type <tt><a>IO</a> a</tt> is a computation which, when
--   performed, does some I/O before returning a value of type <tt>a</tt>.
--   
--   There is really only one way to "perform" an I/O action: bind it to
--   <tt>Main.main</tt> in your program. When your program is run, the I/O
--   will be performed. It isn't possible to perform I/O from an arbitrary
--   function, unless that function is itself in the <a>IO</a> monad and
--   called at some point, directly or indirectly, from <tt>Main.main</tt>.
--   
--   <a>IO</a> is a monad, so <a>IO</a> actions can be combined using
--   either the do-notation or the <a>&gt;&gt;</a> and <a>&gt;&gt;=</a>
--   operations from the <a>Monad</a> class.
data IO a

-- | A <a>Word</a> is an unsigned integral type, with the same size as
--   <a>Int</a>.
data Word

-- | The <a>Either</a> type represents values with two possibilities: a
--   value of type <tt><a>Either</a> a b</tt> is either <tt><a>Left</a>
--   a</tt> or <tt><a>Right</a> b</tt>.
--   
--   The <a>Either</a> type is sometimes used to represent a value which is
--   either correct or an error; by convention, the <a>Left</a> constructor
--   is used to hold an error value and the <a>Right</a> constructor is
--   used to hold a correct value (mnemonic: "right" also means "correct").
--   
--   <h4><b>Examples</b></h4>
--   
--   The type <tt><a>Either</a> <a>String</a> <a>Int</a></tt> is the type
--   of values which can be either a <a>String</a> or an <a>Int</a>. The
--   <a>Left</a> constructor can be used only on <a>String</a>s, and the
--   <a>Right</a> constructor can be used only on <a>Int</a>s:
--   
--   <pre>
--   &gt;&gt;&gt; let s = Left "foo" :: Either String Int
--   
--   &gt;&gt;&gt; s
--   Left "foo"
--   
--   &gt;&gt;&gt; let n = Right 3 :: Either String Int
--   
--   &gt;&gt;&gt; n
--   Right 3
--   
--   &gt;&gt;&gt; :type s
--   s :: Either String Int
--   
--   &gt;&gt;&gt; :type n
--   n :: Either String Int
--   </pre>
--   
--   The <a>fmap</a> from our <a>Functor</a> instance will ignore
--   <a>Left</a> values, but will apply the supplied function to values
--   contained in a <a>Right</a>:
--   
--   <pre>
--   &gt;&gt;&gt; let s = Left "foo" :: Either String Int
--   
--   &gt;&gt;&gt; let n = Right 3 :: Either String Int
--   
--   &gt;&gt;&gt; fmap (*2) s
--   Left "foo"
--   
--   &gt;&gt;&gt; fmap (*2) n
--   Right 6
--   </pre>
--   
--   The <a>Monad</a> instance for <a>Either</a> allows us to chain
--   together multiple actions which may fail, and fail overall if any of
--   the individual steps failed. First we'll write a function that can
--   either parse an <a>Int</a> from a <a>Char</a>, or fail.
--   
--   <pre>
--   &gt;&gt;&gt; import Data.Char ( digitToInt, isDigit )
--   
--   &gt;&gt;&gt; :{
--       let parseEither :: Char -&gt; Either String Int
--           parseEither c
--             | isDigit c = Right (digitToInt c)
--             | otherwise = Left "parse error"
--   
--   &gt;&gt;&gt; :}
--   </pre>
--   
--   The following should work, since both <tt>'1'</tt> and <tt>'2'</tt>
--   can be parsed as <a>Int</a>s.
--   
--   <pre>
--   &gt;&gt;&gt; :{
--       let parseMultiple :: Either String Int
--           parseMultiple = do
--             x &lt;- parseEither '1'
--             y &lt;- parseEither '2'
--             return (x + y)
--   
--   &gt;&gt;&gt; :}
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; parseMultiple
--   Right 3
--   </pre>
--   
--   But the following should fail overall, since the first operation where
--   we attempt to parse <tt>'m'</tt> as an <a>Int</a> will fail:
--   
--   <pre>
--   &gt;&gt;&gt; :{
--       let parseMultiple :: Either String Int
--           parseMultiple = do
--             x &lt;- parseEither 'm'
--             y &lt;- parseEither '2'
--             return (x + y)
--   
--   &gt;&gt;&gt; :}
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; parseMultiple
--   Left "parse error"
--   </pre>
data Either a b
Left :: a -> Either a b
Right :: b -> Either a b

-- | <a>error</a> stops execution and displays an error message.
error :: forall (r :: RuntimeRep) (a :: TYPE r). HasCallStack => [Char] -> a

-- | The <a>readIO</a> function is similar to <a>read</a> except that it
--   signals parse failure to the <a>IO</a> monad instead of terminating
--   the program.
readIO :: Read a => String -> IO a

-- | The <a>readLn</a> function combines <a>getLine</a> and <a>readIO</a>.
readLn :: Read a => IO a

-- | The <a>interact</a> function takes a function of type
--   <tt>String-&gt;String</tt> as its argument. The entire input from the
--   standard input device is passed to this function as its argument, and
--   the resulting string is output on the standard output device.
interact :: (String -> String) -> IO ()

-- | The <a>getContents</a> operation returns all user input as a single
--   string, which is read lazily as it is needed (same as
--   <a>hGetContents</a> <a>stdin</a>).
getContents :: IO String

-- | Read a line from the standard input device (same as <a>hGetLine</a>
--   <a>stdin</a>).
getLine :: IO String

-- | Read a character from the standard input device (same as
--   <a>hGetChar</a> <a>stdin</a>).
getChar :: IO Char

-- | The same as <a>putStr</a>, but adds a newline character.
putStrLn :: String -> IO ()

-- | Write a string to the standard output device (same as <a>hPutStr</a>
--   <a>stdout</a>).
putStr :: String -> IO ()

-- | Write a character to the standard output device (same as
--   <a>hPutChar</a> <a>stdout</a>).
putChar :: Char -> IO ()

-- | Raise an <a>IOError</a> in the <a>IO</a> monad.
ioError :: IOError -> IO a

-- | File and directory names are values of type <a>String</a>, whose
--   precise meaning is operating system dependent. Files can be opened,
--   yielding a handle which can then be used to operate on the contents of
--   that file.
type FilePath = String

-- | Construct an <a>IOError</a> value with a string describing the error.
--   The <tt>fail</tt> method of the <a>IO</a> instance of the <a>Monad</a>
--   class raises a <a>userError</a>, thus:
--   
--   <pre>
--   instance Monad IO where
--     ...
--     fail s = ioError (userError s)
--   </pre>
userError :: String -> IOError

-- | The Haskell 2010 type for exceptions in the <a>IO</a> monad. Any I/O
--   operation may raise an <a>IOError</a> instead of returning a result.
--   For a more general type of exception, including also those that arise
--   in pure code, see <a>Exception</a>.
--   
--   In Haskell 2010, this is an opaque type.
type IOError = IOException

-- | <a>notElem</a> is the negation of <a>elem</a>.
notElem :: (Foldable t, Eq a) => a -> t a -> Bool
infix 4 `notElem`

-- | Determines whether all elements of the structure satisfy the
--   predicate.
all :: Foldable t => (a -> Bool) -> t a -> Bool

-- | Determines whether any element of the structure satisfies the
--   predicate.
any :: Foldable t => (a -> Bool) -> t a -> Bool

-- | <a>or</a> returns the disjunction of a container of Bools. For the
--   result to be <a>False</a>, the container must be finite; <a>True</a>,
--   however, results from a <a>True</a> value finitely far from the left
--   end.
or :: Foldable t => t Bool -> Bool

-- | <a>and</a> returns the conjunction of a container of Bools. For the
--   result to be <a>True</a>, the container must be finite; <a>False</a>,
--   however, results from a <a>False</a> value finitely far from the left
--   end.
and :: Foldable t => t Bool -> Bool

-- | Map a function over all the elements of a container and concatenate
--   the resulting lists.
concatMap :: Foldable t => (a -> [b]) -> t a -> [b]

-- | The concatenation of all the elements of a container of lists.
concat :: Foldable t => t [a] -> [a]

-- | Evaluate each monadic action in the structure from left to right, and
--   ignore the results. For a version that doesn't ignore the results see
--   <a>sequence</a>.
--   
--   As of base 4.8.0.0, <a>sequence_</a> is just <a>sequenceA_</a>,
--   specialized to <a>Monad</a>.
sequence_ :: (Foldable t, Monad m) => t (m a) -> m ()

-- | Map each element of a structure to a monadic action, evaluate these
--   actions from left to right, and ignore the results. For a version that
--   doesn't ignore the results see <a>mapM</a>.
--   
--   As of base 4.8.0.0, <a>mapM_</a> is just <a>traverse_</a>, specialized
--   to <a>Monad</a>.
mapM_ :: (Foldable t, Monad m) => (a -> m b) -> t a -> m ()

-- | <a>unwords</a> is an inverse operation to <a>words</a>. It joins words
--   with separating spaces.
--   
--   <pre>
--   &gt;&gt;&gt; unwords ["Lorem", "ipsum", "dolor"]
--   "Lorem ipsum dolor"
--   </pre>
unwords :: [String] -> String

-- | <a>words</a> breaks a string up into a list of words, which were
--   delimited by white space.
--   
--   <pre>
--   &gt;&gt;&gt; words "Lorem ipsum\ndolor"
--   ["Lorem","ipsum","dolor"]
--   </pre>
words :: String -> [String]

-- | <a>unlines</a> is an inverse operation to <a>lines</a>. It joins
--   lines, after appending a terminating newline to each.
--   
--   <pre>
--   &gt;&gt;&gt; unlines ["Hello", "World", "!"]
--   "Hello\nWorld\n!\n"
--   </pre>
unlines :: [String] -> String

-- | <a>lines</a> breaks a string up into a list of strings at newline
--   characters. The resulting strings do not contain newlines.
--   
--   Note that after splitting the string at newline characters, the last
--   part of the string is considered a line even if it doesn't end with a
--   newline. For example,
--   
--   <pre>
--   &gt;&gt;&gt; lines ""
--   []
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; lines "\n"
--   [""]
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; lines "one"
--   ["one"]
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; lines "one\n"
--   ["one"]
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; lines "one\n\n"
--   ["one",""]
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; lines "one\ntwo"
--   ["one","two"]
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; lines "one\ntwo\n"
--   ["one","two"]
--   </pre>
--   
--   Thus <tt><a>lines</a> s</tt> contains at least as many elements as
--   newlines in <tt>s</tt>.
lines :: String -> [String]

-- | The <a>read</a> function reads input from a string, which must be
--   completely consumed by the input process. <a>read</a> fails with an
--   <a>error</a> if the parse is unsuccessful, and it is therefore
--   discouraged from being used in real applications. Use <a>readMaybe</a>
--   or <a>readEither</a> for safe alternatives.
--   
--   <pre>
--   &gt;&gt;&gt; read "123" :: Int
--   123
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; read "hello" :: Int
--   *** Exception: Prelude.read: no parse
--   </pre>
read :: Read a => String -> a

-- | equivalent to <a>readsPrec</a> with a precedence of 0.
reads :: Read a => ReadS a

-- | Case analysis for the <a>Either</a> type. If the value is
--   <tt><a>Left</a> a</tt>, apply the first function to <tt>a</tt>; if it
--   is <tt><a>Right</a> b</tt>, apply the second function to <tt>b</tt>.
--   
--   <h4><b>Examples</b></h4>
--   
--   We create two values of type <tt><a>Either</a> <a>String</a>
--   <a>Int</a></tt>, one using the <a>Left</a> constructor and another
--   using the <a>Right</a> constructor. Then we apply "either" the
--   <a>length</a> function (if we have a <a>String</a>) or the "times-two"
--   function (if we have an <a>Int</a>):
--   
--   <pre>
--   &gt;&gt;&gt; let s = Left "foo" :: Either String Int
--   
--   &gt;&gt;&gt; let n = Right 3 :: Either String Int
--   
--   &gt;&gt;&gt; either length (*2) s
--   3
--   
--   &gt;&gt;&gt; either length (*2) n
--   6
--   </pre>
either :: (a -> c) -> (b -> c) -> Either a b -> c

-- | The <a>lex</a> function reads a single lexeme from the input,
--   discarding initial white space, and returning the characters that
--   constitute the lexeme. If the input string contains only white space,
--   <a>lex</a> returns a single successful `lexeme' consisting of the
--   empty string. (Thus <tt><a>lex</a> "" = [("","")]</tt>.) If there is
--   no legal lexeme at the beginning of the input string, <a>lex</a> fails
--   (i.e. returns <tt>[]</tt>).
--   
--   This lexer is not completely faithful to the Haskell lexical syntax in
--   the following respects:
--   
--   <ul>
--   <li>Qualified names are not handled properly</li>
--   <li>Octal and hexadecimal numerics are not recognized as a single
--   token</li>
--   <li>Comments are not treated properly</li>
--   </ul>
lex :: ReadS String

-- | <tt><a>readParen</a> <a>True</a> p</tt> parses what <tt>p</tt> parses,
--   but surrounded with parentheses.
--   
--   <tt><a>readParen</a> <a>False</a> p</tt> parses what <tt>p</tt>
--   parses, but optionally surrounded with parentheses.
readParen :: Bool -> ReadS a -> ReadS a

-- | A parser for a type <tt>a</tt>, represented as a function that takes a
--   <a>String</a> and returns a list of possible parses as
--   <tt>(a,<a>String</a>)</tt> pairs.
--   
--   Note that this kind of backtracking parser is very inefficient;
--   reading a large structure may be quite slow (cf <a>ReadP</a>).
type ReadS a = String -> [(a, String)]

-- | <tt><a>lcm</a> x y</tt> is the smallest positive integer that both
--   <tt>x</tt> and <tt>y</tt> divide.
lcm :: Integral a => a -> a -> a

-- | <tt><a>gcd</a> x y</tt> is the non-negative factor of both <tt>x</tt>
--   and <tt>y</tt> of which every common factor of <tt>x</tt> and
--   <tt>y</tt> is also a factor; for example <tt><a>gcd</a> 4 2 = 2</tt>,
--   <tt><a>gcd</a> (-4) 6 = 2</tt>, <tt><a>gcd</a> 0 4</tt> = <tt>4</tt>.
--   <tt><a>gcd</a> 0 0</tt> = <tt>0</tt>. (That is, the common divisor
--   that is "greatest" in the divisibility preordering.)
--   
--   Note: Since for signed fixed-width integer types, <tt><a>abs</a>
--   <a>minBound</a> &lt; 0</tt>, the result may be negative if one of the
--   arguments is <tt><a>minBound</a></tt> (and necessarily is if the other
--   is <tt>0</tt> or <tt><a>minBound</a></tt>) for such types.
gcd :: Integral a => a -> a -> a

-- | raise a number to an integral power
(^^) :: (Fractional a, Integral b) => a -> b -> a
infixr 8 ^^

-- | raise a number to a non-negative integral power
(^) :: (Num a, Integral b) => a -> b -> a
infixr 8 ^
odd :: Integral a => a -> Bool
even :: Integral a => a -> Bool

-- | utility function that surrounds the inner show function with
--   parentheses when the <a>Bool</a> parameter is <a>True</a>.
showParen :: Bool -> ShowS -> ShowS

-- | utility function converting a <a>String</a> to a show function that
--   simply prepends the string unchanged.
showString :: String -> ShowS

-- | utility function converting a <a>Char</a> to a show function that
--   simply prepends the character unchanged.
showChar :: Char -> ShowS

-- | equivalent to <a>showsPrec</a> with a precedence of 0.
shows :: Show a => a -> ShowS

-- | The <tt>shows</tt> functions return a function that prepends the
--   output <a>String</a> to an existing <a>String</a>. This allows
--   constant-time concatenation of results using function composition.
type ShowS = String -> String

-- | The <a>unzip3</a> function takes a list of triples and returns three
--   lists, analogous to <a>unzip</a>.
unzip3 :: [(a, b, c)] -> ([a], [b], [c])

-- | <a>unzip</a> transforms a list of pairs into a list of first
--   components and a list of second components.
unzip :: [(a, b)] -> ([a], [b])

-- | The <a>zipWith3</a> function takes a function which combines three
--   elements, as well as three lists and returns a list of their
--   point-wise combination, analogous to <a>zipWith</a>. It is capable of
--   list fusion, but it is restricted to its first list argument and its
--   resulting list.
zipWith3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]

-- | <i>O(min(m,n))</i>. <a>zipWith</a> generalises <a>zip</a> by zipping
--   with the function given as the first argument, instead of a tupling
--   function. For example, <tt><a>zipWith</a> (+)</tt> is applied to two
--   lists to produce the list of corresponding sums:
--   
--   <pre>
--   &gt;&gt;&gt; zipWith (+) [1, 2, 3] [4, 5, 6]
--   [5,7,9]
--   </pre>
--   
--   <a>zipWith</a> is right-lazy:
--   
--   <pre>
--   zipWith f [] _|_ = []
--   </pre>
--   
--   <a>zipWith</a> is capable of list fusion, but it is restricted to its
--   first list argument and its resulting list.
zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]

-- | <a>zip3</a> takes three lists and returns a list of triples, analogous
--   to <a>zip</a>. It is capable of list fusion, but it is restricted to
--   its first list argument and its resulting list.
zip3 :: [a] -> [b] -> [c] -> [(a, b, c)]

-- | List index (subscript) operator, starting from 0. It is an instance of
--   the more general <a>genericIndex</a>, which takes an index of any
--   integral type.
(!!) :: [a] -> Int -> a
infixl 9 !!

-- | <i>O(n)</i>. <a>lookup</a> <tt>key assocs</tt> looks up a key in an
--   association list.
--   
--   <pre>
--   &gt;&gt;&gt; lookup 2 [(1, "first"), (2, "second"), (3, "third")]
--   Just "second"
--   </pre>
lookup :: Eq a => a -> [(a, b)] -> Maybe b

-- | <a>reverse</a> <tt>xs</tt> returns the elements of <tt>xs</tt> in
--   reverse order. <tt>xs</tt> must be finite.
reverse :: [a] -> [a]

-- | <a>break</a>, applied to a predicate <tt>p</tt> and a list
--   <tt>xs</tt>, returns a tuple where first element is longest prefix
--   (possibly empty) of <tt>xs</tt> of elements that <i>do not satisfy</i>
--   <tt>p</tt> and second element is the remainder of the list:
--   
--   <pre>
--   break (&gt; 3) [1,2,3,4,1,2,3,4] == ([1,2,3],[4,1,2,3,4])
--   break (&lt; 9) [1,2,3] == ([],[1,2,3])
--   break (&gt; 9) [1,2,3] == ([1,2,3],[])
--   </pre>
--   
--   <a>break</a> <tt>p</tt> is equivalent to <tt><a>span</a> (<a>not</a> .
--   p)</tt>.
break :: (a -> Bool) -> [a] -> ([a], [a])

-- | <a>span</a>, applied to a predicate <tt>p</tt> and a list <tt>xs</tt>,
--   returns a tuple where first element is longest prefix (possibly empty)
--   of <tt>xs</tt> of elements that satisfy <tt>p</tt> and second element
--   is the remainder of the list:
--   
--   <pre>
--   span (&lt; 3) [1,2,3,4,1,2,3,4] == ([1,2],[3,4,1,2,3,4])
--   span (&lt; 9) [1,2,3] == ([1,2,3],[])
--   span (&lt; 0) [1,2,3] == ([],[1,2,3])
--   </pre>
--   
--   <a>span</a> <tt>p xs</tt> is equivalent to <tt>(<a>takeWhile</a> p xs,
--   <a>dropWhile</a> p xs)</tt>
span :: (a -> Bool) -> [a] -> ([a], [a])

-- | <a>splitAt</a> <tt>n xs</tt> returns a tuple where first element is
--   <tt>xs</tt> prefix of length <tt>n</tt> and second element is the
--   remainder of the list:
--   
--   <pre>
--   splitAt 6 "Hello World!" == ("Hello ","World!")
--   splitAt 3 [1,2,3,4,5] == ([1,2,3],[4,5])
--   splitAt 1 [1,2,3] == ([1],[2,3])
--   splitAt 3 [1,2,3] == ([1,2,3],[])
--   splitAt 4 [1,2,3] == ([1,2,3],[])
--   splitAt 0 [1,2,3] == ([],[1,2,3])
--   splitAt (-1) [1,2,3] == ([],[1,2,3])
--   </pre>
--   
--   It is equivalent to <tt>(<a>take</a> n xs, <a>drop</a> n xs)</tt> when
--   <tt>n</tt> is not <tt>_|_</tt> (<tt>splitAt _|_ xs = _|_</tt>).
--   <a>splitAt</a> is an instance of the more general
--   <a>genericSplitAt</a>, in which <tt>n</tt> may be of any integral
--   type.
splitAt :: Int -> [a] -> ([a], [a])

-- | <a>drop</a> <tt>n xs</tt> returns the suffix of <tt>xs</tt> after the
--   first <tt>n</tt> elements, or <tt>[]</tt> if <tt>n &gt; <a>length</a>
--   xs</tt>:
--   
--   <pre>
--   drop 6 "Hello World!" == "World!"
--   drop 3 [1,2,3,4,5] == [4,5]
--   drop 3 [1,2] == []
--   drop 3 [] == []
--   drop (-1) [1,2] == [1,2]
--   drop 0 [1,2] == [1,2]
--   </pre>
--   
--   It is an instance of the more general <a>genericDrop</a>, in which
--   <tt>n</tt> may be of any integral type.
drop :: Int -> [a] -> [a]

-- | <a>take</a> <tt>n</tt>, applied to a list <tt>xs</tt>, returns the
--   prefix of <tt>xs</tt> of length <tt>n</tt>, or <tt>xs</tt> itself if
--   <tt>n &gt; <a>length</a> xs</tt>:
--   
--   <pre>
--   take 5 "Hello World!" == "Hello"
--   take 3 [1,2,3,4,5] == [1,2,3]
--   take 3 [1,2] == [1,2]
--   take 3 [] == []
--   take (-1) [1,2] == []
--   take 0 [1,2] == []
--   </pre>
--   
--   It is an instance of the more general <a>genericTake</a>, in which
--   <tt>n</tt> may be of any integral type.
take :: Int -> [a] -> [a]

-- | <a>dropWhile</a> <tt>p xs</tt> returns the suffix remaining after
--   <a>takeWhile</a> <tt>p xs</tt>:
--   
--   <pre>
--   dropWhile (&lt; 3) [1,2,3,4,5,1,2,3] == [3,4,5,1,2,3]
--   dropWhile (&lt; 9) [1,2,3] == []
--   dropWhile (&lt; 0) [1,2,3] == [1,2,3]
--   </pre>
dropWhile :: (a -> Bool) -> [a] -> [a]

-- | <a>takeWhile</a>, applied to a predicate <tt>p</tt> and a list
--   <tt>xs</tt>, returns the longest prefix (possibly empty) of
--   <tt>xs</tt> of elements that satisfy <tt>p</tt>:
--   
--   <pre>
--   takeWhile (&lt; 3) [1,2,3,4,1,2,3,4] == [1,2]
--   takeWhile (&lt; 9) [1,2,3] == [1,2,3]
--   takeWhile (&lt; 0) [1,2,3] == []
--   </pre>
takeWhile :: (a -> Bool) -> [a] -> [a]

-- | <a>cycle</a> ties a finite list into a circular one, or equivalently,
--   the infinite repetition of the original list. It is the identity on
--   infinite lists.
cycle :: [a] -> [a]

-- | <a>replicate</a> <tt>n x</tt> is a list of length <tt>n</tt> with
--   <tt>x</tt> the value of every element. It is an instance of the more
--   general <a>genericReplicate</a>, in which <tt>n</tt> may be of any
--   integral type.
replicate :: Int -> a -> [a]

-- | <a>repeat</a> <tt>x</tt> is an infinite list, with <tt>x</tt> the
--   value of every element.
repeat :: a -> [a]

-- | <a>iterate</a> <tt>f x</tt> returns an infinite list of repeated
--   applications of <tt>f</tt> to <tt>x</tt>:
--   
--   <pre>
--   iterate f x == [x, f x, f (f x), ...]
--   </pre>
--   
--   Note that <a>iterate</a> is lazy, potentially leading to thunk
--   build-up if the consumer doesn't force each iterate. See
--   <a>iterate'</a> for a strict variant of this function.
iterate :: (a -> a) -> a -> [a]

-- | <i>O(n)</i>. <a>scanr1</a> is a variant of <a>scanr</a> that has no
--   starting value argument.
scanr1 :: (a -> a -> a) -> [a] -> [a]

-- | <i>O(n)</i>. <a>scanr</a> is the right-to-left dual of <a>scanl</a>.
--   Note that
--   
--   <pre>
--   head (scanr f z xs) == foldr f z xs.
--   </pre>
scanr :: (a -> b -> b) -> b -> [a] -> [b]

-- | <i>O(n)</i>. <a>scanl1</a> is a variant of <a>scanl</a> that has no
--   starting value argument:
--   
--   <pre>
--   scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]
--   </pre>
scanl1 :: (a -> a -> a) -> [a] -> [a]

-- | <i>O(n)</i>. <a>scanl</a> is similar to <a>foldl</a>, but returns a
--   list of successive reduced values from the left:
--   
--   <pre>
--   scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
--   </pre>
--   
--   Note that
--   
--   <pre>
--   last (scanl f z xs) == foldl f z xs.
--   </pre>
scanl :: (b -> a -> b) -> b -> [a] -> [b]

-- | <i>O(n)</i>. Return all the elements of a list except the last one.
--   The list must be non-empty.
init :: [a] -> [a]

-- | <i>O(n)</i>. Extract the last element of a list, which must be finite
--   and non-empty.
last :: [a] -> a

-- | <i>O(1)</i>. Extract the elements after the head of a list, which must
--   be non-empty.
tail :: [a] -> [a]

-- | <i>O(1)</i>. Extract the first element of a list, which must be
--   non-empty.
head :: [a] -> a

-- | The <a>maybe</a> function takes a default value, a function, and a
--   <a>Maybe</a> value. If the <a>Maybe</a> value is <a>Nothing</a>, the
--   function returns the default value. Otherwise, it applies the function
--   to the value inside the <a>Just</a> and returns the result.
--   
--   <h4><b>Examples</b></h4>
--   
--   Basic usage:
--   
--   <pre>
--   &gt;&gt;&gt; maybe False odd (Just 3)
--   True
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; maybe False odd Nothing
--   False
--   </pre>
--   
--   Read an integer from a string using <a>readMaybe</a>. If we succeed,
--   return twice the integer; that is, apply <tt>(*2)</tt> to it. If
--   instead we fail to parse an integer, return <tt>0</tt> by default:
--   
--   <pre>
--   &gt;&gt;&gt; import Text.Read ( readMaybe )
--   
--   &gt;&gt;&gt; maybe 0 (*2) (readMaybe "5")
--   10
--   
--   &gt;&gt;&gt; maybe 0 (*2) (readMaybe "")
--   0
--   </pre>
--   
--   Apply <a>show</a> to a <tt>Maybe Int</tt>. If we have <tt>Just n</tt>,
--   we want to show the underlying <a>Int</a> <tt>n</tt>. But if we have
--   <a>Nothing</a>, we return the empty string instead of (for example)
--   "Nothing":
--   
--   <pre>
--   &gt;&gt;&gt; maybe "" show (Just 5)
--   "5"
--   
--   &gt;&gt;&gt; maybe "" show Nothing
--   ""
--   </pre>
maybe :: b -> (a -> b) -> Maybe a -> b

-- | An infix synonym for <a>fmap</a>.
--   
--   The name of this operator is an allusion to <a>$</a>. Note the
--   similarities between their types:
--   
--   <pre>
--    ($)  ::              (a -&gt; b) -&gt;   a -&gt;   b
--   (&lt;$&gt;) :: Functor f =&gt; (a -&gt; b) -&gt; f a -&gt; f b
--   </pre>
--   
--   Whereas <a>$</a> is function application, <a>&lt;$&gt;</a> is function
--   application lifted over a <a>Functor</a>.
--   
--   <h4><b>Examples</b></h4>
--   
--   Convert from a <tt><a>Maybe</a> <a>Int</a></tt> to a <tt><a>Maybe</a>
--   <a>String</a></tt> using <a>show</a>:
--   
--   <pre>
--   &gt;&gt;&gt; show &lt;$&gt; Nothing
--   Nothing
--   
--   &gt;&gt;&gt; show &lt;$&gt; Just 3
--   Just "3"
--   </pre>
--   
--   Convert from an <tt><a>Either</a> <a>Int</a> <a>Int</a></tt> to an
--   <tt><a>Either</a> <a>Int</a></tt> <a>String</a> using <a>show</a>:
--   
--   <pre>
--   &gt;&gt;&gt; show &lt;$&gt; Left 17
--   Left 17
--   
--   &gt;&gt;&gt; show &lt;$&gt; Right 17
--   Right "17"
--   </pre>
--   
--   Double each element of a list:
--   
--   <pre>
--   &gt;&gt;&gt; (*2) &lt;$&gt; [1,2,3]
--   [2,4,6]
--   </pre>
--   
--   Apply <a>even</a> to the second element of a pair:
--   
--   <pre>
--   &gt;&gt;&gt; even &lt;$&gt; (2,2)
--   (2,True)
--   </pre>
(<$>) :: Functor f => (a -> b) -> f a -> f b
infixl 4 <$>

-- | <a>uncurry</a> converts a curried function to a function on pairs.
--   
--   <h4><b>Examples</b></h4>
--   
--   <pre>
--   &gt;&gt;&gt; uncurry (+) (1,2)
--   3
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; uncurry ($) (show, 1)
--   "1"
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; map (uncurry max) [(1,2), (3,4), (6,8)]
--   [2,4,8]
--   </pre>
uncurry :: (a -> b -> c) -> (a, b) -> c

-- | <a>curry</a> converts an uncurried function to a curried function.
--   
--   <h4><b>Examples</b></h4>
--   
--   <pre>
--   &gt;&gt;&gt; curry fst 1 2
--   1
--   </pre>
curry :: ((a, b) -> c) -> a -> b -> c

-- | the same as <tt><a>flip</a> (<a>-</a>)</tt>.
--   
--   Because <tt>-</tt> is treated specially in the Haskell grammar,
--   <tt>(-</tt> <i>e</i><tt>)</tt> is not a section, but an application of
--   prefix negation. However, <tt>(<a>subtract</a></tt>
--   <i>exp</i><tt>)</tt> is equivalent to the disallowed section.
subtract :: Num a => a -> a -> a

-- | <a>asTypeOf</a> is a type-restricted version of <a>const</a>. It is
--   usually used as an infix operator, and its typing forces its first
--   argument (which is usually overloaded) to have the same type as the
--   second.
asTypeOf :: a -> a -> a

-- | <tt><a>until</a> p f</tt> yields the result of applying <tt>f</tt>
--   until <tt>p</tt> holds.
until :: (a -> Bool) -> (a -> a) -> a -> a

-- | Strict (call-by-value) application operator. It takes a function and
--   an argument, evaluates the argument to weak head normal form (WHNF),
--   then calls the function with that value.
($!) :: forall (r :: RuntimeRep) a (b :: TYPE r). (a -> b) -> a -> b
infixr 0 $!

-- | <tt><a>flip</a> f</tt> takes its (first) two arguments in the reverse
--   order of <tt>f</tt>.
--   
--   <pre>
--   &gt;&gt;&gt; flip (++) "hello" "world"
--   "worldhello"
--   </pre>
flip :: (a -> b -> c) -> b -> a -> c

-- | Function composition.
(.) :: (b -> c) -> (a -> b) -> a -> c
infixr 9 .

-- | <tt>const x</tt> is a unary function which evaluates to <tt>x</tt> for
--   all inputs.
--   
--   <pre>
--   &gt;&gt;&gt; const 42 "hello"
--   42
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; map (const 42) [0..3]
--   [42,42,42,42]
--   </pre>
const :: a -> b -> a

-- | Identity function.
--   
--   <pre>
--   id x = x
--   </pre>
id :: a -> a

-- | Same as <a>&gt;&gt;=</a>, but with the arguments interchanged.
(=<<) :: Monad m => (a -> m b) -> m a -> m b
infixr 1 =<<

-- | A <a>String</a> is a list of characters. String constants in Haskell
--   are values of type <a>String</a>.
type String = [Char]

-- | A special case of <a>error</a>. It is expected that compilers will
--   recognize this and insert error messages which are more appropriate to
--   the context in which <a>undefined</a> appears.
undefined :: forall (r :: RuntimeRep) (a :: TYPE r). HasCallStack => a

-- | A variant of <a>error</a> that does not produce a stack trace.
errorWithoutStackTrace :: forall (r :: RuntimeRep) (a :: TYPE r). [Char] -> a

-- | Boolean "and"
(&&) :: Bool -> Bool -> Bool
infixr 3 &&

-- | Boolean "or"
(||) :: Bool -> Bool -> Bool
infixr 2 ||

-- | Boolean "not"
not :: Bool -> Bool

-- | Append two lists, i.e.,
--   
--   <pre>
--   [x1, ..., xm] ++ [y1, ..., yn] == [x1, ..., xm, y1, ..., yn]
--   [x1, ..., xm] ++ [y1, ...] == [x1, ..., xm, y1, ...]
--   </pre>
--   
--   If the first list is not finite, the result is the first list.
(++) :: [a] -> [a] -> [a]
infixr 5 ++

-- | <i>O(n)</i>. <a>filter</a>, applied to a predicate and a list, returns
--   the list of those elements that satisfy the predicate; i.e.,
--   
--   <pre>
--   filter p xs = [ x | x &lt;- xs, p x]
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; filter odd [1, 2, 3]
--   [1,3]
--   </pre>
filter :: (a -> Bool) -> [a] -> [a]

-- | <i>O(min(m,n))</i>. <a>zip</a> takes two lists and returns a list of
--   corresponding pairs.
--   
--   <pre>
--   zip [1, 2] ['a', 'b'] = [(1, 'a'), (2, 'b')]
--   </pre>
--   
--   If one input list is short, excess elements of the longer list are
--   discarded:
--   
--   <pre>
--   zip [1] ['a', 'b'] = [(1, 'a')]
--   zip [1, 2] ['a'] = [(1, 'a')]
--   </pre>
--   
--   <a>zip</a> is right-lazy:
--   
--   <pre>
--   zip [] _|_ = []
--   zip _|_ [] = _|_
--   </pre>
--   
--   <a>zip</a> is capable of list fusion, but it is restricted to its
--   first list argument and its resulting list.
zip :: [a] -> [b] -> [(a, b)]

-- | <i>O(n)</i>. <a>map</a> <tt>f xs</tt> is the list obtained by applying
--   <tt>f</tt> to each element of <tt>xs</tt>, i.e.,
--   
--   <pre>
--   map f [x1, x2, ..., xn] == [f x1, f x2, ..., f xn]
--   map f [x1, x2, ...] == [f x1, f x2, ...]
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; map (+1) [1, 2, 3]
--   </pre>
map :: (a -> b) -> [a] -> [b]

-- | Right-associative fold of a structure.
--   
--   In the case of lists, <a>foldr</a>, when applied to a binary operator,
--   a starting value (typically the right-identity of the operator), and a
--   list, reduces the list using the binary operator, from right to left:
--   
--   <pre>
--   foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...)
--   </pre>
--   
--   Note that, since the head of the resulting expression is produced by
--   an application of the operator to the first element of the list,
--   <a>foldr</a> can produce a terminating expression from an infinite
--   list.
--   
--   For a general <a>Foldable</a> structure this should be semantically
--   identical to,
--   
--   <pre>
--   foldr f z = <a>foldr</a> f z . <a>toList</a>
--   </pre>
foldr :: Foldable t => (a -> b -> b) -> b -> t a -> b

-- | Left-associative fold of a structure.
--   
--   In the case of lists, <a>foldl</a>, when applied to a binary operator,
--   a starting value (typically the left-identity of the operator), and a
--   list, reduces the list using the binary operator, from left to right:
--   
--   <pre>
--   foldl f z [x1, x2, ..., xn] == (...((z `f` x1) `f` x2) `f`...) `f` xn
--   </pre>
--   
--   Note that to produce the outermost application of the operator the
--   entire input list must be traversed. This means that <a>foldl'</a>
--   will diverge if given an infinite list.
--   
--   Also note that if you want an efficient left-fold, you probably want
--   to use <a>foldl'</a> instead of <a>foldl</a>. The reason for this is
--   that latter does not force the "inner" results (e.g. <tt>z `f` x1</tt>
--   in the above example) before applying them to the operator (e.g. to
--   <tt>(`f` x2)</tt>). This results in a thunk chain <tt>O(n)</tt>
--   elements long, which then must be evaluated from the outside-in.
--   
--   For a general <a>Foldable</a> structure this should be semantically
--   identical to,
--   
--   <pre>
--   foldl f z = <a>foldl</a> f z . <a>toList</a>
--   </pre>
foldl :: Foldable t => (b -> a -> b) -> b -> t a -> b

-- | Left-associative fold of a structure but with strict application of
--   the operator.
--   
--   This ensures that each step of the fold is forced to weak head normal
--   form before being applied, avoiding the collection of thunks that
--   would otherwise occur. This is often what you want to strictly reduce
--   a finite list to a single, monolithic result (e.g. <a>length</a>).
--   
--   For a general <a>Foldable</a> structure this should be semantically
--   identical to,
--   
--   <pre>
--   foldl' f z = <a>foldl'</a> f z . <a>toList</a>
--   </pre>
foldl' :: Foldable t => (b -> a -> b) -> b -> t a -> b

-- | A variant of <a>foldl</a> that has no base case, and thus may only be
--   applied to non-empty structures.
--   
--   <pre>
--   <a>foldl1</a> f = <a>foldl1</a> f . <a>toList</a>
--   </pre>
foldl1 :: Foldable t => (a -> a -> a) -> t a -> a

-- | The <a>product</a> function computes the product of the numbers of a
--   structure.
product :: (Foldable t, Num a) => t a -> a

-- | A variant of <a>foldr</a> that has no base case, and thus may only be
--   applied to non-empty structures.
--   
--   <pre>
--   <a>foldr1</a> f = <a>foldr1</a> f . <a>toList</a>
--   </pre>
foldr1 :: Foldable t => (a -> a -> a) -> t a -> a

-- | The largest element of a non-empty structure.
maximum :: (Foldable t, Ord a) => t a -> a

-- | The least element of a non-empty structure.
minimum :: (Foldable t, Ord a) => t a -> a

-- | Does the element occur in the structure?
elem :: (Foldable t, Eq a) => a -> t a -> Bool
infix 4 `elem`

-- | The <a>isSubsequenceOf</a> function takes two lists and returns
--   <a>True</a> if all the elements of the first list occur, in order, in
--   the second. The elements do not have to occur consecutively.
--   
--   <tt><a>isSubsequenceOf</a> x y</tt> is equivalent to <tt><a>elem</a> x
--   (<a>subsequences</a> y)</tt>.
--   
--   <h4><b>Examples</b></h4>
--   
--   <pre>
--   &gt;&gt;&gt; isSubsequenceOf "GHC" "The Glorious Haskell Compiler"
--   True
--   
--   &gt;&gt;&gt; isSubsequenceOf ['a','d'..'z'] ['a'..'z']
--   True
--   
--   &gt;&gt;&gt; isSubsequenceOf [1..10] [10,9..0]
--   False
--   </pre>
isSubsequenceOf :: Eq a => [a] -> [a] -> Bool

-- | The <a>mapAccumR</a> function behaves like a combination of
--   <a>fmap</a> and <a>foldr</a>; it applies a function to each element of
--   a structure, passing an accumulating parameter from right to left, and
--   returning a final value of this accumulator together with the new
--   structure.
mapAccumR :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c)

-- | The <a>mapAccumL</a> function behaves like a combination of
--   <a>fmap</a> and <a>foldl</a>; it applies a function to each element of
--   a structure, passing an accumulating parameter from left to right, and
--   returning a final value of this accumulator together with the new
--   structure.
mapAccumL :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c)

-- | The <a>find</a> function takes a predicate and a structure and returns
--   the leftmost element of the structure matching the predicate, or
--   <a>Nothing</a> if there is no such element.
find :: Foldable t => (a -> Bool) -> t a -> Maybe a

-- | <a>notElem</a> is the negation of <a>elem</a>.
notElem :: (Foldable t, Eq a) => a -> t a -> Bool
infix 4 `notElem`

-- | The least element of a non-empty structure with respect to the given
--   comparison function.
minimumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a

-- | The largest element of a non-empty structure with respect to the given
--   comparison function.
maximumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a

-- | Determines whether all elements of the structure satisfy the
--   predicate.
all :: Foldable t => (a -> Bool) -> t a -> Bool

-- | Determines whether any element of the structure satisfies the
--   predicate.
any :: Foldable t => (a -> Bool) -> t a -> Bool

-- | <a>or</a> returns the disjunction of a container of Bools. For the
--   result to be <a>False</a>, the container must be finite; <a>True</a>,
--   however, results from a <a>True</a> value finitely far from the left
--   end.
or :: Foldable t => t Bool -> Bool

-- | <a>and</a> returns the conjunction of a container of Bools. For the
--   result to be <a>True</a>, the container must be finite; <a>False</a>,
--   however, results from a <a>False</a> value finitely far from the left
--   end.
and :: Foldable t => t Bool -> Bool

-- | Map a function over all the elements of a container and concatenate
--   the resulting lists.
concatMap :: Foldable t => (a -> [b]) -> t a -> [b]

-- | The concatenation of all the elements of a container of lists.
concat :: Foldable t => t [a] -> [a]

-- | <a>unwords</a> is an inverse operation to <a>words</a>. It joins words
--   with separating spaces.
--   
--   <pre>
--   &gt;&gt;&gt; unwords ["Lorem", "ipsum", "dolor"]
--   "Lorem ipsum dolor"
--   </pre>
unwords :: [String] -> String

-- | <a>words</a> breaks a string up into a list of words, which were
--   delimited by white space.
--   
--   <pre>
--   &gt;&gt;&gt; words "Lorem ipsum\ndolor"
--   ["Lorem","ipsum","dolor"]
--   </pre>
words :: String -> [String]

-- | <a>unlines</a> is an inverse operation to <a>lines</a>. It joins
--   lines, after appending a terminating newline to each.
--   
--   <pre>
--   &gt;&gt;&gt; unlines ["Hello", "World", "!"]
--   "Hello\nWorld\n!\n"
--   </pre>
unlines :: [String] -> String

-- | <a>lines</a> breaks a string up into a list of strings at newline
--   characters. The resulting strings do not contain newlines.
--   
--   Note that after splitting the string at newline characters, the last
--   part of the string is considered a line even if it doesn't end with a
--   newline. For example,
--   
--   <pre>
--   &gt;&gt;&gt; lines ""
--   []
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; lines "\n"
--   [""]
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; lines "one"
--   ["one"]
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; lines "one\n"
--   ["one"]
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; lines "one\n\n"
--   ["one",""]
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; lines "one\ntwo"
--   ["one","two"]
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; lines "one\ntwo\n"
--   ["one","two"]
--   </pre>
--   
--   Thus <tt><a>lines</a> s</tt> contains at least as many elements as
--   newlines in <tt>s</tt>.
lines :: String -> [String]

-- | The <a>unfoldr</a> function is a `dual' to <a>foldr</a>: while
--   <a>foldr</a> reduces a list to a summary value, <a>unfoldr</a> builds
--   a list from a seed value. The function takes the element and returns
--   <a>Nothing</a> if it is done producing the list or returns <a>Just</a>
--   <tt>(a,b)</tt>, in which case, <tt>a</tt> is a prepended to the list
--   and <tt>b</tt> is used as the next element in a recursive call. For
--   example,
--   
--   <pre>
--   iterate f == unfoldr (\x -&gt; Just (x, f x))
--   </pre>
--   
--   In some cases, <a>unfoldr</a> can undo a <a>foldr</a> operation:
--   
--   <pre>
--   unfoldr f' (foldr f z xs) == xs
--   </pre>
--   
--   if the following holds:
--   
--   <pre>
--   f' (f x y) = Just (x,y)
--   f' z       = Nothing
--   </pre>
--   
--   A simple use of unfoldr:
--   
--   <pre>
--   &gt;&gt;&gt; unfoldr (\b -&gt; if b == 0 then Nothing else Just (b, b-1)) 10
--   [10,9,8,7,6,5,4,3,2,1]
--   </pre>
unfoldr :: (b -> Maybe (a, b)) -> b -> [a]

-- | Sort a list by comparing the results of a key function applied to each
--   element. <tt>sortOn f</tt> is equivalent to <tt>sortBy (comparing
--   f)</tt>, but has the performance advantage of only evaluating
--   <tt>f</tt> once for each element in the input list. This is called the
--   decorate-sort-undecorate paradigm, or Schwartzian transform.
--   
--   Elements are arranged from from lowest to highest, keeping duplicates
--   in the order they appeared in the input.
--   
--   <pre>
--   &gt;&gt;&gt; sortOn fst [(2, "world"), (4, "!"), (1, "Hello")]
--   [(1,"Hello"),(2,"world"),(4,"!")]
--   </pre>
sortOn :: Ord b => (a -> b) -> [a] -> [a]

-- | The <a>sortBy</a> function is the non-overloaded version of
--   <a>sort</a>.
--   
--   <pre>
--   &gt;&gt;&gt; sortBy (\(a,_) (b,_) -&gt; compare a b) [(2, "world"), (4, "!"), (1, "Hello")]
--   [(1,"Hello"),(2,"world"),(4,"!")]
--   </pre>
sortBy :: (a -> a -> Ordering) -> [a] -> [a]

-- | The <a>sort</a> function implements a stable sorting algorithm. It is
--   a special case of <a>sortBy</a>, which allows the programmer to supply
--   their own comparison function.
--   
--   Elements are arranged from from lowest to highest, keeping duplicates
--   in the order they appeared in the input.
--   
--   <pre>
--   &gt;&gt;&gt; sort [1,6,4,3,2,5]
--   [1,2,3,4,5,6]
--   </pre>
sort :: Ord a => [a] -> [a]

-- | The <a>permutations</a> function returns the list of all permutations
--   of the argument.
--   
--   <pre>
--   &gt;&gt;&gt; permutations "abc"
--   ["abc","bac","cba","bca","cab","acb"]
--   </pre>
permutations :: [a] -> [[a]]

-- | The <a>subsequences</a> function returns the list of all subsequences
--   of the argument.
--   
--   <pre>
--   &gt;&gt;&gt; subsequences "abc"
--   ["","a","b","ab","c","ac","bc","abc"]
--   </pre>
subsequences :: [a] -> [[a]]

-- | <i>O(n)</i>. The <a>tails</a> function returns all final segments of
--   the argument, longest first. For example,
--   
--   <pre>
--   &gt;&gt;&gt; tails "abc"
--   ["abc","bc","c",""]
--   </pre>
--   
--   Note that <a>tails</a> has the following strictness property:
--   <tt>tails _|_ = _|_ : _|_</tt>
tails :: [a] -> [[a]]

-- | The <a>inits</a> function returns all initial segments of the
--   argument, shortest first. For example,
--   
--   <pre>
--   &gt;&gt;&gt; inits "abc"
--   ["","a","ab","abc"]
--   </pre>
--   
--   Note that <a>inits</a> has the following strictness property:
--   <tt>inits (xs ++ _|_) = inits xs ++ _|_</tt>
--   
--   In particular, <tt>inits _|_ = [] : _|_</tt>
inits :: [a] -> [[a]]

-- | The <a>groupBy</a> function is the non-overloaded version of
--   <a>group</a>.
groupBy :: (a -> a -> Bool) -> [a] -> [[a]]

-- | The <a>group</a> function takes a list and returns a list of lists
--   such that the concatenation of the result is equal to the argument.
--   Moreover, each sublist in the result contains only equal elements. For
--   example,
--   
--   <pre>
--   &gt;&gt;&gt; group "Mississippi"
--   ["M","i","ss","i","ss","i","pp","i"]
--   </pre>
--   
--   It is a special case of <a>groupBy</a>, which allows the programmer to
--   supply their own equality test.
group :: Eq a => [a] -> [[a]]

-- | The <a>deleteFirstsBy</a> function takes a predicate and two lists and
--   returns the first list with the first occurrence of each element of
--   the second list removed.
deleteFirstsBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]

-- | The <a>unzip7</a> function takes a list of seven-tuples and returns
--   seven lists, analogous to <a>unzip</a>.
unzip7 :: [(a, b, c, d, e, f, g)] -> ([a], [b], [c], [d], [e], [f], [g])

-- | The <a>unzip6</a> function takes a list of six-tuples and returns six
--   lists, analogous to <a>unzip</a>.
unzip6 :: [(a, b, c, d, e, f)] -> ([a], [b], [c], [d], [e], [f])

-- | The <a>unzip5</a> function takes a list of five-tuples and returns
--   five lists, analogous to <a>unzip</a>.
unzip5 :: [(a, b, c, d, e)] -> ([a], [b], [c], [d], [e])

-- | The <a>unzip4</a> function takes a list of quadruples and returns four
--   lists, analogous to <a>unzip</a>.
unzip4 :: [(a, b, c, d)] -> ([a], [b], [c], [d])

-- | The <a>zipWith7</a> function takes a function which combines seven
--   elements, as well as seven lists and returns a list of their
--   point-wise combination, analogous to <a>zipWith</a>. It is capable of
--   list fusion, but it is restricted to its first list argument and its
--   resulting list.
zipWith7 :: (a -> b -> c -> d -> e -> f -> g -> h) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [h]

-- | The <a>zipWith6</a> function takes a function which combines six
--   elements, as well as six lists and returns a list of their point-wise
--   combination, analogous to <a>zipWith</a>. It is capable of list
--   fusion, but it is restricted to its first list argument and its
--   resulting list.
zipWith6 :: (a -> b -> c -> d -> e -> f -> g) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g]

-- | The <a>zipWith5</a> function takes a function which combines five
--   elements, as well as five lists and returns a list of their point-wise
--   combination, analogous to <a>zipWith</a>. It is capable of list
--   fusion, but it is restricted to its first list argument and its
--   resulting list.
zipWith5 :: (a -> b -> c -> d -> e -> f) -> [a] -> [b] -> [c] -> [d] -> [e] -> [f]

-- | The <a>zipWith4</a> function takes a function which combines four
--   elements, as well as four lists and returns a list of their point-wise
--   combination, analogous to <a>zipWith</a>. It is capable of list
--   fusion, but it is restricted to its first list argument and its
--   resulting list.
zipWith4 :: (a -> b -> c -> d -> e) -> [a] -> [b] -> [c] -> [d] -> [e]

-- | The <a>zip7</a> function takes seven lists and returns a list of
--   seven-tuples, analogous to <a>zip</a>. It is capable of list fusion,
--   but it is restricted to its first list argument and its resulting
--   list.
zip7 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [g] -> [(a, b, c, d, e, f, g)]

-- | The <a>zip6</a> function takes six lists and returns a list of
--   six-tuples, analogous to <a>zip</a>. It is capable of list fusion, but
--   it is restricted to its first list argument and its resulting list.
zip6 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] -> [(a, b, c, d, e, f)]

-- | The <a>zip5</a> function takes five lists and returns a list of
--   five-tuples, analogous to <a>zip</a>. It is capable of list fusion,
--   but it is restricted to its first list argument and its resulting
--   list.
zip5 :: [a] -> [b] -> [c] -> [d] -> [e] -> [(a, b, c, d, e)]

-- | The <a>zip4</a> function takes four lists and returns a list of
--   quadruples, analogous to <a>zip</a>. It is capable of list fusion, but
--   it is restricted to its first list argument and its resulting list.
zip4 :: [a] -> [b] -> [c] -> [d] -> [(a, b, c, d)]

-- | The <a>genericReplicate</a> function is an overloaded version of
--   <a>replicate</a>, which accepts any <a>Integral</a> value as the
--   number of repetitions to make.
genericReplicate :: Integral i => i -> a -> [a]

-- | The <a>genericIndex</a> function is an overloaded version of
--   <a>!!</a>, which accepts any <a>Integral</a> value as the index.
genericIndex :: Integral i => [a] -> i -> a

-- | The <a>genericSplitAt</a> function is an overloaded version of
--   <a>splitAt</a>, which accepts any <a>Integral</a> value as the
--   position at which to split.
genericSplitAt :: Integral i => i -> [a] -> ([a], [a])

-- | The <a>genericDrop</a> function is an overloaded version of
--   <a>drop</a>, which accepts any <a>Integral</a> value as the number of
--   elements to drop.
genericDrop :: Integral i => i -> [a] -> [a]

-- | The <a>genericTake</a> function is an overloaded version of
--   <a>take</a>, which accepts any <a>Integral</a> value as the number of
--   elements to take.
genericTake :: Integral i => i -> [a] -> [a]

-- | <i>O(n)</i>. The <a>genericLength</a> function is an overloaded
--   version of <a>length</a>. In particular, instead of returning an
--   <a>Int</a>, it returns any type which is an instance of <a>Num</a>. It
--   is, however, less efficient than <a>length</a>.
--   
--   <pre>
--   &gt;&gt;&gt; genericLength [1, 2, 3] :: Int
--   3
--   
--   &gt;&gt;&gt; genericLength [1, 2, 3] :: Float
--   3.0
--   </pre>
genericLength :: Num i => [a] -> i

-- | <i>O(n)</i>. The non-overloaded version of <a>insert</a>.
insertBy :: (a -> a -> Ordering) -> a -> [a] -> [a]

-- | <i>O(n)</i>. The <a>insert</a> function takes an element and a list
--   and inserts the element into the list at the first position where it
--   is less than or equal to the next element. In particular, if the list
--   is sorted before the call, the result will also be sorted. It is a
--   special case of <a>insertBy</a>, which allows the programmer to supply
--   their own comparison function.
--   
--   <pre>
--   &gt;&gt;&gt; insert 4 [1,2,3,5,6,7]
--   [1,2,3,4,5,6,7]
--   </pre>
insert :: Ord a => a -> [a] -> [a]

-- | The <a>partition</a> function takes a predicate a list and returns the
--   pair of lists of elements which do and do not satisfy the predicate,
--   respectively; i.e.,
--   
--   <pre>
--   partition p xs == (filter p xs, filter (not . p) xs)
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; partition (`elem` "aeiou") "Hello World!"
--   ("eoo","Hll Wrld!")
--   </pre>
partition :: (a -> Bool) -> [a] -> ([a], [a])

-- | The <a>transpose</a> function transposes the rows and columns of its
--   argument. For example,
--   
--   <pre>
--   &gt;&gt;&gt; transpose [[1,2,3],[4,5,6]]
--   [[1,4],[2,5],[3,6]]
--   </pre>
--   
--   If some of the rows are shorter than the following rows, their
--   elements are skipped:
--   
--   <pre>
--   &gt;&gt;&gt; transpose [[10,11],[20],[],[30,31,32]]
--   [[10,20,30],[11,31],[32]]
--   </pre>
transpose :: [[a]] -> [[a]]

-- | <a>intercalate</a> <tt>xs xss</tt> is equivalent to <tt>(<a>concat</a>
--   (<a>intersperse</a> xs xss))</tt>. It inserts the list <tt>xs</tt> in
--   between the lists in <tt>xss</tt> and concatenates the result.
--   
--   <pre>
--   &gt;&gt;&gt; intercalate ", " ["Lorem", "ipsum", "dolor"]
--   "Lorem, ipsum, dolor"
--   </pre>
intercalate :: [a] -> [[a]] -> [a]

-- | <i>O(n)</i>. The <a>intersperse</a> function takes an element and a
--   list and `intersperses' that element between the elements of the list.
--   For example,
--   
--   <pre>
--   &gt;&gt;&gt; intersperse ',' "abcde"
--   "a,b,c,d,e"
--   </pre>
intersperse :: a -> [a] -> [a]

-- | The <a>intersectBy</a> function is the non-overloaded version of
--   <a>intersect</a>.
intersectBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]

-- | The <a>intersect</a> function takes the list intersection of two
--   lists. For example,
--   
--   <pre>
--   &gt;&gt;&gt; [1,2,3,4] `intersect` [2,4,6,8]
--   [2,4]
--   </pre>
--   
--   If the first list contains duplicates, so will the result.
--   
--   <pre>
--   &gt;&gt;&gt; [1,2,2,3,4] `intersect` [6,4,4,2]
--   [2,2,4]
--   </pre>
--   
--   It is a special case of <a>intersectBy</a>, which allows the
--   programmer to supply their own equality test. If the element is found
--   in both the first and the second list, the element from the first list
--   will be used.
intersect :: Eq a => [a] -> [a] -> [a]

-- | The <a>unionBy</a> function is the non-overloaded version of
--   <a>union</a>.
unionBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]

-- | The <a>union</a> function returns the list union of the two lists. For
--   example,
--   
--   <pre>
--   &gt;&gt;&gt; "dog" `union` "cow"
--   "dogcw"
--   </pre>
--   
--   Duplicates, and elements of the first list, are removed from the the
--   second list, but if the first list contains duplicates, so will the
--   result. It is a special case of <a>unionBy</a>, which allows the
--   programmer to supply their own equality test.
union :: Eq a => [a] -> [a] -> [a]

-- | The <a>\\</a> function is list difference (non-associative). In the
--   result of <tt>xs</tt> <a>\\</a> <tt>ys</tt>, the first occurrence of
--   each element of <tt>ys</tt> in turn (if any) has been removed from
--   <tt>xs</tt>. Thus
--   
--   <pre>
--   (xs ++ ys) \\ xs == ys.
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; "Hello World!" \\ "ell W"
--   "Hoorld!"
--   </pre>
--   
--   It is a special case of <a>deleteFirstsBy</a>, which allows the
--   programmer to supply their own equality test.
(\\) :: Eq a => [a] -> [a] -> [a]
infix 5 \\

-- | <i>O(n)</i>. The <a>deleteBy</a> function behaves like <a>delete</a>,
--   but takes a user-supplied equality predicate.
--   
--   <pre>
--   &gt;&gt;&gt; deleteBy (&lt;=) 4 [1..10]
--   [1,2,3,5,6,7,8,9,10]
--   </pre>
deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a]

-- | <i>O(n)</i>. <a>delete</a> <tt>x</tt> removes the first occurrence of
--   <tt>x</tt> from its list argument. For example,
--   
--   <pre>
--   &gt;&gt;&gt; delete 'a' "banana"
--   "bnana"
--   </pre>
--   
--   It is a special case of <a>deleteBy</a>, which allows the programmer
--   to supply their own equality test.
delete :: Eq a => a -> [a] -> [a]

-- | The <a>nubBy</a> function behaves just like <a>nub</a>, except it uses
--   a user-supplied equality predicate instead of the overloaded <a>==</a>
--   function.
--   
--   <pre>
--   &gt;&gt;&gt; nubBy (\x y -&gt; mod x 3 == mod y 3) [1,2,4,5,6]
--   [1,2,6]
--   </pre>
nubBy :: (a -> a -> Bool) -> [a] -> [a]

-- | <i>O(n^2)</i>. The <a>nub</a> function removes duplicate elements from
--   a list. In particular, it keeps only the first occurrence of each
--   element. (The name <a>nub</a> means `essence'.) It is a special case
--   of <a>nubBy</a>, which allows the programmer to supply their own
--   equality test.
--   
--   <pre>
--   &gt;&gt;&gt; nub [1,2,3,4,3,2,1,2,4,3,5]
--   [1,2,3,4,5]
--   </pre>
nub :: Eq a => [a] -> [a]

-- | The <a>isInfixOf</a> function takes two lists and returns <a>True</a>
--   iff the first list is contained, wholly and intact, anywhere within
--   the second.
--   
--   <pre>
--   &gt;&gt;&gt; isInfixOf "Haskell" "I really like Haskell."
--   True
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; isInfixOf "Ial" "I really like Haskell."
--   False
--   </pre>
isInfixOf :: Eq a => [a] -> [a] -> Bool

-- | The <a>isSuffixOf</a> function takes two lists and returns <a>True</a>
--   iff the first list is a suffix of the second. The second list must be
--   finite.
--   
--   <pre>
--   &gt;&gt;&gt; "ld!" `isSuffixOf` "Hello World!"
--   True
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; "World" `isSuffixOf` "Hello World!"
--   False
--   </pre>
isSuffixOf :: Eq a => [a] -> [a] -> Bool

-- | <i>O(min(m,n))</i>. The <a>isPrefixOf</a> function takes two lists and
--   returns <a>True</a> iff the first list is a prefix of the second.
--   
--   <pre>
--   &gt;&gt;&gt; "Hello" `isPrefixOf` "Hello World!"
--   True
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; "Hello" `isPrefixOf` "Wello Horld!"
--   False
--   </pre>
isPrefixOf :: Eq a => [a] -> [a] -> Bool

-- | The <a>findIndices</a> function extends <a>findIndex</a>, by returning
--   the indices of all elements satisfying the predicate, in ascending
--   order.
--   
--   <pre>
--   &gt;&gt;&gt; findIndices (`elem` "aeiou") "Hello World!"
--   [1,4,7]
--   </pre>
findIndices :: (a -> Bool) -> [a] -> [Int]

-- | The <a>findIndex</a> function takes a predicate and a list and returns
--   the index of the first element in the list satisfying the predicate,
--   or <a>Nothing</a> if there is no such element.
--   
--   <pre>
--   &gt;&gt;&gt; findIndex isSpace "Hello World!"
--   Just 5
--   </pre>
findIndex :: (a -> Bool) -> [a] -> Maybe Int

-- | The <a>elemIndices</a> function extends <a>elemIndex</a>, by returning
--   the indices of all elements equal to the query element, in ascending
--   order.
--   
--   <pre>
--   &gt;&gt;&gt; elemIndices 'o' "Hello World"
--   [4,7]
--   </pre>
elemIndices :: Eq a => a -> [a] -> [Int]

-- | The <a>elemIndex</a> function returns the index of the first element
--   in the given list which is equal (by <a>==</a>) to the query element,
--   or <a>Nothing</a> if there is no such element.
--   
--   <pre>
--   &gt;&gt;&gt; elemIndex 4 [0..]
--   Just 4
--   </pre>
elemIndex :: Eq a => a -> [a] -> Maybe Int

-- | <i>O(min(m,n))</i>. The <a>stripPrefix</a> function drops the given
--   prefix from a list. It returns <a>Nothing</a> if the list did not
--   start with the prefix given, or <a>Just</a> the list after the prefix,
--   if it does.
--   
--   <pre>
--   &gt;&gt;&gt; stripPrefix "foo" "foobar"
--   Just "bar"
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; stripPrefix "foo" "foo"
--   Just ""
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; stripPrefix "foo" "barfoo"
--   Nothing
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; stripPrefix "foo" "barfoobaz"
--   Nothing
--   </pre>
stripPrefix :: Eq a => [a] -> [a] -> Maybe [a]

-- | The <a>dropWhileEnd</a> function drops the largest suffix of a list in
--   which the given predicate holds for all elements. For example:
--   
--   <pre>
--   &gt;&gt;&gt; dropWhileEnd isSpace "foo\n"
--   "foo"
--   </pre>
--   
--   <pre>
--   &gt;&gt;&gt; dropWhileEnd isSpace "foo bar"
--   "foo bar"
--   </pre>
--   
--   <pre>
--   dropWhileEnd isSpace ("foo\n" ++ undefined) == "foo" ++ undefined
--   </pre>
dropWhileEnd :: (a -> Bool) -> [a] -> [a]

-- | The <a>unzip3</a> function takes a list of triples and returns three
--   lists, analogous to <a>unzip</a>.
unzip3 :: [(a, b, c)] -> ([a], [b], [c])

-- | <a>unzip</a> transforms a list of pairs into a list of first
--   components and a list of second components.
unzip :: [(a, b)] -> ([a], [b])

-- | The <a>zipWith3</a> function takes a function which combines three
--   elements, as well as three lists and returns a list of their
--   point-wise combination, analogous to <a>zipWith</a>. It is capable of
--   list fusion, but it is restricted to its first list argument and its
--   resulting list.
zipWith3 :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]

-- | <i>O(min(m,n))</i>. <a>zipWith</a> generalises <a>zip</a> by zipping
--   with the function given as the first argument, instead of a tupling
--   function. For example, <tt><a>zipWith</a> (+)</tt> is applied to two
--   lists to produce the list of corresponding sums:
--   
--   <pre>
--   &gt;&gt;&gt; zipWith (+) [1, 2, 3] [4, 5, 6]
--   [5,7,9]
--   </pre>
--   
--   <a>zipWith</a> is right-lazy:
--   
--   <pre>
--   zipWith f [] _|_ = []
--   </pre>
--   
--   <a>zipWith</a> is capable of list fusion, but it is restricted to its
--   first list argument and its resulting list.
zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]

-- | <a>zip3</a> takes three lists and returns a list of triples, analogous
--   to <a>zip</a>. It is capable of list fusion, but it is restricted to
--   its first list argument and its resulting list.
zip3 :: [a] -> [b] -> [c] -> [(a, b, c)]

-- | List index (subscript) operator, starting from 0. It is an instance of
--   the more general <a>genericIndex</a>, which takes an index of any
--   integral type.
(!!) :: [a] -> Int -> a
infixl 9 !!

-- | <i>O(n)</i>. <a>lookup</a> <tt>key assocs</tt> looks up a key in an
--   association list.
--   
--   <pre>
--   &gt;&gt;&gt; lookup 2 [(1, "first"), (2, "second"), (3, "third")]
--   Just "second"
--   </pre>
lookup :: Eq a => a -> [(a, b)] -> Maybe b

-- | <a>reverse</a> <tt>xs</tt> returns the elements of <tt>xs</tt> in
--   reverse order. <tt>xs</tt> must be finite.
reverse :: [a] -> [a]

-- | <a>break</a>, applied to a predicate <tt>p</tt> and a list
--   <tt>xs</tt>, returns a tuple where first element is longest prefix
--   (possibly empty) of <tt>xs</tt> of elements that <i>do not satisfy</i>
--   <tt>p</tt> and second element is the remainder of the list:
--   
--   <pre>
--   break (&gt; 3) [1,2,3,4,1,2,3,4] == ([1,2,3],[4,1,2,3,4])
--   break (&lt; 9) [1,2,3] == ([],[1,2,3])
--   break (&gt; 9) [1,2,3] == ([1,2,3],[])
--   </pre>
--   
--   <a>break</a> <tt>p</tt> is equivalent to <tt><a>span</a> (<a>not</a> .
--   p)</tt>.
break :: (a -> Bool) -> [a] -> ([a], [a])

-- | <a>span</a>, applied to a predicate <tt>p</tt> and a list <tt>xs</tt>,
--   returns a tuple where first element is longest prefix (possibly empty)
--   of <tt>xs</tt> of elements that satisfy <tt>p</tt> and second element
--   is the remainder of the list:
--   
--   <pre>
--   span (&lt; 3) [1,2,3,4,1,2,3,4] == ([1,2],[3,4,1,2,3,4])
--   span (&lt; 9) [1,2,3] == ([1,2,3],[])
--   span (&lt; 0) [1,2,3] == ([],[1,2,3])
--   </pre>
--   
--   <a>span</a> <tt>p xs</tt> is equivalent to <tt>(<a>takeWhile</a> p xs,
--   <a>dropWhile</a> p xs)</tt>
span :: (a -> Bool) -> [a] -> ([a], [a])

-- | <a>splitAt</a> <tt>n xs</tt> returns a tuple where first element is
--   <tt>xs</tt> prefix of length <tt>n</tt> and second element is the
--   remainder of the list:
--   
--   <pre>
--   splitAt 6 "Hello World!" == ("Hello ","World!")
--   splitAt 3 [1,2,3,4,5] == ([1,2,3],[4,5])
--   splitAt 1 [1,2,3] == ([1],[2,3])
--   splitAt 3 [1,2,3] == ([1,2,3],[])
--   splitAt 4 [1,2,3] == ([1,2,3],[])
--   splitAt 0 [1,2,3] == ([],[1,2,3])
--   splitAt (-1) [1,2,3] == ([],[1,2,3])
--   </pre>
--   
--   It is equivalent to <tt>(<a>take</a> n xs, <a>drop</a> n xs)</tt> when
--   <tt>n</tt> is not <tt>_|_</tt> (<tt>splitAt _|_ xs = _|_</tt>).
--   <a>splitAt</a> is an instance of the more general
--   <a>genericSplitAt</a>, in which <tt>n</tt> may be of any integral
--   type.
splitAt :: Int -> [a] -> ([a], [a])

-- | <a>drop</a> <tt>n xs</tt> returns the suffix of <tt>xs</tt> after the
--   first <tt>n</tt> elements, or <tt>[]</tt> if <tt>n &gt; <a>length</a>
--   xs</tt>:
--   
--   <pre>
--   drop 6 "Hello World!" == "World!"
--   drop 3 [1,2,3,4,5] == [4,5]
--   drop 3 [1,2] == []
--   drop 3 [] == []
--   drop (-1) [1,2] == [1,2]
--   drop 0 [1,2] == [1,2]
--   </pre>
--   
--   It is an instance of the more general <a>genericDrop</a>, in which
--   <tt>n</tt> may be of any integral type.
drop :: Int -> [a] -> [a]

-- | <a>take</a> <tt>n</tt>, applied to a list <tt>xs</tt>, returns the
--   prefix of <tt>xs</tt> of length <tt>n</tt>, or <tt>xs</tt> itself if
--   <tt>n &gt; <a>length</a> xs</tt>:
--   
--   <pre>
--   take 5 "Hello World!" == "Hello"
--   take 3 [1,2,3,4,5] == [1,2,3]
--   take 3 [1,2] == [1,2]
--   take 3 [] == []
--   take (-1) [1,2] == []
--   take 0 [1,2] == []
--   </pre>
--   
--   It is an instance of the more general <a>genericTake</a>, in which
--   <tt>n</tt> may be of any integral type.
take :: Int -> [a] -> [a]

-- | <a>dropWhile</a> <tt>p xs</tt> returns the suffix remaining after
--   <a>takeWhile</a> <tt>p xs</tt>:
--   
--   <pre>
--   dropWhile (&lt; 3) [1,2,3,4,5,1,2,3] == [3,4,5,1,2,3]
--   dropWhile (&lt; 9) [1,2,3] == []
--   dropWhile (&lt; 0) [1,2,3] == [1,2,3]
--   </pre>
dropWhile :: (a -> Bool) -> [a] -> [a]

-- | <a>takeWhile</a>, applied to a predicate <tt>p</tt> and a list
--   <tt>xs</tt>, returns the longest prefix (possibly empty) of
--   <tt>xs</tt> of elements that satisfy <tt>p</tt>:
--   
--   <pre>
--   takeWhile (&lt; 3) [1,2,3,4,1,2,3,4] == [1,2]
--   takeWhile (&lt; 9) [1,2,3] == [1,2,3]
--   takeWhile (&lt; 0) [1,2,3] == []
--   </pre>
takeWhile :: (a -> Bool) -> [a] -> [a]

-- | <a>cycle</a> ties a finite list into a circular one, or equivalently,
--   the infinite repetition of the original list. It is the identity on
--   infinite lists.
cycle :: [a] -> [a]

-- | <a>replicate</a> <tt>n x</tt> is a list of length <tt>n</tt> with
--   <tt>x</tt> the value of every element. It is an instance of the more
--   general <a>genericReplicate</a>, in which <tt>n</tt> may be of any
--   integral type.
replicate :: Int -> a -> [a]

-- | <a>repeat</a> <tt>x</tt> is an infinite list, with <tt>x</tt> the
--   value of every element.
repeat :: a -> [a]

-- | <a>iterate'</a> is the strict version of <a>iterate</a>.
--   
--   It ensures that the result of each application of force to weak head
--   normal form before proceeding.
iterate' :: (a -> a) -> a -> [a]

-- | <a>iterate</a> <tt>f x</tt> returns an infinite list of repeated
--   applications of <tt>f</tt> to <tt>x</tt>:
--   
--   <pre>
--   iterate f x == [x, f x, f (f x), ...]
--   </pre>
--   
--   Note that <a>iterate</a> is lazy, potentially leading to thunk
--   build-up if the consumer doesn't force each iterate. See
--   <a>iterate'</a> for a strict variant of this function.
iterate :: (a -> a) -> a -> [a]

-- | <i>O(n)</i>. <a>scanr1</a> is a variant of <a>scanr</a> that has no
--   starting value argument.
scanr1 :: (a -> a -> a) -> [a] -> [a]

-- | <i>O(n)</i>. <a>scanr</a> is the right-to-left dual of <a>scanl</a>.
--   Note that
--   
--   <pre>
--   head (scanr f z xs) == foldr f z xs.
--   </pre>
scanr :: (a -> b -> b) -> b -> [a] -> [b]

-- | <i>O(n)</i>. A strictly accumulating version of <a>scanl</a>
scanl' :: (b -> a -> b) -> b -> [a] -> [b]

-- | <i>O(n)</i>. <a>scanl1</a> is a variant of <a>scanl</a> that has no
--   starting value argument:
--   
--   <pre>
--   scanl1 f [x1, x2, ...] == [x1, x1 `f` x2, ...]
--   </pre>
scanl1 :: (a -> a -> a) -> [a] -> [a]

-- | <i>O(n)</i>. <a>scanl</a> is similar to <a>foldl</a>, but returns a
--   list of successive reduced values from the left:
--   
--   <pre>
--   scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]
--   </pre>
--   
--   Note that
--   
--   <pre>
--   last (scanl f z xs) == foldl f z xs.
--   </pre>
scanl :: (b -> a -> b) -> b -> [a] -> [b]

-- | A strict version of <a>foldl1</a>
foldl1' :: (a -> a -> a) -> [a] -> a

-- | <i>O(n)</i>. Return all the elements of a list except the last one.
--   The list must be non-empty.
init :: [a] -> [a]

-- | <i>O(n)</i>. Extract the last element of a list, which must be finite
--   and non-empty.
last :: [a] -> a

-- | <i>O(1)</i>. Extract the elements after the head of a list, which must
--   be non-empty.
tail :: [a] -> [a]

-- | <i>O(1)</i>. Decompose a list into its head and tail. If the list is
--   empty, returns <a>Nothing</a>. If the list is non-empty, returns
--   <tt><a>Just</a> (x, xs)</tt>, where <tt>x</tt> is the head of the list
--   and <tt>xs</tt> its tail.
uncons :: [a] -> Maybe (a, [a])

-- | <i>O(1)</i>. Extract the first element of a list, which must be
--   non-empty.
head :: [a] -> a

-- | The class of semigroups (types with an associative binary operation).
--   
--   Instances should satisfy the following:
--   
--   <ul>
--   <li><i>Associativity</i> <tt>x <a>&lt;&gt;</a> (y <a>&lt;&gt;</a> z) =
--   (x <a>&lt;&gt;</a> y) <a>&lt;&gt;</a> z</tt></li>
--   </ul>
class Semigroup a

-- | An associative operation.
(<>) :: Semigroup a => a -> a -> a
infixr 6 <>

-- | If the first argument evaluates to <a>True</a>, then the result is the
--   second argument. Otherwise an <a>AssertionFailed</a> exception is
--   raised, containing a <a>String</a> with the source file and line
--   number of the call to <a>assert</a>.
--   
--   Assertions can normally be turned on or off with a compiler flag (for
--   GHC, assertions are normally on unless optimisation is turned on with
--   <tt>-O</tt> or the <tt>-fignore-asserts</tt> option is given). When
--   assertions are turned off, the first argument to <a>assert</a> is
--   ignored, and the second argument is returned as the result.
assert :: Bool -> a -> a

-- | Like <a>all</a>, but if the predicate fails, blame all the list
--   elements and especially those for which it fails. To be used as in
--   
--   <pre>
--   assert (allB (&lt;= height) [yf, y1, y2])
--   </pre>
allB :: Show a => (a -> Bool) -> [a] -> Bool

-- | Syntactic sugar for the pair operation, to be used for <a>blame</a> as
--   in
--   
--   <pre>
--   assert (age &lt; 120 `blame` "age too high" `swith` age) $ savings / (120 - age)
--   </pre>
--   
--   Fixing the first component of the pair to <tt>String</tt> prevents
--   warnings about defaulting, even when <tt>OverloadedStrings</tt>
--   extension is enabled.
swith :: String -> v -> (String, v)
infix 2 `swith`

-- | A helper function for <a>error</a>. To be used as in
--   
--   <pre>
--   case xs of
--     0 : _ -&gt; error $ "insignificant zero" `showFailure` xs
--   </pre>
--   
--   Fixing the first argument to <tt>String</tt> instead of anything
--   Showable prevents warnings about defaulting, even when
--   <tt>OverloadedStrings</tt> extension is enabled.
showFailure :: Show v => String -> v -> String
infix 2 `showFailure`

-- | If the condition fails, display the value blamed for the failure. Used
--   as in
--   
--   <pre>
--   assert (age &lt; 120 `blame` age) $ savings / (120 - age)
--   </pre>
blame :: Show a => Bool -> a -> Bool
infix 1 `blame`

-- | A space efficient, packed, unboxed Unicode text type.
data Text
(<+>) :: Text -> Text -> Text

-- | Show and pack the result.
tshow :: Show a => a -> Text

-- | Integer division, rounding up.
divUp :: Integral a => a -> a -> a
infixl 7 `divUp`
sum :: Num a => [a] -> a
(<$$>) :: (Functor f, Functor g) => (a -> b) -> f (g a) -> f (g b)
infixl 4 <$$>
partitionM :: Applicative m => (a -> m Bool) -> [a] -> m ([a], [a])

-- | A version specialized to lists to avoid errors such as taking length
--   of <tt>Maybe [a]</tt> instead of <tt>[a]</tt>. Such errors are hard to
--   detect, because the type of elements of the list is not constrained.
length :: [a] -> Int

-- | A version specialized to lists to avoid errors such as taking null of
--   <tt>Maybe [a]</tt> instead of <tt>[a]</tt>. Such errors are hard to
--   detect, because the type of elements of the list is not constrained.
null :: [a] -> Bool

-- | Split the input between the two argument arrows and combine their
--   output. Note that this is in general not a functor.
--   
--   The default definition may be overridden with a more efficient version
--   if desired.
(***) :: Arrow a => a b c -> a b' c' -> a (b, b') (c, c')
infixr 3 ***

-- | Fanout: send the input to both argument arrows and combine their
--   output.
--   
--   The default definition may be overridden with a more efficient version
--   if desired.
(&&&) :: Arrow a => a b c -> a b c' -> a b (c, c')
infixr 3 &&&

-- | Send the first component of the input through the argument arrow, and
--   copy the rest unchanged to the output.
first :: Arrow a => a b c -> a (b, d) (c, d)

-- | A mirror image of <a>first</a>.
--   
--   The default definition may be overridden with a more efficient version
--   if desired.
second :: Arrow a => a b c -> a (d, b) (d, c)
instance (GHC.Enum.Enum k, Data.Binary.Class.Binary k, Data.Binary.Class.Binary e) => Data.Binary.Class.Binary (Data.EnumMap.Base.EnumMap k e)
instance (GHC.Enum.Enum k, Data.Binary.Class.Binary k) => Data.Binary.Class.Binary (Data.EnumSet.EnumSet k)
instance Data.Binary.Class.Binary Data.Time.Clock.Internal.NominalDiffTime.NominalDiffTime
instance (Data.Hashable.Class.Hashable k, GHC.Classes.Eq k, Data.Binary.Class.Binary k, Data.Binary.Class.Binary v) => Data.Binary.Class.Binary (Data.HashMap.Base.HashMap k v)
instance Data.Key.Zip (Data.EnumMap.Base.EnumMap k)
instance GHC.Enum.Enum k => Data.Key.ZipWithKey (Data.EnumMap.Base.EnumMap k)
instance GHC.Enum.Enum k => Data.Key.Keyed (Data.EnumMap.Base.EnumMap k)
instance GHC.Enum.Enum k => Data.Key.FoldableWithKey (Data.EnumMap.Base.EnumMap k)
instance GHC.Enum.Enum k => Data.Key.TraversableWithKey (Data.EnumMap.Base.EnumMap k)
instance GHC.Enum.Enum k => Data.Key.Indexable (Data.EnumMap.Base.EnumMap k)
instance GHC.Enum.Enum k => Data.Key.Lookup (Data.EnumMap.Base.EnumMap k)
instance GHC.Enum.Enum k => Data.Key.Adjustable (Data.EnumMap.Base.EnumMap k)
instance (GHC.Enum.Enum k, Data.Hashable.Class.Hashable k, Data.Hashable.Class.Hashable e) => Data.Hashable.Class.Hashable (Data.EnumMap.Base.EnumMap k e)
instance (GHC.Enum.Enum k, Data.Hashable.Class.Hashable k) => Data.Hashable.Class.Hashable (Data.EnumSet.EnumSet k)
instance Control.DeepSeq.NFData NLP.Miniutter.English.Part
instance Control.DeepSeq.NFData NLP.Miniutter.English.Person
instance Control.DeepSeq.NFData NLP.Miniutter.English.Polarity


-- | A list of entities with relative frequencies of appearance.
module Game.LambdaHack.Core.Frequency

-- | The frequency distribution type. Not normalized (operations may or may
--   not group the same elements and sum their frequencies). However,
--   elements with zero frequency are removed upon construction.
--   
--   The <tt>Eq</tt> instance compares raw representations, not relative,
--   normalized frequencies, so operations don't need to preserve the
--   expected equalities.
data Frequency a

-- | Uniform discrete frequency distribution.
uniformFreq :: Text -> [a] -> Frequency a

-- | Takes a name and a list of frequencies and items into the frequency
--   distribution.
toFreq :: Text -> [(Int, a)] -> Frequency a

-- | Scale frequency distribution, multiplying it by a positive integer
--   constant.
scaleFreq :: Show a => Int -> Frequency a -> Frequency a

-- | Change the description of the frequency.
renameFreq :: Text -> Frequency a -> Frequency a

-- | Set frequency of an element.
setFreq :: Eq a => Frequency a -> a -> Int -> Frequency a

-- | Test if the frequency distribution is empty.
nullFreq :: Frequency a -> Bool

-- | give acces to raw frequency values
runFrequency :: Frequency a -> [(Int, a)]

-- | short description for debug, etc.
nameFrequency :: Frequency a -> Text
minFreq :: Ord a => Frequency a -> Maybe a
maxFreq :: Ord a => Frequency a -> Maybe a
mostFreq :: Frequency a -> Maybe a
instance GHC.Generics.Generic (Game.LambdaHack.Core.Frequency.Frequency a)
instance Data.Traversable.Traversable Game.LambdaHack.Core.Frequency.Frequency
instance Data.Foldable.Foldable Game.LambdaHack.Core.Frequency.Frequency
instance GHC.Classes.Ord a => GHC.Classes.Ord (Game.LambdaHack.Core.Frequency.Frequency a)
instance GHC.Classes.Eq a => GHC.Classes.Eq (Game.LambdaHack.Core.Frequency.Frequency a)
instance GHC.Show.Show a => GHC.Show.Show (Game.LambdaHack.Core.Frequency.Frequency a)
instance GHC.Base.Monad Game.LambdaHack.Core.Frequency.Frequency
instance GHC.Base.Functor Game.LambdaHack.Core.Frequency.Frequency
instance GHC.Base.Applicative Game.LambdaHack.Core.Frequency.Frequency
instance GHC.Base.MonadPlus Game.LambdaHack.Core.Frequency.Frequency
instance GHC.Base.Alternative Game.LambdaHack.Core.Frequency.Frequency


-- | Representation of dice scaled with current level depth.
module Game.LambdaHack.Core.Dice

-- | Multiple dice rolls, some scaled with current level depth, in which
--   case the sum of all rolls is scaled in proportion to current depth
--   divided by maximal dungeon depth.
--   
--   The simple dice should have positive number of rolls and number of
--   sides.
--   
--   The <tt>Num</tt> instance doesn't have <tt>abs</tt> nor
--   <tt>signum</tt> defined, because the functions for computing infimum,
--   supremum and mean dice results would be too costly.
data Dice

-- | Absolute depth in the dungeon. When used for the maximum depth of the
--   whole dungeon, this can be different than dungeon size, e.g., when the
--   dungeon is branched, and it can even be different than the length of
--   the longest branch, if levels at some depths are missing.
newtype AbsDepth
AbsDepth :: Int -> AbsDepth

-- | Cast dice scaled with current level depth. When scaling, we round up,
--   so that the value of <tt>1 <a>dL</a> 1</tt> is 1 even at the lowest
--   level.
--   
--   The implementation calls RNG as many times as there are dice rolls,
--   which is costly, so content should prefer to case fewer dice and then
--   multiply them by a constant. If rounded results are not desired (often
--   they are, to limit the number of distinct item varieties in
--   inventory), another dice may be added to the result.
--   
--   A different possible implementation, with dice represented as
--   <tt>Frequency</tt>, makes only one RNG call per dice, but due to lists
--   lengths proportional to the maximal value of the dice, it's is
--   intractable for 1000d1000 and problematic already for 100d100.
castDice :: forall m. Monad m => ((Int, Int) -> m Int) -> AbsDepth -> AbsDepth -> Dice -> m Int

-- | A die, rolled the given number of times. E.g., <tt>1 <a>d</a> 2</tt>
--   rolls 2-sided die one time.
d :: Int -> Int -> Dice

-- | A die rolled the given number of times, with the result scaled with
--   dungeon level depth.
dL :: Int -> Int -> Dice

-- | A die, starting from zero, ending at one less than the bound, rolled
--   the given number of times. E.g., <tt>1 <a>z</a> 1</tt> always rolls
--   zero.
z :: Int -> Int -> Dice

-- | A die, starting from zero, ending at one less than the bound, rolled
--   the given number of times, with the result scaled with dungeon level
--   depth.
zL :: Int -> Int -> Dice
intToDice :: Int -> Dice
minDice :: Dice -> Dice -> Dice
maxDice :: Dice -> Dice -> Dice

-- | Minimal and maximal possible value of the dice.
--   
--   <tt>divUp</tt> in the implementation corresponds to <tt>ceiling</tt>,
--   applied to results of <tt>meanDice</tt> elsewhere in the code, and
--   prevents treating 1d1-power effects (on shallow levels) as null
--   effects.
infsupDice :: Dice -> (Int, Int)

-- | Maximal value of dice. The scaled part taken assuming median level.
supDice :: Dice -> Int

-- | Minimal value of dice. The scaled part taken assuming median level.
infDice :: Dice -> Int

-- | Mean value of dice. The scaled part taken assuming median level.
meanDice :: Dice -> Double
reduceDice :: Dice -> Maybe Int

-- | Dice for rolling a pair of integer parameters pertaining to,
--   respectively, the X and Y cartesian 2D coordinates.
data DiceXY
DiceXY :: Dice -> Dice -> DiceXY

-- | Maximal value of DiceXY.
supDiceXY :: DiceXY -> (Int, Int)

-- | Minimal value of DiceXY.
infDiceXY :: DiceXY -> (Int, Int)

-- | Mean value of DiceXY.
meanDiceXY :: DiceXY -> (Double, Double)
instance GHC.Generics.Generic Game.LambdaHack.Core.Dice.DiceXY
instance GHC.Show.Show Game.LambdaHack.Core.Dice.DiceXY
instance Data.Binary.Class.Binary Game.LambdaHack.Core.Dice.AbsDepth
instance Data.Hashable.Class.Hashable Game.LambdaHack.Core.Dice.AbsDepth
instance GHC.Classes.Ord Game.LambdaHack.Core.Dice.AbsDepth
instance GHC.Classes.Eq Game.LambdaHack.Core.Dice.AbsDepth
instance GHC.Show.Show Game.LambdaHack.Core.Dice.AbsDepth
instance GHC.Generics.Generic Game.LambdaHack.Core.Dice.Dice
instance GHC.Classes.Eq Game.LambdaHack.Core.Dice.Dice
instance Data.Binary.Class.Binary Game.LambdaHack.Core.Dice.DiceXY
instance GHC.Show.Show Game.LambdaHack.Core.Dice.Dice
instance Data.Binary.Class.Binary Game.LambdaHack.Core.Dice.Dice
instance GHC.Num.Num Game.LambdaHack.Core.Dice.Dice


-- | Keeping track of forked threads.
module Game.LambdaHack.Common.Thread
forkChild :: MVar [Async ()] -> IO () -> IO ()
waitForChildren :: MVar [Async ()] -> IO ()


-- | Ring buffers.
module Game.LambdaHack.Common.RingBuffer

-- | Ring buffers of a size determined at initialization.
data RingBuffer a
empty :: Int -> a -> RingBuffer a
cons :: a -> RingBuffer a -> RingBuffer a
uncons :: RingBuffer a -> Maybe (a, RingBuffer a)
toList :: RingBuffer a -> [a]
length :: RingBuffer a -> Int
instance GHC.Generics.Generic (Game.LambdaHack.Common.RingBuffer.RingBuffer a)
instance GHC.Show.Show a => GHC.Show.Show (Game.LambdaHack.Common.RingBuffer.RingBuffer a)
instance Data.Binary.Class.Binary a => Data.Binary.Class.Binary (Game.LambdaHack.Common.RingBuffer.RingBuffer a)


-- | Hacks that haven't found their home yet.
module Game.LambdaHack.Common.Misc

-- | Re-exported English phrase creation functions, applied to our custom
--   irregular word sets.
makePhrase :: [Part] -> Text

-- | Re-exported English phrase creation functions, applied to our custom
--   irregular word sets.
makeSentence :: [Part] -> Text

-- | Apply the <tt>WWandW</tt> constructor, first representing repetitions
--   as <tt>CardinalWs</tt>. The parts are not sorted, only grouped, to
--   keep the order. The internal structure of speech parts is compared,
--   not their string rendering, so some coincidental clashes are avoided
--   (and code is simpler).
squashedWWandW :: [Part] -> (Part, Person)

-- | Personal data directory for the game. Depends on the OS and the game,
--   e.g., for LambdaHack under Linux it's <tt>~/.LambdaHack/</tt>.
appDataDir :: IO FilePath
xM :: Int -> Int64
xD :: Double -> Double
minusM :: Int64
minusM1 :: Int64
minusM2 :: Int64
oneM :: Int64
tenthM :: Int64
show64With2 :: Int64 -> Text
workaroundOnMainThreadMVar :: MVar (IO ())


-- | Game time and speed.
module Game.LambdaHack.Common.Time

-- | Game time in ticks. The time dimension. One tick is 1 microsecond (one
--   millionth of a second), one turn is 0.5 s.
data Time
timeTicks :: Time -> Int64

-- | Start of the game time, or zero lenght time interval.
timeZero :: Time

-- | An infinitesimal time period.
timeEpsilon :: Time

-- | At least once per clip all moves are resolved and a frame or a frame
--   delay is generated. Currently one clip is 0.05 s, but it may change,
--   and the code should not depend on this fixed value.
timeClip :: Time

-- | One turn is 0.5 s. The code may depend on that. Actors at normal speed
--   (2 m/s) take one turn to move one tile (1 m by 1 m).
timeTurn :: Time

-- | This many ticks fits in a single second. Do not export,
timeSecond :: Time

-- | This many clips fit in one turn. Determines the resolution of actor
--   move sampling and display updates.
clipsInTurn :: Int

-- | Absolute time addition, e.g., for summing the total game session time
--   from the times of individual games.
absoluteTimeAdd :: Time -> Time -> Time
absoluteTimeSubtract :: Time -> Time -> Time

-- | Absolute time negation. To be used for reversing time flow, e.g., for
--   comparing absolute times in the reverse order.
absoluteTimeNegate :: Time -> Time

-- | How many time intervals of the latter kind fits in an interval of the
--   former kind.
timeFit :: Time -> Time -> Int

-- | How many time intervals of the latter kind cover an interval of the
--   former kind (rounded up).
timeFitUp :: Time -> Time -> Int

-- | One-dimentional vectors. Introduced to tell apart the 2 uses of Time:
--   as an absolute game time and as an increment.
newtype Delta a
Delta :: a -> Delta a

-- | Shifting an absolute time by a time vector.
timeShift :: Time -> Delta Time -> Time

-- | Time time vector between the second and the first absolute times. The
--   arguments are in the same order as in the underlying scalar
--   subtraction.
timeDeltaToFrom :: Time -> Time -> Delta Time

-- | Addition of time deltas.
timeDeltaAdd :: Delta Time -> Delta Time -> Delta Time

-- | Subtraction of time deltas. The arguments are in the same order as in
--   the underlying scalar subtraction.
timeDeltaSubtract :: Delta Time -> Delta Time -> Delta Time

-- | Reverse a time vector.
timeDeltaReverse :: Delta Time -> Delta Time

-- | Scale the time vector by an <tt>Int</tt> scalar value.
timeDeltaScale :: Delta Time -> Int -> Delta Time

-- | Take the given percent of the time vector.
timeDeltaPercent :: Delta Time -> Int -> Delta Time

-- | Divide a time vector.
timeDeltaDiv :: Delta Time -> Int -> Delta Time

-- | Represent the main 10 thresholds of a time range by digits, given the
--   total length of the time range.
timeDeltaToDigit :: Delta Time -> Delta Time -> Char
timeDeltaInSecondsText :: Delta Time -> Text

-- | Speed in meters per 1 million seconds (m/Ms). Actors at normal speed
--   (2 m/s) take one time turn (0.5 s) to make one step (move one tile,
--   which is 1 m by 1 m).
data Speed

-- | Constructor for content definitions.
toSpeed :: Int -> Speed

-- | Readable representation of speed in the format used in content
--   definitions.
fromSpeed :: Speed -> Int
minSpeed :: Int

-- | Pretty-print speed given in the format used in content definitions.
displaySpeed :: Int -> String

-- | No movement possible at that speed.
speedZero :: Speed

-- | Fast walk speed (2 m/s) that suffices to move one tile in one turn.
speedWalk :: Speed

-- | Limp speed (1 m/s) that suffices to move one tile in two turns. This
--   is the minimal speed for projectiles to fly just one space and drop.
speedLimp :: Speed

-- | Sword thrust speed (10 m/s). Base weapon damages, both melee and
--   ranged, are given assuming this speed and ranged damage is modified
--   accordingly when projectile speeds differ. Differences in melee weapon
--   swing speeds are captured in damage bonuses instead, since many other
--   factors influence total damage.
--   
--   Billiard ball is 25 m<i>s, sword swing at the tip is 35 m</i>s,
--   medieval bow is 70 m<i>s, AK47 is 700 m</i>s.
speedThrust :: Speed

-- | Modify damage when projectiles is at a non-standard speed. Energy and
--   so damage is proportional to the square of speed, hence the formula.
modifyDamageBySpeed :: Int64 -> Speed -> Int64

-- | Scale speed by an <tt>Int</tt> scalar value.
speedScale :: Rational -> Speed -> Speed

-- | Speed addition.
speedAdd :: Speed -> Speed -> Speed

-- | The number of time ticks it takes to walk 1 meter at the given speed.
ticksPerMeter :: Speed -> Delta Time

-- | Calculate projectile speed from item weight in grams and velocity
--   percent modifier. See
--   <a>https://github.com/LambdaHack/LambdaHack/wiki/Item-statistics</a>.
speedFromWeight :: Int -> Int -> Speed

-- | Calculate maximum range taking into account the linger percentage.
rangeFromSpeedAndLinger :: Speed -> Int -> Int

-- | The smallest unit of time. Should not be exported and used elsewhere,
--   because the proportion of turn to tick is an implementation detail.
--   The significance of this detail is only that it determines resolution
--   of the time dimension.
_timeTick :: Time

-- | This many turns fit in a single second.
turnsInSecond :: Int64

-- | Number of seconds in a mega-second.
sInMs :: Int64

-- | The minimal speed is half a meter (half a step across a tile) per
--   second (two standard turns, which the time span during which
--   projectile moves, unless it has modified linger value). This is four
--   times slower than standard human movement speed.
--   
--   It needen't be lower, because <tt>rangeFromSpeed</tt> gives 0 steps
--   with such speed, so the actor's trajectory is empty, so it drops down
--   at once. Twice that speed already moves a normal projectile one step
--   before it stops. It shouldn't be lower or a slow actor would incur
--   such a time debt for performing a single action that he'd be paralyzed
--   for many turns, e.g., leaving his dead body on the screen for very
--   long.
minimalSpeed :: Int64

-- | Calculate maximum range in meters of a projectile from its speed. See
--   <a>https://github.com/LambdaHack/LambdaHack/wiki/Item-statistics</a>.
--   With this formula, each projectile flies for at most 1 second, that is
--   2 standard turns, and then drops to the ground.
rangeFromSpeed :: Speed -> Int
instance Data.Binary.Class.Binary Game.LambdaHack.Common.Time.Speed
instance GHC.Classes.Ord Game.LambdaHack.Common.Time.Speed
instance GHC.Classes.Eq Game.LambdaHack.Common.Time.Speed
instance GHC.Base.Functor Game.LambdaHack.Common.Time.Delta
instance Data.Binary.Class.Binary a => Data.Binary.Class.Binary (Game.LambdaHack.Common.Time.Delta a)
instance GHC.Classes.Ord a => GHC.Classes.Ord (Game.LambdaHack.Common.Time.Delta a)
instance GHC.Classes.Eq a => GHC.Classes.Eq (Game.LambdaHack.Common.Time.Delta a)
instance GHC.Show.Show a => GHC.Show.Show (Game.LambdaHack.Common.Time.Delta a)
instance Data.Binary.Class.Binary Game.LambdaHack.Common.Time.Time
instance GHC.Classes.Ord Game.LambdaHack.Common.Time.Time
instance GHC.Classes.Eq Game.LambdaHack.Common.Time.Time
instance GHC.Show.Show Game.LambdaHack.Common.Time.Time
instance GHC.Show.Show Game.LambdaHack.Common.Time.Speed


-- | Saving/loading to files, with serialization and compression.
module Game.LambdaHack.Common.File

-- | Serialize, compress and save data with an EOF marker. The <tt>OK</tt>
--   is used as an EOF marker to ensure any apparent problems with
--   corrupted files are reported to the user ASAP.
encodeEOF :: Binary b => FilePath -> Version -> b -> IO ()

-- | Read, decompress and deserialize data with an EOF marker. The
--   <tt>OK</tt> EOF marker ensures any easily detectable file corruption
--   is discovered and reported before any value is decoded from the second
--   component and before the file handle is closed. OTOH, binary encoding
--   corruption is not discovered until a version check elswere ensures
--   that binary formats are compatible.
strictDecodeEOF :: Binary b => FilePath -> IO (Version, b)

-- | Try to create a directory, if it doesn't exist. We catch exceptions in
--   case many clients try to do the same thing at the same time.
tryCreateDir :: FilePath -> IO ()

-- | The operation <a>doesFileExist</a> returns <a>True</a> if the argument
--   file exists and is not a directory, and <a>False</a> otherwise.
doesFileExist :: FilePath -> IO Bool

-- | Try to write a file, given content, if the file not already there. We
--   catch exceptions in case many clients try to do the same thing at the
--   same time.
tryWriteFile :: FilePath -> String -> IO ()

-- | The <a>readFile</a> function reads a file and returns the contents of
--   the file as a string. The file is read lazily, on demand, as with
--   <a>getContents</a>.
readFile :: FilePath -> IO String

-- | <tt><a>renameFile</a> old new</tt> changes the name of an existing
--   file system object from <i>old</i> to <i>new</i>. If the <i>new</i>
--   object already exists, it is atomically replaced by the <i>old</i>
--   object. Neither path may refer to an existing directory. A conformant
--   implementation need not support renaming files in all situations (e.g.
--   renaming across different physical devices), but the constraints must
--   be documented.
--   
--   The operation may fail with:
--   
--   <ul>
--   <li><tt>HardwareFault</tt> A physical I/O error has occurred.
--   <tt>[EIO]</tt></li>
--   <li><tt>InvalidArgument</tt> Either operand is not a valid file name.
--   <tt>[ENAMETOOLONG, ELOOP]</tt></li>
--   <li><a>isDoesNotExistError</a> The original file does not exist, or
--   there is no path to the target. <tt>[ENOENT, ENOTDIR]</tt></li>
--   <li><a>isPermissionError</a> The process has insufficient privileges
--   to perform the operation. <tt>[EROFS, EACCES, EPERM]</tt></li>
--   <li><a>isFullError</a> Insufficient resources are available to perform
--   the operation. <tt>[EDQUOT, ENOSPC, ENOMEM, EMLINK]</tt></li>
--   <li><tt>UnsatisfiedConstraints</tt> Implementation-dependent
--   constraints are not satisfied. <tt>[EBUSY]</tt></li>
--   <li><tt>UnsupportedOperation</tt> The implementation does not support
--   renaming in this situation. <tt>[EXDEV]</tt></li>
--   <li><tt>InappropriateType</tt> Either path refers to an existing
--   directory. <tt>[ENOTDIR, EISDIR, EINVAL, EEXIST, ENOTEMPTY]</tt></li>
--   </ul>
renameFile :: FilePath -> FilePath -> IO ()


-- | Options that affect the behaviour of the client.
module Game.LambdaHack.Client.ClientOptions

-- | Options that affect the behaviour of the client (but not game rules).
data ClientOptions
ClientOptions :: Maybe Text -> Maybe Text -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Bool -> Maybe Bool -> Bool -> Bool -> Maybe Text -> Maybe FilePath -> String -> Bool -> Bool -> Bool -> Bool -> Maybe Int -> Maybe Int -> Bool -> Bool -> Bool -> Bool -> ClientOptions

-- | Font family to use for the GTK main game window.
[sgtkFontFamily] :: ClientOptions -> Maybe Text

-- | Font file to use for the SDL2 main game window.
[sdlFontFile] :: ClientOptions -> Maybe Text

-- | Pixels to add to map cells on top of scalable font max glyph height.
--   To get symmetric padding, add an even number.
[sdlScalableSizeAdd] :: ClientOptions -> Maybe Int

-- | Pixels to add to map cells on top of fixed font max glyph height. To
--   get symmetric padding, add an even number.
[sdlBitmapSizeAdd] :: ClientOptions -> Maybe Int

-- | Font size to use for the main game window.
[sscalableFontSize] :: ClientOptions -> Maybe Int

-- | How much to log (e.g., from SDL). 1 is all, 5 is errors, the default.
[slogPriority] :: ClientOptions -> Maybe Int

-- | Maximal frames per second. This is better low and fixed, to avoid
--   jerkiness and delays that tell the player there are many intelligent
--   enemies on the level. That's better than scaling AI sofistication down
--   based on the FPS setting and machine speed.
[smaxFps] :: ClientOptions -> Maybe Int

-- | Never auto-answer all prompts, even if under AI control.
[sdisableAutoYes] :: ClientOptions -> Bool

-- | Don't show any animations.
[snoAnim] :: ClientOptions -> Maybe Bool

-- | Start a new game, overwriting the save file.
[snewGameCli] :: ClientOptions -> Bool

-- | Don't create directories and files and show time stats.
[sbenchmark] :: ClientOptions -> Bool
[stitle] :: ClientOptions -> Maybe Text
[sfontDir] :: ClientOptions -> Maybe FilePath

-- | Prefix of the save game file name.
[ssavePrefixCli] :: ClientOptions -> String

-- | Whether to use the stdout/stdin frontend.
[sfrontendTeletype] :: ClientOptions -> Bool

-- | Whether to use null (no input/output) frontend.
[sfrontendNull] :: ClientOptions -> Bool

-- | Whether to use lazy (output not even calculated) frontend.
[sfrontendLazy] :: ClientOptions -> Bool

-- | Show clients' internal debug messages.
[sdbgMsgCli] :: ClientOptions -> Bool
[sstopAfterSeconds] :: ClientOptions -> Maybe Int
[sstopAfterFrames] :: ClientOptions -> Maybe Int
[sprintEachScreen] :: ClientOptions -> Bool
[sexposePlaces] :: ClientOptions -> Bool
[sexposeItems] :: ClientOptions -> Bool
[sexposeActors] :: ClientOptions -> Bool

-- | Default value of client options.
defClientOptions :: ClientOptions
instance GHC.Generics.Generic Game.LambdaHack.Client.ClientOptions.ClientOptions
instance GHC.Classes.Eq Game.LambdaHack.Client.ClientOptions.ClientOptions
instance GHC.Show.Show Game.LambdaHack.Client.ClientOptions.ClientOptions
instance Data.Binary.Class.Binary Game.LambdaHack.Client.ClientOptions.ClientOptions


-- | AI strategies to direct actors not controlled directly by human
--   players. No operation in this module involves the <tt>State</tt> type
--   or any of our client/server monads types.
module Game.LambdaHack.Client.AI.Strategy

-- | A strategy is a choice of (non-empty) frequency tables of possible
--   actions.
--   
--   Currently, the way we use it, the list could have at most one element
--   (we filter out void frequencies early and only ever access the first).
--   except for the argument of <tt>mapStrategyM</tt>, which may even be
--   process to the end of the list, if no earlier strategies can be
--   transformed into non-null ones.
data Strategy a
nullStrategy :: Strategy a -> Bool

-- | Strategy where only the actions from the given single frequency table
--   can be picked.
liftFrequency :: Frequency a -> Strategy a

-- | Strategy with the actions from both argument strategies, with original
--   frequencies.
(.|) :: Strategy a -> Strategy a -> Strategy a
infixr 2 .|

-- | Strategy with no actions at all.
reject :: Strategy a

-- | Conditionally accepted strategy.
(.=>) :: Bool -> Strategy a -> Strategy a
infix 3 .=>

-- | Strategy with all actions not satisfying the predicate removed. The
--   remaining actions keep their original relative frequency values.
only :: (a -> Bool) -> Strategy a -> Strategy a

-- | When better choices are towards the start of the list, this is the
--   best frequency of the strategy.
bestVariant :: Strategy a -> Frequency a

-- | Overwrite the description of all frequencies within the strategy.
renameStrategy :: Text -> Strategy a -> Strategy a

-- | Like <a>return</a>, but pick a name of the single frequency.
returN :: Text -> a -> Strategy a
mapStrategyM :: Monad m => (a -> m (Maybe b)) -> Strategy a -> m (Strategy b)
instance Data.Traversable.Traversable Game.LambdaHack.Client.AI.Strategy.Strategy
instance Data.Foldable.Foldable Game.LambdaHack.Client.AI.Strategy.Strategy
instance GHC.Show.Show a => GHC.Show.Show (Game.LambdaHack.Client.AI.Strategy.Strategy a)
instance GHC.Base.Monad Game.LambdaHack.Client.AI.Strategy.Strategy
instance GHC.Base.Functor Game.LambdaHack.Client.AI.Strategy.Strategy
instance GHC.Base.Applicative Game.LambdaHack.Client.AI.Strategy.Strategy
instance GHC.Base.MonadPlus Game.LambdaHack.Client.AI.Strategy.Strategy
instance GHC.Base.Alternative Game.LambdaHack.Client.AI.Strategy.Strategy


-- | Representation of probabilities and random computations.
module Game.LambdaHack.Core.Random

-- | The monad of computations with random generator state.
type Rnd a = State StdGen a

-- | Get a random object within a range with a uniform distribution.
randomR :: Random a => (a, a) -> Rnd a

-- | Get a random object of a given type with a uniform distribution.
random :: Random a => Rnd a

-- | Get any element of a list with equal probability.
oneOf :: [a] -> Rnd a

-- | Generates a random permutation. Naive, but good enough for small
--   inputs.
shuffle :: Eq a => [a] -> Rnd [a]

-- | Gen an element according to a frequency distribution.
frequency :: Show a => Frequency a -> Rnd a

-- | Fractional chance.
type Chance = Rational

-- | Give <tt>True</tt>, with probability determined by the fraction.
chance :: Chance -> Rnd Bool

-- | Cast dice scaled with current level depth. Note that at the first
--   level, the scaled dice are always ignored.
castDice :: AbsDepth -> AbsDepth -> Dice -> Rnd Int

-- | Cast dice scaled with current level depth and return <tt>True</tt> if
--   the results is greater than 50.
oddsDice :: AbsDepth -> AbsDepth -> Dice -> Rnd Bool

-- | Cast dice, scaled with current level depth, for coordinates.
castDiceXY :: AbsDepth -> AbsDepth -> DiceXY -> Rnd (Int, Int)
foldrM :: Foldable t => (a -> b -> Rnd b) -> b -> t a -> Rnd b
foldlM' :: Foldable t => (b -> a -> Rnd b) -> b -> t a -> Rnd b

-- | Randomly choose an item according to the distribution.
rollFreq :: Show a => Frequency a -> StdGen -> (a, StdGen)


-- | Abilities of items, actors and factions.
module Game.LambdaHack.Definition.Ability

-- | Actor and faction skills. They are a subset of actor aspects. See
--   <a>skillDesc</a> for documentation.
data Skill
SkMove :: Skill
SkMelee :: Skill
SkDisplace :: Skill
SkAlter :: Skill
SkWait :: Skill
SkMoveItem :: Skill
SkProject :: Skill
SkApply :: Skill
SkSwimming :: Skill
SkFlying :: Skill
SkHurtMelee :: Skill
SkArmorMelee :: Skill
SkArmorRanged :: Skill
SkMaxHP :: Skill
SkMaxCalm :: Skill
SkSpeed :: Skill

-- | FOV radius, where 1 means a single tile FOV
SkSight :: Skill
SkSmell :: Skill
SkShine :: Skill
SkNocto :: Skill
SkHearing :: Skill
SkAggression :: Skill
SkOdor :: Skill

-- | Strength of particular skills. This is cumulative from actor organs
--   and equipment and so pertain to an actor as well as to items.
--   
--   This representation is sparse, so better than a record when there are
--   more item kinds (with few skills) than actors (with many skills),
--   especially if the number of skills grows as the engine is developed.
--   It's also easier to code and maintain.
--   
--   The tree is by construction sparse, so the derived equality is
--   semantical.
data Skills

-- | Item flag aspects.
data Flag

-- | as a projectile, break at target tile, even if no hit; also, at each
--   periodic activation a copy is destroyed and all other copies require
--   full cooldown (timeout)
Fragile :: Flag

-- | drop at target tile, even if no hit
Lobable :: Flag

-- | don't break even when hitting or applying
Durable :: Flag

-- | AI and UI flag: consider equipping (may or may not have
--   <a>EqpSlot</a>, e.g., if the benefit is periodic)
Equipable :: Flag

-- | AI and UI flag: consider meleeing with
Meleeable :: Flag

-- | AI and UI flag: don't risk identifying by use; also, can't throw or
--   apply if not calm enough; also may be used for UI flavour or AI hints
Precious :: Flag

-- | the item is an explosion blast particle
Blast :: Flag

-- | item is a condition (buff or de-buff) of an actor and is displayed as
--   such; this differs from belonging to the <tt>condition</tt> group,
--   which doesn't guarantee display as a condition, but governs removal by
--   items that drop <tt>condition</tt>
Condition :: Flag

-- | at most one copy can ever be generated
Unique :: Flag

-- | at most one of any copies without cooldown (timeout) activates each
--   turn; the cooldown required after activation is specified in
--   <tt>Timeout</tt> (or is zero); the initial cooldown can also be
--   specified as <tt>TimerDice</tt> in <tt>CreateItem</tt> effect;
--   uniquely, this activation never destroys a copy, unless item is
--   fragile; all this happens only for items in equipment or organs
Periodic :: Flag

-- | override: the effects on this item are considered minor and so not
--   causing identification on use, and so this item will identify on
--   pick-up
MinorEffects :: Flag
newtype Flags
Flags :: EnumSet Flag -> Flags
[flags] :: Flags -> EnumSet Flag

-- | Tactic of non-leader actors. Apart of determining AI operation, each
--   tactic implies a skill modifier, that is added to the non-leader
--   skills defined in <tt>fskillsOther</tt> field of <tt>Player</tt>.
data Tactic

-- | if enemy nearby, attack, if no items, etc., explore unknown
TExplore :: Tactic

-- | always follow leader's target or his position if no target
TFollow :: Tactic

-- | follow but don't do any item management nor use
TFollowNoItems :: Tactic

-- | only melee and do ranged combat
TMeleeAndRanged :: Tactic

-- | only melee (or wait)
TMeleeAdjacent :: Tactic

-- | always only wait, even if enemy in melee range
TBlock :: Tactic

-- | if enemy nearby, attack, if no items, etc., roam randomly
TRoam :: Tactic

-- | find an open and uncrowded area, patrol it according to sight radius
--   and fallback temporarily to <tt>TRoam</tt> when enemy is seen by the
--   faction and is within the actor's sight radius
TPatrol :: Tactic

-- | AI and UI hints about the role of the item.
data EqpSlot
EqpSlotMove :: EqpSlot
EqpSlotMelee :: EqpSlot
EqpSlotDisplace :: EqpSlot
EqpSlotAlter :: EqpSlot
EqpSlotWait :: EqpSlot
EqpSlotMoveItem :: EqpSlot
EqpSlotProject :: EqpSlot
EqpSlotApply :: EqpSlot
EqpSlotSwimming :: EqpSlot
EqpSlotFlying :: EqpSlot
EqpSlotHurtMelee :: EqpSlot
EqpSlotArmorMelee :: EqpSlot
EqpSlotArmorRanged :: EqpSlot
EqpSlotMaxHP :: EqpSlot
EqpSlotSpeed :: EqpSlot
EqpSlotSight :: EqpSlot
EqpSlotShine :: EqpSlot
EqpSlotMiscBonus :: EqpSlot
EqpSlotWeaponFast :: EqpSlot
EqpSlotWeaponBig :: EqpSlot
getSk :: Skill -> Skills -> Int
addSk :: Skill -> Int -> Skills -> Skills
checkFl :: Flag -> Flags -> Bool
skillsToList :: Skills -> [(Skill, Int)]
zeroSkills :: Skills
addSkills :: Skills -> Skills -> Skills
sumScaledSkills :: [(Skills, Int)] -> Skills
nameTactic :: Tactic -> Text
describeTactic :: Tactic -> Text
tacticSkills :: Tactic -> Skills
blockOnly :: Skills
meleeAdjacent :: Skills
meleeAndRanged :: Skills
ignoreItems :: Skills
compactSkills :: EnumMap Skill Int -> EnumMap Skill Int
scaleSkills :: Int -> EnumMap Skill Int -> EnumMap Skill Int
instance GHC.Generics.Generic Game.LambdaHack.Definition.Ability.EqpSlot
instance GHC.Enum.Bounded Game.LambdaHack.Definition.Ability.EqpSlot
instance GHC.Enum.Enum Game.LambdaHack.Definition.Ability.EqpSlot
instance GHC.Classes.Ord Game.LambdaHack.Definition.Ability.EqpSlot
instance GHC.Classes.Eq Game.LambdaHack.Definition.Ability.EqpSlot
instance GHC.Show.Show Game.LambdaHack.Definition.Ability.EqpSlot
instance GHC.Generics.Generic Game.LambdaHack.Definition.Ability.Tactic
instance GHC.Enum.Bounded Game.LambdaHack.Definition.Ability.Tactic
instance GHC.Enum.Enum Game.LambdaHack.Definition.Ability.Tactic
instance GHC.Classes.Ord Game.LambdaHack.Definition.Ability.Tactic
instance GHC.Classes.Eq Game.LambdaHack.Definition.Ability.Tactic
instance GHC.Show.Show Game.LambdaHack.Definition.Ability.Tactic
instance Data.Binary.Class.Binary Game.LambdaHack.Definition.Ability.Flags
instance Data.Hashable.Class.Hashable Game.LambdaHack.Definition.Ability.Flags
instance GHC.Generics.Generic Game.LambdaHack.Definition.Ability.Flags
instance GHC.Classes.Ord Game.LambdaHack.Definition.Ability.Flags
instance GHC.Classes.Eq Game.LambdaHack.Definition.Ability.Flags
instance GHC.Show.Show Game.LambdaHack.Definition.Ability.Flags
instance GHC.Enum.Bounded Game.LambdaHack.Definition.Ability.Flag
instance GHC.Enum.Enum Game.LambdaHack.Definition.Ability.Flag
instance GHC.Generics.Generic Game.LambdaHack.Definition.Ability.Flag
instance GHC.Classes.Ord Game.LambdaHack.Definition.Ability.Flag
instance GHC.Classes.Eq Game.LambdaHack.Definition.Ability.Flag
instance GHC.Show.Show Game.LambdaHack.Definition.Ability.Flag
instance Data.Binary.Class.Binary Game.LambdaHack.Definition.Ability.Skills
instance Data.Hashable.Class.Hashable Game.LambdaHack.Definition.Ability.Skills
instance GHC.Generics.Generic Game.LambdaHack.Definition.Ability.Skills
instance GHC.Classes.Ord Game.LambdaHack.Definition.Ability.Skills
instance GHC.Classes.Eq Game.LambdaHack.Definition.Ability.Skills
instance GHC.Show.Show Game.LambdaHack.Definition.Ability.Skills
instance GHC.Enum.Bounded Game.LambdaHack.Definition.Ability.Skill
instance GHC.Enum.Enum Game.LambdaHack.Definition.Ability.Skill
instance GHC.Generics.Generic Game.LambdaHack.Definition.Ability.Skill
instance GHC.Classes.Ord Game.LambdaHack.Definition.Ability.Skill
instance GHC.Classes.Eq Game.LambdaHack.Definition.Ability.Skill
instance GHC.Show.Show Game.LambdaHack.Definition.Ability.Skill
instance Data.Binary.Class.Binary Game.LambdaHack.Definition.Ability.EqpSlot
instance Data.Hashable.Class.Hashable Game.LambdaHack.Definition.Ability.EqpSlot
instance Data.Binary.Class.Binary Game.LambdaHack.Definition.Ability.Tactic
instance Data.Hashable.Class.Hashable Game.LambdaHack.Definition.Ability.Tactic
instance Data.Binary.Class.Binary Game.LambdaHack.Definition.Ability.Flag
instance Data.Hashable.Class.Hashable Game.LambdaHack.Definition.Ability.Flag
instance Data.Binary.Class.Binary Game.LambdaHack.Definition.Ability.Skill
instance Data.Hashable.Class.Hashable Game.LambdaHack.Definition.Ability.Skill


-- | Colours and text attributes.
module Game.LambdaHack.Definition.Color

-- | Colours supported by the major frontends.
data Color
Black :: Color
Red :: Color
Green :: Color
Brown :: Color
Blue :: Color
Magenta :: Color
Cyan :: Color
White :: Color
AltWhite :: Color
BrBlack :: Color
BrRed :: Color
BrGreen :: Color
BrYellow :: Color
BrBlue :: Color
BrMagenta :: Color
BrCyan :: Color
BrWhite :: Color

-- | The default colours, to optimize attribute setting.
defFG :: Color

-- | A helper for the terminal frontends that display bright via bold.
isBright :: Color -> Bool

-- | Colour sets.
darkCol :: [Color]

-- | Colour sets.
brightCol :: [Color]

-- | Colour sets.
stdCol :: [Color]

-- | Colour sets.
legalFgCol :: [Color]

-- | Translationg to heavily modified Linux console color RGB values.
--   
--   Warning: SDL frontend sadly duplicates this code.
colorToRGB :: Color -> Text

-- | Additional map cell highlight, e.g., a colorful square around the cell
--   or a colorful background.
--   
--   Note: the highlight underscored by the terminal cursor is the maximal
--   element of this type present of this screen.
data Highlight
HighlightNone :: Highlight
HighlightGreen :: Highlight
HighlightBlue :: Highlight
HighlightGrey :: Highlight
HighlightWhite :: Highlight
HighlightMagenta :: Highlight
HighlightRed :: Highlight
HighlightYellow :: Highlight
HighlightYellowAim :: Highlight
HighlightRedAim :: Highlight
HighlightNoneCursor :: Highlight

-- | Text attributes: foreground color and highlight.
data Attr
Attr :: Color -> Highlight -> Attr

-- | foreground colour
[fg] :: Attr -> Color

-- | highlight
[bg] :: Attr -> Highlight
highlightToColor :: Highlight -> Color

-- | The default attribute, to optimize attribute setting.
defAttr :: Attr

-- | Character to display, with its attribute.
data AttrChar
AttrChar :: Attr -> Char -> AttrChar
[acAttr] :: AttrChar -> Attr
[acChar] :: AttrChar -> Char

-- | Optimized representation of <a>AttrChar</a>.
newtype AttrCharW32
AttrCharW32 :: Word32 -> AttrCharW32
[attrCharW32] :: AttrCharW32 -> Word32
attrCharToW32 :: AttrChar -> AttrCharW32
attrCharFromW32 :: AttrCharW32 -> AttrChar
fgFromW32 :: AttrCharW32 -> Color
bgFromW32 :: AttrCharW32 -> Highlight
charFromW32 :: AttrCharW32 -> Char
attrFromW32 :: AttrCharW32 -> Attr
attrEnumFromW32 :: AttrCharW32 -> Int
spaceAttrW32 :: AttrCharW32
retAttrW32 :: AttrCharW32
attrChar2ToW32 :: Color -> Char -> AttrCharW32
attrChar1ToW32 :: Char -> AttrCharW32
instance Data.Binary.Class.Binary Game.LambdaHack.Definition.Color.AttrCharW32
instance GHC.Enum.Enum Game.LambdaHack.Definition.Color.AttrCharW32
instance GHC.Classes.Ord Game.LambdaHack.Definition.Color.AttrCharW32
instance GHC.Classes.Eq Game.LambdaHack.Definition.Color.AttrCharW32
instance GHC.Show.Show Game.LambdaHack.Definition.Color.AttrCharW32
instance GHC.Classes.Ord Game.LambdaHack.Definition.Color.AttrChar
instance GHC.Classes.Eq Game.LambdaHack.Definition.Color.AttrChar
instance GHC.Show.Show Game.LambdaHack.Definition.Color.AttrChar
instance GHC.Classes.Ord Game.LambdaHack.Definition.Color.Attr
instance GHC.Classes.Eq Game.LambdaHack.Definition.Color.Attr
instance GHC.Show.Show Game.LambdaHack.Definition.Color.Attr
instance GHC.Generics.Generic Game.LambdaHack.Definition.Color.Highlight
instance GHC.Enum.Bounded Game.LambdaHack.Definition.Color.Highlight
instance GHC.Enum.Enum Game.LambdaHack.Definition.Color.Highlight
instance GHC.Classes.Ord Game.LambdaHack.Definition.Color.Highlight
instance GHC.Classes.Eq Game.LambdaHack.Definition.Color.Highlight
instance GHC.Show.Show Game.LambdaHack.Definition.Color.Highlight
instance GHC.Generics.Generic Game.LambdaHack.Definition.Color.Color
instance GHC.Enum.Enum Game.LambdaHack.Definition.Color.Color
instance GHC.Classes.Ord Game.LambdaHack.Definition.Color.Color
instance GHC.Classes.Eq Game.LambdaHack.Definition.Color.Color
instance GHC.Read.Read Game.LambdaHack.Definition.Color.Color
instance GHC.Show.Show Game.LambdaHack.Definition.Color.Color
instance Data.Binary.Class.Binary Game.LambdaHack.Definition.Color.Color
instance Data.Hashable.Class.Hashable Game.LambdaHack.Definition.Color.Color
instance Control.DeepSeq.NFData Game.LambdaHack.Definition.Color.Color


-- | Basic types for content definitions.
module Game.LambdaHack.Definition.Defs

-- | X spacial dimension for points and vectors.
type X = Int

-- | Y xpacial dimension for points and vectors.
type Y = Int
data GroupName a
toGroupName :: Text -> GroupName a
fromGroupName :: GroupName a -> Text

-- | For each group that the kind belongs to, denoted by a
--   <tt>GroupName</tt> in the first component of a pair, the second
--   component of a pair shows how common the kind is within the group.
type Freqs a = [(GroupName a, Int)]

-- | Rarity on given depths.
type Rarity = [(Double, Int)]
linearInterpolation :: Int -> Int -> Rarity -> Int

-- | Content identifiers for the content type <tt>c</tt>.
data ContentId c
toContentId :: Word16 -> ContentId c
fromContentId :: ContentId c -> Word16
contentIdIndex :: ContentId k -> Int

-- | Actor's item stores.
data CStore
CGround :: CStore
COrgan :: CStore
CEqp :: CStore
CInv :: CStore
CSha :: CStore
ppCStore :: CStore -> (Text, Text)
ppCStoreIn :: CStore -> Text
verbCStore :: CStore -> Text

-- | Item slot and lore categories.
data SLore
SItem :: SLore
SOrgan :: SLore
STrunk :: SLore
SCondition :: SLore
SBlast :: SLore
SEmbed :: SLore
data ItemDialogMode

-- | a leader's store
MStore :: CStore -> ItemDialogMode

-- | leader's organs
MOrgans :: ItemDialogMode

-- | all party's items
MOwned :: ItemDialogMode

-- | not items, but determined by leader's items
MSkills :: ItemDialogMode

-- | not party's items, but all known generalized items
MLore :: SLore -> ItemDialogMode

-- | not items at all, but definitely a lore
MPlaces :: ItemDialogMode
ppSLore :: SLore -> Text
headingSLore :: SLore -> Text
ppItemDialogMode :: ItemDialogMode -> (Text, Text)
ppItemDialogModeIn :: ItemDialogMode -> Text
ppItemDialogModeFrom :: ItemDialogMode -> Text
instance GHC.Generics.Generic Game.LambdaHack.Definition.Defs.ItemDialogMode
instance GHC.Classes.Ord Game.LambdaHack.Definition.Defs.ItemDialogMode
instance GHC.Classes.Eq Game.LambdaHack.Definition.Defs.ItemDialogMode
instance GHC.Read.Read Game.LambdaHack.Definition.Defs.ItemDialogMode
instance GHC.Show.Show Game.LambdaHack.Definition.Defs.ItemDialogMode
instance GHC.Generics.Generic Game.LambdaHack.Definition.Defs.SLore
instance GHC.Enum.Bounded Game.LambdaHack.Definition.Defs.SLore
instance GHC.Enum.Enum Game.LambdaHack.Definition.Defs.SLore
instance GHC.Classes.Ord Game.LambdaHack.Definition.Defs.SLore
instance GHC.Classes.Eq Game.LambdaHack.Definition.Defs.SLore
instance GHC.Read.Read Game.LambdaHack.Definition.Defs.SLore
instance GHC.Show.Show Game.LambdaHack.Definition.Defs.SLore
instance GHC.Generics.Generic Game.LambdaHack.Definition.Defs.CStore
instance GHC.Enum.Bounded Game.LambdaHack.Definition.Defs.CStore
instance GHC.Enum.Enum Game.LambdaHack.Definition.Defs.CStore
instance GHC.Classes.Ord Game.LambdaHack.Definition.Defs.CStore
instance GHC.Classes.Eq Game.LambdaHack.Definition.Defs.CStore
instance GHC.Read.Read Game.LambdaHack.Definition.Defs.CStore
instance GHC.Show.Show Game.LambdaHack.Definition.Defs.CStore
instance GHC.Generics.Generic (Game.LambdaHack.Definition.Defs.ContentId c)
instance Data.Binary.Class.Binary (Game.LambdaHack.Definition.Defs.ContentId c)
instance GHC.Enum.Enum (Game.LambdaHack.Definition.Defs.ContentId c)
instance GHC.Classes.Ord (Game.LambdaHack.Definition.Defs.ContentId c)
instance GHC.Classes.Eq (Game.LambdaHack.Definition.Defs.ContentId c)
instance GHC.Show.Show (Game.LambdaHack.Definition.Defs.ContentId c)
instance GHC.Generics.Generic (Game.LambdaHack.Definition.Defs.GroupName a)
instance Data.Binary.Class.Binary (Game.LambdaHack.Definition.Defs.GroupName a)
instance Data.Hashable.Class.Hashable (Game.LambdaHack.Definition.Defs.GroupName a)
instance GHC.Classes.Ord (Game.LambdaHack.Definition.Defs.GroupName a)
instance GHC.Classes.Eq (Game.LambdaHack.Definition.Defs.GroupName a)
instance GHC.Show.Show (Game.LambdaHack.Definition.Defs.GroupName a)
instance Control.DeepSeq.NFData Game.LambdaHack.Definition.Defs.ItemDialogMode
instance Data.Binary.Class.Binary Game.LambdaHack.Definition.Defs.ItemDialogMode
instance Data.Binary.Class.Binary Game.LambdaHack.Definition.Defs.SLore
instance Control.DeepSeq.NFData Game.LambdaHack.Definition.Defs.SLore
instance Data.Binary.Class.Binary Game.LambdaHack.Definition.Defs.CStore
instance Control.DeepSeq.NFData Game.LambdaHack.Definition.Defs.CStore
instance Data.Hashable.Class.Hashable (Game.LambdaHack.Definition.Defs.ContentId c)
instance Data.String.IsString (Game.LambdaHack.Definition.Defs.GroupName a)
instance Control.DeepSeq.NFData (Game.LambdaHack.Definition.Defs.GroupName a)


-- | A game requires the engine provided by the library, perhaps
--   customized, and game content, defined completely afresh for the
--   particular game. The possible kinds of content are fixed in the
--   library and all defined within the library source code directory. On
--   the other hand, game content, is defined in the directory hosting the
--   particular game definition.
--   
--   Content of a given kind is just a list of content items. After the
--   list is verified and the data preprocessed, it's held in the
--   <tt>ContentData</tt> datatype.
module Game.LambdaHack.Definition.ContentData

-- | Verified and preprocessed content data of a particular kind.
data ContentData c
validateRarity :: Rarity -> [Text]
validFreqs :: Freqs a -> Bool
emptyContentData :: ContentData a
makeContentData :: Show c => String -> (c -> Text) -> (c -> Freqs c) -> (c -> [Text]) -> ([c] -> ContentData c -> [Text]) -> [c] -> ContentData c

-- | Content element at given id.
okind :: ContentData a -> ContentId a -> a
omemberGroup :: ContentData a -> GroupName a -> Bool
oisSingletonGroup :: ContentData a -> GroupName a -> Bool

-- | The id of the unique member of a singleton content group.
ouniqGroup :: Show a => ContentData a -> GroupName a -> ContentId a

-- | Pick a random id belonging to a group and satisfying a predicate.
opick :: Show a => ContentData a -> GroupName a -> (a -> Bool) -> Rnd (Maybe (ContentId a))

-- | Fold strictly over all content <tt>a</tt>.
ofoldlWithKey' :: ContentData a -> (b -> ContentId a -> a -> b) -> b -> b

-- | Fold over the given group only.
ofoldlGroup' :: ContentData a -> GroupName a -> (b -> Int -> ContentId a -> a -> b) -> b -> b
omapVector :: ContentData a -> (a -> b) -> Vector b
oimapVector :: ContentData a -> (ContentId a -> a -> b) -> Vector b

-- | Size of content <tt>a</tt>.
olength :: ContentData a -> Int


-- | The type of game rules and assorted game data.
module Game.LambdaHack.Content.RuleKind

-- | The type of game rules and assorted game data.
data RuleContent
RuleContent :: Text -> X -> Y -> FilePath -> Version -> FilePath -> String -> Int -> Int -> FilePath -> Int -> [Text] -> Char -> RuleContent

-- | title of the game (not lib)
[rtitle] :: RuleContent -> Text

-- | maximum level width; for now, keep equal to ScreenContent.rwidth
[rXmax] :: RuleContent -> X

-- | maximum level height; for now, keep equal to ScreenContent.rheight - 3
[rYmax] :: RuleContent -> Y

-- | font directory for the game (not lib)
[rfontDir] :: RuleContent -> FilePath

-- | version of the game
[rexeVersion] :: RuleContent -> Version

-- | name of the UI config file
[rcfgUIName] :: RuleContent -> FilePath

-- | the default UI settings config file
[rcfgUIDefault] :: RuleContent -> String

-- | game saved that often (not on browser)
[rwriteSaveClips] :: RuleContent -> Int

-- | server switches leader level that often
[rleadLevelClips] :: RuleContent -> Int

-- | name of the scores file
[rscoresFile] :: RuleContent -> FilePath

-- | what is a close distance between actors
[rnearby] :: RuleContent -> Int

-- | words that can't be dropped from stair name as it goes through levels
[rstairWordCarried] :: RuleContent -> [Text]
[rsymbolProjectile] :: RuleContent -> Char
emptyRuleContent :: RuleContent
makeData :: RuleContent -> RuleContent

-- | Catch invalid rule kind definitions.
validateSingle :: RuleContent -> [Text]


-- | Basic operations on 2D points represented as linear offsets.
module Game.LambdaHack.Common.Point

-- | 2D points in cartesian representation. Coordinates grow to the right
--   and down, so that the (0, 0) point is in the top-left corner of the
--   screen. Coordinates are never negative.
data Point
Point :: X -> Y -> Point
[px] :: Point -> X
[py] :: Point -> Y

-- | Enumeration representation of <tt>Point</tt>.
type PointI = Int

-- | The distance between two points in the chessboard metric.
chessDist :: Point -> Point -> Int

-- | Squared euclidean distance between two points.
euclidDistSq :: Point -> Point -> Int

-- | Checks whether two points are adjacent on the map (horizontally,
--   vertically or diagonally).
adjacent :: Point -> Point -> Bool

-- | Bresenham's line algorithm generalized to arbitrary starting
--   <tt>eps</tt> (<tt>eps</tt> value of 0 gives the standard BLA). Skips
--   the source point and goes through the second point to the edge of the
--   level. Gives <tt>Nothing</tt> if the points are equal. The target is
--   given as <tt>Point</tt> to permit aiming out of the level, e.g., to
--   get uniform distributions of directions for explosions close to the
--   edge of the level.
bla :: X -> Y -> Int -> Point -> Point -> Maybe [Point]

-- | A list of all points on a straight vertical or straight horizontal
--   line between two points. Fails if no such line exists.
fromTo :: Point -> Point -> [Point]
originPoint :: Point

-- | This is a hack to pass the X size of the dungeon, defined in game
--   content, to the <tt>Enum</tt> instances of <tt>Point</tt> and
--   <tt>Vector</tt>. This is already slower and has higher allocation than
--   hardcoding the value, so passing the value explicitly to a
--   generalization of the <tt>Enum</tt> conversions is out of the
--   question. Perhaps this can be done cleanly and efficiently at
--   link-time via Backpack, but it's probably not supported yet by GHCJS
--   (not verified). For now, we need to be careful never to modify this
--   array, except for setting it at program start before it's used for the
--   first time. Which is easy, because <tt>Point</tt> is never mentioned
--   in content definitions. The <tt>PrimArray</tt> has much smaller
--   overhead than <tt>IORef</tt> and reading from it looks cleaner, hence
--   its use.
speedupHackXSize :: PrimArray X

-- | Bresenham's line algorithm generalized to arbitrary starting
--   <tt>eps</tt> (<tt>eps</tt> value of 0 gives the standard BLA).
--   Includes the source point and goes through the target point to
--   infinity.
blaXY :: Int -> Point -> Point -> [Point]

-- | See
--   <a>http://roguebasin.roguelikedevelopment.org/index.php/Digital_lines</a>.
balancedWord :: Int -> Int -> Int -> [Int]
instance GHC.Generics.Generic Game.LambdaHack.Common.Point.Point
instance GHC.Classes.Ord Game.LambdaHack.Common.Point.Point
instance GHC.Classes.Eq Game.LambdaHack.Common.Point.Point
instance GHC.Show.Show Game.LambdaHack.Common.Point.Point
instance Data.Binary.Class.Binary Game.LambdaHack.Common.Point.Point
instance GHC.Enum.Enum Game.LambdaHack.Common.Point.Point


-- | Basic operations on bounded 2D vectors, with an efficient, but not 1-1
--   and not monotonic <tt>Enum</tt> instance.
module Game.LambdaHack.Common.Vector

-- | 2D vectors in cartesian representation. Coordinates grow to the right
--   and down, so that the (1, 1) vector points to the bottom-right corner
--   of the screen.
data Vector
Vector :: X -> Y -> Vector
[vx] :: Vector -> X
[vy] :: Vector -> Y

-- | Enumeration representation of <tt>Vector</tt>.
type VectorI = Int

-- | Tells if a vector has length 1 in the chessboard metric.
isUnit :: Vector -> Bool

-- | Checks whether a unit vector is a diagonal direction, as opposed to
--   cardinal. If the vector is not unit, it checks that the vector is not
--   horizontal nor vertical.
isDiagonal :: Vector -> Bool

-- | Reverse an arbirary vector.
neg :: Vector -> Vector

-- | The lenght of a vector in the chessboard metric, where diagonal moves
--   cost 1.
chessDistVector :: Vector -> Int

-- | Squared euclidean distance between two vectors.
euclidDistSqVector :: Vector -> Vector -> Int

-- | Vectors of all unit moves in the chessboard metric, clockwise,
--   starting north-west.
moves :: [Vector]

-- | Vectors of all cardinal direction unit moves, clockwise, starting
--   north.
movesCardinal :: [Vector]
movesCardinalI :: [VectorI]

-- | Vectors of all diagonal direction unit moves, clockwise, starting
--   north.
movesDiagonal :: [Vector]
movesDiagonalI :: [VectorI]
compassText :: Vector -> Text

-- | All (8 at most) closest neighbours of a point within an area.
vicinityBounded :: X -> Y -> Point -> [Point]
vicinityUnsafe :: Point -> [Point]

-- | All (4 at most) cardinal direction neighbours of a point within an
--   area.
vicinityCardinal :: X -> Y -> Point -> [Point]
vicinityCardinalUnsafe :: Point -> [Point]
squareUnsafeSet :: Point -> EnumSet Point

-- | Translate a point by a vector.
shift :: Point -> Vector -> Point

-- | Translate a point by a vector, but only if the result fits in an area.
shiftBounded :: X -> Y -> Point -> Vector -> Point

-- | A list of points that a list of vectors leads to.
trajectoryToPath :: Point -> [Vector] -> [Point]

-- | A list of points that a list of vectors leads to, bounded by level
--   size.
trajectoryToPathBounded :: X -> Y -> Point -> [Vector] -> [Point]

-- | The vector between the second point and the first. We have
--   
--   <pre>
--   shift pos1 (pos2 `vectorToFrom` pos1) == pos2
--   </pre>
--   
--   The arguments are in the same order as in the underlying scalar
--   subtraction.
vectorToFrom :: Point -> Point -> Vector
computeTrajectory :: Int -> Int -> Int -> [Point] -> ([Vector], (Speed, Int))
type RadianAngle = Double

-- | Rotate a vector by the given angle (expressed in radians)
--   counterclockwise and return a unit vector approximately in the
--   resulting direction.
rotate :: RadianAngle -> Vector -> Vector

-- | Given two distinct positions, determine the direction (a unit vector)
--   in which one should move from the first in order to get closer to the
--   second. Ignores obstacles. Of several equally good directions (in the
--   chessboard metric) it picks one of those that visually (in the
--   euclidean metric) maximally align with the vector between the two
--   points.
towards :: Point -> Point -> Vector

-- | Currently unused.
_moveTexts :: [Text]
longMoveTexts :: [Text]
movesSquare :: [VectorI]

-- | A list of vectors between a list of points.
pathToTrajectory :: [Point] -> [Vector]

-- | Given a vector of arbitrary non-zero length, produce a unit vector
--   that points in the same direction (in the chessboard metric). Of
--   several equally good directions it picks one of those that visually
--   (in the euclidean metric) maximally align with the original vector.
normalize :: Double -> Double -> Vector
normalizeVector :: Vector -> Vector
instance GHC.Generics.Generic Game.LambdaHack.Common.Vector.Vector
instance GHC.Classes.Ord Game.LambdaHack.Common.Vector.Vector
instance GHC.Classes.Eq Game.LambdaHack.Common.Vector.Vector
instance GHC.Read.Read Game.LambdaHack.Common.Vector.Vector
instance GHC.Show.Show Game.LambdaHack.Common.Vector.Vector
instance Data.Binary.Class.Binary Game.LambdaHack.Common.Vector.Vector
instance GHC.Enum.Enum Game.LambdaHack.Common.Vector.Vector
instance Control.DeepSeq.NFData Game.LambdaHack.Common.Vector.Vector


-- | Abstract identifiers for the main types in the engine. This is
--   imported by modules that don't need to know the internal structure of
--   the types. As a side effect, this prevents mutual dependencies among
--   modules.
module Game.LambdaHack.Common.Types

-- | A unique identifier of an item in the dungeon.
data ItemId

-- | A unique identifier of a faction in a game.
data FactionId

-- | Abstract level identifiers.
data LevelId

-- | A unique identifier of an actor in the dungeon.
data ActorId

-- | Item container type.
data Container
CFloor :: LevelId -> Point -> Container
CEmbed :: LevelId -> Point -> Container
CActor :: ActorId -> CStore -> Container

-- | for bootstrapping actor bodies
CTrunk :: FactionId -> LevelId -> Point -> Container
ppContainer :: Container -> Text
instance GHC.Generics.Generic Game.LambdaHack.Common.Types.Container
instance GHC.Classes.Ord Game.LambdaHack.Common.Types.Container
instance GHC.Classes.Eq Game.LambdaHack.Common.Types.Container
instance GHC.Show.Show Game.LambdaHack.Common.Types.Container
instance Data.Binary.Class.Binary Game.LambdaHack.Common.Types.ActorId
instance GHC.Enum.Enum Game.LambdaHack.Common.Types.ActorId
instance GHC.Classes.Ord Game.LambdaHack.Common.Types.ActorId
instance GHC.Classes.Eq Game.LambdaHack.Common.Types.ActorId
instance GHC.Show.Show Game.LambdaHack.Common.Types.ActorId
instance Data.Binary.Class.Binary Game.LambdaHack.Common.Types.LevelId
instance Data.Hashable.Class.Hashable Game.LambdaHack.Common.Types.LevelId
instance GHC.Classes.Ord Game.LambdaHack.Common.Types.LevelId
instance GHC.Classes.Eq Game.LambdaHack.Common.Types.LevelId
instance GHC.Show.Show Game.LambdaHack.Common.Types.LevelId
instance Data.Binary.Class.Binary Game.LambdaHack.Common.Types.FactionId
instance Data.Hashable.Class.Hashable Game.LambdaHack.Common.Types.FactionId
instance GHC.Enum.Enum Game.LambdaHack.Common.Types.FactionId
instance GHC.Classes.Ord Game.LambdaHack.Common.Types.FactionId
instance GHC.Classes.Eq Game.LambdaHack.Common.Types.FactionId
instance GHC.Show.Show Game.LambdaHack.Common.Types.FactionId
instance Data.Binary.Class.Binary Game.LambdaHack.Common.Types.ItemId
instance GHC.Enum.Enum Game.LambdaHack.Common.Types.ItemId
instance GHC.Classes.Ord Game.LambdaHack.Common.Types.ItemId
instance GHC.Classes.Eq Game.LambdaHack.Common.Types.ItemId
instance GHC.Show.Show Game.LambdaHack.Common.Types.ItemId
instance Data.Binary.Class.Binary Game.LambdaHack.Common.Types.Container
instance GHC.Enum.Enum Game.LambdaHack.Common.Types.LevelId


-- | Arrays, based on Data.Vector.Unboxed, indexed by <tt>Point</tt>.
module Game.LambdaHack.Common.PointArray
class (Ord c, Eq (UnboxRep c), Ord (UnboxRep c), Bounded (UnboxRep c), Binary (UnboxRep c), Unbox (UnboxRep c)) => UnboxRepClass c where {
    type family UnboxRep c;
    type UnboxRep c = c;
}
toUnboxRepUnsafe :: UnboxRepClass c => c -> UnboxRep c
fromUnboxRep :: UnboxRepClass c => UnboxRep c -> c

-- | Arrays indexed by <tt>Point</tt>.
data Array c
Array :: X -> Y -> Vector (UnboxRep c) -> Array c
[axsize] :: Array c -> X
[aysize] :: Array c -> Y
[avector] :: Array c -> Vector (UnboxRep c)
empty :: UnboxRepClass c => Array c

-- | Array lookup.
(!) :: UnboxRepClass c => Array c -> Point -> c
accessI :: UnboxRepClass c => Array c -> Int -> UnboxRep c

-- | Construct an array updated with the association list.
(//) :: UnboxRepClass c => Array c -> [(Point, c)] -> Array c
unsafeUpdateA :: UnboxRepClass c => Array c -> [(Point, c)] -> ()
unsafeWriteA :: UnboxRepClass c => Array c -> Point -> c -> ()
unsafeWriteManyA :: UnboxRepClass c => Array c -> [Point] -> c -> ()

-- | Create an array from a replicated element.
replicateA :: UnboxRepClass c => X -> Y -> c -> Array c

-- | Create an array from a replicated monadic action.
replicateMA :: (Monad m, UnboxRepClass c) => X -> Y -> m c -> m (Array c)

-- | Create an array from a function.
generateA :: UnboxRepClass c => X -> Y -> (Point -> c) -> Array c

-- | Create an array from a monadic function.
generateMA :: (Monad m, UnboxRepClass c) => X -> Y -> (Point -> m c) -> m (Array c)
unfoldrNA :: UnboxRepClass c => X -> Y -> (b -> (c, b)) -> b -> Array c

-- | Content identifiers array size.
sizeA :: Array c -> (X, Y)

-- | Fold right over an array.
foldrA :: UnboxRepClass c => (c -> a -> a) -> a -> Array c -> a

-- | Fold right strictly over an array.
foldrA' :: UnboxRepClass c => (c -> a -> a) -> a -> Array c -> a

-- | Fold left strictly over an array.
foldlA' :: UnboxRepClass c => (a -> c -> a) -> a -> Array c -> a

-- | Fold right over an array (function applied to each element and its
--   index).
ifoldrA :: UnboxRepClass c => (Point -> c -> a -> a) -> a -> Array c -> a

-- | Fold right strictly over an array (function applied to each element
--   and its index).
ifoldrA' :: UnboxRepClass c => (Point -> c -> a -> a) -> a -> Array c -> a

-- | Fold left strictly over an array (function applied to each element and
--   its index).
ifoldlA' :: UnboxRepClass c => (a -> Point -> c -> a) -> a -> Array c -> a

-- | Fold monadically strictly over an array.
foldMA' :: (Monad m, UnboxRepClass c) => (a -> c -> m a) -> a -> Array c -> m a

-- | Fold monadically strictly over an array (function applied to each
--   element and its index).
ifoldMA' :: (Monad m, UnboxRepClass c) => (a -> Point -> c -> m a) -> a -> Array c -> m a

-- | Map over an array.
mapA :: (UnboxRepClass c, UnboxRepClass d) => (c -> d) -> Array c -> Array d

-- | Map over an array (function applied to each element and its index).
imapA :: (UnboxRepClass c, UnboxRepClass d) => (Point -> c -> d) -> Array c -> Array d

-- | Map monadically over an array (function applied to each element and
--   its index) and ignore the results.
imapMA_ :: (Monad m, UnboxRepClass c) => (Point -> c -> m ()) -> Array c -> m ()

-- | Set all elements to the given value, in place, if possible.
safeSetA :: UnboxRepClass c => c -> Array c -> Array c

-- | Set all elements to the given value, in place.
unsafeSetA :: UnboxRepClass c => c -> Array c -> Array c

-- | Yield the point coordinates of a minimum element of the array. The
--   array may not be empty.
minIndexA :: UnboxRepClass c => Array c -> Point

-- | Yield the point coordinates of the last minimum element of the array.
--   The array may not be empty.
minLastIndexA :: UnboxRepClass c => Array c -> Point

-- | Yield the point coordinates of all the minimum elements of the array.
--   The array may not be empty.
minIndexesA :: UnboxRepClass c => Array c -> [Point]

-- | Yield the point coordinates of the first maximum element of the array.
--   The array may not be empty.
maxIndexA :: UnboxRepClass c => Array c -> Point

-- | Yield the point coordinates of the first maximum element of the array.
--   The array may not be empty.
maxIndexByA :: UnboxRepClass c => (c -> c -> Ordering) -> Array c -> Point

-- | Yield the point coordinates of the last maximum element of the array.
--   The array may not be empty.
maxLastIndexA :: UnboxRepClass c => Array c -> Point

-- | Force the array not to retain any extra memory.
forceA :: UnboxRepClass c => Array c -> Array c
fromListA :: UnboxRepClass c => X -> Y -> [c] -> Array c
toListA :: UnboxRepClass c => Array c -> [c]
toUnboxRep :: UnboxRepClass c => c -> UnboxRep c
instance Game.LambdaHack.Common.PointArray.UnboxRepClass c => GHC.Classes.Eq (Game.LambdaHack.Common.PointArray.Array c)
instance GHC.Show.Show (Game.LambdaHack.Common.PointArray.Array c)
instance Game.LambdaHack.Common.PointArray.UnboxRepClass c => Data.Binary.Class.Binary (Game.LambdaHack.Common.PointArray.Array c)
instance Game.LambdaHack.Common.PointArray.UnboxRepClass GHC.Types.Bool
instance Game.LambdaHack.Common.PointArray.UnboxRepClass GHC.Word.Word8
instance Game.LambdaHack.Common.PointArray.UnboxRepClass (Game.LambdaHack.Definition.Defs.ContentId k)
instance Game.LambdaHack.Common.PointArray.UnboxRepClass Game.LambdaHack.Definition.Color.AttrCharW32


-- | Actors perceiving other actors and the dungeon level.
--   
--   Visibility works according to KISS. Everything that player sees is
--   real. There are no unmarked hidden tiles and only solid tiles can be
--   marked, so there are no invisible walls and to pass through an
--   illusory wall, you have to use a turn bumping into it first. Only
--   tiles marked with Suspect can turn out to be another tile. (So, if all
--   tiles are marked with Suspect, the player knows nothing for sure, but
--   this should be avoided, because searching becomes too time-consuming.)
--   Each actor sees adjacent tiles, even when blind, so adjacent tiles are
--   known, so the actor can decide accurately whether to pass thorugh or
--   alter, etc.
--   
--   Items are always real and visible. Actors are real, but can be
--   invisible. Invisible actors in walls can't be hit, but are hinted at
--   when altering the tile, so the player can flee or block. Invisible
--   actors in open space can be hit.
module Game.LambdaHack.Common.Perception

-- | Visible positions.
newtype PerVisible
PerVisible :: EnumSet Point -> PerVisible
[pvisible] :: PerVisible -> EnumSet Point

-- | Smelled positions.
newtype PerSmelled
PerSmelled :: EnumSet Point -> PerSmelled
[psmelled] :: PerSmelled -> EnumSet Point

-- | The type representing the perception of a faction on a level.
data Perception
Perception :: PerVisible -> PerSmelled -> Perception
[psight] :: Perception -> PerVisible
[psmell] :: Perception -> PerSmelled

-- | Perception of a single faction, indexed by level identifier.
type PerLid = EnumMap LevelId Perception

-- | Perception indexed by faction identifier. This can't be added to
--   <tt>FactionDict</tt>, because clients can't see it for other factions.
type PerFid = EnumMap FactionId PerLid

-- | The set of tiles visible by at least one hero.
totalVisible :: Perception -> EnumSet Point

-- | The set of tiles smelt by at least one hero.
totalSmelled :: Perception -> EnumSet Point
emptyPer :: Perception
nullPer :: Perception -> Bool
addPer :: Perception -> Perception -> Perception
diffPer :: Perception -> Perception -> Perception
instance GHC.Generics.Generic Game.LambdaHack.Common.Perception.Perception
instance GHC.Classes.Eq Game.LambdaHack.Common.Perception.Perception
instance GHC.Show.Show Game.LambdaHack.Common.Perception.Perception
instance Data.Binary.Class.Binary Game.LambdaHack.Common.Perception.PerSmelled
instance GHC.Classes.Eq Game.LambdaHack.Common.Perception.PerSmelled
instance GHC.Show.Show Game.LambdaHack.Common.Perception.PerSmelled
instance Data.Binary.Class.Binary Game.LambdaHack.Common.Perception.PerVisible
instance GHC.Classes.Eq Game.LambdaHack.Common.Perception.PerVisible
instance GHC.Show.Show Game.LambdaHack.Common.Perception.PerVisible
instance Data.Binary.Class.Binary Game.LambdaHack.Common.Perception.Perception


-- | Frontend-independent keyboard input operations.
module Game.LambdaHack.Client.UI.Key

-- | Frontend-independent datatype to represent keys.
data Key
Esc :: Key
Return :: Key
Space :: Key
Tab :: Key
BackTab :: Key
BackSpace :: Key
PgUp :: Key
PgDn :: Key
Left :: Key
Right :: Key
Up :: Key
Down :: Key
End :: Key
Begin :: Key
Insert :: Key
Delete :: Key
PrintScreen :: Key
Home :: Key

-- | a keypad key for a character (digits and operators)
KP :: Char -> Key

-- | a single printable character
Char :: Char -> Key

-- | function key
Fun :: Int -> Key

-- | left mouse button pressed
LeftButtonPress :: Key

-- | middle mouse button pressed
MiddleButtonPress :: Key

-- | right mouse button pressed
RightButtonPress :: Key

-- | left mouse button released
LeftButtonRelease :: Key

-- | middle mouse button released
MiddleButtonRelease :: Key

-- | right mouse button released
RightButtonRelease :: Key

-- | mouse wheel rotated north
WheelNorth :: Key

-- | mouse wheel rotated south
WheelSouth :: Key

-- | an unknown key, registered to warn the user
Unknown :: String -> Key
DeadKey :: Key

-- | Our own encoding of modifiers.
data Modifier
NoModifier :: Modifier
ControlShift :: Modifier
Shift :: Modifier
Control :: Modifier
Alt :: Modifier

-- | Key and modifier.
data KM
KM :: Modifier -> Key -> KM
[modifier] :: KM -> Modifier
[key] :: KM -> Key

-- | Key, modifier and position of mouse pointer.
data KMP
KMP :: KM -> Point -> KMP
[kmpKeyMod] :: KMP -> KM
[kmpPointer] :: KMP -> Point

-- | Common and terse names for keys.
showKey :: Key -> String

-- | Show a key with a modifier, if any.
showKM :: KM -> String
escKM :: KM
controlEscKM :: KM
spaceKM :: KM
safeSpaceKM :: KM
undefinedKM :: KM
returnKM :: KM
pgupKM :: KM
pgdnKM :: KM
wheelNorthKM :: KM
wheelSouthKM :: KM
upKM :: KM
downKM :: KM
leftKM :: KM
rightKM :: KM
homeKM :: KM
endKM :: KM
backspaceKM :: KM
controlP :: KM
leftButtonReleaseKM :: KM
middleButtonReleaseKM :: KM
rightButtonReleaseKM :: KM
dirAllKey :: Bool -> Bool -> [Key]

-- | Configurable event handler for the direction keys. Used for directed
--   commands such as close door.
handleDir :: Bool -> Bool -> KM -> Maybe Vector

-- | Binding of both sets of movement keys, vi and laptop.
moveBinding :: Bool -> Bool -> (Vector -> a) -> (Vector -> a) -> [(KM, a)]
mkKM :: String -> KM
mkChar :: Char -> KM
mkKP :: Char -> KM

-- | Translate key from a GTK string description to our internal key type.
--   To be used, in particular, for the command bindings and macros in the
--   config file.
--   
--   See <a>https://github.com/twobob/gtk-/blob/master/gdk/keynames.txt</a>
keyTranslate :: String -> Key

-- | Translate key from a Web API string description
--   (<a>https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key#Key_values</a>)
--   to our internal key type. To be used in web frontends. The argument
--   says whether Shift is pressed.
keyTranslateWeb :: String -> Bool -> Key
dirKeypadKey :: [Key]
dirKeypadShiftChar :: [Char]
dirKeypadShiftKey :: [Key]
dirLaptopKey :: [Key]
dirLaptopShiftKey :: [Key]
dirViChar :: [Char]
dirViKey :: [Key]
dirViShiftKey :: [Key]
dirMoveNoModifier :: Bool -> Bool -> [Key]
dirRunNoModifier :: Bool -> Bool -> [Key]
dirRunControl :: [Key]
dirRunShift :: [Key]
instance GHC.Generics.Generic Game.LambdaHack.Client.UI.Key.KM
instance GHC.Classes.Eq Game.LambdaHack.Client.UI.Key.KM
instance GHC.Classes.Ord Game.LambdaHack.Client.UI.Key.KM
instance GHC.Generics.Generic Game.LambdaHack.Client.UI.Key.Modifier
instance GHC.Classes.Eq Game.LambdaHack.Client.UI.Key.Modifier
instance GHC.Classes.Ord Game.LambdaHack.Client.UI.Key.Modifier
instance GHC.Show.Show Game.LambdaHack.Client.UI.Key.Modifier
instance GHC.Generics.Generic Game.LambdaHack.Client.UI.Key.Key
instance GHC.Classes.Eq Game.LambdaHack.Client.UI.Key.Key
instance GHC.Classes.Ord Game.LambdaHack.Client.UI.Key.Key
instance Data.Binary.Class.Binary Game.LambdaHack.Client.UI.Key.KM
instance Control.DeepSeq.NFData Game.LambdaHack.Client.UI.Key.KM
instance GHC.Show.Show Game.LambdaHack.Client.UI.Key.KM
instance Data.Binary.Class.Binary Game.LambdaHack.Client.UI.Key.Modifier
instance Control.DeepSeq.NFData Game.LambdaHack.Client.UI.Key.Modifier
instance Data.Binary.Class.Binary Game.LambdaHack.Client.UI.Key.Key
instance Control.DeepSeq.NFData Game.LambdaHack.Client.UI.Key.Key


-- | Rectangular areas of levels and their basic operations.
module Game.LambdaHack.Common.Area

-- | The type of areas. The bottom left and the top right points.
data Area

-- | Checks if it's an area with at least one field.
toArea :: (X, Y, X, Y) -> Maybe Area
fromArea :: Area -> (X, Y, X, Y)
spanArea :: Area -> (Point, X, Y)
trivialArea :: Point -> Area
isTrivialArea :: Area -> Bool

-- | Checks that a point belongs to an area.
inside :: Point -> Area -> Bool

-- | Shrink the given area on all fours sides by the amount.
shrink :: Area -> Maybe Area
expand :: Area -> Area
middlePoint :: Area -> Point
areaInnerBorder :: Area -> [Point]
sumAreas :: Area -> Area -> Area
punindex :: X -> Int -> Point
instance GHC.Classes.Eq Game.LambdaHack.Common.Area.Area
instance GHC.Show.Show Game.LambdaHack.Common.Area.Area
instance Data.Binary.Class.Binary Game.LambdaHack.Common.Area.Area


-- | Per-actor analytics of personal feats.
module Game.LambdaHack.Common.Analytics

-- | Summary analytics data for each faction.
type FactionAnalytics = EnumMap FactionId Analytics

-- | Analytics data for each live actor.
type ActorAnalytics = EnumMap ActorId Analytics

-- | Statistics of possible and actual generation of items for each lore
--   kind.
type GenerationAnalytics = EnumMap SLore (EnumMap ItemId Int)
type KillMap = EnumMap FactionId (EnumMap ItemId Int)

-- | Statistics of past events concerning an actor.
newtype Analytics
Analytics :: EnumMap KillHow KillMap -> Analytics
[akillCounts] :: Analytics -> EnumMap KillHow KillMap

-- | Labels of individual kill count analytics.
data KillHow
KillKineticMelee :: KillHow
KillKineticRanged :: KillHow
KillKineticBlast :: KillHow
KillKineticPush :: KillHow
KillOtherMelee :: KillHow
KillOtherRanged :: KillHow
KillOtherBlast :: KillHow
KillOtherPush :: KillHow
KillActorLaunch :: KillHow
KillTileLaunch :: KillHow
KillDropLaunch :: KillHow
KillCatch :: KillHow
emptyAnalytics :: Analytics
addFactionKill :: FactionId -> KillHow -> FactionId -> ItemId -> FactionAnalytics -> FactionAnalytics
addActorKill :: ActorId -> KillHow -> FactionId -> ItemId -> ActorAnalytics -> ActorAnalytics
addKill :: KillHow -> FactionId -> ItemId -> Maybe Analytics -> Analytics
instance Data.Binary.Class.Binary Game.LambdaHack.Common.Analytics.Analytics
instance GHC.Classes.Eq Game.LambdaHack.Common.Analytics.Analytics
instance GHC.Show.Show Game.LambdaHack.Common.Analytics.Analytics
instance GHC.Generics.Generic Game.LambdaHack.Common.Analytics.KillHow
instance GHC.Enum.Enum Game.LambdaHack.Common.Analytics.KillHow
instance GHC.Classes.Eq Game.LambdaHack.Common.Analytics.KillHow
instance GHC.Show.Show Game.LambdaHack.Common.Analytics.KillHow
instance Data.Binary.Class.Binary Game.LambdaHack.Common.Analytics.KillHow


-- | Screen overlays.
module Game.LambdaHack.Client.UI.Overlay

-- | Line of colourful text.
type AttrLine = [AttrCharW32]
emptyAttrLine :: Int -> AttrLine
textToAL :: Text -> AttrLine
textFgToAL :: Color -> Text -> AttrLine
stringToAL :: String -> AttrLine
(<+:>) :: AttrLine -> AttrLine -> AttrLine
infixr 6 <+:>

-- | A series of screen lines that either fit the width of the screen or
--   are intended for truncation when displayed. The length of overlay may
--   exceed the length of the screen, unlike in <tt>SingleFrame</tt>. An
--   exception is lines generated from animation, which have to fit in
--   either dimension.
type Overlay = [AttrLine]

-- | Sparse screen overlay representation where only the indicated rows are
--   overlayed and the remaining rows are kept unchanged.
type IntOverlay = [(Int, AttrLine)]

-- | Split a string into lines. Avoids ending the line with a character
--   other than space. Space characters are removed from the start, but
--   never from the end of lines. Newlines are respected.
--   
--   Note that we only split wrt <tt>White</tt> space, nothing else.
splitAttrLine :: X -> AttrLine -> Overlay
indentSplitAttrLine :: X -> AttrLine -> [AttrLine]
glueLines :: Overlay -> Overlay -> Overlay
updateLines :: Int -> (AttrLine -> AttrLine) -> Overlay -> Overlay

-- | Color mode for the display.
data ColorMode

-- | normal, with full colours
ColorFull :: ColorMode

-- | black and white only
ColorBW :: ColorMode
linesAttr :: AttrLine -> Overlay
splitAttrPhrase :: X -> AttrLine -> Overlay
instance GHC.Classes.Eq Game.LambdaHack.Client.UI.Overlay.ColorMode


-- | Game messages displayed on top of the screen for the player to read
--   and then saved to player history.
module Game.LambdaHack.Client.UI.Msg

-- | The type of a single game message.
data Msg
toMsg :: Maybe (EnumMap MsgClass Color) -> MsgClass -> Text -> Msg
data MsgClass
MsgAdmin :: MsgClass
MsgBecome :: MsgClass
MsgNoLonger :: MsgClass
MsgLongerUs :: MsgClass
MsgLonger :: MsgClass
MsgItemCreation :: MsgClass
MsgItemDestruction :: MsgClass
MsgDeathGood :: MsgClass
MsgDeathBad :: MsgClass
MsgDeath :: MsgClass
MsgDeathThreat :: MsgClass
MsgLeader :: MsgClass
MsgDiplomacy :: MsgClass
MsgOutcome :: MsgClass
MsgPlot :: MsgClass
MsgLandscape :: MsgClass
MsgTileDisco :: MsgClass
MsgItemDisco :: MsgClass
MsgActorSpot :: MsgClass
MsgFirstEnemySpot :: MsgClass
MsgItemSpot :: MsgClass
MsgItemMove :: MsgClass
MsgAction :: MsgClass
MsgActionMinor :: MsgClass
MsgEffectMajor :: MsgClass
MsgEffect :: MsgClass
MsgEffectMinor :: MsgClass
MsgMisc :: MsgClass
MsgHeardClose :: MsgClass
MsgHeard :: MsgClass
MsgFocus :: MsgClass
MsgWarning :: MsgClass
MsgRangedPowerfulWe :: MsgClass
MsgRangedPowerfulUs :: MsgClass
MsgRanged :: MsgClass
MsgRangedUs :: MsgClass
MsgRare :: MsgClass
MsgVeryRare :: MsgClass
MsgMeleePowerfulWe :: MsgClass
MsgMeleePowerfulUs :: MsgClass
MsgMeleeInterestingWe :: MsgClass
MsgMeleeInterestingUs :: MsgClass
MsgMelee :: MsgClass
MsgMeleeUs :: MsgClass
MsgDone :: MsgClass
MsgAtFeetMajor :: MsgClass
MsgAtFeet :: MsgClass
MsgNumeric :: MsgClass
MsgSpam :: MsgClass
MsgMacro :: MsgClass
MsgRunStop :: MsgClass
MsgPrompt :: MsgClass
MsgPromptFocus :: MsgClass
MsgAlert :: MsgClass
MsgStopPlayback :: MsgClass
interruptsRunning :: MsgClass -> Bool
disturbsResting :: MsgClass -> Bool

-- | The set of messages, with repetitions, to show at the screen at once.
data Report

-- | Test if the set of messages is empty.
nullReport :: Report -> Bool

-- | Add a message to the start of report.
consReport :: Msg -> Report -> Report

-- | Render a report as a (possibly very long) <a>AttrLine</a>. Filter out
--   messages not meant for display.
renderReport :: Report -> AttrLine
anyInReport :: (MsgClass -> Bool) -> Report -> Bool

-- | The history of reports. This is a ring buffer of the given length
--   containing old archived history and two most recent reports stored
--   separately.
data History
newReport :: History -> Report

-- | Empty history of the given maximal length.
emptyHistory :: Int -> History

-- | Add a message to the new report of history, eliminating a possible
--   duplicate and noting its existence in the result.
addToReport :: History -> Msg -> Int -> Time -> (History, Bool)

-- | Archive old report to history, filtering out messages with 0
--   duplicates and prompts. Set up new report with a new timestamp.
archiveReport :: History -> History
lengthHistory :: History -> Int

-- | Render history as many lines of text. New report is not rendered. It's
--   expected to be empty when history is shown.
renderHistory :: History -> [AttrLine]
isSavedToHistory :: MsgClass -> Bool
isDisplayed :: MsgClass -> Bool
bindsPronouns :: MsgClass -> Bool
msgColor :: MsgClass -> Color
type UAttrLine = Vector Word32
data RepMsgN
uToAttrLine :: UAttrLine -> AttrLine
attrLineToU :: AttrLine -> UAttrLine

-- | Empty set of messages.
emptyReport :: Report

-- | Add a message to the end of the report.
snocReport :: Report -> Msg -> Int -> Report

-- | Render a report as a (possibly very long) <a>AttrLine</a>.
renderWholeReport :: Report -> AttrLine
renderRepetition :: RepMsgN -> AttrLine
scrapRepetition :: History -> Maybe History
renderTimeReport :: Time -> Report -> [AttrLine]
instance GHC.Generics.Generic Game.LambdaHack.Client.UI.Msg.History
instance GHC.Show.Show Game.LambdaHack.Client.UI.Msg.History
instance Data.Binary.Class.Binary Game.LambdaHack.Client.UI.Msg.Report
instance GHC.Show.Show Game.LambdaHack.Client.UI.Msg.Report
instance GHC.Generics.Generic Game.LambdaHack.Client.UI.Msg.RepMsgN
instance GHC.Show.Show Game.LambdaHack.Client.UI.Msg.RepMsgN
instance GHC.Generics.Generic Game.LambdaHack.Client.UI.Msg.Msg
instance GHC.Classes.Eq Game.LambdaHack.Client.UI.Msg.Msg
instance GHC.Show.Show Game.LambdaHack.Client.UI.Msg.Msg
instance GHC.Generics.Generic Game.LambdaHack.Client.UI.Msg.MsgClass
instance GHC.Enum.Enum Game.LambdaHack.Client.UI.Msg.MsgClass
instance GHC.Classes.Eq Game.LambdaHack.Client.UI.Msg.MsgClass
instance GHC.Read.Read Game.LambdaHack.Client.UI.Msg.MsgClass
instance GHC.Show.Show Game.LambdaHack.Client.UI.Msg.MsgClass
instance Data.Binary.Class.Binary Game.LambdaHack.Client.UI.Msg.History
instance Data.Binary.Class.Binary Game.LambdaHack.Client.UI.Msg.RepMsgN
instance Data.Binary.Class.Binary Game.LambdaHack.Client.UI.Msg.Msg
instance Control.DeepSeq.NFData Game.LambdaHack.Client.UI.Msg.MsgClass
instance Data.Binary.Class.Binary Game.LambdaHack.Client.UI.Msg.MsgClass


-- | The type of definitions of screen layout and features.
module Game.LambdaHack.Client.UI.Content.Screen

-- | Screen layout and features definition.
data ScreenContent
ScreenContent :: X -> Y -> Text -> [String] -> [String] -> EnumMap Char Text -> ScreenContent

-- | screen width
[rwidth] :: ScreenContent -> X

-- | screen height
[rheight] :: ScreenContent -> Y

-- | the ASCII art for the main menu
[rmainMenuArt] :: ScreenContent -> Text

-- | the intro screen (first help screen) text
[rintroScreen] :: ScreenContent -> [String]

-- | the fixed move key help blurb
[rmoveKeysScreen] :: ScreenContent -> [String]

-- | verbs to use for apply actions
[rapplyVerbMap] :: ScreenContent -> EnumMap Char Text
makeData :: ScreenContent -> ScreenContent

-- | Catch invalid rule kind definitions.
validateSingle :: ScreenContent -> [Text]


-- | Screen frames.
module Game.LambdaHack.Client.UI.Frame
type FrameST s = Mutable Vector s Word32 -> ST s ()

-- | Efficiently composable representation of an operation on a frame, that
--   is, on a mutable vector. When the composite operation is eventually
--   performed, the vector is frozen to become a <a>SingleFrame</a>.
newtype FrameForall
FrameForall :: (forall s. FrameST s) -> FrameForall
[unFrameForall] :: FrameForall -> forall s. FrameST s

-- | Action that results in a base frame, to be modified further.
newtype FrameBase
FrameBase :: (forall s. ST s (Mutable Vector s Word32)) -> FrameBase
[unFrameBase] :: FrameBase -> forall s. ST s (Mutable Vector s Word32)

-- | A frame, that is, a base frame and all its modifications.
type Frame = (FrameBase, FrameForall)

-- | Components of a frame, before it's decided if the first can be
--   overwritten in-place or needs to be copied.
type PreFrame = (Vector Word32, FrameForall)

-- | Sequence of screen frames, including delays. Potentially based on a
--   single base frame.
type PreFrames = [Maybe PreFrame]

-- | An overlay that fits on the screen (or is meant to be truncated on
--   display) and is padded to fill the whole screen and is displayed as a
--   single game screen frame.
--   
--   Note that we don't provide a list of color-highlighed positions
--   separately, because overlays need to obscure not only map, but the
--   highlights as well.
newtype SingleFrame
SingleFrame :: Array AttrCharW32 -> SingleFrame
[singleFrame] :: SingleFrame -> Array AttrCharW32
blankSingleFrame :: ScreenContent -> SingleFrame

-- | Overlays either the game map only or the whole empty screen frame. We
--   assume the lines of the overlay are not too long nor too many.
overlayFrame :: IntOverlay -> PreFrame -> PreFrame
overlayFrameWithLines :: ScreenContent -> Bool -> Overlay -> PreFrame -> PreFrame

-- | Add a space at the message end, for display overlayed over the level
--   map. Also trim (do not wrap!) too long lines.
truncateAttrLine :: X -> AttrLine -> X -> AttrLine
instance GHC.Show.Show Game.LambdaHack.Client.UI.Frame.SingleFrame
instance GHC.Classes.Eq Game.LambdaHack.Client.UI.Frame.SingleFrame


-- | Screen frames and animations.
module Game.LambdaHack.Client.UI.Frontend.Common

-- | Raw frontend definition. The minimal closed set of values that need to
--   depend on the specifics of the chosen frontend.
data RawFrontend
RawFrontend :: (SingleFrame -> IO ()) -> IO () -> MVar () -> TQueue KMP -> IO () -> ScreenContent -> RawFrontend
[fdisplay] :: RawFrontend -> SingleFrame -> IO ()
[fshutdown] :: RawFrontend -> IO ()
[fshowNow] :: RawFrontend -> MVar ()
[fchanKey] :: RawFrontend -> TQueue KMP
[fprintScreen] :: RawFrontend -> IO ()
[fcoscreen] :: RawFrontend -> ScreenContent

-- | Start up a frontend on a bound thread.
--   
--   In fact, it is started on the very main thread, via a hack, because
--   apparently some SDL backends are not thread-safe
--   (<a>https://wiki.libsdl.org/FAQDevelopment</a>; "this should only be
--   run in the thread that initialized the video subsystem, and for extra
--   safety, you should consider only doing those things on the main thread
--   in any case") and at least the newer OS X obtusely requires the main
--   thread, see
--   <a>https://github.com/AllureOfTheStars/Allure/issues/79</a> In case
--   any other exotic architecture requires the main thread, we make the
--   hack the default for all (on frontends that require a bound thread,
--   e.g., SLD2 or GTK).
startupBound :: (MVar RawFrontend -> IO ()) -> IO RawFrontend
createRawFrontend :: ScreenContent -> (SingleFrame -> IO ()) -> IO () -> IO RawFrontend

-- | Empty the keyboard channel.
resetChanKey :: TQueue KMP -> IO ()
saveKMP :: RawFrontend -> Modifier -> Key -> Point -> IO ()

-- | Translates modifiers to our own encoding.
modifierTranslate :: Bool -> Bool -> Bool -> Bool -> Modifier


-- | Screen frames and animations.
module Game.LambdaHack.Client.UI.Animation

-- | Animation is a list of frame modifications to play one by one, where
--   each modification if a map from positions to level map symbols.
data Animation

-- | Render animations on top of a screen frame.
--   
--   Located in this module to keep <tt>Animation</tt> abstract.
renderAnim :: PreFrame -> Animation -> PreFrames
pushAndDelay :: Animation

-- | Attack animation. A part of it also reused for self-damage and
--   healing.
twirlSplash :: ScreenContent -> (Point, Point) -> Color -> Color -> Animation

-- | Attack that hits through a block.
blockHit :: ScreenContent -> (Point, Point) -> Color -> Color -> Animation

-- | Attack that is blocked.
blockMiss :: ScreenContent -> (Point, Point) -> Animation

-- | Attack that is subtle (e.g., damage dice 0).
subtleHit :: ScreenContent -> Point -> Animation

-- | Death animation for an organic body.
deathBody :: ScreenContent -> Point -> Animation

-- | Death animation for an organic body, short version (e.g., for
--   enemies).
shortDeathBody :: ScreenContent -> Point -> Animation

-- | Mark actor location animation.
actorX :: ScreenContent -> Point -> Animation

-- | Actor teleport animation.
teleport :: ScreenContent -> (Point, Point) -> Animation

-- | Swap-places animation, both hostile and friendly.
swapPlaces :: ScreenContent -> (Point, Point) -> Animation
fadeout :: ScreenContent -> Bool -> Int -> Rnd Animation
blank :: Maybe AttrCharW32
cSym :: Color -> Char -> Maybe AttrCharW32
mapPosToOffset :: ScreenContent -> (Point, AttrCharW32) -> (Int, [AttrCharW32])
mzipSingleton :: ScreenContent -> Point -> Maybe AttrCharW32 -> IntOverlay
mzipPairs :: ScreenContent -> (Point, Point) -> (Maybe AttrCharW32, Maybe AttrCharW32) -> IntOverlay
instance GHC.Show.Show Game.LambdaHack.Client.UI.Animation.Animation
instance GHC.Classes.Eq Game.LambdaHack.Client.UI.Animation.Animation


-- | The default screen layout and features definition.
module Client.UI.Content.Screen

-- | Description of default screen layout and features.
standardLayoutAndFeatures :: ScreenContent


-- | The appearance of in-game items, as communicated to the player.
module Game.LambdaHack.Definition.Flavour

-- | The type of item flavours.
data Flavour
Flavour :: FancyName -> Color -> Flavour

-- | Turn a colour set into a flavour set.
zipPlain :: [Color] -> [Flavour]

-- | Turn a colour set into a flavour set.
zipFancy :: [Color] -> [Flavour]

-- | Turn a colour set into a flavour set.
zipLiquid :: [Color] -> [Flavour]

-- | Turn a colour set into a flavour set.
zipGlassPlain :: [Color] -> [Flavour]

-- | Turn a colour set into a flavour set.
zipGlassFancy :: [Color] -> [Flavour]

-- | Get the underlying base colour of a flavour.
flavourToColor :: Flavour -> Color

-- | Construct the full name of a flavour.
flavourToName :: Flavour -> Text

-- | Human-readable names for item colors. The plain set.
colorToPlainName :: Color -> Text

-- | Human-readable names for item colors. The fancy set.
colorToFancyName :: Color -> Text

-- | Simple names for team colors (bright colours preferred).
colorToTeamName :: Color -> Text
data FancyName

-- | Human-readable names for item colors. The liquid set.
colorToLiquidName :: Color -> Text

-- | Human-readable names for item colors. The plain glass set.
colorToGlassPlainName :: Color -> Text

-- | Human-readable names for item colors. The fancy glass set.
colorToGlassFancyName :: Color -> Text
instance GHC.Generics.Generic Game.LambdaHack.Definition.Flavour.Flavour
instance GHC.Classes.Ord Game.LambdaHack.Definition.Flavour.Flavour
instance GHC.Classes.Eq Game.LambdaHack.Definition.Flavour.Flavour
instance GHC.Show.Show Game.LambdaHack.Definition.Flavour.Flavour
instance GHC.Generics.Generic Game.LambdaHack.Definition.Flavour.FancyName
instance GHC.Enum.Bounded Game.LambdaHack.Definition.Flavour.FancyName
instance GHC.Enum.Enum Game.LambdaHack.Definition.Flavour.FancyName
instance GHC.Classes.Ord Game.LambdaHack.Definition.Flavour.FancyName
instance GHC.Classes.Eq Game.LambdaHack.Definition.Flavour.FancyName
instance GHC.Show.Show Game.LambdaHack.Definition.Flavour.FancyName
instance GHC.Enum.Enum Game.LambdaHack.Definition.Flavour.Flavour
instance Data.Hashable.Class.Hashable Game.LambdaHack.Definition.Flavour.Flavour
instance Data.Binary.Class.Binary Game.LambdaHack.Definition.Flavour.Flavour


-- | The type of kinds of weapons, treasure, organs, blasts, etc.
module Game.LambdaHack.Content.ItemKind

-- | Item properties that are fixed for a given kind of items. Of these,
--   aspects and effects are jointly called item powers. Note that this
--   type is mutually recursive with <a>Effect</a> and <a>Aspect</a>.
data ItemKind
ItemKind :: Char -> Text -> Freqs ItemKind -> [Flavour] -> Dice -> Rarity -> Text -> Int -> Dice -> [Aspect] -> [Effect] -> [(GroupName ItemKind, CStore)] -> Text -> ItemKind

-- | map symbol
[isymbol] :: ItemKind -> Char

-- | generic name; is pluralized if needed
[iname] :: ItemKind -> Text

-- | frequency within groups
[ifreq] :: ItemKind -> Freqs ItemKind

-- | possible flavours
[iflavour] :: ItemKind -> [Flavour]

-- | created in that quantity
[icount] :: ItemKind -> Dice

-- | rarity on given depths
[irarity] :: ItemKind -> Rarity

-- | the verb for hitting
[iverbHit] :: ItemKind -> Text

-- | weight in grams
[iweight] :: ItemKind -> Int

-- | basic kinetic damage
[idamage] :: ItemKind -> Dice

-- | affect the actor continuously
[iaspects] :: ItemKind -> [Aspect]

-- | cause the effects when triggered
[ieffects] :: ItemKind -> [Effect]

-- | accompanying organs and equipment
[ikit] :: ItemKind -> [(GroupName ItemKind, CStore)]

-- | description
[idesc] :: ItemKind -> Text
makeData :: [ItemKind] -> ContentData ItemKind

-- | Aspects of items. Aspect <tt>AddSkill</tt> is additive (starting at 0)
--   for all items wielded by an actor and it affects the actor. The others
--   affect only the item in question, not the actor carrying it, and so
--   are not additive in any sense.
data Aspect

-- | specifies the cooldown before an item may be applied again; if a copy
--   of an item is applied manually (not via periodic activation), all
--   effects on a single copy of the item are disabled until the copy
--   recharges for the given time expressed in game turns; all copies
--   recharge concurrently
Timeout :: Dice -> Aspect

-- | bonus to a skill; in content, avoid boosting skills such as SkApply
--   via permanent equipment, to avoid micromanagement through swapping
--   items among party members before each skill use
AddSkill :: Skill -> Dice -> Aspect

-- | item feature
SetFlag :: Flag -> Aspect

-- | extra label of the item; it's not pluralized
ELabel :: Text -> Aspect

-- | parameters modifying a throw
ToThrow :: ThrowMod -> Aspect

-- | until identified, presents as this unique kind
HideAs :: GroupName ItemKind -> Aspect

-- | AI and UI flag that leaks item intended use
EqpSlot :: EqpSlot -> Aspect

-- | if level-scaled dice roll &gt; 50, pick the former aspects, otherwise
--   the latter
Odds :: Dice -> [Aspect] -> [Aspect] -> Aspect

-- | Effects of items. Can be invoked by the item wielder to affect another
--   actor or the wielder himself. Many occurences in the same item are
--   possible.
data Effect

-- | burn with this damage
Burn :: Dice -> Effect

-- | explode producing this group of blasts
Explode :: GroupName ItemKind -> Effect

-- | modify HP of the actor by this amount
RefillHP :: Int -> Effect

-- | modify Calm of the actor by this amount
RefillCalm :: Int -> Effect

-- | change actor's allegiance
Dominate :: Effect

-- | make actor susceptible to domination
Impress :: Effect

-- | put actor to sleep, also calming him
PutToSleep :: Effect

-- | make the actor yell/yawn, waking him and others up
Yell :: Effect

-- | summon the given number of actors of this group
Summon :: GroupName ItemKind -> Dice -> Effect

-- | ascend to another level of the dungeon
Ascend :: Bool -> Effect

-- | escape from the dungeon
Escape :: Effect

-- | paralyze for this many game clips
Paralyze :: Dice -> Effect

-- | paralyze for this many game clips due to water
ParalyzeInWater :: Dice -> Effect

-- | give actor this many extra tenths of actor move
InsertMove :: Dice -> Effect

-- | teleport actor across rougly this distance
Teleport :: Dice -> Effect

-- | create an item of the group and insert into the store with the given
--   random timer
CreateItem :: CStore -> GroupName ItemKind -> TimerDice -> Effect

-- | make the actor drop items of the given group from the given store; the
--   first integer says how many item kinds to drop, the second, how many
--   copies of each kind to drop; for non-organs, beware of not dropping
--   all, or cluttering store with rubbish becomes beneficial
DropItem :: Int -> Int -> CStore -> GroupName ItemKind -> Effect

-- | get a suitable (i.e., numerous enough) non-unique common item stack on
--   the floor and polymorph it to a stack of random common items, with
--   current depth coefficient
PolyItem :: Effect

-- | get a suitable (i.e., with any random aspects) single item (even
--   unique) on the floor and change the random bonuses of the items
--   randomly, with maximal depth coefficient
RerollItem :: Effect

-- | exactly duplicate a single non-unique, non-valuable item on the floor
DupItem :: Effect

-- | find a suitable (i.e., not identified) item, starting from the floor,
--   and identify it
Identify :: Effect

-- | detect something on the map in the given radius
Detect :: DetectKind -> Int -> Effect

-- | send an actor flying (push or pull, depending)
SendFlying :: ThrowMod -> Effect

-- | push an actor
PushActor :: ThrowMod -> Effect

-- | pull an actor
PullActor :: ThrowMod -> Effect

-- | make the actor drop its best weapon
DropBestWeapon :: Effect

-- | activate all items with this symbol in inventory; space character
--   means all symbols
ActivateInv :: Char -> Effect

-- | remove all smell on the level
ApplyPerfume :: Effect

-- | trigger one of the effects with equal probability
OneOf :: [Effect] -> Effect

-- | trigger the effect when item smashed (not when applied nor meleed);
OnSmash :: Effect -> Effect

-- | only fire next effect if previous fully activated
Composite :: [Effect] -> Effect

-- | a sentence with the actor causing the effect as subject and the given
--   text as verb is emitted when the activation causes item to expire; no
--   spam is emitted if a projectile
VerbNoLonger :: Text -> Effect

-- | a sentence with the actor causing the effect as subject and the given
--   text as verb is emitted whenever the item is activated; no spam is
--   emitted if a projectile
VerbMsg :: Text -> Effect
data DetectKind
DetectAll :: DetectKind
DetectActor :: DetectKind
DetectLoot :: DetectKind
DetectExit :: DetectKind
DetectHidden :: DetectKind
DetectEmbed :: DetectKind

-- | Specification of how to randomly roll a timer at item creation to
--   obtain a fixed timer for the item's lifetime.
data TimerDice

-- | Parameters modifying a throw of a projectile or flight of pushed
--   actor. Not additive and don't start at 0.
data ThrowMod
ThrowMod :: Int -> Int -> Int -> ThrowMod

-- | fly with this percentage of base throw speed
[throwVelocity] :: ThrowMod -> Int

-- | fly for this percentage of 2 turns
[throwLinger] :: ThrowMod -> Int

-- | start flight with this many HP
[throwHP] :: ThrowMod -> Int
boostItemKindList :: StdGen -> [ItemKind] -> [ItemKind]

-- | Whether the effect has a chance of exhibiting any potentially
--   noticeable behaviour, except when the item is destroyed. We assume at
--   least one of <tt>OneOf</tt> effects must be noticeable.
forApplyEffect :: Effect -> Bool
strengthOnSmash :: ItemKind -> [Effect]
getDropOrgans :: ItemKind -> [GroupName ItemKind]
getMandatoryHideAsFromKind :: ItemKind -> Maybe (GroupName ItemKind)
isEffEscape :: Effect -> Bool
isEffEscapeOrAscend :: Effect -> Bool
timeoutAspect :: Aspect -> Bool
onSmashEffect :: Effect -> Bool
damageUsefulness :: ItemKind -> Double
verbMsgNoLonger :: Text -> Effect
verbMsgLess :: Text -> Effect
toVelocity :: Int -> Aspect
toLinger :: Int -> Aspect
timerNone :: TimerDice
isTimerNone :: TimerDice -> Bool
foldTimer :: a -> (Dice -> a) -> (Dice -> a) -> TimerDice -> a
toOrganBad :: GroupName ItemKind -> Dice -> Effect
toOrganGood :: GroupName ItemKind -> Dice -> Effect
toOrganNoTimer :: GroupName ItemKind -> Effect
boostItemKind :: ItemKind -> ItemKind

-- | Catch invalid item kind definitions.
validateSingle :: ItemKind -> [Text]

-- | Validate all item kinds.
validateAll :: [ItemKind] -> ContentData ItemKind -> [Text]
validateDups :: ItemKind -> Aspect -> [Text]
validateDamage :: Dice -> [Text]
hardwiredItemGroups :: [GroupName ItemKind]
instance GHC.Generics.Generic Game.LambdaHack.Content.ItemKind.Effect
instance GHC.Classes.Eq Game.LambdaHack.Content.ItemKind.Effect
instance GHC.Show.Show Game.LambdaHack.Content.ItemKind.Effect
instance GHC.Generics.Generic Game.LambdaHack.Content.ItemKind.ItemKind
instance GHC.Show.Show Game.LambdaHack.Content.ItemKind.ItemKind
instance GHC.Generics.Generic Game.LambdaHack.Content.ItemKind.Aspect
instance GHC.Classes.Eq Game.LambdaHack.Content.ItemKind.Aspect
instance GHC.Show.Show Game.LambdaHack.Content.ItemKind.Aspect
instance GHC.Generics.Generic Game.LambdaHack.Content.ItemKind.ThrowMod
instance GHC.Classes.Ord Game.LambdaHack.Content.ItemKind.ThrowMod
instance GHC.Classes.Eq Game.LambdaHack.Content.ItemKind.ThrowMod
instance GHC.Show.Show Game.LambdaHack.Content.ItemKind.ThrowMod
instance GHC.Generics.Generic Game.LambdaHack.Content.ItemKind.TimerDice
instance GHC.Classes.Eq Game.LambdaHack.Content.ItemKind.TimerDice
instance GHC.Generics.Generic Game.LambdaHack.Content.ItemKind.DetectKind
instance GHC.Classes.Eq Game.LambdaHack.Content.ItemKind.DetectKind
instance GHC.Show.Show Game.LambdaHack.Content.ItemKind.DetectKind
instance Data.Binary.Class.Binary Game.LambdaHack.Content.ItemKind.Effect
instance Data.Binary.Class.Binary Game.LambdaHack.Content.ItemKind.ThrowMod
instance Data.Hashable.Class.Hashable Game.LambdaHack.Content.ItemKind.ThrowMod
instance GHC.Show.Show Game.LambdaHack.Content.ItemKind.TimerDice
instance Data.Binary.Class.Binary Game.LambdaHack.Content.ItemKind.TimerDice
instance Data.Binary.Class.Binary Game.LambdaHack.Content.ItemKind.DetectKind


-- | The type of kinds of terrain tiles.
module Game.LambdaHack.Content.TileKind

-- | The type of kinds of terrain tiles. See <tt>Tile.hs</tt> for
--   explanation of the absence of a corresponding type <tt>Tile</tt> that
--   would hold particular concrete tiles in the dungeon. Note that tile
--   names (and any other content names) should not be plural (that would
--   lead to "a stairs"), so "road with cobblestones" is fine, but "granite
--   cobblestones" is wrong.
--   
--   Tile kind for unknown space has the minimal <tt>ContentId</tt> index.
--   The <tt>talter</tt> for unknown space is <tt>1</tt> and no other tile
--   kind has that value.
data TileKind
TileKind :: Char -> Text -> Freqs TileKind -> Color -> Color -> Word8 -> [Feature] -> TileKind

-- | map symbol
[tsymbol] :: TileKind -> Char

-- | short description
[tname] :: TileKind -> Text

-- | frequency within groups
[tfreq] :: TileKind -> Freqs TileKind

-- | map color
[tcolor] :: TileKind -> Color

-- | map color when not in FOV
[tcolor2] :: TileKind -> Color

-- | minimal skill needed to alter the tile
[talter] :: TileKind -> Word8

-- | properties
[tfeature] :: TileKind -> [Feature]

-- | All possible terrain tile features.
data Feature

-- | initially an item of this group is embedded; we assume the item has
--   effects and is supposed to be triggered
Embed :: GroupName ItemKind -> Feature

-- | goes from a closed to (randomly closed or) open tile when altered
OpenTo :: GroupName TileKind -> Feature

-- | goes from an open to (randomly opened or) closed tile when altered
CloseTo :: GroupName TileKind -> Feature

-- | alters tile, but does not change walkability
ChangeTo :: GroupName TileKind -> Feature

-- | when hidden, looks as the unique tile of the group
HideAs :: GroupName TileKind -> Feature

-- | when generating, may be transformed to the unique tile of the group
BuildAs :: GroupName TileKind -> Feature

-- | when generating in opening, can be revealed to belong to the group
RevealAs :: GroupName TileKind -> Feature

-- | when generating in solid wall, can be revealed to belong to the group
ObscureAs :: GroupName TileKind -> Feature

-- | actors can walk through
Walkable :: Feature

-- | actors can see through
Clear :: Feature

-- | is not lit with an ambient light
Dark :: Feature

-- | initial items often generated there
OftenItem :: Feature

-- | initial items very often generated there
VeryOftenItem :: Feature

-- | initial actors often generated there
OftenActor :: Feature

-- | no items ever generated there
NoItem :: Feature

-- | no actors ever generated there
NoActor :: Feature

-- | even if otherwise uninteresting, taken into account for triggering by
--   AI
ConsideredByAI :: Feature

-- | used for visible trails throughout the level
Trail :: Feature

-- | in place normal legend and in override, don't roll a tile kind only
--   once per place, but roll for each position; one non-spicy (according
--   to frequencies of non-spicy) and at most one spicy (according to their
--   frequencies) is rolled per place and then, once for each position, one
--   of the two is semi-randomly chosen (according to their individual
--   frequencies only)
Spice :: Feature
makeData :: ContentData ItemKind -> [TileKind] -> ContentData TileKind
isUknownSpace :: ContentId TileKind -> Bool
unknownId :: ContentId TileKind
isSuspectKind :: TileKind -> Bool
isOpenableKind :: TileKind -> Bool
isClosableKind :: TileKind -> Bool
talterForStairs :: Word8
floorSymbol :: Char

-- | Validate a single tile kind.
validateSingle :: TileKind -> [Text]

-- | Validate all tile kinds.
--   
--   We don't check it any more, but if tiles look the same on the map
--   (symbol and color), their substantial features should be the same,
--   too, unless there is a good reason they shouldn't. Otherwise the
--   player has to inspect manually all the tiles with this look to see if
--   any is special. This tends to be tedious. Note that tiles may freely
--   differ wrt text blurb, dungeon generation rules, AI preferences, etc.,
--   whithout causing the tedium.
validateAll :: ContentData ItemKind -> [TileKind] -> ContentData TileKind -> [Text]
validateDups :: TileKind -> Feature -> [Text]
hardwiredTileGroups :: [GroupName TileKind]
instance GHC.Show.Show Game.LambdaHack.Content.TileKind.TileKind
instance GHC.Generics.Generic Game.LambdaHack.Content.TileKind.Feature
instance GHC.Classes.Ord Game.LambdaHack.Content.TileKind.Feature
instance GHC.Classes.Eq Game.LambdaHack.Content.TileKind.Feature
instance GHC.Show.Show Game.LambdaHack.Content.TileKind.Feature
instance Data.Binary.Class.Binary Game.LambdaHack.Content.TileKind.Feature
instance Data.Hashable.Class.Hashable Game.LambdaHack.Content.TileKind.Feature
instance Control.DeepSeq.NFData Game.LambdaHack.Content.TileKind.Feature


-- | The type of kinds of rooms, halls and passages.
module Game.LambdaHack.Content.PlaceKind

-- | Parameters for the generation of small areas within a dungeon level.
data PlaceKind
PlaceKind :: Char -> Text -> Freqs PlaceKind -> Rarity -> Cover -> Fence -> [Text] -> [(Char, GroupName TileKind)] -> [(Char, GroupName TileKind)] -> PlaceKind

-- | a symbol
[psymbol] :: PlaceKind -> Char

-- | short description, singular or plural
[pname] :: PlaceKind -> Text

-- | frequency within groups
[pfreq] :: PlaceKind -> Freqs PlaceKind

-- | rarity on given depths
[prarity] :: PlaceKind -> Rarity

-- | how to fill whole place using the corner
[pcover] :: PlaceKind -> Cover

-- | whether to fence place with solid border
[pfence] :: PlaceKind -> Fence

-- | plan of the top-left corner of the place
[ptopLeft] :: PlaceKind -> [Text]

-- | dark legend override
[poverrideDark] :: PlaceKind -> [(Char, GroupName TileKind)]

-- | lit legend override
[poverrideLit] :: PlaceKind -> [(Char, GroupName TileKind)]
makeData :: ContentData TileKind -> [PlaceKind] -> ContentData PlaceKind

-- | A method of filling the whole area (except for CVerbatim and CMirror,
--   which are just placed in the middle of the area) by transforming a
--   given corner.
data Cover

-- | reflect every other corner, overlapping 1 row and column
CAlternate :: Cover

-- | fill symmetrically 4 corners and stretch their borders
CStretch :: Cover

-- | tile separately and symmetrically quarters of the place
CReflect :: Cover

-- | just build the given interior, without filling the area
CVerbatim :: Cover

-- | build the given interior in one of 4 mirrored variants
CMirror :: Cover

-- | The choice of a fence type for the place.
data Fence

-- | put a solid wall fence around the place
FWall :: Fence

-- | leave an empty space, like the room's floor
FFloor :: Fence

-- | leave an empty space, like the cave's ground
FGround :: Fence

-- | skip the fence and fill all with the place proper
FNone :: Fence
data PlaceEntry
PEntry :: ContentId PlaceKind -> PlaceEntry
PAround :: ContentId PlaceKind -> PlaceEntry
PEnd :: ContentId PlaceKind -> PlaceEntry
deadEndId :: ContentId PlaceKind

-- | Catch invalid place kind definitions. In particular, verify that the
--   top-left corner map is rectangular and not empty.
validateSingle :: PlaceKind -> [Text]

-- | Validate all place kinds.
validateAll :: ContentData TileKind -> [PlaceKind] -> ContentData PlaceKind -> [Text]
instance GHC.Generics.Generic Game.LambdaHack.Content.PlaceKind.PlaceEntry
instance GHC.Classes.Eq Game.LambdaHack.Content.PlaceKind.PlaceEntry
instance GHC.Show.Show Game.LambdaHack.Content.PlaceKind.PlaceEntry
instance GHC.Show.Show Game.LambdaHack.Content.PlaceKind.PlaceKind
instance GHC.Classes.Eq Game.LambdaHack.Content.PlaceKind.Fence
instance GHC.Show.Show Game.LambdaHack.Content.PlaceKind.Fence
instance GHC.Classes.Eq Game.LambdaHack.Content.PlaceKind.Cover
instance GHC.Show.Show Game.LambdaHack.Content.PlaceKind.Cover
instance Data.Binary.Class.Binary Game.LambdaHack.Content.PlaceKind.PlaceEntry


-- | Abstract syntax of human player commands.
module Game.LambdaHack.Client.UI.HumanCmd
data CmdCategory
CmdMainMenu :: CmdCategory
CmdDashboard :: CmdCategory
CmdItemMenu :: CmdCategory
CmdMove :: CmdCategory
CmdItem :: CmdCategory
CmdAim :: CmdCategory
CmdMeta :: CmdCategory
CmdMouse :: CmdCategory
CmdInternal :: CmdCategory
CmdNoHelp :: CmdCategory
CmdDebug :: CmdCategory
CmdMinimal :: CmdCategory
categoryDescription :: CmdCategory -> Text

-- | Symbolic representation of areas of the screen used to define the
--   meaning of mouse button presses relative to where the mouse points to.
data CmdArea
CaMessage :: CmdArea
CaMapLeader :: CmdArea
CaMapParty :: CmdArea
CaMap :: CmdArea
CaLevelNumber :: CmdArea
CaArenaName :: CmdArea
CaPercentSeen :: CmdArea
CaXhairDesc :: CmdArea
CaSelected :: CmdArea
CaCalmGauge :: CmdArea
CaCalmValue :: CmdArea
CaHPGauge :: CmdArea
CaHPValue :: CmdArea
CaLeaderDesc :: CmdArea
areaDescription :: CmdArea -> Text

-- | This triple of command categories, description and the command term
--   itself defines the meaning of a human command as entered via a
--   keypress, mouse click or chosen from a menu.
type CmdTriple = ([CmdCategory], Text, HumanCmd)
data AimModeCmd
AimModeCmd :: HumanCmd -> HumanCmd -> AimModeCmd
[exploration] :: AimModeCmd -> HumanCmd
[aiming] :: AimModeCmd -> HumanCmd

-- | Abstract syntax of human player commands.
data HumanCmd
Macro :: [String] -> HumanCmd
ByArea :: [(CmdArea, HumanCmd)] -> HumanCmd
ByAimMode :: AimModeCmd -> HumanCmd
ComposeIfLocal :: HumanCmd -> HumanCmd -> HumanCmd
ComposeUnlessError :: HumanCmd -> HumanCmd -> HumanCmd
Compose2ndLocal :: HumanCmd -> HumanCmd -> HumanCmd
LoopOnNothing :: HumanCmd -> HumanCmd
ExecuteIfClear :: HumanCmd -> HumanCmd
Wait :: HumanCmd
Wait10 :: HumanCmd
Yell :: HumanCmd
MoveDir :: Vector -> HumanCmd
RunDir :: Vector -> HumanCmd
RunOnceAhead :: HumanCmd
MoveOnceToXhair :: HumanCmd
RunOnceToXhair :: HumanCmd
ContinueToXhair :: HumanCmd
MoveItem :: [CStore] -> CStore -> Maybe Part -> Bool -> HumanCmd
Project :: HumanCmd
Apply :: HumanCmd
AlterDir :: [TriggerTile] -> HumanCmd
AlterWithPointer :: [TriggerTile] -> HumanCmd
Help :: HumanCmd
Hint :: HumanCmd
ItemMenu :: HumanCmd
MainMenu :: HumanCmd
MainMenuAutoOn :: HumanCmd
MainMenuAutoOff :: HumanCmd
Dashboard :: HumanCmd
GameDifficultyIncr :: HumanCmd
GameWolfToggle :: HumanCmd
GameFishToggle :: HumanCmd
GameScenarioIncr :: HumanCmd
GameRestart :: HumanCmd
GameQuit :: HumanCmd
GameDrop :: HumanCmd
GameExit :: HumanCmd
GameSave :: HumanCmd
Tactic :: HumanCmd
Automate :: HumanCmd
AutomateToggle :: HumanCmd
AutomateBack :: HumanCmd
ChooseItem :: ItemDialogMode -> HumanCmd
ChooseItemMenu :: ItemDialogMode -> HumanCmd
ChooseItemProject :: [TriggerItem] -> HumanCmd
ChooseItemApply :: [TriggerItem] -> HumanCmd
PickLeader :: Int -> HumanCmd
PickLeaderWithPointer :: HumanCmd
MemberCycle :: HumanCmd
MemberBack :: HumanCmd
SelectActor :: HumanCmd
SelectNone :: HumanCmd
SelectWithPointer :: HumanCmd
Repeat :: Int -> HumanCmd
Record :: HumanCmd
AllHistory :: HumanCmd
LastHistory :: HumanCmd
MarkVision :: HumanCmd
MarkSmell :: HumanCmd
MarkSuspect :: HumanCmd
SettingsMenu :: HumanCmd
ChallengesMenu :: HumanCmd
PrintScreen :: HumanCmd
Cancel :: HumanCmd
Accept :: HumanCmd
ClearTargetIfItemClear :: HumanCmd
ItemClear :: HumanCmd
MoveXhair :: Vector -> Int -> HumanCmd
AimTgt :: HumanCmd
AimFloor :: HumanCmd
AimEnemy :: HumanCmd
AimItem :: HumanCmd
AimAscend :: Int -> HumanCmd
EpsIncr :: Bool -> HumanCmd
XhairUnknown :: HumanCmd
XhairItem :: HumanCmd
XhairStair :: Bool -> HumanCmd
XhairPointerFloor :: HumanCmd
XhairPointerEnemy :: HumanCmd
AimPointerFloor :: HumanCmd
AimPointerEnemy :: HumanCmd

-- | Description of how item manipulation is triggered and communicated to
--   the player.
data TriggerItem
TriggerItem :: Part -> Part -> [Char] -> TriggerItem
[tiverb] :: TriggerItem -> Part
[tiobject] :: TriggerItem -> Part
[tisymbols] :: TriggerItem -> [Char]

-- | Description of how tile altering is triggered and communicated to the
--   player.
data TriggerTile
TriggerTile :: Part -> Part -> Feature -> TriggerTile
[ttverb] :: TriggerTile -> Part
[ttobject] :: TriggerTile -> Part
[ttfeature] :: TriggerTile -> Feature
instance GHC.Generics.Generic Game.LambdaHack.Client.UI.HumanCmd.AimModeCmd
instance GHC.Classes.Ord Game.LambdaHack.Client.UI.HumanCmd.AimModeCmd
instance GHC.Classes.Eq Game.LambdaHack.Client.UI.HumanCmd.AimModeCmd
instance GHC.Read.Read Game.LambdaHack.Client.UI.HumanCmd.AimModeCmd
instance GHC.Show.Show Game.LambdaHack.Client.UI.HumanCmd.AimModeCmd
instance GHC.Generics.Generic Game.LambdaHack.Client.UI.HumanCmd.HumanCmd
instance GHC.Classes.Ord Game.LambdaHack.Client.UI.HumanCmd.HumanCmd
instance GHC.Classes.Eq Game.LambdaHack.Client.UI.HumanCmd.HumanCmd
instance GHC.Read.Read Game.LambdaHack.Client.UI.HumanCmd.HumanCmd
instance GHC.Show.Show Game.LambdaHack.Client.UI.HumanCmd.HumanCmd
instance GHC.Generics.Generic Game.LambdaHack.Client.UI.HumanCmd.TriggerTile
instance GHC.Classes.Ord Game.LambdaHack.Client.UI.HumanCmd.TriggerTile
instance GHC.Classes.Eq Game.LambdaHack.Client.UI.HumanCmd.TriggerTile
instance GHC.Show.Show Game.LambdaHack.Client.UI.HumanCmd.TriggerTile
instance GHC.Generics.Generic Game.LambdaHack.Client.UI.HumanCmd.TriggerItem
instance GHC.Classes.Ord Game.LambdaHack.Client.UI.HumanCmd.TriggerItem
instance GHC.Classes.Eq Game.LambdaHack.Client.UI.HumanCmd.TriggerItem
instance GHC.Show.Show Game.LambdaHack.Client.UI.HumanCmd.TriggerItem
instance GHC.Generics.Generic Game.LambdaHack.Client.UI.HumanCmd.CmdArea
instance GHC.Classes.Ord Game.LambdaHack.Client.UI.HumanCmd.CmdArea
instance GHC.Classes.Eq Game.LambdaHack.Client.UI.HumanCmd.CmdArea
instance GHC.Read.Read Game.LambdaHack.Client.UI.HumanCmd.CmdArea
instance GHC.Show.Show Game.LambdaHack.Client.UI.HumanCmd.CmdArea
instance GHC.Generics.Generic Game.LambdaHack.Client.UI.HumanCmd.CmdCategory
instance GHC.Classes.Eq Game.LambdaHack.Client.UI.HumanCmd.CmdCategory
instance GHC.Read.Read Game.LambdaHack.Client.UI.HumanCmd.CmdCategory
instance GHC.Show.Show Game.LambdaHack.Client.UI.HumanCmd.CmdCategory
instance Control.DeepSeq.NFData Game.LambdaHack.Client.UI.HumanCmd.AimModeCmd
instance Data.Binary.Class.Binary Game.LambdaHack.Client.UI.HumanCmd.AimModeCmd
instance Control.DeepSeq.NFData Game.LambdaHack.Client.UI.HumanCmd.HumanCmd
instance Data.Binary.Class.Binary Game.LambdaHack.Client.UI.HumanCmd.HumanCmd
instance GHC.Read.Read Game.LambdaHack.Client.UI.HumanCmd.TriggerTile
instance Control.DeepSeq.NFData Game.LambdaHack.Client.UI.HumanCmd.TriggerTile
instance Data.Binary.Class.Binary Game.LambdaHack.Client.UI.HumanCmd.TriggerTile
instance GHC.Read.Read Game.LambdaHack.Client.UI.HumanCmd.TriggerItem
instance Control.DeepSeq.NFData Game.LambdaHack.Client.UI.HumanCmd.TriggerItem
instance Data.Binary.Class.Binary Game.LambdaHack.Client.UI.HumanCmd.TriggerItem
instance Control.DeepSeq.NFData Game.LambdaHack.Client.UI.HumanCmd.CmdArea
instance Data.Binary.Class.Binary Game.LambdaHack.Client.UI.HumanCmd.CmdArea
instance Control.DeepSeq.NFData Game.LambdaHack.Client.UI.HumanCmd.CmdCategory
instance Data.Binary.Class.Binary Game.LambdaHack.Client.UI.HumanCmd.CmdCategory


-- | UI client options.
module Game.LambdaHack.Client.UI.UIOptions

-- | Options that affect the UI of the client.
data UIOptions
UIOptions :: [(KM, CmdTriple)] -> [(Int, (Text, Text))] -> Bool -> Bool -> Text -> Text -> Int -> Int -> Int -> Int -> Int -> Bool -> Int -> Maybe [(MsgClass, Color)] -> [String] -> UIOptions
[uCommands] :: UIOptions -> [(KM, CmdTriple)]
[uHeroNames] :: UIOptions -> [(Int, (Text, Text))]

-- | the option for Vi keys takes precendence
[uVi] :: UIOptions -> Bool

-- | because the laptop keys are the default
[uLaptop] :: UIOptions -> Bool
[uGtkFontFamily] :: UIOptions -> Text
[uSdlFontFile] :: UIOptions -> Text
[uSdlScalableSizeAdd] :: UIOptions -> Int
[uSdlBitmapSizeAdd] :: UIOptions -> Int
[uScalableFontSize] :: UIOptions -> Int
[uHistoryMax] :: UIOptions -> Int
[uMaxFps] :: UIOptions -> Int
[uNoAnim] :: UIOptions -> Bool

-- | HP percent at which warning is emitted.
[uhpWarningPercent] :: UIOptions -> Int
[uMessageColors] :: UIOptions -> Maybe [(MsgClass, Color)]

-- | Hardwired commandline arguments to process.
[uCmdline] :: UIOptions -> [String]
instance GHC.Generics.Generic Game.LambdaHack.Client.UI.UIOptions.UIOptions
instance GHC.Show.Show Game.LambdaHack.Client.UI.UIOptions.UIOptions
instance Control.DeepSeq.NFData Game.LambdaHack.Client.UI.UIOptions.UIOptions
instance Data.Binary.Class.Binary Game.LambdaHack.Client.UI.UIOptions.UIOptions


-- | The type of definitions of key-command mappings to be used for the UI
--   and shorthands for specifying command triples in the content files.
module Game.LambdaHack.Client.UI.Content.Input

-- | Key-command mappings to be specified in content and used for the UI.
newtype InputContentRaw
InputContentRaw :: [(KM, CmdTriple)] -> InputContentRaw

-- | Bindings and other information about human player commands.
data InputContent
InputContent :: Map KM CmdTriple -> [(KM, CmdTriple)] -> Map HumanCmd [KM] -> InputContent

-- | binding of keys to commands
[bcmdMap] :: InputContent -> Map KM CmdTriple

-- | the properly ordered list of commands for the help menu
[bcmdList] :: InputContent -> [(KM, CmdTriple)]

-- | and from commands to their keys
[brevMap] :: InputContent -> Map HumanCmd [KM]

-- | Create binding of keys to movement and other standard commands, as
--   well as commands defined in the config file.
makeData :: UIOptions -> InputContentRaw -> InputContent
evalKeyDef :: (String, CmdTriple) -> (KM, CmdTriple)
addCmdCategory :: CmdCategory -> CmdTriple -> CmdTriple
replaceDesc :: Text -> CmdTriple -> CmdTriple
moveItemTriple :: [CStore] -> CStore -> Part -> Bool -> CmdTriple
repeatTriple :: Int -> CmdTriple
mouseLMB :: HumanCmd -> Text -> CmdTriple
mouseMMB :: CmdTriple
mouseRMB :: CmdTriple
goToCmd :: HumanCmd
runToAllCmd :: HumanCmd
autoexploreCmd :: HumanCmd
autoexplore25Cmd :: HumanCmd
aimFlingCmd :: HumanCmd
projectI :: [TriggerItem] -> CmdTriple
projectA :: [TriggerItem] -> CmdTriple
flingTs :: [TriggerItem]
applyIK :: [TriggerItem] -> CmdTriple
applyI :: [TriggerItem] -> CmdTriple
grabItems :: Text -> CmdTriple
dropItems :: Text -> CmdTriple
descIs :: [TriggerItem] -> Text
descTs :: [TriggerTile] -> Text
defaultHeroSelect :: Int -> (String, CmdTriple)
replaceCmd :: HumanCmd -> CmdTriple -> CmdTriple
projectICmd :: [TriggerItem] -> HumanCmd
grabCmd :: HumanCmd
dropCmd :: HumanCmd


-- | General content types and operations.
module Game.LambdaHack.Client.UI.ContentClientUI

-- | Operations for all content types, gathered together.
data CCUI
CCUI :: InputContent -> ScreenContent -> CCUI
[coinput] :: CCUI -> InputContent
[coscreen] :: CCUI -> ScreenContent
emptyCCUI :: CCUI


-- | Line terminal text frontend based on stdin/stdout, intended for
--   logging tests, but may be used on a teletype terminal, or with
--   keyboard and printer.
module Game.LambdaHack.Client.UI.Frontend.Teletype

-- | Set up the frontend input and output.
startup :: ScreenContent -> IO RawFrontend

-- | The name of the frontend.
frontendName :: String


-- | Text frontend based on SDL2.
module Game.LambdaHack.Client.UI.Frontend.Sdl

-- | Set up and start the main loop providing input and output.
--   
--   Because of Windows and OS X, SDL2 needs to be on a bound thread, so we
--   can't avoid the communication overhead of bound threads.
startup :: ScreenContent -> ClientOptions -> IO RawFrontend

-- | The name of the frontend.
frontendName :: String
type FontAtlas = EnumMap AttrCharW32 Texture

-- | Session data maintained by the frontend.
data FrontendSession
FrontendSession :: Window -> Renderer -> Font -> IORef FontAtlas -> IORef Texture -> IORef SingleFrame -> IORef Bool -> IORef Bool -> MVar SingleFrame -> MVar () -> FrontendSession
[swindow] :: FrontendSession -> Window
[srenderer] :: FrontendSession -> Renderer
[sfont] :: FrontendSession -> Font
[satlas] :: FrontendSession -> IORef FontAtlas
[stexture] :: FrontendSession -> IORef Texture
[spreviousFrame] :: FrontendSession -> IORef SingleFrame
[sforcedShutdown] :: FrontendSession -> IORef Bool
[scontinueSdlLoop] :: FrontendSession -> IORef Bool
[sframeQueue] :: FrontendSession -> MVar SingleFrame
[sframeDrawn] :: FrontendSession -> MVar ()
startupFun :: ScreenContent -> ClientOptions -> MVar RawFrontend -> IO ()
shutdown :: FrontendSession -> IO ()
forceShutdown :: FrontendSession -> IO ()

-- | Add a frame to be drawn.
display :: FrontendSession -> SingleFrame -> IO ()
drawFrame :: ClientOptions -> FrontendSession -> SingleFrame -> IO ()
printScreen :: FrontendSession -> IO ()

-- | Translates modifiers to our own encoding.
modTranslate :: KeyModifier -> Modifier
keyTranslate :: Bool -> Keycode -> Key
colorToRGBA :: Color -> V4 Word8


-- | Re-export the operations of the chosen raw frontend (determined at
--   compile time with cabal flags).
module Game.LambdaHack.Client.UI.Frontend.Chosen

-- | Set up and start the main loop providing input and output.
--   
--   Because of Windows and OS X, SDL2 needs to be on a bound thread, so we
--   can't avoid the communication overhead of bound threads.
startup :: ScreenContent -> ClientOptions -> IO RawFrontend

-- | The name of the frontend.
frontendName :: String


-- | Display game data on the screen and receive user input using one of
--   the available raw frontends and derived operations.
module Game.LambdaHack.Client.UI.Frontend

-- | The instructions sent by clients to the raw frontend, indexed by the
--   returned value.
data FrontReq :: * -> *

-- | Show a frame.
[FrontFrame] :: Frame -> FrontReq ()

-- | Perform an explicit delay of the given length.
[FrontDelay] :: Int -> FrontReq ()

-- | Flush frames, display a frame and ask for a keypress.
[FrontKey] :: [KM] -> Frame -> FrontReq KMP

-- | Tell if a keypress is pending.
[FrontPressed] :: FrontReq Bool

-- | Discard a key in the queue, if any.
[FrontDiscardKey] :: FrontReq ()

-- | Discard all keys in the queue.
[FrontResetKeys] :: FrontReq ()

-- | Add a key to the queue.
[FrontAdd] :: KMP -> FrontReq ()

-- | Set in the frontend that it should auto-answer prompts.
[FrontAutoYes] :: Bool -> FrontReq ()

-- | Shut the frontend down.
[FrontShutdown] :: FrontReq ()

-- | Take screenshot.
[FrontPrintScreen] :: FrontReq ()

-- | Connection channel between a frontend and a client. Frontend acts as a
--   server, serving keys, etc., when given frames to display.
newtype ChanFrontend
ChanFrontend :: (forall a. FrontReq a -> IO a) -> ChanFrontend

-- | Initialize the frontend chosen by the player via client options.
chanFrontendIO :: ScreenContent -> ClientOptions -> IO ChanFrontend

-- | The name of the chosen frontend.
frontendName :: String

-- | Machinery allocated for an individual frontend at its startup,
--   unchanged for its lifetime.
data FrontSetup
getKey :: FrontSetup -> RawFrontend -> [KM] -> Frame -> IO KMP
fchanFrontend :: FrontSetup -> RawFrontend -> ChanFrontend
display :: RawFrontend -> Frame -> IO ()
defaultMaxFps :: Int
microInSec :: Int
frameTimeoutThread :: Int -> MVar Int -> RawFrontend -> IO ()
lazyStartup :: ScreenContent -> IO RawFrontend
nullStartup :: ScreenContent -> IO RawFrontend
seqFrame :: SingleFrame -> IO ()


-- | Terrain tile definitions.
module Content.TileKind
content :: [TileKind]


-- | Room, hall and passage definitions.
module Content.PlaceKind
content :: [PlaceKind]


-- | The default game key-command mapping to be used for UI. Can be
--   overridden via macros in the config file.
module Client.UI.Content.Input

-- | Description of default key-command bindings.
--   
--   In addition to these commands, mouse and keys have a standard meaning
--   when navigating various menus.
standardKeysAndMouse :: InputContentRaw
closeDoorTriggers :: [TriggerTile]
applyTs :: [TriggerItem]


-- | The type of cave kinds.
module Game.LambdaHack.Content.CaveKind

-- | Parameters for the generation of dungeon levels. Warning: for
--   efficiency, avoid embedded items in any of the common tiles.
data CaveKind
CaveKind :: Char -> Text -> Freqs CaveKind -> X -> Y -> DiceXY -> DiceXY -> DiceXY -> Dice -> Dice -> Rational -> Rational -> Int -> Dice -> Chance -> Chance -> Int -> Int -> Freqs ItemKind -> Dice -> Freqs ItemKind -> Freqs PlaceKind -> Bool -> Bool -> GroupName TileKind -> GroupName TileKind -> GroupName TileKind -> GroupName TileKind -> GroupName TileKind -> GroupName TileKind -> GroupName TileKind -> GroupName TileKind -> GroupName TileKind -> Bool -> GroupName TileKind -> GroupName TileKind -> Freqs PlaceKind -> Freqs PlaceKind -> Freqs PlaceKind -> Text -> CaveKind

-- | a symbol
[csymbol] :: CaveKind -> Char

-- | short description
[cname] :: CaveKind -> Text

-- | frequency within groups
[cfreq] :: CaveKind -> Freqs CaveKind

-- | minimal X size of the whole cave
[cXminSize] :: CaveKind -> X

-- | minimal Y size of the whole cave
[cYminSize] :: CaveKind -> Y

-- | size of a map cell holding a place
[ccellSize] :: CaveKind -> DiceXY

-- | minimal size of places; for merging
[cminPlaceSize] :: CaveKind -> DiceXY

-- | maximal size of places; for growing
[cmaxPlaceSize] :: CaveKind -> DiceXY

-- | the odds a place is dark (level-scaled dice roll &gt; 50)
[cdarkOdds] :: CaveKind -> Dice

-- | the odds the cave is dark (level-scaled dice roll &gt; 50)
[cnightOdds] :: CaveKind -> Dice

-- | a proportion of extra connections
[cauxConnects] :: CaveKind -> Rational

-- | at most this proportion of rooms may be void
[cmaxVoid] :: CaveKind -> Rational

-- | minimal distance between stairs
[cminStairDist] :: CaveKind -> Int

-- | extra stairs on top of from above
[cextraStairs] :: CaveKind -> Dice

-- | the chance of a door in an opening
[cdoorChance] :: CaveKind -> Chance

-- | if there's a door, is it open?
[copenChance] :: CaveKind -> Chance

-- | if not open, hidden one in n times
[chidden] :: CaveKind -> Int

-- | the lower, the more monsters spawn
[cactorCoeff] :: CaveKind -> Int

-- | actor groups to consider
[cactorFreq] :: CaveKind -> Freqs ItemKind

-- | number of initial items in the cave
[citemNum] :: CaveKind -> Dice

-- | item groups to consider
[citemFreq] :: CaveKind -> Freqs ItemKind

-- | place groups to consider
[cplaceFreq] :: CaveKind -> Freqs PlaceKind

-- | are passable default tiles permitted
[cpassable] :: CaveKind -> Bool

-- | waste of time for AI to explore
[labyrinth] :: CaveKind -> Bool

-- | the default cave tile
[cdefTile] :: CaveKind -> GroupName TileKind

-- | the dark cave corridor tile
[cdarkCorTile] :: CaveKind -> GroupName TileKind

-- | the lit cave corridor tile
[clitCorTile] :: CaveKind -> GroupName TileKind

-- | the tile used for <tt>FWall</tt> fence
[cwallTile] :: CaveKind -> GroupName TileKind

-- | tile used for the fence corners
[ccornerTile] :: CaveKind -> GroupName TileKind

-- | the outer fence N wall
[cfenceTileN] :: CaveKind -> GroupName TileKind

-- | the outer fence E wall
[cfenceTileE] :: CaveKind -> GroupName TileKind

-- | the outer fence S wall
[cfenceTileS] :: CaveKind -> GroupName TileKind

-- | the outer fence W wall
[cfenceTileW] :: CaveKind -> GroupName TileKind

-- | are places touching fence banned
[cfenceApart] :: CaveKind -> Bool

-- | the dark place plan legend
[clegendDarkTile] :: CaveKind -> GroupName TileKind

-- | the lit place plan legend
[clegendLitTile] :: CaveKind -> GroupName TileKind

-- | escape groups, if any
[cescapeFreq] :: CaveKind -> Freqs PlaceKind

-- | place groups for created stairs
[cstairFreq] :: CaveKind -> Freqs PlaceKind

-- | extra groups for inherited
[cstairAllowed] :: CaveKind -> Freqs PlaceKind

-- | full cave description
[cdesc] :: CaveKind -> Text
makeData :: ContentData ItemKind -> ContentData PlaceKind -> ContentData TileKind -> [CaveKind] -> ContentData CaveKind

-- | Catch caves with not enough space for all the places. Check the size
--   of the cave descriptions to make sure they fit on screen. Etc.
validateSingle :: CaveKind -> [Text]

-- | Validate all cave kinds. Note that names don't have to be unique: we
--   can have several variants of a cave with a given name.
validateAll :: ContentData ItemKind -> ContentData PlaceKind -> ContentData TileKind -> [CaveKind] -> ContentData CaveKind -> [Text]
instance GHC.Show.Show Game.LambdaHack.Content.CaveKind.CaveKind


-- | The type of kinds of game modes.
module Game.LambdaHack.Content.ModeKind

-- | Game mode specification.
data ModeKind
ModeKind :: Char -> Text -> Freqs ModeKind -> Roster -> Caves -> [(Outcome, Text)] -> Text -> ModeKind

-- | a symbol
[msymbol] :: ModeKind -> Char

-- | short description
[mname] :: ModeKind -> Text

-- | frequency within groups
[mfreq] :: ModeKind -> Freqs ModeKind

-- | players taking part in the game
[mroster] :: ModeKind -> Roster

-- | arena of the game
[mcaves] :: ModeKind -> Caves

-- | messages displayed at particular game ends; if no message, the screen
--   is skipped
[mendMsg] :: ModeKind -> [(Outcome, Text)]

-- | description
[mdesc] :: ModeKind -> Text
makeData :: ContentData CaveKind -> ContentData ItemKind -> [ModeKind] -> ContentData ModeKind

-- | Requested cave groups for particular level intervals.
type Caves = [([Int], [GroupName CaveKind])]

-- | The specification of players for the game mode.
data Roster
Roster :: [(Player, [(Int, Dice, GroupName ItemKind)])] -> [(Text, Text)] -> [(Text, Text)] -> Roster

-- | players in the particular team and levels, numbers and groups of their
--   initial members
[rosterList] :: Roster -> [(Player, [(Int, Dice, GroupName ItemKind)])]

-- | the initial enmity matrix
[rosterEnemy] :: Roster -> [(Text, Text)]

-- | the initial aliance matrix
[rosterAlly] :: Roster -> [(Text, Text)]

-- | Outcome of a game.
data Outcome

-- | the faction was eliminated
Killed :: Outcome

-- | the faction lost the game in another way
Defeated :: Outcome

-- | game is supended
Camping :: Outcome

-- | the player won by eliminating all rivals
Conquer :: Outcome

-- | the player escaped the dungeon alive
Escape :: Outcome

-- | game is restarted
Restart :: Outcome

-- | Conditional polynomial representing score calculation for this player.
type HiCondPoly = [HiSummand]
type HiSummand = (HiPolynomial, [Outcome])
type HiPolynomial = [(HiIndeterminant, Double)]
data HiIndeterminant
HiConst :: HiIndeterminant
HiLoot :: HiIndeterminant
HiSprint :: HiIndeterminant
HiBlitz :: HiIndeterminant
HiSurvival :: HiIndeterminant
HiKill :: HiIndeterminant
HiLoss :: HiIndeterminant

-- | Properties of a particular player.
data Player
Player :: Text -> [GroupName ItemKind] -> Skills -> Bool -> Bool -> HiCondPoly -> Bool -> Tactic -> LeaderMode -> Bool -> Player

-- | name of the player
[fname] :: Player -> Text

-- | names of actor groups that may naturally fall under player's control,
--   e.g., upon spawning or summoning
[fgroups] :: Player -> [GroupName ItemKind]

-- | fixed skill modifiers to the non-leader actors; also summed with
--   skills implied by ftactic (which is not fixed)
[fskillsOther] :: Player -> Skills

-- | the player can escape the dungeon
[fcanEscape] :: Player -> Bool

-- | the faction declared killed if no actors
[fneverEmpty] :: Player -> Bool

-- | score polynomial for the player
[fhiCondPoly] :: Player -> HiCondPoly

-- | whether actors have gender
[fhasGender] :: Player -> Bool

-- | non-leaders behave according to this tactic; can be changed during the
--   game
[ftactic] :: Player -> Tactic

-- | the mode of switching the leader
[fleaderMode] :: Player -> LeaderMode

-- | does the faction have a UI client (for control or passive observation)
[fhasUI] :: Player -> Bool

-- | If a faction with <tt>LeaderUI</tt> and <tt>LeaderAI</tt> has any
--   actor, it has a leader.
data LeaderMode

-- | faction can have no leader, is whole under AI control
LeaderNull :: LeaderMode

-- | leader under AI control
LeaderAI :: AutoLeader -> LeaderMode

-- | leader under UI control, assumes <tt>fhasUI</tt>
LeaderUI :: AutoLeader -> LeaderMode
data AutoLeader
AutoLeader :: Bool -> Bool -> AutoLeader

-- | leader switching between levels is automatically done by the server
--   and client is not permitted to change to leaders from other levels
--   (the frequency of leader level switching done by the server is
--   controlled by <tt>RuleKind.rleadLevelClips</tt>); if the flag is
--   <tt>False</tt>, server still does a subset of the automatic switching,
--   e.g., when the old leader dies and no other actor of the faction
--   resides on his level, but the client (particularly UI) is expected to
--   do changes as well
[autoDungeon] :: AutoLeader -> Bool

-- | client is discouraged from leader switching (e.g., because non-leader
--   actors have the same skills as leader); server is guaranteed to switch
--   leader within a level very rarely, e.g., when the old leader dies; if
--   the flag is <tt>False</tt>, server still does a subset of the
--   automatic switching, but the client is expected to do more, because
--   it's advantageous for that kind of a faction
[autoLevel] :: AutoLeader -> Bool
horrorGroup :: GroupName ItemKind
genericEndMessages :: [(Outcome, Text)]

-- | Catch invalid game mode kind definitions.
validateSingle :: ModeKind -> [Text]

-- | Validate game mode kinds together.
validateAll :: ContentData CaveKind -> ContentData ItemKind -> [ModeKind] -> ContentData ModeKind -> [Text]

-- | Checks, in particular, that there is at least one faction with
--   fneverEmpty or the game would get stuck as soon as the dungeon is
--   devoid of actors.
validateSingleRoster :: Caves -> Roster -> [Text]
validateSinglePlayer :: Player -> [Text]
hardwiredModeGroups :: [GroupName ModeKind]
instance GHC.Show.Show Game.LambdaHack.Content.ModeKind.ModeKind
instance GHC.Show.Show Game.LambdaHack.Content.ModeKind.Roster
instance GHC.Generics.Generic Game.LambdaHack.Content.ModeKind.Player
instance GHC.Classes.Eq Game.LambdaHack.Content.ModeKind.Player
instance GHC.Show.Show Game.LambdaHack.Content.ModeKind.Player
instance GHC.Generics.Generic Game.LambdaHack.Content.ModeKind.LeaderMode
instance GHC.Classes.Ord Game.LambdaHack.Content.ModeKind.LeaderMode
instance GHC.Classes.Eq Game.LambdaHack.Content.ModeKind.LeaderMode
instance GHC.Show.Show Game.LambdaHack.Content.ModeKind.LeaderMode
instance GHC.Generics.Generic Game.LambdaHack.Content.ModeKind.AutoLeader
instance GHC.Classes.Ord Game.LambdaHack.Content.ModeKind.AutoLeader
instance GHC.Classes.Eq Game.LambdaHack.Content.ModeKind.AutoLeader
instance GHC.Show.Show Game.LambdaHack.Content.ModeKind.AutoLeader
instance GHC.Generics.Generic Game.LambdaHack.Content.ModeKind.HiIndeterminant
instance GHC.Classes.Ord Game.LambdaHack.Content.ModeKind.HiIndeterminant
instance GHC.Classes.Eq Game.LambdaHack.Content.ModeKind.HiIndeterminant
instance GHC.Show.Show Game.LambdaHack.Content.ModeKind.HiIndeterminant
instance GHC.Generics.Generic Game.LambdaHack.Content.ModeKind.Outcome
instance GHC.Enum.Bounded Game.LambdaHack.Content.ModeKind.Outcome
instance GHC.Enum.Enum Game.LambdaHack.Content.ModeKind.Outcome
instance GHC.Classes.Ord Game.LambdaHack.Content.ModeKind.Outcome
instance GHC.Classes.Eq Game.LambdaHack.Content.ModeKind.Outcome
instance GHC.Show.Show Game.LambdaHack.Content.ModeKind.Outcome
instance Data.Binary.Class.Binary Game.LambdaHack.Content.ModeKind.Player
instance Data.Binary.Class.Binary Game.LambdaHack.Content.ModeKind.LeaderMode
instance Data.Binary.Class.Binary Game.LambdaHack.Content.ModeKind.AutoLeader
instance Data.Binary.Class.Binary Game.LambdaHack.Content.ModeKind.HiIndeterminant
instance Data.Binary.Class.Binary Game.LambdaHack.Content.ModeKind.Outcome


-- | Basic players definitions.
module Content.ModeKindPlayer
playerHero :: Player
playerAntiHero :: Player
playerCivilian :: Player
playerMonster :: Player
playerAntiMonster :: Player
playerAnimal :: Player

-- | A special player, for summoned actors that don't belong to any of the
--   main players of a given game. E.g., animals summoned during a brawl
--   game between two hero factions land in the horror faction. In every
--   game, either all factions for which summoning items exist should be
--   present or a horror player should be added to host them.
playerHorror :: Player
playerMonsterTourist :: Player
playerHunamConvict :: Player
playerAnimalMagnificent :: Player
playerAnimalExquisite :: Player
hiHeroShort :: HiCondPoly
hiHeroMedium :: HiCondPoly
hiHeroLong :: HiCondPoly
hiDweller :: HiCondPoly


-- | Game mode definitions.
module Content.ModeKind
content :: [ModeKind]


-- | Cave properties.
module Content.CaveKind
content :: [CaveKind]


-- | The type of item aspects and its operations.
module Game.LambdaHack.Common.ItemAspect

-- | Record of skills conferred by an item as well as of item flags and
--   other item aspects.
data AspectRecord
AspectRecord :: Int -> Skills -> Flags -> Text -> ThrowMod -> Maybe (GroupName ItemKind) -> Maybe EqpSlot -> AspectRecord
[aTimeout] :: AspectRecord -> Int
[aSkills] :: AspectRecord -> Skills
[aFlags] :: AspectRecord -> Flags
[aELabel] :: AspectRecord -> Text
[aToThrow] :: AspectRecord -> ThrowMod
[aHideAs] :: AspectRecord -> Maybe (GroupName ItemKind)
[aEqpSlot] :: AspectRecord -> Maybe EqpSlot

-- | Partial information about an item, deduced from its item kind. These
--   are assigned to each <a>ItemKind</a>. The <tt>kmConst</tt> flag says
--   whether the item's aspect record is constant rather than random or
--   dependent on item creation dungeon level.
data KindMean
KindMean :: Bool -> AspectRecord -> KindMean

-- | whether the item doesn't need second identification
[kmConst] :: KindMean -> Bool

-- | mean value of item's possible aspect records
[kmMean] :: KindMean -> AspectRecord
emptyAspectRecord :: AspectRecord
addMeanAspect :: AspectRecord -> Aspect -> AspectRecord
castAspect :: AbsDepth -> AbsDepth -> AspectRecord -> Aspect -> Rnd AspectRecord
aspectsRandom :: [Aspect] -> Bool
aspectRecordToList :: AspectRecord -> [Aspect]
rollAspectRecord :: [Aspect] -> AbsDepth -> AbsDepth -> Rnd AspectRecord
getSkill :: Skill -> AspectRecord -> Int
checkFlag :: Flag -> AspectRecord -> Bool
meanAspect :: ItemKind -> AspectRecord
onlyMinorEffects :: AspectRecord -> ItemKind -> Bool
itemTrajectory :: AspectRecord -> ItemKind -> [Point] -> ([Vector], (Speed, Int))
totalRange :: AspectRecord -> ItemKind -> Int
isHumanTrinket :: ItemKind -> Bool
goesIntoEqp :: AspectRecord -> Bool
goesIntoInv :: AspectRecord -> Bool
goesIntoSha :: AspectRecord -> Bool
loreFromMode :: ItemDialogMode -> SLore
loreFromContainer :: AspectRecord -> Container -> SLore
ceilingMeanDice :: Dice -> Int
instance GHC.Generics.Generic Game.LambdaHack.Common.ItemAspect.KindMean
instance GHC.Classes.Ord Game.LambdaHack.Common.ItemAspect.KindMean
instance GHC.Classes.Eq Game.LambdaHack.Common.ItemAspect.KindMean
instance GHC.Show.Show Game.LambdaHack.Common.ItemAspect.KindMean
instance GHC.Generics.Generic Game.LambdaHack.Common.ItemAspect.AspectRecord
instance GHC.Classes.Ord Game.LambdaHack.Common.ItemAspect.AspectRecord
instance GHC.Classes.Eq Game.LambdaHack.Common.ItemAspect.AspectRecord
instance GHC.Show.Show Game.LambdaHack.Common.ItemAspect.AspectRecord
instance Data.Hashable.Class.Hashable Game.LambdaHack.Common.ItemAspect.AspectRecord
instance Data.Binary.Class.Binary Game.LambdaHack.Common.ItemAspect.AspectRecord


-- | General content types and operations.
module Game.LambdaHack.Common.Kind

-- | Verified and preprocessed content data of a particular kind.
data ContentData c

-- | Operations for all content types, gathered together.
data COps
COps :: ContentData CaveKind -> ContentData ItemKind -> ContentData ModeKind -> ContentData PlaceKind -> RuleContent -> ContentData TileKind -> ItemSpeedup -> TileSpeedup -> COps
[cocave] :: COps -> ContentData CaveKind
[coitem] :: COps -> ContentData ItemKind
[comode] :: COps -> ContentData ModeKind
[coplace] :: COps -> ContentData PlaceKind
[corule] :: COps -> RuleContent
[cotile] :: COps -> ContentData TileKind
[coItemSpeedup] :: COps -> ItemSpeedup
[coTileSpeedup] :: COps -> TileSpeedup
emptyCOps :: COps

-- | Map from an item kind identifier to the mean aspect value for the
--   kind.
data ItemSpeedup
emptyItemSpeedup :: ItemSpeedup
getKindMean :: ContentId ItemKind -> ItemSpeedup -> KindMean
speedupItem :: ContentData ItemKind -> ItemSpeedup

-- | A lot of tabulated maps from tile kind identifier to a property of the
--   tile kind.
data TileSpeedup
TileSpeedup :: Tab Bool -> Tab Bool -> Tab Bool -> Tab Bool -> Tab Bool -> Tab Bool -> Tab Bool -> Tab Bool -> Tab Bool -> Tab Bool -> Tab Bool -> Tab Bool -> Tab Bool -> Tab Bool -> Tab Bool -> Tab Bool -> Tab Word8 -> Tab Word8 -> TileSpeedup
[isClearTab] :: TileSpeedup -> Tab Bool
[isLitTab] :: TileSpeedup -> Tab Bool
[isWalkableTab] :: TileSpeedup -> Tab Bool
[isDoorTab] :: TileSpeedup -> Tab Bool
[isChangableTab] :: TileSpeedup -> Tab Bool
[isSuspectTab] :: TileSpeedup -> Tab Bool
[isHideAsTab] :: TileSpeedup -> Tab Bool
[consideredByAITab] :: TileSpeedup -> Tab Bool
[isVeryOftenItemTab] :: TileSpeedup -> Tab Bool
[isCommonItemTab] :: TileSpeedup -> Tab Bool
[isOftenActorTab] :: TileSpeedup -> Tab Bool
[isNoItemTab] :: TileSpeedup -> Tab Bool
[isNoActorTab] :: TileSpeedup -> Tab Bool
[isEasyOpenTab] :: TileSpeedup -> Tab Bool
[isEmbedTab] :: TileSpeedup -> Tab Bool
[isAquaticTab] :: TileSpeedup -> Tab Bool
[alterMinSkillTab] :: TileSpeedup -> Tab Word8
[alterMinWalkTab] :: TileSpeedup -> Tab Word8

-- | A map morally indexed by <tt>ContentId TileKind</tt>.
newtype Tab a
Tab :: Vector a -> Tab a
emptyTileSpeedup :: TileSpeedup
emptyTab :: Unbox a => Tab a

-- | Content element at given id.
okind :: ContentData a -> ContentId a -> a
omemberGroup :: ContentData a -> GroupName a -> Bool
oisSingletonGroup :: ContentData a -> GroupName a -> Bool

-- | The id of the unique member of a singleton content group.
ouniqGroup :: Show a => ContentData a -> GroupName a -> ContentId a

-- | Pick a random id belonging to a group and satisfying a predicate.
opick :: Show a => ContentData a -> GroupName a -> (a -> Bool) -> Rnd (Maybe (ContentId a))

-- | Fold strictly over all content <tt>a</tt>.
ofoldlWithKey' :: ContentData a -> (b -> ContentId a -> a -> b) -> b -> b

-- | Fold over the given group only.
ofoldlGroup' :: ContentData a -> GroupName a -> (b -> Int -> ContentId a -> a -> b) -> b -> b
omapVector :: ContentData a -> (a -> b) -> Vector b
oimapVector :: ContentData a -> (ContentId a -> a -> b) -> Vector b

-- | Size of content <tt>a</tt>.
olength :: ContentData a -> Int
linearInterpolation :: Int -> Int -> Rarity -> Int
instance GHC.Show.Show Game.LambdaHack.Common.Kind.COps
instance GHC.Classes.Eq Game.LambdaHack.Common.Kind.COps


-- | Operations concerning dungeon level tiles.
--   
--   Unlike for many other content types, there is no type <tt>Tile</tt>,
--   of particular concrete tiles in the dungeon, corresponding to
--   <a>TileKind</a> (the type of kinds of terrain tiles). This is because
--   the tiles are too numerous and there's not enough storage space for a
--   well-rounded <tt>Tile</tt> type, on one hand, and on the other hand,
--   tiles are accessed too often in performance critical code to try to
--   compress their representation and/or recompute them. Instead, of
--   defining a <tt>Tile</tt> type, we express various properties of
--   concrete tiles by arrays or sparse EnumMaps, as appropriate.
--   
--   Actors at normal speed (2 m/s) take one turn to move one tile (1 m by
--   1 m).
module Game.LambdaHack.Common.Tile
speedupTile :: Bool -> ContentData TileKind -> TileSpeedup

-- | Whether a tile does not block vision. Essential for efficiency of
--   <a>FOV</a>, hence tabulated.
isClear :: TileSpeedup -> ContentId TileKind -> Bool

-- | Whether a tile has ambient light --- is lit on its own. Essential for
--   efficiency of <a>Perception</a>, hence tabulated.
isLit :: TileSpeedup -> ContentId TileKind -> Bool

-- | Whether actors can walk into a tile. Essential for efficiency of
--   pathfinding, hence tabulated.
isWalkable :: TileSpeedup -> ContentId TileKind -> Bool

-- | Whether a tile is a door, open or closed. Essential for efficiency of
--   pathfinding, hence tabulated.
isDoor :: TileSpeedup -> ContentId TileKind -> Bool

-- | Whether a tile is changable.
isChangable :: TileSpeedup -> ContentId TileKind -> Bool

-- | Whether a tile is suspect. Essential for efficiency of pathfinding,
--   hence tabulated.
isSuspect :: TileSpeedup -> ContentId TileKind -> Bool
isHideAs :: TileSpeedup -> ContentId TileKind -> Bool
consideredByAI :: TileSpeedup -> ContentId TileKind -> Bool

-- | Whether one can easily explore a tile, possibly finding a treasure,
--   either spawned there or dropped there by a (dying from poison) foe.
--   Doors can't be explorable since revealing a secret tile should not
--   change it's (walkable and) explorable status. Door status should not
--   depend on whether they are open or not so that a foe opening a door
--   doesn't force us to backtrack to explore it. Still, a foe that digs
--   through a wall will affect our exploration counter and if content lets
--   walls contain threasure, such backtraking makes sense.
isExplorable :: TileSpeedup -> ContentId TileKind -> Bool
isVeryOftenItem :: TileSpeedup -> ContentId TileKind -> Bool
isCommonItem :: TileSpeedup -> ContentId TileKind -> Bool
isOftenActor :: TileSpeedup -> ContentId TileKind -> Bool
isNoItem :: TileSpeedup -> ContentId TileKind -> Bool
isNoActor :: TileSpeedup -> ContentId TileKind -> Bool

-- | Whether a tile kind (specified by its id) has an <tt>OpenTo</tt>
--   feature or is walkable even without opening.
isEasyOpen :: TileSpeedup -> ContentId TileKind -> Bool
isEmbed :: TileSpeedup -> ContentId TileKind -> Bool
isAquatic :: TileSpeedup -> ContentId TileKind -> Bool
alterMinSkill :: TileSpeedup -> ContentId TileKind -> Int
alterMinWalk :: TileSpeedup -> ContentId TileKind -> Int

-- | Whether a tile kind has the given feature.
kindHasFeature :: Feature -> TileKind -> Bool

-- | Whether a tile kind (specified by its id) has the given feature.
hasFeature :: ContentData TileKind -> Feature -> ContentId TileKind -> Bool
openTo :: ContentData TileKind -> ContentId TileKind -> Rnd (ContentId TileKind)
closeTo :: ContentData TileKind -> ContentId TileKind -> Rnd (ContentId TileKind)
embeddedItems :: ContentData TileKind -> ContentId TileKind -> [GroupName ItemKind]
revealAs :: ContentData TileKind -> ContentId TileKind -> Rnd (ContentId TileKind)
obscureAs :: ContentData TileKind -> ContentId TileKind -> Rnd (ContentId TileKind)
hideAs :: ContentData TileKind -> ContentId TileKind -> Maybe (ContentId TileKind)
buildAs :: ContentData TileKind -> ContentId TileKind -> ContentId TileKind
isEasyOpenKind :: TileKind -> Bool

-- | Whether a tile kind (specified by its id) has an OpenTo feature.
isOpenable :: ContentData TileKind -> ContentId TileKind -> Bool

-- | Whether a tile kind (specified by its id) has a CloseTo feature.
isClosable :: ContentData TileKind -> ContentId TileKind -> Bool
isModifiable :: TileSpeedup -> ContentId TileKind -> Bool
createTab :: Unbox a => ContentData TileKind -> (TileKind -> a) -> Tab a
createTabWithKey :: Unbox a => ContentData TileKind -> (ContentId TileKind -> TileKind -> a) -> Tab a
accessTab :: Unbox a => Tab a -> ContentId TileKind -> a
alterMinSkillKind :: ContentId TileKind -> TileKind -> Word8
alterMinWalkKind :: ContentId TileKind -> TileKind -> Word8


-- | Saving and restoring game state, used by both server and clients.
module Game.LambdaHack.Common.Save
type ChanSave a = MVar (Maybe a)
saveToChan :: ChanSave a -> a -> IO ()
wrapInSaves :: Binary a => COps -> (a -> FilePath) -> (ChanSave a -> IO ()) -> IO ()

-- | Restore a saved game, if it exists. Initialize directory structure and
--   copy over data files, if needed.
restoreGame :: Binary a => COps -> FilePath -> IO (Maybe a)
saveNameCli :: COps -> FactionId -> String
saveNameSer :: COps -> String
compatibleVersion :: Version -> Version -> Bool

-- | Repeatedly save serialized snapshots of current state.
--   
--   Running with <tt>-N2</tt> ca reduce <tt>Max pause</tt> from 0.2s to
--   0.01s and <tt>bytes copied during GC</tt> 10-fold, but framerate nor
--   the frequency of not making a backup save are unaffected (at standard
--   backup settings), even with null frontend, because saving takes so few
--   resources. So, generally, backup save settings are relevant only due
--   to latency impact on very slow computers or in JS.
loopSave :: Binary a => COps -> (a -> FilePath) -> ChanSave a -> IO ()
delayPrint :: Text -> IO ()


-- | UI client options.
module Game.LambdaHack.Client.UI.UIOptionsParse

-- | Read and parse UI config file.
mkUIOptions :: COps -> Bool -> IO UIOptions

-- | Modify client options with UI options.
applyUIOptions :: COps -> UIOptions -> ClientOptions -> ClientOptions
configError :: String -> a
readError :: Read a => String -> a
parseConfig :: Config -> UIOptions


-- | Weapons, treasure and all the other items in the game.
module Game.LambdaHack.Common.Item

-- | Game items in actor possesion or strewn around the dungeon. The
--   information contained in this time is available to the player from the
--   moment the item is first seen and is never mutated.
--   
--   Some items are not created identified (<tt>IdentityCovered</tt>). Then
--   they are presented as having a template kind that is really not their
--   own, though usually close. Full kind information about item's kind is
--   available through the <tt>ItemKindIx</tt> index once the item is
--   identified and full information about the value of item's aspect
--   record is available elsewhere (both <tt>IdentityObvious</tt> and
--   <tt>IdentityCovered</tt> items may or may not need identification of
--   their aspect record).
data Item
Item :: ItemIdentity -> Maybe FactionId -> Flavour -> Item

-- | the kind of the item, or an indiretion
[jkind] :: Item -> ItemIdentity

-- | the faction that created the item, if any
[jfid] :: Item -> Maybe FactionId

-- | flavour, always the real one, not hidden; people may not recognize
--   shape, but they remember colour and old vs fancy look
[jflavour] :: Item -> Flavour

-- | Either the explicit obvious kind of the item or the kind it's hidden
--   under, with the details covered under the index indirection.
data ItemIdentity
IdentityObvious :: ContentId ItemKind -> ItemIdentity
IdentityCovered :: ItemKindIx -> ContentId ItemKind -> ItemIdentity

-- | An index of the kind identifier of an item. Clients have partial
--   knowledge how these idexes map to kind ids. They gain knowledge by
--   identifying items. The indexes and kind identifiers are 1-1.
data ItemKindIx

-- | The secret part of the information about an item. If a faction knows
--   the aspect record of the item, this is the complete secret
--   information. Items that don't need second identification (the
--   <tt>kmConst</tt> flag is set) may be identified or not and both cases
--   are OK (their display flavour will differ and that may be the point).
data ItemDisco
ItemDiscoFull :: AspectRecord -> ItemDisco
ItemDiscoMean :: KindMean -> ItemDisco

-- | Full information about an item.
data ItemFull
ItemFull :: Item -> ContentId ItemKind -> ItemKind -> ItemDisco -> Bool -> ItemFull
[itemBase] :: ItemFull -> Item
[itemKindId] :: ItemFull -> ContentId ItemKind
[itemKind] :: ItemFull -> ItemKind
[itemDisco] :: ItemFull -> ItemDisco
[itemSuspect] :: ItemFull -> Bool
type ItemFullKit = (ItemFull, ItemQuant)

-- | The map of item kind indexes to item kind ids. The full map, as known
--   by the server, is 1-1. Because it's sparse and changes, we don't
--   represent it as an (unboxed) vector, until it becomes a bottleneck (if
--   ever, likely on JS, where only vectors are fast).
type DiscoveryKind = EnumMap ItemKindIx (ContentId ItemKind)

-- | The map of item ids to item aspect reocrd. The full map is known by
--   the server.
type DiscoveryAspect = EnumMap ItemId AspectRecord

-- | The map of item kind indexes to identifiers of items that have that
--   kind. Used to update data about items when their kinds become known,
--   e.g., AI item use benefit data.
type ItemIxMap = EnumMap ItemKindIx (EnumSet ItemId)

-- | The fields are, in order: 1. whether the item should be kept in
--   equipment (not in pack nor stash) 2. the total benefit from picking
--   the item up (to use or to put in equipment) 3. the benefit of applying
--   the item to self 4. the (usually negative, for him) value of hitting a
--   foe in melee with it 5. the (usually negative, for him) value of
--   flinging the item at an opponent
data Benefit
Benefit :: Bool -> Double -> Double -> Double -> Double -> Benefit
[benInEqp] :: Benefit -> Bool
[benPickup] :: Benefit -> Double
[benApply] :: Benefit -> Double
[benMelee] :: Benefit -> Double
[benFling] :: Benefit -> Double
type DiscoveryBenefit = EnumMap ItemId Benefit
type ItemTimer = [Time]

-- | Number of items in a bag, together with recharging timer, in case of
--   items that need recharging, exists only temporarily or auto-activate
--   at regular intervals.
type ItemQuant = (Int, ItemTimer)

-- | A bag of items, e.g., one of the stores of an actor or the items on a
--   particular floor position or embedded in a particular map tile.
type ItemBag = EnumMap ItemId ItemQuant

-- | All items in the dungeon (including in actor inventories), indexed by
--   item identifier.
type ItemDict = EnumMap ItemId Item
itemToFull6 :: COps -> DiscoveryKind -> DiscoveryAspect -> ItemId -> Item -> ItemFull
aspectRecordFull :: ItemFull -> AspectRecord
strongestSlot :: DiscoveryBenefit -> EqpSlot -> [(ItemId, ItemFullKit)] -> [(Int, (ItemId, ItemFullKit))]
ncharges :: Time -> ItemFull -> ItemQuant -> Int
hasCharge :: Time -> ItemFull -> ItemQuant -> Bool
strongestMelee :: Bool -> Maybe DiscoveryBenefit -> Time -> [(ItemId, ItemFullKit)] -> [(Double, (Int, (ItemId, ItemFullKit)))]
unknownMeleeBonus :: [ItemFull] -> Bool
unknownSpeedBonus :: [ItemFull] -> Bool
conditionMeleeBonus :: [ItemFullKit] -> Int
conditionSpeedBonus :: [ItemFullKit] -> Int
armorHurtCalculation :: Bool -> Skills -> Skills -> Int
valueAtEqpSlot :: EqpSlot -> AspectRecord -> Int
unknownAspect :: (Aspect -> [Dice]) -> ItemFull -> Bool
instance GHC.Generics.Generic Game.LambdaHack.Common.Item.Benefit
instance GHC.Show.Show Game.LambdaHack.Common.Item.Benefit
instance GHC.Show.Show Game.LambdaHack.Common.Item.ItemFull
instance GHC.Classes.Ord Game.LambdaHack.Common.Item.ItemDisco
instance GHC.Classes.Eq Game.LambdaHack.Common.Item.ItemDisco
instance GHC.Show.Show Game.LambdaHack.Common.Item.ItemDisco
instance GHC.Generics.Generic Game.LambdaHack.Common.Item.Item
instance GHC.Classes.Eq Game.LambdaHack.Common.Item.Item
instance GHC.Show.Show Game.LambdaHack.Common.Item.Item
instance GHC.Generics.Generic Game.LambdaHack.Common.Item.ItemIdentity
instance GHC.Classes.Eq Game.LambdaHack.Common.Item.ItemIdentity
instance GHC.Show.Show Game.LambdaHack.Common.Item.ItemIdentity
instance Data.Binary.Class.Binary Game.LambdaHack.Common.Item.ItemKindIx
instance Data.Hashable.Class.Hashable Game.LambdaHack.Common.Item.ItemKindIx
instance GHC.Arr.Ix Game.LambdaHack.Common.Item.ItemKindIx
instance GHC.Enum.Enum Game.LambdaHack.Common.Item.ItemKindIx
instance GHC.Classes.Ord Game.LambdaHack.Common.Item.ItemKindIx
instance GHC.Classes.Eq Game.LambdaHack.Common.Item.ItemKindIx
instance GHC.Show.Show Game.LambdaHack.Common.Item.ItemKindIx
instance Data.Binary.Class.Binary Game.LambdaHack.Common.Item.Benefit
instance Data.Hashable.Class.Hashable Game.LambdaHack.Common.Item.Item
instance Data.Binary.Class.Binary Game.LambdaHack.Common.Item.Item
instance Data.Hashable.Class.Hashable Game.LambdaHack.Common.Item.ItemIdentity
instance Data.Binary.Class.Binary Game.LambdaHack.Common.Item.ItemIdentity


-- | Possible causes of failure of request.
module Game.LambdaHack.Common.ReqFailure

-- | Possible causes of failure of request.
data ReqFailure
MoveUnskilled :: ReqFailure
MoveNothing :: ReqFailure
MeleeUnskilled :: ReqFailure
MeleeSelf :: ReqFailure
MeleeDistant :: ReqFailure
DisplaceUnskilled :: ReqFailure
DisplaceDistant :: ReqFailure
DisplaceAccess :: ReqFailure
DisplaceMultiple :: ReqFailure
DisplaceDying :: ReqFailure
DisplaceBraced :: ReqFailure
DisplaceImmobile :: ReqFailure
DisplaceSupported :: ReqFailure
AlterUnskilled :: ReqFailure
AlterUnwalked :: ReqFailure
AlterDistant :: ReqFailure
AlterBlockActor :: ReqFailure
AlterBlockItem :: ReqFailure
AlterNothing :: ReqFailure
WaitUnskilled :: ReqFailure
YellUnskilled :: ReqFailure
MoveItemUnskilled :: ReqFailure
EqpOverfull :: ReqFailure
EqpStackFull :: ReqFailure
ApplyUnskilled :: ReqFailure
ApplyFood :: ReqFailure
ApplyRead :: ReqFailure
ApplyPeriodic :: ReqFailure
ApplyOutOfReach :: ReqFailure
ApplyCharging :: ReqFailure
ApplyNoEffects :: ReqFailure
ItemNothing :: ReqFailure
ItemNotCalm :: ReqFailure
NotCalmPrecious :: ReqFailure
ProjectUnskilled :: ReqFailure
ProjectAimOnself :: ReqFailure
ProjectBlockTerrain :: ReqFailure
ProjectBlockActor :: ReqFailure
ProjectLobable :: ReqFailure
ProjectOutOfReach :: ReqFailure
TriggerNothing :: ReqFailure
NoChangeDunLeader :: ReqFailure
impossibleReqFailure :: ReqFailure -> Bool
showReqFailure :: ReqFailure -> Text
permittedPrecious :: Bool -> Bool -> ItemFull -> Either ReqFailure Bool
permittedProject :: Bool -> Int -> Bool -> ItemFull -> Either ReqFailure Bool
permittedProjectAI :: Int -> Bool -> ItemFull -> Bool
permittedApply :: Time -> Int -> Bool -> ItemFull -> ItemQuant -> Either ReqFailure Bool
instance GHC.Generics.Generic Game.LambdaHack.Common.ReqFailure.ReqFailure
instance GHC.Classes.Eq Game.LambdaHack.Common.ReqFailure.ReqFailure
instance GHC.Show.Show Game.LambdaHack.Common.ReqFailure.ReqFailure
instance Data.Binary.Class.Binary Game.LambdaHack.Common.ReqFailure.ReqFailure


-- | Inhabited dungeon levels and the operations to query and change them
--   as the game progresses.
module Game.LambdaHack.Common.Level

-- | The complete dungeon is a map from level identifiers to levels.
type Dungeon = EnumMap LevelId Level
dungeonBounds :: Dungeon -> (LevelId, LevelId)

-- | Levels in the current branch, one level up (or down) from the current.
ascendInBranch :: Dungeon -> Bool -> LevelId -> [LevelId]

-- | Compute the level identifier and stair position on the new level,
--   after a level change.
--   
--   We assume there is never a staircase up and down at the same position.
whereTo :: LevelId -> Point -> Bool -> Dungeon -> [(LevelId, Point)]

-- | Items located on map tiles.
type ItemFloor = EnumMap Point ItemBag

-- | Big actors located on map tiles.
type BigActorMap = EnumMap Point ActorId

-- | Collections of projectiles located on map tiles.
type ProjectileMap = EnumMap Point [ActorId]

-- | Tile kinds on the map.
type TileMap = Array (ContentId TileKind)

-- | Current smell on map tiles.
type SmellMap = EnumMap Point Time

-- | A view on single, inhabited dungeon level. <a>Remembered</a> fields
--   carry a subset of the info in the client copies of levels.
data Level
Level :: ContentId CaveKind -> AbsDepth -> ItemFloor -> ItemFloor -> BigActorMap -> ProjectileMap -> TileMap -> EntryMap -> Area -> SmellMap -> ([Point], [Point]) -> [Point] -> Int -> Int -> Time -> Bool -> Level

-- | the kind of cave the level is an instance of
[lkind] :: Level -> ContentId CaveKind

-- | absolute depth of the level
[ldepth] :: Level -> AbsDepth

-- | remembered items lying on the floor
[lfloor] :: Level -> ItemFloor

-- | remembered items embedded in the tile
[lembed] :: Level -> ItemFloor

-- | seen big (non-projectile) actors at positions on the level; could be
--   recomputed at resume, but small enough
[lbig] :: Level -> BigActorMap

-- | seen projectiles at positions on the level; could be recomputed at
--   resume
[lproj] :: Level -> ProjectileMap

-- | remembered level map
[ltile] :: Level -> TileMap

-- | room entrances on the level
[lentry] :: Level -> EntryMap

-- | area of the level
[larea] :: Level -> Area

-- | remembered smells on the level
[lsmell] :: Level -> SmellMap

-- | positions of (up, down) stairs
[lstair] :: Level -> ([Point], [Point])

-- | positions of IK.Escape tiles
[lescape] :: Level -> [Point]

-- | currently remembered clear tiles
[lseen] :: Level -> Int

-- | total number of explorable tiles
[lexpl] :: Level -> Int

-- | local time on the level (possibly frozen)
[ltime] :: Level -> Time

-- | whether the level is covered in darkness
[lnight] :: Level -> Bool
updateFloor :: (ItemFloor -> ItemFloor) -> Level -> Level
updateEmbed :: (ItemFloor -> ItemFloor) -> Level -> Level
updateBigMap :: (BigActorMap -> BigActorMap) -> Level -> Level
updateProjMap :: (ProjectileMap -> ProjectileMap) -> Level -> Level
updateTile :: (TileMap -> TileMap) -> Level -> Level
updateEntry :: (EntryMap -> EntryMap) -> Level -> Level
updateSmell :: (SmellMap -> SmellMap) -> Level -> Level

-- | Query for tile kinds on the map.
at :: Level -> Point -> ContentId TileKind
posToBigLvl :: Point -> Level -> Maybe ActorId
occupiedBigLvl :: Point -> Level -> Bool
posToProjsLvl :: Point -> Level -> [ActorId]
occupiedProjLvl :: Point -> Level -> Bool
posToAidsLvl :: Point -> Level -> [ActorId]

-- | Try to find a random position on the map satisfying conjunction of the
--   mandatory and an optional predicate. If the permitted number of
--   attempts is not enough, try again the same number of times without the
--   next optional predicate, and fall back to trying with only the
--   mandatory predicate.
findPosTry :: Int -> Level -> (Point -> ContentId TileKind -> Bool) -> [Point -> ContentId TileKind -> Bool] -> Rnd (Maybe Point)
findPosTry2 :: Int -> Level -> (Point -> ContentId TileKind -> Bool) -> [Point -> ContentId TileKind -> Bool] -> (Point -> ContentId TileKind -> Bool) -> [Point -> ContentId TileKind -> Bool] -> Rnd (Maybe Point)
nearbyFreePoints :: COps -> Level -> (ContentId TileKind -> Bool) -> Point -> [Point]
sortEmbeds :: COps -> (ItemId -> ItemKind) -> ContentId TileKind -> ItemBag -> [(ItemId, ItemQuant)]

-- | Entries of places on the map.
type EntryMap = EnumMap Point PlaceEntry

-- | Generate a list of all passable points on (connected component of) the
--   level in the order of path distance from the starting position (BFS).
--   The starting position needn't be passable and is always included.
nearbyPassablePoints :: COps -> Level -> Point -> [Point]
assertSparseItems :: ItemFloor -> ItemFloor
assertSparseProjectiles :: ProjectileMap -> ProjectileMap
instance GHC.Classes.Eq Game.LambdaHack.Common.Level.Level
instance GHC.Show.Show Game.LambdaHack.Common.Level.Level
instance Data.Binary.Class.Binary Game.LambdaHack.Common.Level.Level


-- | Breadth first search algorithm.
module Game.LambdaHack.Client.Bfs

-- | Weighted distance between points along shortest paths.
data BfsDistance

-- | State of legality of moves between adjacent points.
data MoveLegal
MoveBlocked :: MoveLegal
MoveToOpen :: MoveLegal
MoveToClosed :: MoveLegal
MoveToUnknown :: MoveLegal
subtractBfsDistance :: BfsDistance -> BfsDistance -> Int

-- | The minimal distance value assigned to paths that don't enter any
--   unknown tiles.
minKnownBfs :: BfsDistance

-- | The distance value that denotes no legal path between points, either
--   due to blocked tiles or pathfinding aborted at earlier tiles, e.g.,
--   due to unknown tiles.
apartBfs :: BfsDistance

-- | Maximum value of the type.
maxBfsDistance :: BfsDistance

-- | Create and fill a BFS array for the given level. Unsafe array
--   operations are OK here, because the intermediate values of the vector
--   don't leak anywhere outside nor are kept unevaluated and so they can't
--   be overwritten by the unsafe side-effect.
--   
--   When computing move cost, we assume doors openable at no cost, because
--   other actors use them, too, so the cost is shared and the extra
--   visiblity is valuable, too. We treat unknown tiles specially. Whether
--   suspect tiles are considered openable depends on
--   <tt>smarkSuspect</tt>.
--   
--   Instead of a BFS queue (list) we use the two tabs (arrays), for (JS)
--   speed.
fillBfs :: Array Word8 -> Word8 -> Point -> (PrimArray PointI, PrimArray PointI) -> Array BfsDistance
data AndPath
AndPath :: Point -> [Point] -> Point -> Int -> AndPath
[pathSource] :: AndPath -> Point
[pathList] :: AndPath -> [Point]
[pathGoal] :: AndPath -> Point
[pathLen] :: AndPath -> Int
actorsAvoidedDist :: Int

-- | Find a path, without the source position, with the smallest length.
--   The <tt>eps</tt> coefficient determines which direction (of the
--   closest directions available) that path should prefer, where 0 means
--   north-west and 1 means north. The path tries hard to avoid actors and
--   tries to avoid tiles that need altering and ambient light. Actors are
--   avoided only close to the start of the path, because elsewhere they
--   are likely to move before they are reached. Even projectiles are
--   avoided, which sometimes has the effect of choosing a safer route
--   (regardless if the projectiles are friendly fire or not).
--   
--   An unwelcome side effect of avoiding actors is that friends will
--   sometimes avoid displacing and instead perform two separate moves,
--   wasting 1 turn in total. But in corridors they will still displace and
--   elsewhere this scenario was quite rare already.
findPathBfs :: BigActorMap -> Array Word8 -> (PointI -> Bool) -> Point -> Point -> Int -> Array BfsDistance -> Maybe AndPath

-- | Access a BFS array and interpret the looked up distance value.
accessBfs :: Array BfsDistance -> Point -> Maybe Int
succBfsDistance :: BfsDistance -> BfsDistance
predBfsDistance :: BfsDistance -> BfsDistance

-- | The distance value that denotes that path search was aborted at this
--   tile due to too large actual distance and that the tile was unknown.
--   It is also a true distance value for this tile.
abortedUnknownBfs :: BfsDistance
instance GHC.Generics.Generic Game.LambdaHack.Client.Bfs.AndPath
instance GHC.Show.Show Game.LambdaHack.Client.Bfs.AndPath
instance GHC.Classes.Eq Game.LambdaHack.Client.Bfs.MoveLegal
instance Data.Bits.Bits Game.LambdaHack.Client.Bfs.BfsDistance
instance GHC.Classes.Ord Game.LambdaHack.Client.Bfs.BfsDistance
instance GHC.Classes.Eq Game.LambdaHack.Client.Bfs.BfsDistance
instance GHC.Show.Show Game.LambdaHack.Client.Bfs.BfsDistance
instance Data.Binary.Class.Binary Game.LambdaHack.Client.Bfs.AndPath
instance Game.LambdaHack.Common.PointArray.UnboxRepClass Game.LambdaHack.Client.Bfs.BfsDistance


-- | Factions taking part in the game, e.g., a hero faction, a monster
--   faction and an animal faction.
module Game.LambdaHack.Common.Faction

-- | All factions in the game, indexed by faction identifier.
type FactionDict = EnumMap FactionId Faction

-- | The faction datatype.
data Faction
Faction :: Text -> Color -> Player -> [(Int, Int, GroupName ItemKind)] -> Dipl -> Maybe Status -> Maybe ActorId -> ItemBag -> EnumMap (ContentId ItemKind) Int -> EnumMap (ContentId ModeKind) (IntMap (EnumMap (ContentId ItemKind) Int)) -> Faction

-- | individual name
[gname] :: Faction -> Text

-- | color of actors or their frames
[gcolor] :: Faction -> Color

-- | the player spec for this faction
[gplayer] :: Faction -> Player

-- | initial actors
[ginitial] :: Faction -> [(Int, Int, GroupName ItemKind)]

-- | diplomatic standing
[gdipl] :: Faction -> Dipl

-- | cause of game end/exit
[gquit] :: Faction -> Maybe Status

-- | the leader of the faction; don't use in place of sleader on clients
[_gleader] :: Faction -> Maybe ActorId

-- | faction's shared inventory
[gsha] :: Faction -> ItemBag

-- | members killed
[gvictims] :: Faction -> EnumMap (ContentId ItemKind) Int

-- | members killed in the past, by game mode and difficulty level
[gvictimsD] :: Faction -> EnumMap (ContentId ModeKind) (IntMap (EnumMap (ContentId ItemKind) Int))

-- | Diplomacy states. Higher overwrite lower in case of asymmetric
--   content.
data Diplomacy
Unknown :: Diplomacy
Neutral :: Diplomacy
Alliance :: Diplomacy
War :: Diplomacy

-- | Current game status.
data Status
Status :: Outcome -> Int -> Maybe (GroupName ModeKind) -> Status

-- | current game outcome
[stOutcome] :: Status -> Outcome

-- | depth of the final encounter
[stDepth] :: Status -> Int

-- | new game group to start, if any
[stNewGame] :: Status -> Maybe (GroupName ModeKind)
data Challenge
Challenge :: Int -> Bool -> Bool -> Challenge

-- | game difficulty level (HP bonus or malus)
[cdiff] :: Challenge -> Int

-- | lone wolf challenge (only one starting character)
[cwolf] :: Challenge -> Bool

-- | cold fish challenge (no healing from enemies)
[cfish] :: Challenge -> Bool
gleader :: Faction -> Maybe ActorId

-- | Tell whether the faction consists of summoned horrors only.
--   
--   Horror player is special, for summoned actors that don't belong to any
--   of the main players of a given game. E.g., animals summoned during a
--   skirmish game between two hero factions land in the horror faction. In
--   every game, either all factions for which summoning items exist should
--   be present or a horror player should be added to host them.
isHorrorFact :: Faction -> Bool
noRunWithMulti :: Faction -> Bool
isAIFact :: Faction -> Bool
autoDungeonLevel :: Faction -> (Bool, Bool)
automatePlayer :: Bool -> Player -> Player

-- | Check if factions are at war. Assumes symmetry.
isFoe :: FactionId -> Faction -> FactionId -> Bool

-- | Check if factions are allied or are the same faction. Assumes
--   symmetry.
isFriend :: FactionId -> Faction -> FactionId -> Bool
difficultyBound :: Int
difficultyDefault :: Int
difficultyCoeff :: Int -> Int
difficultyInverse :: Int -> Int
defaultChallenge :: Challenge
possibleActorFactions :: ItemKind -> FactionDict -> [(FactionId, Faction)]
type Dipl = EnumMap FactionId Diplomacy
instance GHC.Generics.Generic Game.LambdaHack.Common.Faction.Challenge
instance GHC.Classes.Ord Game.LambdaHack.Common.Faction.Challenge
instance GHC.Classes.Eq Game.LambdaHack.Common.Faction.Challenge
instance GHC.Show.Show Game.LambdaHack.Common.Faction.Challenge
instance GHC.Generics.Generic Game.LambdaHack.Common.Faction.Faction
instance GHC.Classes.Eq Game.LambdaHack.Common.Faction.Faction
instance GHC.Show.Show Game.LambdaHack.Common.Faction.Faction
instance GHC.Generics.Generic Game.LambdaHack.Common.Faction.Status
instance GHC.Classes.Ord Game.LambdaHack.Common.Faction.Status
instance GHC.Classes.Eq Game.LambdaHack.Common.Faction.Status
instance GHC.Show.Show Game.LambdaHack.Common.Faction.Status
instance GHC.Generics.Generic Game.LambdaHack.Common.Faction.Diplomacy
instance GHC.Enum.Enum Game.LambdaHack.Common.Faction.Diplomacy
instance GHC.Classes.Ord Game.LambdaHack.Common.Faction.Diplomacy
instance GHC.Classes.Eq Game.LambdaHack.Common.Faction.Diplomacy
instance GHC.Show.Show Game.LambdaHack.Common.Faction.Diplomacy
instance Data.Binary.Class.Binary Game.LambdaHack.Common.Faction.Challenge
instance Data.Binary.Class.Binary Game.LambdaHack.Common.Faction.Faction
instance Data.Binary.Class.Binary Game.LambdaHack.Common.Faction.Status
instance Data.Binary.Class.Binary Game.LambdaHack.Common.Faction.Diplomacy


-- | High score table operations.
module Game.LambdaHack.Common.HighScore

-- | The list of scores, in decreasing order.
data ScoreTable

-- | A dictionary from game mode IDs to scores tables.
type ScoreDict = EnumMap (ContentId ModeKind) ScoreTable

-- | Empty score table
empty :: ScoreDict

-- | Register a new score in a score table.
register :: ScoreTable -> Int -> Int -> Time -> Status -> POSIXTime -> Challenge -> Text -> EnumMap (ContentId ItemKind) Int -> EnumMap (ContentId ItemKind) Int -> HiCondPoly -> (Bool, (ScoreTable, Int))

-- | Show a single high score, from the given ranking in the high score
--   table.
showScore :: TimeZone -> Int -> ScoreRecord -> [Text]
showAward :: Int -> ScoreTable -> Int -> Text -> Text
getTable :: ContentId ModeKind -> ScoreDict -> ScoreTable
unTable :: ScoreTable -> [ScoreRecord]
getRecord :: Int -> ScoreTable -> ScoreRecord

-- | A single score record. Records are ordered in the highscore table,
--   from the best to the worst, in lexicographic ordering wrt the fields
--   below.
data ScoreRecord

-- | Insert a new score into the table, Return new table and the ranking.
--   Make sure the table doesn't grow too large.
insertPos :: ScoreRecord -> ScoreTable -> (ScoreTable, Int)
instance Data.Binary.Class.Binary Game.LambdaHack.Common.HighScore.ScoreTable
instance GHC.Classes.Eq Game.LambdaHack.Common.HighScore.ScoreTable
instance GHC.Generics.Generic Game.LambdaHack.Common.HighScore.ScoreRecord
instance GHC.Classes.Ord Game.LambdaHack.Common.HighScore.ScoreRecord
instance GHC.Classes.Eq Game.LambdaHack.Common.HighScore.ScoreRecord
instance GHC.Show.Show Game.LambdaHack.Common.HighScore.ScoreRecord
instance GHC.Show.Show Game.LambdaHack.Common.HighScore.ScoreTable
instance Data.Binary.Class.Binary Game.LambdaHack.Common.HighScore.ScoreRecord


-- | Abstract syntax of requests.
--   
--   See
--   <a>https://github.com/LambdaHack/LambdaHack/wiki/Client-server-architecture</a>.
module Game.LambdaHack.Client.Request

-- | Requests sent by AI clients to the server. If faction leader is to be
--   changed, it's included as the second component.
type RequestAI = (ReqAI, Maybe ActorId)

-- | Possible forms of requests sent by AI clients.
data ReqAI
ReqAINop :: ReqAI
ReqAITimed :: RequestTimed -> ReqAI

-- | Requests sent by UI clients to the server. If faction leader is to be
--   changed, it's included as the second component.
type RequestUI = (ReqUI, Maybe ActorId)

-- | Possible forms of requests sent by UI clients.
data ReqUI
ReqUINop :: ReqUI
ReqUITimed :: RequestTimed -> ReqUI
ReqUIGameRestart :: GroupName ModeKind -> Challenge -> ReqUI
ReqUIGameDropAndExit :: ReqUI
ReqUIGameSaveAndExit :: ReqUI
ReqUIGameSave :: ReqUI
ReqUITactic :: Tactic -> ReqUI
ReqUIAutomate :: ReqUI

-- | Requests that take game time.
data RequestTimed
ReqMove :: Vector -> RequestTimed
ReqMelee :: ActorId -> ItemId -> CStore -> RequestTimed
ReqDisplace :: ActorId -> RequestTimed
ReqAlter :: Point -> RequestTimed
ReqWait :: RequestTimed
ReqWait10 :: RequestTimed
ReqYell :: RequestTimed
ReqMoveItems :: [(ItemId, Int, CStore, CStore)] -> RequestTimed
ReqProject :: Point -> Int -> ItemId -> CStore -> RequestTimed
ReqApply :: ItemId -> CStore -> RequestTimed
instance GHC.Show.Show Game.LambdaHack.Client.Request.ReqAI
instance GHC.Show.Show Game.LambdaHack.Client.Request.ReqUI
instance GHC.Show.Show Game.LambdaHack.Client.Request.RequestTimed


-- | Actors in the game: heroes, monsters, etc.
module Game.LambdaHack.Common.Actor

-- | Actor attributes that are changing throughout the game. If they appear
--   to be dublets of aspects from actor kinds, e.g. HP, they may be
--   results of casting the dice specified in their respective actor kind
--   and/or may be modified temporarily, but return to the original value
--   from their respective kind over time.
--   
--   Other properties of an actor, in particular its current aspects, are
--   derived from the actor's trunk, organs and equipment. A class of the
--   aspects, the boolean ones, are called flags. Another class are skills.
--   Stats are a subclass that determines if particular actions are
--   permitted for the actor (or faction).
data Actor
Actor :: ItemId -> Int64 -> ResDelta -> Int64 -> ResDelta -> Point -> Maybe Point -> LevelId -> FactionId -> Maybe ([Vector], Speed) -> ItemBag -> ItemBag -> ItemBag -> Int -> Watchfulness -> Bool -> Actor

-- | the trunk organ of the actor's body
[btrunk] :: Actor -> ItemId

-- | current hit points * 1M
[bhp] :: Actor -> Int64

-- | HP delta this turn * 1M
[bhpDelta] :: Actor -> ResDelta

-- | current calm * 1M
[bcalm] :: Actor -> Int64

-- | calm delta this turn * 1M
[bcalmDelta] :: Actor -> ResDelta

-- | current position
[bpos] :: Actor -> Point

-- | previous position, if any
[boldpos] :: Actor -> Maybe Point

-- | current level
[blid] :: Actor -> LevelId

-- | faction the actor currently belongs to
[bfid] :: Actor -> FactionId

-- | trajectory the actor must travel and his travel speed
[btrajectory] :: Actor -> Maybe ([Vector], Speed)

-- | organs
[borgan] :: Actor -> ItemBag

-- | personal equipment
[beqp] :: Actor -> ItemBag

-- | personal inventory pack
[binv] :: Actor -> ItemBag

-- | number of weapons among eqp and organs
[bweapon] :: Actor -> Int

-- | state of the actor's watchfulness
[bwatch] :: Actor -> Watchfulness

-- | is a projectile? affects being able to fly through other projectiles,
--   etc.
[bproj] :: Actor -> Bool

-- | Representation of recent changes to HP of Calm of an actor. This is
--   reset every time the actor perfoms an action, so this is aggregated
--   over actor turn (move), not time turn. The resource changes recorded
--   in the tuple are, respectively, negative and positive.
data ResDelta
ResDelta :: (Int64, Int64) -> (Int64, Int64) -> ResDelta

-- | resource change this move
[resCurrentTurn] :: ResDelta -> (Int64, Int64)

-- | resource change previous move
[resPreviousTurn] :: ResDelta -> (Int64, Int64)
type ActorMaxSkills = EnumMap ActorId Skills
data Watchfulness
WWatch :: Watchfulness
WWait :: Int -> Watchfulness
WSleep :: Watchfulness
WWake :: Watchfulness
deltasSerious :: ResDelta -> Bool
deltasHears :: ResDelta -> Bool
deltaBenign :: ResDelta -> Bool
deltaWasBenign :: ResDelta -> Bool
actorCanMelee :: ActorMaxSkills -> ActorId -> Actor -> Bool

-- | The speed from organs and gear; being pushed is ignored.
gearSpeed :: Skills -> Speed
actorTemplate :: ItemId -> Int64 -> Int64 -> Point -> LevelId -> FactionId -> Bool -> Actor
actorWaits :: Actor -> Bool
actorWaitsOrSleeps :: Actor -> Bool
actorDying :: Actor -> Bool
hpTooLow :: Actor -> Skills -> Bool
calmEnough :: Actor -> Skills -> Bool
hpEnough :: Actor -> Skills -> Bool
hpFull :: Actor -> Skills -> Bool

-- | Has the skill and can wake up easily, so can sleep safely.
canSleep :: Skills -> Bool

-- | Can't loot, so sometimes prefers to sleep instead of exploring.
prefersSleep :: Skills -> Bool
checkAdjacent :: Actor -> Actor -> Bool
eqpOverfull :: Actor -> Int -> Bool
eqpFreeN :: Actor -> Int

-- | All actors on the level, indexed by actor identifier.
type ActorDict = EnumMap ActorId Actor

-- | Chance that a new monster is generated. Depends on the number of
--   monsters already present, and on the level depth and its cave kind.
monsterGenChance :: AbsDepth -> AbsDepth -> Int -> Int -> Rnd Bool

-- | How long until an actor's smell vanishes from a tile.
smellTimeout :: Delta Time
instance GHC.Generics.Generic Game.LambdaHack.Common.Actor.Actor
instance GHC.Classes.Eq Game.LambdaHack.Common.Actor.Actor
instance GHC.Show.Show Game.LambdaHack.Common.Actor.Actor
instance GHC.Generics.Generic Game.LambdaHack.Common.Actor.Watchfulness
instance GHC.Classes.Eq Game.LambdaHack.Common.Actor.Watchfulness
instance GHC.Show.Show Game.LambdaHack.Common.Actor.Watchfulness
instance GHC.Generics.Generic Game.LambdaHack.Common.Actor.ResDelta
instance GHC.Classes.Eq Game.LambdaHack.Common.Actor.ResDelta
instance GHC.Show.Show Game.LambdaHack.Common.Actor.ResDelta
instance Data.Binary.Class.Binary Game.LambdaHack.Common.Actor.Actor
instance Data.Binary.Class.Binary Game.LambdaHack.Common.Actor.Watchfulness
instance Data.Binary.Class.Binary Game.LambdaHack.Common.Actor.ResDelta


-- | The common server and client basic game state type and its operations.
module Game.LambdaHack.Common.State

-- | View on the basic game state. The <tt>remembered</tt> fields, in
--   client copies of the state, carry only a subset of the full
--   information that the server keeps. Clients never directly change their
--   <tt>State</tt>, but apply atomic actions sent by the server to do so
--   (and/or the server applies the actions to each client state in turn).
data State
sdungeon :: State -> Dungeon
stotalDepth :: State -> AbsDepth
sactorD :: State -> ActorDict
sitemD :: State -> ItemDict
sitemIxMap :: State -> ItemIxMap
sfactionD :: State -> FactionDict
stime :: State -> Time
scops :: State -> COps
sgold :: State -> Int
shigh :: State -> ScoreDict
sgameModeId :: State -> ContentId ModeKind
sdiscoKind :: State -> DiscoveryKind
sdiscoAspect :: State -> DiscoveryAspect
sactorMaxSkills :: State -> ActorMaxSkills

-- | Initial complete global game state.
defStateGlobal :: Dungeon -> AbsDepth -> FactionDict -> COps -> ScoreDict -> ContentId ModeKind -> DiscoveryKind -> State

-- | Initial empty state.
emptyState :: State

-- | Local state created by removing secret information from global state
--   components.
localFromGlobal :: State -> State

-- | Update dungeon data within state.
updateDungeon :: (Dungeon -> Dungeon) -> State -> State

-- | Update dungeon depth.
updateDepth :: (AbsDepth -> AbsDepth) -> State -> State

-- | Update the actor dictionary.
updateActorD :: (ActorDict -> ActorDict) -> State -> State

-- | Update the item dictionary.
updateItemD :: (ItemDict -> ItemDict) -> State -> State

-- | Update the item kind index map.
updateItemIxMap :: (ItemIxMap -> ItemIxMap) -> State -> State

-- | Update faction data within state.
updateFactionD :: (FactionDict -> FactionDict) -> State -> State

-- | Update global time within state.
updateTime :: (Time -> Time) -> State -> State

-- | Update content data within state and recompute the cached data.
updateCOpsAndCachedData :: (COps -> COps) -> State -> State

-- | Update total gold value in the dungeon.
updateGold :: (Int -> Int) -> State -> State
updateDiscoKind :: (DiscoveryKind -> DiscoveryKind) -> State -> State
updateDiscoAspect :: (DiscoveryAspect -> DiscoveryAspect) -> State -> State
updateActorMaxSkills :: (ActorMaxSkills -> ActorMaxSkills) -> State -> State
getItemBody :: ItemId -> State -> Item
aspectRecordFromItem :: ItemId -> Item -> State -> AspectRecord
aspectRecordFromIid :: ItemId -> State -> AspectRecord
maxSkillsFromActor :: Actor -> State -> Skills
maxSkillsInDungeon :: State -> ActorMaxSkills
unknownLevel :: COps -> ContentId CaveKind -> AbsDepth -> Area -> ([Point], [Point]) -> [Point] -> Int -> Bool -> Level
unknownTileMap :: Area -> ContentId TileKind -> X -> Y -> TileMap
instance GHC.Classes.Eq Game.LambdaHack.Common.State.State
instance GHC.Show.Show Game.LambdaHack.Common.State.State
instance Data.Binary.Class.Binary Game.LambdaHack.Common.State.State


-- | Operations on the <a>Actor</a> type, and related, that need the
--   <a>State</a> type, but not our custom monad types.
module Game.LambdaHack.Common.ActorState
fidActorNotProjGlobalAssocs :: FactionId -> State -> [(ActorId, Actor)]
actorAssocs :: (FactionId -> Bool) -> LevelId -> State -> [(ActorId, Actor)]
fidActorRegularAssocs :: FactionId -> LevelId -> State -> [(ActorId, Actor)]
fidActorRegularIds :: FactionId -> LevelId -> State -> [ActorId]
foeRegularAssocs :: FactionId -> LevelId -> State -> [(ActorId, Actor)]
foeRegularList :: FactionId -> LevelId -> State -> [Actor]
friendRegularAssocs :: FactionId -> LevelId -> State -> [(ActorId, Actor)]
friendRegularList :: FactionId -> LevelId -> State -> [Actor]
bagAssocs :: State -> ItemBag -> [(ItemId, Item)]
bagAssocsK :: State -> ItemBag -> [(ItemId, (Item, ItemQuant))]
posToBig :: Point -> LevelId -> State -> Maybe ActorId
posToBigAssoc :: Point -> LevelId -> State -> Maybe (ActorId, Actor)
posToProjs :: Point -> LevelId -> State -> [ActorId]
posToProjAssocs :: Point -> LevelId -> State -> [(ActorId, Actor)]
posToAids :: Point -> LevelId -> State -> [ActorId]
posToAidAssocs :: Point -> LevelId -> State -> [(ActorId, Actor)]

-- | Calculate loot's worth for a given faction.
calculateTotal :: FactionId -> State -> (ItemBag, Int)

-- | Price an item, taking count into consideration.
itemPrice :: Int -> ItemKind -> Int
mergeItemQuant :: ItemQuant -> ItemQuant -> ItemQuant
findIid :: ActorId -> FactionId -> ItemId -> State -> [(ActorId, (Actor, CStore))]
combinedGround :: FactionId -> State -> ItemBag
combinedOrgan :: FactionId -> State -> ItemBag
combinedEqp :: FactionId -> State -> ItemBag
combinedInv :: FactionId -> State -> ItemBag
combinedItems :: FactionId -> State -> ItemBag
combinedFromLore :: SLore -> FactionId -> State -> ItemBag
getActorBody :: ActorId -> State -> Actor
getActorMaxSkills :: ActorId -> State -> Skills
actorCurrentSkills :: Maybe ActorId -> ActorId -> State -> Skills
canTraverse :: ActorId -> State -> Bool
getCarriedAssocsAndTrunk :: Actor -> State -> [(ItemId, Item)]
getCarriedIidCStore :: Actor -> [(ItemId, CStore)]
getContainerBag :: Container -> State -> ItemBag
getFloorBag :: LevelId -> Point -> State -> ItemBag
getEmbedBag :: LevelId -> Point -> State -> ItemBag
getBodyStoreBag :: Actor -> CStore -> State -> ItemBag
mapActorItems_ :: Monad m => (CStore -> ItemId -> ItemQuant -> m a) -> Actor -> State -> m ()
getActorAssocs :: ActorId -> CStore -> State -> [(ItemId, Item)]
getActorAssocsK :: ActorId -> CStore -> State -> [(ItemId, (Item, ItemQuant))]

-- | Checks if the actor is present on the current level. The order of
--   argument here and in other functions is set to allow
--   
--   <pre>
--   b &lt;- getsState (memActor a)
--   </pre>
memActor :: ActorId -> LevelId -> State -> Bool

-- | Get current time from the dungeon data.
getLocalTime :: LevelId -> State -> Time
regenCalmDelta :: ActorId -> Actor -> State -> Int64
actorInAmbient :: Actor -> State -> Bool
canDeAmbientList :: Actor -> State -> [Point]
dispEnemy :: ActorId -> ActorId -> Skills -> State -> Bool
itemToFull :: ItemId -> State -> ItemFull
fullAssocs :: ActorId -> [CStore] -> State -> [(ItemId, ItemFull)]
kitAssocs :: ActorId -> [CStore] -> State -> [(ItemId, ItemFullKit)]
getItemKindId :: Item -> State -> ContentId ItemKind
getIidKindId :: ItemId -> State -> ContentId ItemKind
getItemKind :: Item -> State -> ItemKind
getIidKind :: ItemId -> State -> ItemKind
getItemKindIdServer :: Item -> State -> ContentId ItemKind
getIidKindIdServer :: ItemId -> State -> ContentId ItemKind
getItemKindServer :: Item -> State -> ItemKind
getIidKindServer :: ItemId -> State -> ItemKind

-- | Determine the dungeon level of the container. If the item is in a
--   shared stash, the level depends on which actor asks.
lidFromC :: Container -> State -> LevelId
posFromC :: Container -> State -> Point

-- | Require that any non-dying foe is adjacent. We include even
--   projectiles that explode when stricken down, because they can be
--   caught and then they don't explode, so it makes sense to focus on
--   handling them. If there are many projectiles in a single adjacent
--   position, we only test the first one, the one that would be hit in
--   melee (this is not optimal if the actor would need to flee instead of
--   meleeing, but fleeing with *many* projectiles adjacent is a possible
--   waste of a move anyway).
anyFoeAdj :: ActorId -> State -> Bool
adjacentBigAssocs :: Actor -> State -> [(ActorId, Actor)]
adjacentProjAssocs :: Actor -> State -> [(ActorId, Actor)]
armorHurtBonus :: ActorId -> ActorId -> State -> Int

-- | Check if any non-dying foe (projectile or not) is adjacent to any of
--   our normal actors (whether they can melee or just need to flee, in
--   which case alert is needed so that they are not slowed down by
--   others). This is needed only by AI and computed as lazily as possible.
inMelee :: FactionId -> LevelId -> State -> Bool


-- | Game state reading monad and basic operations.
module Game.LambdaHack.Common.MonadStateRead

-- | Monad for reading game state. A state monad with state modification
--   disallowed (another constraint is needed to permit that). The basic
--   server and client monads are like that, because server and clients
--   freely modify their internal session data, but don't modify the main
--   game state, except in very restricted and synchronized way.
class (Monad m, Functor m, Applicative m) => MonadStateRead m
getsState :: MonadStateRead m => (State -> a) -> m a
getState :: MonadStateRead m => m State
getLevel :: MonadStateRead m => LevelId -> m Level
getGameMode :: MonadStateRead m => m ModeKind
isNoConfirmsGame :: MonadStateRead m => m Bool
getEntryArena :: MonadStateRead m => Faction -> m LevelId
pickWeaponM :: MonadStateRead m => Bool -> Maybe DiscoveryBenefit -> [(ItemId, ItemFullKit)] -> Skills -> ActorId -> m [(Double, (Int, (ItemId, ItemFullKit)))]
displayTaunt :: MonadStateRead m => Bool -> (Rnd (Text, Text) -> m (Text, Text)) -> ActorId -> m (Text, Text)


-- | Description of effects.
module Game.LambdaHack.Client.UI.EffectDescription
data DetailLevel
DetailNone :: DetailLevel
DetailLow :: DetailLevel
DetailMedium :: DetailLevel
DetailHigh :: DetailLevel
DetailAll :: DetailLevel

-- | Suffix to append to a basic content name if the content causes the
--   effect.
--   
--   We show absolute time in seconds, not <tt>moves</tt>, because actors
--   can have different speeds (and actions can potentially take different
--   time intervals). We call the time taken by one player move, when
--   walking, a <tt>move</tt>. <tt>Turn</tt> and <tt>clip</tt> are used
--   mostly internally, the former as an absolute time unit. We show
--   distances in <tt>steps</tt>, because one step, from a tile to another
--   tile, is always 1 meter. We don't call steps <tt>tiles</tt>, reserving
--   that term for the context of terrain kinds or units of area.
effectToSuffix :: DetailLevel -> Effect -> Text
detectToObject :: DetectKind -> Text
detectToVerb :: DetectKind -> Text
skillName :: Skill -> Text
skillDesc :: Skill -> Text
skillToDecorator :: Skill -> Actor -> Int -> Text
skillSlots :: [Skill]
kindAspectToSuffix :: Aspect -> Text
aspectToSentence :: Aspect -> Maybe Text
affixDice :: Dice -> Text
slotToSentence :: EqpSlot -> Text
tmodToSuff :: Text -> ThrowMod -> Text
affixBonus :: Int -> Text
wrapInParens :: Text -> Text
wrapInChevrons :: Text -> Text
instance GHC.Enum.Bounded Game.LambdaHack.Client.UI.EffectDescription.DetailLevel
instance GHC.Enum.Enum Game.LambdaHack.Client.UI.EffectDescription.DetailLevel
instance GHC.Classes.Ord Game.LambdaHack.Client.UI.EffectDescription.DetailLevel
instance GHC.Classes.Eq Game.LambdaHack.Client.UI.EffectDescription.DetailLevel


-- | UI aspects of actors.
module Game.LambdaHack.Client.UI.ActorUI
data ActorUI
ActorUI :: Char -> Text -> Text -> Color -> ActorUI

-- | individual map symbol
[bsymbol] :: ActorUI -> Char

-- | individual name
[bname] :: ActorUI -> Text

-- | individual pronoun
[bpronoun] :: ActorUI -> Text

-- | individual map color
[bcolor] :: ActorUI -> Color
type ActorDictUI = EnumMap ActorId ActorUI
keySelected :: (ActorId, Actor, ActorUI) -> (Bool, Bool, Bool, Char, Color, ActorId)

-- | The part of speech describing the actor.
partActor :: ActorUI -> Part

-- | The part of speech containing the actor's pronoun.
partPronoun :: ActorUI -> Part
ppCStoreWownW :: Bool -> CStore -> Part -> [Part]
ppContainerWownW :: (ActorId -> Part) -> Bool -> Container -> [Part]
tryFindActor :: State -> (ActorId -> Actor -> Bool) -> Maybe (ActorId, Actor)
tryFindHeroK :: ActorDictUI -> FactionId -> Int -> State -> Maybe (ActorId, Actor)
instance GHC.Generics.Generic Game.LambdaHack.Client.UI.ActorUI.ActorUI
instance GHC.Classes.Eq Game.LambdaHack.Client.UI.ActorUI.ActorUI
instance GHC.Show.Show Game.LambdaHack.Client.UI.ActorUI.ActorUI
instance Data.Binary.Class.Binary Game.LambdaHack.Client.UI.ActorUI.ActorUI


-- | Item slots for UI and AI item collections.
module Game.LambdaHack.Client.UI.ItemSlot

-- | Slot label. Usually just a character. Sometimes with a numerical
--   prefix.
data SlotChar
SlotChar :: Int -> Char -> SlotChar
[slotPrefix] :: SlotChar -> Int
[slotChar] :: SlotChar -> Char

-- | A collection of mappings from slot labels to item identifiers.
newtype ItemSlots
ItemSlots :: EnumMap SLore SingleItemSlots -> ItemSlots
type SingleItemSlots = EnumMap SlotChar ItemId
allSlots :: [SlotChar]
intSlots :: [SlotChar]
slotLabel :: SlotChar -> Text

-- | Assigns a slot to an item, e.g., for inclusion in the inventory of a
--   hero. At first, e.g., when item is spotted on the floor, the slot is
--   not user-friendly. After any player's item manipulation action, slots
--   are sorted and a fully human-readable slot is then assigned. Only then
--   the slot can be viewed by the player.
assignSlot :: SingleItemSlots -> SlotChar
partyItemSet :: SLore -> FactionId -> Maybe Actor -> State -> EnumSet ItemId
sortSlotMap :: (ItemId -> ItemFull) -> SingleItemSlots -> SingleItemSlots
mergeItemSlots :: (ItemId -> ItemFull) -> [SingleItemSlots] -> SingleItemSlots
instance Data.Binary.Class.Binary Game.LambdaHack.Client.UI.ItemSlot.ItemSlots
instance GHC.Show.Show Game.LambdaHack.Client.UI.ItemSlot.ItemSlots
instance GHC.Classes.Eq Game.LambdaHack.Client.UI.ItemSlot.SlotChar
instance GHC.Show.Show Game.LambdaHack.Client.UI.ItemSlot.SlotChar
instance GHC.Classes.Ord Game.LambdaHack.Client.UI.ItemSlot.SlotChar
instance Data.Binary.Class.Binary Game.LambdaHack.Client.UI.ItemSlot.SlotChar
instance GHC.Enum.Enum Game.LambdaHack.Client.UI.ItemSlot.SlotChar


-- | Slideshows.
module Game.LambdaHack.Client.UI.Slideshow

-- | A key or an item slot label at a given position on the screen.
type KYX = (Either [KM] SlotChar, (Y, X, X))

-- | An Overlay of text with an associated list of keys or slots that
--   activated when the specified screen position is pointed at. The list
--   should be sorted wrt rows and then columns.
type OKX = (Overlay, [KYX])

-- | A list of active screenfulls to be shown one after another. Each
--   screenful has an independent numbering of rows and columns.
data Slideshow
emptySlideshow :: Slideshow
unsnoc :: Slideshow -> Maybe (Slideshow, OKX)
toSlideshow :: [OKX] -> Slideshow
menuToSlideshow :: OKX -> Slideshow
wrapOKX :: Y -> X -> X -> [(KM, String)] -> OKX
splitOverlay :: X -> Y -> Report -> [KM] -> OKX -> Slideshow
splitOKX :: X -> Y -> AttrLine -> [KM] -> OKX -> [OKX]

-- | Generate a slideshow with the current and previous scores.
highSlideshow :: X -> Y -> ScoreTable -> Int -> Text -> TimeZone -> Slideshow
moreMsg :: String
endMsg :: String
keysOKX :: Y -> X -> X -> [KM] -> OKX

-- | Show a screenful of the high scores table. Parameter <tt>entries</tt>
--   is the number of (3-line) scores to be shown.
showTable :: TimeZone -> Int -> ScoreTable -> Int -> Int -> [AttrLine]

-- | Produce a couple of renderings of the high scores table.
showNearbyScores :: TimeZone -> Int -> ScoreTable -> Int -> [[AttrLine]]
instance GHC.Classes.Eq Game.LambdaHack.Client.UI.Slideshow.Slideshow
instance GHC.Show.Show Game.LambdaHack.Client.UI.Slideshow.Slideshow


-- | Verifying, aggregating and displaying binding of keys to commands.
module Game.LambdaHack.Client.UI.KeyBindings

-- | Produce a set of help/menu screens from the key bindings.
--   
--   When the intro screen mentions KP_5, this really is KP_Begin, but
--   since that is harder to understand we assume a different, non-default
--   state of NumLock in the help text than in the code that handles keys.
keyHelp :: COps -> CCUI -> Int -> [(Text, OKX)]

-- | Turn the specified portion of bindings into a menu.
okxsN :: InputContent -> Int -> Int -> (HumanCmd -> Bool) -> Bool -> CmdCategory -> [Text] -> [Text] -> OKX


-- | Client-specific game state components.
module Game.LambdaHack.Client.State

-- | Client state, belonging to a single faction.
data StateClient
StateClient :: Int -> EnumMap ActorId TgtAndPath -> EnumMap ActorId Point -> EnumSet LevelId -> EnumMap ActorId BfsAndPath -> () -> DiscoveryBenefit -> PerLid -> AlterLid -> StdGen -> Maybe ActorId -> FactionId -> Bool -> Challenge -> Challenge -> Int -> Int -> EnumMap LevelId Bool -> EnumMap (ContentId ModeKind) (Map Challenge Int) -> ClientOptions -> (PrimArray PointI, PrimArray PointI) -> StateClient

-- | a parameter of the aiming digital line
[seps] :: StateClient -> Int

-- | targets of our actors in the dungeon; this is only useful for AI and
--   for directing henchmen, in particular with following tactics, where
--   henchmen go to the leader's target
[stargetD] :: StateClient -> EnumMap ActorId TgtAndPath

-- | the position when fleeing requested
[sfleeD] :: StateClient -> EnumMap ActorId Point

-- | the set of fully explored levels
[sexplored] :: StateClient -> EnumSet LevelId

-- | pathfinding data for our actors
[sbfsD] :: StateClient -> EnumMap ActorId BfsAndPath
[sundo] :: StateClient -> ()

-- | remembered AI benefits of items; could be recomputed at resume, but
--   they are costly to generate and not too large
[sdiscoBenefit] :: StateClient -> DiscoveryBenefit

-- | faction perception indexed by level
[sfper] :: StateClient -> PerLid

-- | cached alter skill data for positions
[salter] :: StateClient -> AlterLid

-- | current random generator
[srandom] :: StateClient -> StdGen

-- | candidate new leader of the faction; Faction.gleader is the old leader
[_sleader] :: StateClient -> Maybe ActorId

-- | faction controlled by the client
[_sside] :: StateClient -> FactionId

-- | exit the game loop
[squit] :: StateClient -> Bool

-- | current game challenge setup
[scurChal] :: StateClient -> Challenge

-- | next game challenge setup
[snxtChal] :: StateClient -> Challenge

-- | next game scenario number
[snxtScenario] :: StateClient -> Int

-- | whether to mark suspect features
[smarkSuspect] :: StateClient -> Int

-- | whether we are in melee, per level
[scondInMelee] :: StateClient -> EnumMap LevelId Bool

-- | won games at particular difficulty lvls
[svictories] :: StateClient -> EnumMap (ContentId ModeKind) (Map Challenge Int)

-- | client options
[soptions] :: StateClient -> ClientOptions

-- | Instead of a BFS queue (list) we use these two arrays, for (JS) speed.
--   They need to be per-client distinct, because sometimes multiple
--   clients interleave BFS computation.
[stabs] :: StateClient -> (PrimArray PointI, PrimArray PointI)
type AlterLid = EnumMap LevelId (Array Word8)

-- | Pathfinding distances to all reachable positions of an actor and a
--   shortest paths to some of the positions.
data BfsAndPath
BfsInvalid :: BfsAndPath
BfsAndPath :: Array BfsDistance -> EnumMap Point AndPath -> BfsAndPath

-- | Actor's target and a path to it, if any.
data TgtAndPath
TgtAndPath :: Target -> Maybe AndPath -> TgtAndPath
[tapTgt] :: TgtAndPath -> Target
[tapPath] :: TgtAndPath -> Maybe AndPath

-- | The type of na actor target.
data Target

-- | target an enemy
TEnemy :: ActorId -> Target

-- | target a friend or neutral
TNonEnemy :: ActorId -> Target

-- | target a concrete spot
TPoint :: TGoal -> LevelId -> Point -> Target

-- | target position relative to actor
TVector :: Vector -> Target

-- | The goal of an actor.
data TGoal

-- | last seen position of the targeted actor
TEnemyPos :: ActorId -> TGoal

-- | embedded item that can be triggered; in <tt>TPoint (TEmbed bag p) _
--   q</tt> usually <tt>bag</tt> is embbedded in <tt>p</tt> and <tt>q</tt>
--   is an adjacent open tile
TEmbed :: ItemBag -> Point -> TGoal

-- | item lying on the ground
TItem :: ItemBag -> TGoal

-- | smell potentially left by enemies
TSmell :: TGoal

-- | a blocking tile to be approached (and, e.g., revealed to be walkable
--   or altered or searched)
TBlock :: TGoal

-- | an unknown tile to be explored
TUnknown :: TGoal

-- | a known tile to be patrolled
TKnown :: TGoal

-- | Initial empty game client state.
emptyStateClient :: FactionId -> StateClient

-- | Cycle the <a>smarkSuspect</a> setting.
cycleMarkSuspect :: StateClient -> StateClient

-- | Update target parameters within client state.
updateTarget :: ActorId -> (Maybe Target -> Maybe Target) -> StateClient -> StateClient

-- | Get target parameters from client state.
getTarget :: ActorId -> StateClient -> Maybe Target

-- | Update picked leader within state. Verify actor's faction.
updateLeader :: ActorId -> State -> StateClient -> StateClient
sside :: StateClient -> FactionId
sleader :: StateClient -> Maybe ActorId
instance GHC.Show.Show Game.LambdaHack.Client.State.StateClient
instance GHC.Generics.Generic Game.LambdaHack.Client.State.TgtAndPath
instance GHC.Show.Show Game.LambdaHack.Client.State.TgtAndPath
instance GHC.Generics.Generic Game.LambdaHack.Client.State.Target
instance GHC.Classes.Ord Game.LambdaHack.Client.State.Target
instance GHC.Classes.Eq Game.LambdaHack.Client.State.Target
instance GHC.Show.Show Game.LambdaHack.Client.State.Target
instance GHC.Generics.Generic Game.LambdaHack.Client.State.TGoal
instance GHC.Classes.Ord Game.LambdaHack.Client.State.TGoal
instance GHC.Classes.Eq Game.LambdaHack.Client.State.TGoal
instance GHC.Show.Show Game.LambdaHack.Client.State.TGoal
instance GHC.Show.Show Game.LambdaHack.Client.State.BfsAndPath
instance Data.Binary.Class.Binary Game.LambdaHack.Client.State.StateClient
instance Data.Binary.Class.Binary Game.LambdaHack.Client.State.TgtAndPath
instance Data.Binary.Class.Binary Game.LambdaHack.Client.State.Target
instance Data.Binary.Class.Binary Game.LambdaHack.Client.State.TGoal


-- | The client UI session state.
module Game.LambdaHack.Client.UI.SessionUI

-- | The information that is used across a client playing session,
--   including many consecutive games in a single session. Some of it is
--   saved, some is reset when a new playing session starts. An important
--   component is the frontend session.
data SessionUI
SessionUI :: Maybe Target -> ActorDictUI -> ItemDictUI -> ItemSlots -> Maybe (CStore, CStore) -> ChanFrontend -> CCUI -> UIOptions -> Maybe AimMode -> Bool -> Maybe (ItemId, CStore, Bool) -> EnumSet ActorId -> Maybe RunParams -> History -> Point -> LastRecord -> [KM] -> EnumSet ActorId -> Int -> Bool -> Bool -> Bool -> Map String Int -> Bool -> HintMode -> Bool -> POSIXTime -> POSIXTime -> Time -> Int -> Int -> SessionUI

-- | the common xhair
[sxhair] :: SessionUI -> Maybe Target

-- | assigned actor UI presentations
[sactorUI] :: SessionUI -> ActorDictUI

-- | assigned item first seen level
[sitemUI] :: SessionUI -> ItemDictUI

-- | map from slots to items
[sslots] :: SessionUI -> ItemSlots

-- | last item move stores
[slastItemMove] :: SessionUI -> Maybe (CStore, CStore)

-- | connection with the frontend
[schanF] :: SessionUI -> ChanFrontend

-- | UI client content
[sccui] :: SessionUI -> CCUI

-- | UI options as set by the player
[sUIOptions] :: SessionUI -> UIOptions

-- | aiming mode
[saimMode] :: SessionUI -> Maybe AimMode

-- | last mouse aiming not vacuus
[sxhairMoused] :: SessionUI -> Bool

-- | selected item, if any, it's store and whether to override suitability
--   check
[sitemSel] :: SessionUI -> Maybe (ItemId, CStore, Bool)

-- | the set of currently selected actors
[sselected] :: SessionUI -> EnumSet ActorId

-- | parameters of the current run, if any
[srunning] :: SessionUI -> Maybe RunParams

-- | history of messages
[shistory] :: SessionUI -> History

-- | mouse pointer position
[spointer] :: SessionUI -> Point

-- | state of key sequence recording
[slastRecord] :: SessionUI -> LastRecord

-- | state of key sequence playback
[slastPlay] :: SessionUI -> [KM]

-- | actors that just got out of sight
[slastLost] :: SessionUI -> EnumSet ActorId

-- | player just waited this many times
[swaitTimes] :: SessionUI -> Int

-- | the player just exited AI automation
[swasAutomated] :: SessionUI -> Bool

-- | mark leader and party FOV
[smarkVision] :: SessionUI -> Bool

-- | mark smell, if the leader can smell
[smarkSmell] :: SessionUI -> Bool

-- | indices of last used menu items
[smenuIxMap] :: SessionUI -> Map String Int

-- | current level needs displaying
[sdisplayNeeded] :: SessionUI -> Bool

-- | how to show keys hints when no messages
[shintMode] :: SessionUI -> HintMode

-- | whether no report created last UI turn or the report wiped out from
--   screen
[sreportNull] :: SessionUI -> Bool

-- | this session start time
[sstart] :: SessionUI -> POSIXTime

-- | this game start time
[sgstart] :: SessionUI -> POSIXTime

-- | clips from start of session to current game start
[sallTime] :: SessionUI -> Time

-- | this game current frame count
[snframes] :: SessionUI -> Int

-- | frame count from start of session to current game start
[sallNframes] :: SessionUI -> Int
type ItemDictUI = EnumMap ItemId LevelId

-- | Current aiming mode of a client.
newtype AimMode
AimMode :: LevelId -> AimMode
[aimLevelId] :: AimMode -> LevelId

-- | Parameters of the current run.
data RunParams
RunParams :: ActorId -> [ActorId] -> Bool -> Maybe Text -> Int -> RunParams

-- | the original leader from run start
[runLeader] :: RunParams -> ActorId

-- | the list of actors that take part
[runMembers] :: RunParams -> [ActorId]

-- | initial run continuation by any run participant, including run leader
[runInitial] :: RunParams -> Bool

-- | message with the next stop reason
[runStopMsg] :: RunParams -> Maybe Text

-- | waiting for others to move out of the way
[runWaiting] :: RunParams -> Int

-- | State of last recorded and currently being recorded key sequences.
data LastRecord
LastRecord :: [KM] -> [KM] -> Int -> LastRecord

-- | accumulated keys of the current command
[currentKeys] :: LastRecord -> [KM]

-- | keys of the rest of the recorded command batch
[previousKeys] :: LastRecord -> [KM]

-- | space left for commands to record in this batch
[freeSpace] :: LastRecord -> Int
data HintMode
HintAbsent :: HintMode
HintShown :: HintMode
HintWiped :: HintMode
emptySessionUI :: UIOptions -> SessionUI
toggleMarkVision :: SessionUI -> SessionUI
toggleMarkSmell :: SessionUI -> SessionUI
getActorUI :: ActorId -> SessionUI -> ActorUI
instance GHC.Enum.Bounded Game.LambdaHack.Client.UI.SessionUI.HintMode
instance GHC.Enum.Enum Game.LambdaHack.Client.UI.SessionUI.HintMode
instance GHC.Classes.Eq Game.LambdaHack.Client.UI.SessionUI.HintMode
instance GHC.Show.Show Game.LambdaHack.Client.UI.SessionUI.RunParams
instance Data.Binary.Class.Binary Game.LambdaHack.Client.UI.SessionUI.AimMode
instance GHC.Classes.Eq Game.LambdaHack.Client.UI.SessionUI.AimMode
instance GHC.Show.Show Game.LambdaHack.Client.UI.SessionUI.AimMode
instance Data.Binary.Class.Binary Game.LambdaHack.Client.UI.SessionUI.SessionUI
instance Data.Binary.Class.Binary Game.LambdaHack.Client.UI.SessionUI.RunParams


-- | Basic client monad and related operations.
module Game.LambdaHack.Client.MonadClient

-- | Monad for reading client state.
class MonadStateRead m => MonadClientRead m
getsClient :: MonadClientRead m => (StateClient -> a) -> m a
liftIO :: MonadClientRead m => IO a -> m a

-- | Monad for writing to client state.
class MonadClientRead m => MonadClient m
modifyClient :: MonadClient m => (StateClient -> StateClient) -> m ()
getClient :: MonadClientRead m => m StateClient
putClient :: MonadClient m => StateClient -> m ()
debugPossiblyPrint :: MonadClient m => Text -> m ()
createTabBFS :: MonadClient m => m (PrimArray PointI)

-- | Invoke pseudo-random computation with the generator kept in the state.
rndToAction :: MonadClient m => Rnd a -> m a

-- | Invoke pseudo-random computation, don't change generator kept in
--   state. Modify the used generator by <tt>xoring</tt> with current
--   global game time.
rndToActionForget :: MonadClientRead m => Rnd a -> m a


-- | Common client monad operations.
module Game.LambdaHack.Client.CommonM

-- | Get the current perception of a client.
getPerFid :: MonadClientRead m => LevelId -> m Perception

-- | Calculate the position of an actor's target.
aidTgtToPos :: ActorId -> LevelId -> Maybe Target -> State -> Maybe Point

-- | Counts the number of steps until the projectile would hit a
--   non-projectile actor or obstacle. Starts searching with the given eps
--   and returns the first found eps for which the number reaches the
--   distance between actor and target position, or Nothing if none can be
--   found.
makeLine :: MonadStateRead m => Bool -> Actor -> Point -> Int -> m (Maybe Int)
currentSkillsClient :: MonadClientRead m => ActorId -> m Skills
pickWeaponClient :: MonadClient m => ActorId -> ActorId -> m (Maybe RequestTimed)
updateSalter :: MonadClient m => LevelId -> [(Point, ContentId TileKind)] -> m ()
createSalter :: State -> AlterLid


-- | Client monad for interacting with a human through UI.
module Game.LambdaHack.Client.UI.MonadClientUI

-- | The monad that gives the client access to UI operations, but not to
--   modifying client state.
class MonadClientRead m => MonadClientUI m
getsSession :: MonadClientUI m => (SessionUI -> a) -> m a
modifySession :: MonadClientUI m => (SessionUI -> SessionUI) -> m ()
updateClientLeader :: MonadClientUI m => ActorId -> m ()
getCacheBfs :: MonadClientUI m => ActorId -> m (Array BfsDistance)
getCachePath :: MonadClientUI m => ActorId -> Point -> m (Maybe AndPath)
clientPrintUI :: MonadClientUI m => Text -> m ()

-- | The row where the dungeon map starts.
mapStartY :: Y
getSession :: MonadClientUI m => m SessionUI
putSession :: MonadClientUI m => SessionUI -> m ()

-- | Push frames or delays to the frame queue. The frames depict the
--   <tt>lid</tt> level.
displayFrames :: MonadClientUI m => LevelId -> PreFrames -> m ()

-- | Write <a>FrontKey</a> UI request to the frontend, read the reply, set
--   pointer, return key.
connFrontendFrontKey :: MonadClientUI m => [KM] -> PreFrame -> m KM
setFrontAutoYes :: MonadClientUI m => Bool -> m ()
frontendShutdown :: MonadClientUI m => m ()
printScreen :: MonadClientUI m => m ()

-- | Initialize the frontend chosen by the player via client options.
chanFrontend :: MonadClientUI m => ScreenContent -> ClientOptions -> m ChanFrontend
anyKeyPressed :: MonadClientUI m => m Bool
discardPressedKey :: MonadClientUI m => m ()
resetPressedKeys :: MonadClientUI m => m ()
addPressedControlEsc :: MonadClientUI m => m ()
revCmdMap :: MonadClientUI m => m (KM -> HumanCmd -> KM)
getReportUI :: MonadClientUI m => m Report
getLeaderUI :: MonadClientUI m => m ActorId
getArenaUI :: MonadClientUI m => m LevelId
viewedLevelUI :: MonadClientUI m => m LevelId
leaderTgtToPos :: MonadClientUI m => m (Maybe Point)
xhairToPos :: MonadClientUI m => m (Maybe Point)
clearAimMode :: MonadClientUI m => m ()
scoreToSlideshow :: MonadClientUI m => Int -> Status -> m Slideshow
defaultHistory :: MonadClientUI m => m History
tellAllClipPS :: MonadClientUI m => m ()
tellGameClipPS :: MonadClientUI m => m ()
elapsedSessionTimeGT :: MonadClientUI m => Int -> m Bool
resetSessionStart :: MonadClientUI m => m ()
resetGameStart :: MonadClientUI m => m ()

-- | The part of speech describing the actor or the "you" pronoun if he is
--   the leader of the observer's faction.
partActorLeader :: MonadClientUI m => ActorId -> m Part
partActorLeaderFun :: MonadClientUI m => m (ActorId -> Part)

-- | The part of speech with the actor's pronoun or "you" if a leader of
--   the client's faction.
partPronounLeader :: MonadClientUI m => ActorId -> m Part

-- | Try to read saved client game state from the file system.
tryRestore :: MonadClientUI m => m (Maybe (StateClient, Maybe SessionUI))
leaderSkillsClientUI :: MonadClientUI m => m Skills

-- | Write a UI request to the frontend and read a corresponding reply.
connFrontend :: MonadClientUI m => FrontReq a -> m a
displayFrame :: MonadClientUI m => Maybe Frame -> m ()
addPressedKey :: MonadClientUI m => KMP -> m ()


-- | Running and disturbance.
--   
--   The general rule is: whatever is behind you (and so ignored
--   previously), determines what you ignore moving forward. This is
--   calcaulated separately for the tiles to the left, to the right and in
--   the middle along the running direction. So, if you want to ignore
--   something start running when you stand on it (or to the right or left,
--   respectively) or by entering it (or passing to the right or left,
--   respectively).
--   
--   Some things are never ignored, such as: enemies seen, imporant
--   messages heard, solid tiles and actors in the way.
module Game.LambdaHack.Client.UI.RunM

-- | Continue running in the given direction.
continueRun :: MonadClientUI m => LevelId -> RunParams -> m (Either Text RequestTimed)

-- | This function implements the actual logic of running. It checks if we
--   have to stop running because something interesting cropped up, it
--   ajusts the direction given by the vector if we reached a corridor's
--   corner (we never change direction except in corridors) and it
--   increments the counter of traversed tiles.
--   
--   Note that while goto-xhair commands ignore items on the way, here we
--   stop wnenever we touch an item. Running is more cautious to compensate
--   that the player cannot specify the end-point of running. It's also
--   more suited to open, already explored terrain. Goto-xhair works better
--   with unknown terrain, e.g., it stops whenever an item is spotted, but
--   then ignores the item, leaving it to the player to mark the item
--   position as a goal of the next goto.
continueRunDir :: MonadClientUI m => RunParams -> m (Either Text Vector)
walkableDir :: COps -> Level -> Point -> Vector -> Bool
tryTurning :: MonadClientRead m => ActorId -> m (Either Text Vector)
checkAndRun :: MonadClientRead m => ActorId -> Vector -> m (Either Text Vector)


-- | Monadic operations on game messages.
module Game.LambdaHack.Client.UI.MsgM

-- | Add a message to the current report.
msgAddDuplicate :: MonadClientUI m => Text -> MsgClass -> Int -> m Bool

-- | Add a message to the current report. Do not report if it was a
--   duplicate.
msgAdd :: MonadClientUI m => MsgClass -> Text -> m ()

-- | Add a message to the current report with 0 copies for the purpose of
--   collating duplicates. Do not report if it was a duplicate.
msgAdd0 :: MonadClientUI m => MsgClass -> Text -> m ()

-- | Add a prompt to the current report. Do not report if it was a
--   duplicate.
promptAdd :: MonadClientUI m => Text -> m ()

-- | Add a prompt to the current report with 0 copies for the purpose of
--   collating duplicates. Do not report if it was a duplicate.
promptAdd0 :: MonadClientUI m => Text -> m ()

-- | Add a prompt with basic keys description.
promptMainKeys :: MonadClientUI m => m ()

-- | Store new report in the history and archive old report.
recordHistory :: MonadClientUI m => m ()


-- | Breadth first search and related algorithms using the client monad.
module Game.LambdaHack.Client.BfsM
invalidateBfsAid :: MonadClient m => ActorId -> m ()
invalidateBfsPathAid :: MonadClient m => ActorId -> m ()
invalidateBfsLid :: MonadClient m => LevelId -> m ()
invalidateBfsPathLid :: MonadClient m => LevelId -> Point -> m ()
invalidateBfsAll :: MonadClient m => m ()
invalidateBfsPathAll :: MonadClient m => m ()
createBfs :: MonadClientRead m => Bool -> Word8 -> ActorId -> m (Array BfsDistance)

-- | Get cached BFS array and path or, if not stored, generate and store
--   first.
getCacheBfsAndPath :: forall m. MonadClient m => ActorId -> Point -> m (Array BfsDistance, Maybe AndPath)

-- | Get cached BFS array or, if not stored, generate and store first.
getCacheBfs :: MonadClient m => ActorId -> m (Array BfsDistance)

-- | Get cached BFS path or, if not stored, generate and store first.
getCachePath :: MonadClient m => ActorId -> Point -> m (Maybe AndPath)
createPath :: MonadClient m => ActorId -> Target -> m TgtAndPath
condBFS :: MonadClientRead m => ActorId -> m (Bool, Word8)

-- | Furthest (wrt paths) known position.
furthestKnown :: MonadClient m => ActorId -> m Point

-- | Closest reachable unknown tile position, if any.
--   
--   Note: some of these tiles are behind suspect tiles and they are chosen
--   in preference to more distant directly accessible unknown tiles. This
--   is in principle OK, but in dungeons with few hidden doors AI is at a
--   disadvantage (and with many hidden doors, it fares as well as a human
--   that deduced the dungeon properties). Changing Bfs to accomodate all
--   dungeon styles would be complex and would slow down the engine.
--   
--   If the level has inaccessible open areas (at least from the stairs AI
--   used) the level will be nevertheless here finally marked explored, to
--   enable transition to other levels. We should generally avoid such
--   levels, because digging and/or trying to find other stairs leading to
--   disconnected areas is not KISS so we don't do this in AI, so AI is at
--   a disadvantage.
--   
--   If the closest unknown is more than 126 tiles away from the targetting
--   actor, the level will marked as explored. We could complicate the code
--   and not mark if the unknown is too far as opposed to inaccessible, but
--   then if it is both too distant and inaccessible, AI would be
--   permanently stuck on such levels. To cope with this, escapes need to
--   be placed on open or small levels, or in dispersed enough that they
--   don't appear in such potentially unexplored potions of caves. Other
--   than that, this is rather harmless and hard to exploit, so let it be.
--   The principled way to fix this would be to extend BFS to
--   <tt>Word16</tt>, but then it takes too long to compute on maze levels,
--   so we'd need to optimize hard for JS.
closestUnknown :: MonadClient m => ActorId -> m (Maybe Point)

-- | Finds smells closest to the actor, except under the actor, because
--   actors consume smell only moving over them, not standing. Of the
--   closest, prefers the newest smell.
closestSmell :: MonadClient m => ActorId -> m [(Int, (Point, Time))]
data FleeViaStairsOrEscape
ViaStairs :: FleeViaStairsOrEscape
ViaStairsUp :: FleeViaStairsOrEscape
ViaStairsDown :: FleeViaStairsOrEscape
ViaEscape :: FleeViaStairsOrEscape
ViaExit :: FleeViaStairsOrEscape
ViaNothing :: FleeViaStairsOrEscape
ViaAnything :: FleeViaStairsOrEscape
embedBenefit :: MonadClientRead m => FleeViaStairsOrEscape -> ActorId -> [(Point, ItemBag)] -> m [(Double, (Point, ItemBag))]

-- | Closest (wrt paths) AI-triggerable tiles with embedded items. In AI,
--   the level the actor is on is either explored or the actor already has
--   a weapon equipped, so no need to explore further, he tries to find
--   enemies on other levels, but before that, he triggers other tiles in
--   hope of some loot or beneficial effect to enter next level with.
closestTriggers :: MonadClient m => FleeViaStairsOrEscape -> ActorId -> m [(Int, (Point, (Point, ItemBag)))]

-- | Check whether the actor has enough gear to go look for enemies. We
--   assume weapons in equipment are better than any among organs or at
--   least provide some essential diversity. Disabled if, due to tactic,
--   actors follow leader and so would repeatedly move towards and away
--   form stairs at leader change, depending on current leader's gear.
--   Number of items of a single kind is ignored, because variety is
--   needed.
condEnoughGearM :: MonadClientRead m => ActorId -> m Bool

-- | Closest (wrt paths) items.
closestItems :: MonadClient m => ActorId -> m [(Int, (Point, ItemBag))]

-- | Closest (wrt paths) enemy actors.
closestFoes :: MonadClient m => [(ActorId, Actor)] -> ActorId -> m [(Int, (ActorId, Actor))]
unexploredDepth :: MonadClientRead m => Bool -> LevelId -> m Bool
updatePathFromBfs :: MonadClient m => Bool -> BfsAndPath -> ActorId -> Point -> m (Array BfsDistance, Maybe AndPath)
instance GHC.Classes.Eq Game.LambdaHack.Client.BfsM.FleeViaStairsOrEscape
instance GHC.Show.Show Game.LambdaHack.Client.BfsM.FleeViaStairsOrEscape


-- | Assorted conditions used later on in AI logic.
module Game.LambdaHack.Client.AI.ConditionM

-- | Require that the target enemy is visible by the party.
condAimEnemyPresentM :: MonadClient m => ActorId -> m Bool

-- | Require that the target enemy is remembered on the actor's level.
condAimEnemyRememberedM :: MonadClient m => ActorId -> m Bool

-- | Require that the target non-enemy is visible by the party.
condAimNonEnemyPresentM :: MonadClient m => ActorId -> m Bool

-- | Require that the target enemy is visible by the party and doesn't
--   melee.
condAimEnemyNoMeleeM :: MonadClient m => ActorId -> m Bool
condInMeleeM :: MonadClient m => LevelId -> m Bool

-- | Require that the target is crucial to success, e.g., an item, or that
--   it's not too far away and so the changes to get it are high.
condAimCrucialM :: MonadClient m => ActorId -> m Bool

-- | Check if the target is a nonmoving enemy.
condTgtNonmovingEnemyM :: MonadClient m => ActorId -> m Bool

-- | Require that any non-dying foe is adjacent, except projectiles that
--   (possibly) explode upon contact.
condAnyFoeAdjM :: MonadStateRead m => ActorId -> m Bool

-- | Require the actor stands on or adjacent to a triggerable tile (e.g.,
--   stairs).
condAdjTriggerableM :: MonadClient m => ActorId -> m Bool

-- | Produce the chess-distance-sorted list of non-low-HP, melee-cabable
--   foes on the level. We don't consider path-distance, because we are
--   interested in how soon the foe can close in to hit us, which can
--   diverge greately from path distance for short distances, e.g., when
--   terrain gets revealed. We don't consider non-moving actors, because
--   they can't chase us and also because they can't be aggresive so to
--   resolve the stalemate, the opposing AI has to be aggresive by ignoring
--   them and closing in to melee distance.
meleeThreatDistList :: ActorId -> State -> [(Int, (ActorId, Actor))]

-- | Require the actor blocks the paths of any of his party members.
condBlocksFriendsM :: MonadClient m => ActorId -> m Bool

-- | Require the actor stands over a weapon that would be auto-equipped.
condFloorWeaponM :: MonadStateRead m => ActorId -> m Bool

-- | Check whether the actor has no weapon in equipment.
condNoEqpWeaponM :: MonadStateRead m => ActorId -> m Bool

-- | Require that the actor can project any items.
condCanProjectM :: MonadClient m => Int -> ActorId -> m Bool
condProjectListM :: MonadClient m => Int -> ActorId -> m [(Benefit, CStore, ItemId, ItemFull, ItemQuant)]

-- | Produce the list of items from the given stores available to the actor
--   and the items' values.
benAvailableItems :: DiscoveryBenefit -> ActorId -> [CStore] -> State -> [(Benefit, CStore, ItemId, ItemFull, ItemQuant)]
hinders :: Bool -> Bool -> Bool -> Bool -> Skills -> ItemFull -> Bool

-- | Require that the actor stands over a desirable item.
condDesirableFloorItemM :: MonadClient m => ActorId -> m Bool

-- | Produce the list of items on the ground beneath the actor that are
--   worth picking up.
benGroundItems :: MonadClient m => ActorId -> m [(Benefit, CStore, ItemId, ItemFull, ItemQuant)]
desirableItem :: COps -> Bool -> Double -> AspectRecord -> ItemKind -> Int -> Bool
condSupport :: MonadClient m => Int -> ActorId -> m Bool
condSoloM :: MonadClient m => ActorId -> m Bool

-- | Require that the actor stands in the dark and so would be betrayed by
--   his own equipped light,
condShineWouldBetrayM :: MonadStateRead m => ActorId -> m Bool

-- | Produce a list of acceptable adjacent points to flee to.
fleeList :: MonadClient m => ActorId -> m ([(Int, Point)], [(Int, Point)])


-- | Let AI pick the best target for an actor.
module Game.LambdaHack.Client.AI.PickTargetM

-- | Verify and possibly change the target of an actor. This function both
--   updates the target in the client state and returns the new target
--   explicitly.
refreshTarget :: MonadClient m => (ActorId, Actor) -> m (Maybe TgtAndPath)
computeTarget :: forall m. MonadClient m => ActorId -> m (Maybe TgtAndPath)


-- | Picking the AI actor to move and refreshing leader and non-leader
--   targets.
module Game.LambdaHack.Client.AI.PickActorM

-- | Pick a new leader from among the actors on the current level. Refresh
--   the target of the new leader, even if unchanged.
pickActorToMove :: MonadClient m => Maybe ActorId -> m ActorId

-- | Inspect the tactics of the actor and set his target according to it.
setTargetFromTactics :: MonadClient m => ActorId -> m ()


-- | AI procedure for picking the best action for an actor.
module Game.LambdaHack.Client.AI.PickActionM

-- | Pick the most desirable AI ation for the actor.
pickAction :: MonadClient m => ActorId -> Bool -> m RequestTimed
actionStrategy :: forall m. MonadClient m => ActorId -> Bool -> m (Strategy RequestTimed)
waitBlockNow :: MonadClient m => m (Strategy RequestTimed)
yellNow :: MonadClient m => m (Strategy RequestTimed)
pickup :: MonadClient m => ActorId -> Bool -> m (Strategy RequestTimed)
equipItems :: MonadClient m => ActorId -> m (Strategy RequestTimed)
yieldUnneeded :: MonadClient m => ActorId -> m (Strategy RequestTimed)
unEquipItems :: MonadClient m => ActorId -> m (Strategy RequestTimed)
groupByEqpSlot :: [(ItemId, ItemFullKit)] -> EnumMap EqpSlot [(ItemId, ItemFullKit)]
bestByEqpSlot :: DiscoveryBenefit -> [(ItemId, ItemFullKit)] -> [(ItemId, ItemFullKit)] -> [(ItemId, ItemFullKit)] -> [([(Int, (ItemId, ItemFullKit))], [(Int, (ItemId, ItemFullKit))], [(Int, (ItemId, ItemFullKit))])]
harmful :: DiscoveryBenefit -> ItemId -> Bool
meleeBlocker :: MonadClient m => ActorId -> m (Strategy RequestTimed)
meleeAny :: MonadClient m => ActorId -> m (Strategy RequestTimed)
trigger :: MonadClient m => ActorId -> FleeViaStairsOrEscape -> m (Strategy RequestTimed)
projectItem :: MonadClient m => ActorId -> m (Strategy RequestTimed)
data ApplyItemGroup
applyItem :: MonadClient m => ActorId -> ApplyItemGroup -> m (Strategy RequestTimed)
flee :: MonadClient m => ActorId -> [(Int, Point)] -> m (Strategy RequestTimed)
displaceFoe :: MonadClient m => ActorId -> m (Strategy RequestTimed)
displaceBlocker :: MonadClient m => ActorId -> Bool -> m (Strategy RequestTimed)
displaceTgt :: MonadClient m => ActorId -> Point -> Bool -> m (Strategy RequestTimed)
chase :: MonadClient m => ActorId -> Bool -> Bool -> m (Strategy RequestTimed)
moveTowards :: MonadClient m => ActorId -> Point -> Point -> Bool -> m (Strategy Vector)
moveOrRunAid :: MonadClient m => ActorId -> Vector -> m (Maybe RequestTimed)
instance GHC.Classes.Eq Game.LambdaHack.Client.AI.PickActionM.ApplyItemGroup


-- | Ways for the client to use AI to produce server requests, based on the
--   client's view of the game state.
module Game.LambdaHack.Client.AI

-- | Handle the move of an actor under AI control (regardless if the whole
--   faction is under human or computer control).
queryAI :: MonadClient m => ActorId -> m RequestAI

-- | Pick an actor to move and an action for him to perform, given an
--   optional previous candidate actor and action and the server-proposed
--   actor.
pickActorAndAction :: MonadClient m => Maybe ActorId -> ActorId -> m (ActorId, RequestTimed, Maybe Point)


-- | The monad for writing to the main game state.
module Game.LambdaHack.Atomic.MonadStateWrite

-- | The monad for writing to the main game state. Atomic updates
--   (<tt>UpdAtomic</tt>) are given semantics in this monad.
class MonadStateRead m => MonadStateWrite m
modifyState :: MonadStateWrite m => (State -> State) -> m ()
putState :: MonadStateWrite m => State -> m ()

-- | Exception signifying that atomic action failed because the information
--   it carries is inconsistent with the client's state, (e.g., because the
--   client knows too little to understand the command or already deduced
--   the state change from earlier commands or is confused, amnesiac or
--   sees illusory actors or tiles). Whenever we know the failure is
--   logically impossible, we don't throw the <tt>AtomicFail</tt>
--   exception, but insert a normal assertion or <tt>error</tt> call, which
--   are never caught nor handled.
newtype AtomicFail
AtomicFail :: String -> AtomicFail
atomicFail :: String -> a
updateLevel :: MonadStateWrite m => LevelId -> (Level -> Level) -> m ()
updateActor :: MonadStateWrite m => ActorId -> (Actor -> Actor) -> m ()
updateFaction :: MonadStateWrite m => FactionId -> (Faction -> Faction) -> m ()
moveActorMap :: MonadStateWrite m => ActorId -> Actor -> Actor -> m ()
swapActorMap :: MonadStateWrite m => ActorId -> Actor -> ActorId -> Actor -> m ()
insertBagContainer :: MonadStateWrite m => ItemBag -> Container -> m ()
insertItemContainer :: MonadStateWrite m => ItemId -> ItemQuant -> Container -> m ()
insertItemActor :: MonadStateWrite m => ItemId -> ItemQuant -> ActorId -> CStore -> m ()
deleteBagContainer :: MonadStateWrite m => ItemBag -> Container -> m ()
deleteItemContainer :: MonadStateWrite m => ItemId -> ItemQuant -> Container -> m ()
deleteItemActor :: MonadStateWrite m => ItemId -> ItemQuant -> ActorId -> CStore -> m ()
addAis :: MonadStateWrite m => [(ItemId, Item)] -> m ()
itemsMatch :: Item -> Item -> Bool
addItemToActorMaxSkills :: MonadStateWrite m => ItemId -> Item -> Int -> ActorId -> m ()
resetActorMaxSkills :: MonadStateWrite m => m ()
insertItemFloor :: MonadStateWrite m => ItemId -> ItemQuant -> LevelId -> Point -> m ()
insertItemEmbed :: MonadStateWrite m => ItemId -> ItemQuant -> LevelId -> Point -> m ()
insertItemOrgan :: MonadStateWrite m => ItemId -> ItemQuant -> ActorId -> m ()
insertItemEqp :: MonadStateWrite m => ItemId -> ItemQuant -> ActorId -> m ()
insertItemInv :: MonadStateWrite m => ItemId -> ItemQuant -> ActorId -> m ()
insertItemSha :: MonadStateWrite m => ItemId -> ItemQuant -> FactionId -> m ()
deleteItemFloor :: MonadStateWrite m => ItemId -> ItemQuant -> LevelId -> Point -> m ()
deleteItemEmbed :: MonadStateWrite m => ItemId -> ItemQuant -> LevelId -> Point -> m ()
deleteItemOrgan :: MonadStateWrite m => ItemId -> ItemQuant -> ActorId -> m ()
deleteItemEqp :: MonadStateWrite m => ItemId -> ItemQuant -> ActorId -> m ()
deleteItemInv :: MonadStateWrite m => ItemId -> ItemQuant -> ActorId -> m ()
deleteItemSha :: MonadStateWrite m => ItemId -> ItemQuant -> FactionId -> m ()
rmFromBag :: ItemQuant -> ItemId -> ItemBag -> ItemBag
instance GHC.Show.Show Game.LambdaHack.Atomic.MonadStateWrite.AtomicFail
instance GHC.Exception.Type.Exception Game.LambdaHack.Atomic.MonadStateWrite.AtomicFail


-- | A set of atomic commands shared by client and server. These are the
--   largest building blocks that have no components that can be observed
--   in isolation.
--   
--   We try to make atomic commands respect the laws of energy and mass
--   conservation, unless they really can't, e.g., monster spawning. For
--   example item removal from inventory is not an atomic command, but item
--   dropped from the inventory to the ground is. This makes it easier to
--   undo the commands. In principle, the commands are the only way to
--   affect the basic game state (<a>State</a>).
--   
--   See
--   <a>https://github.com/LambdaHack/LambdaHack/wiki/Client-server-architecture</a>.
module Game.LambdaHack.Atomic.CmdAtomic

-- | Abstract syntax of atomic commands, that is, atomic game state
--   transformations.
data CmdAtomic

-- | atomic updates
UpdAtomic :: UpdAtomic -> CmdAtomic

-- | atomic special effects
SfxAtomic :: SfxAtomic -> CmdAtomic

-- | Abstract syntax of atomic updates, that is, atomic commands that
--   really change the <a>State</a>. Most of them are an encoding of a game
--   state diff, though they also carry some intentional hints that help
--   clients determine whether and how to communicate it to players.
data UpdAtomic
UpdCreateActor :: ActorId -> Actor -> [(ItemId, Item)] -> UpdAtomic
UpdDestroyActor :: ActorId -> Actor -> [(ItemId, Item)] -> UpdAtomic
UpdCreateItem :: ItemId -> Item -> ItemQuant -> Container -> UpdAtomic
UpdDestroyItem :: ItemId -> Item -> ItemQuant -> Container -> UpdAtomic
UpdSpotActor :: ActorId -> Actor -> [(ItemId, Item)] -> UpdAtomic
UpdLoseActor :: ActorId -> Actor -> [(ItemId, Item)] -> UpdAtomic
UpdSpotItem :: Bool -> ItemId -> Item -> ItemQuant -> Container -> UpdAtomic
UpdLoseItem :: Bool -> ItemId -> Item -> ItemQuant -> Container -> UpdAtomic
UpdSpotItemBag :: Container -> ItemBag -> [(ItemId, Item)] -> UpdAtomic
UpdLoseItemBag :: Container -> ItemBag -> [(ItemId, Item)] -> UpdAtomic
UpdMoveActor :: ActorId -> Point -> Point -> UpdAtomic
UpdWaitActor :: ActorId -> Watchfulness -> Watchfulness -> UpdAtomic
UpdDisplaceActor :: ActorId -> ActorId -> UpdAtomic
UpdMoveItem :: ItemId -> Int -> ActorId -> CStore -> CStore -> UpdAtomic
UpdRefillHP :: ActorId -> Int64 -> UpdAtomic
UpdRefillCalm :: ActorId -> Int64 -> UpdAtomic
UpdTrajectory :: ActorId -> Maybe ([Vector], Speed) -> Maybe ([Vector], Speed) -> UpdAtomic
UpdQuitFaction :: FactionId -> Maybe Status -> Maybe Status -> Maybe (FactionAnalytics, GenerationAnalytics) -> UpdAtomic
UpdLeadFaction :: FactionId -> Maybe ActorId -> Maybe ActorId -> UpdAtomic
UpdDiplFaction :: FactionId -> FactionId -> Diplomacy -> Diplomacy -> UpdAtomic
UpdTacticFaction :: FactionId -> Tactic -> Tactic -> UpdAtomic
UpdAutoFaction :: FactionId -> Bool -> UpdAtomic
UpdRecordKill :: ActorId -> ContentId ItemKind -> Int -> UpdAtomic
UpdAlterTile :: LevelId -> Point -> ContentId TileKind -> ContentId TileKind -> UpdAtomic
UpdAlterExplorable :: LevelId -> Int -> UpdAtomic
UpdAlterGold :: Int -> UpdAtomic
UpdSearchTile :: ActorId -> Point -> ContentId TileKind -> UpdAtomic
UpdHideTile :: ActorId -> Point -> ContentId TileKind -> UpdAtomic
UpdSpotTile :: LevelId -> [(Point, ContentId TileKind)] -> UpdAtomic
UpdLoseTile :: LevelId -> [(Point, ContentId TileKind)] -> UpdAtomic
UpdSpotEntry :: LevelId -> [(Point, PlaceEntry)] -> UpdAtomic
UpdLoseEntry :: LevelId -> [(Point, PlaceEntry)] -> UpdAtomic
UpdAlterSmell :: LevelId -> Point -> Time -> Time -> UpdAtomic
UpdSpotSmell :: LevelId -> [(Point, Time)] -> UpdAtomic
UpdLoseSmell :: LevelId -> [(Point, Time)] -> UpdAtomic
UpdTimeItem :: ItemId -> Container -> ItemTimer -> ItemTimer -> UpdAtomic
UpdAgeGame :: [LevelId] -> UpdAtomic
UpdUnAgeGame :: [LevelId] -> UpdAtomic
UpdDiscover :: Container -> ItemId -> ContentId ItemKind -> AspectRecord -> UpdAtomic
UpdCover :: Container -> ItemId -> ContentId ItemKind -> AspectRecord -> UpdAtomic
UpdDiscoverKind :: Container -> ItemKindIx -> ContentId ItemKind -> UpdAtomic
UpdCoverKind :: Container -> ItemKindIx -> ContentId ItemKind -> UpdAtomic
UpdDiscoverAspect :: Container -> ItemId -> AspectRecord -> UpdAtomic
UpdCoverAspect :: Container -> ItemId -> AspectRecord -> UpdAtomic
UpdDiscoverServer :: ItemId -> AspectRecord -> UpdAtomic
UpdCoverServer :: ItemId -> AspectRecord -> UpdAtomic
UpdPerception :: LevelId -> Perception -> Perception -> UpdAtomic
UpdRestart :: FactionId -> PerLid -> State -> Challenge -> ClientOptions -> StdGen -> UpdAtomic
UpdRestartServer :: State -> UpdAtomic
UpdResume :: FactionId -> PerLid -> UpdAtomic
UpdResumeServer :: State -> UpdAtomic
UpdKillExit :: FactionId -> UpdAtomic
UpdWriteSave :: UpdAtomic
UpdHearFid :: FactionId -> HearMsg -> UpdAtomic

-- | Symbolic representation of text messages about heard noises, sent by
--   server to clients and shown to players and used by AI.
data HearMsg
HearUpd :: Bool -> UpdAtomic -> HearMsg
HearStrike :: ContentId ItemKind -> HearMsg
HearSummon :: Bool -> GroupName ItemKind -> Dice -> HearMsg
HearTaunt :: Text -> HearMsg

-- | Abstract syntax of atomic special effects, that is, atomic commands
--   that only display special effects and don't change <a>State</a> nor
--   client state.
data SfxAtomic
SfxStrike :: ActorId -> ActorId -> ItemId -> CStore -> SfxAtomic
SfxRecoil :: ActorId -> ActorId -> ItemId -> CStore -> SfxAtomic
SfxSteal :: ActorId -> ActorId -> ItemId -> CStore -> SfxAtomic
SfxRelease :: ActorId -> ActorId -> ItemId -> CStore -> SfxAtomic
SfxProject :: ActorId -> ItemId -> CStore -> SfxAtomic
SfxReceive :: ActorId -> ItemId -> CStore -> SfxAtomic
SfxApply :: ActorId -> ItemId -> CStore -> SfxAtomic
SfxCheck :: ActorId -> ItemId -> CStore -> SfxAtomic
SfxTrigger :: ActorId -> Point -> SfxAtomic
SfxShun :: ActorId -> Point -> SfxAtomic
SfxEffect :: FactionId -> ActorId -> Effect -> Int64 -> SfxAtomic
SfxMsgFid :: FactionId -> SfxMsg -> SfxAtomic
SfxRestart :: SfxAtomic
SfxCollideTile :: ActorId -> Point -> SfxAtomic
SfxTaunt :: Bool -> ActorId -> SfxAtomic

-- | Symbolic representation of text messages sent by server to clients and
--   shown to players.
data SfxMsg
SfxUnexpected :: ReqFailure -> SfxMsg
SfxExpected :: Text -> ReqFailure -> SfxMsg
SfxFizzles :: SfxMsg
SfxNothingHappens :: SfxMsg
SfxVoidDetection :: DetectKind -> SfxMsg
SfxUnimpressed :: ActorId -> SfxMsg
SfxSummonLackCalm :: ActorId -> SfxMsg
SfxSummonTooManyOwn :: ActorId -> SfxMsg
SfxSummonTooManyAll :: ActorId -> SfxMsg
SfxSummonFailure :: ActorId -> SfxMsg
SfxLevelNoMore :: SfxMsg
SfxLevelPushed :: SfxMsg
SfxBracedImmune :: ActorId -> SfxMsg
SfxEscapeImpossible :: SfxMsg
SfxStasisProtects :: SfxMsg
SfxWaterParalysisResisted :: SfxMsg
SfxTransImpossible :: SfxMsg
SfxIdentifyNothing :: SfxMsg
SfxPurposeNothing :: SfxMsg
SfxPurposeTooFew :: Int -> Int -> SfxMsg
SfxPurposeUnique :: SfxMsg
SfxPurposeNotCommon :: SfxMsg
SfxRerollNothing :: SfxMsg
SfxRerollNotRandom :: SfxMsg
SfxDupNothing :: SfxMsg
SfxDupUnique :: SfxMsg
SfxDupValuable :: SfxMsg
SfxColdFish :: SfxMsg
SfxTimerExtended :: LevelId -> ActorId -> ItemId -> CStore -> Delta Time -> SfxMsg
SfxCollideActor :: LevelId -> ActorId -> ActorId -> SfxMsg
undoUpdAtomic :: UpdAtomic -> Maybe UpdAtomic
undoSfxAtomic :: SfxAtomic -> SfxAtomic
undoCmdAtomic :: CmdAtomic -> Maybe CmdAtomic
instance GHC.Show.Show Game.LambdaHack.Atomic.CmdAtomic.CmdAtomic
instance GHC.Show.Show Game.LambdaHack.Atomic.CmdAtomic.SfxAtomic
instance GHC.Show.Show Game.LambdaHack.Atomic.CmdAtomic.SfxMsg
instance GHC.Show.Show Game.LambdaHack.Atomic.CmdAtomic.UpdAtomic
instance GHC.Show.Show Game.LambdaHack.Atomic.CmdAtomic.HearMsg


-- | Representation and computation of visiblity of atomic commands by
--   clients.
--   
--   See
--   <a>https://github.com/LambdaHack/LambdaHack/wiki/Client-server-architecture</a>.
module Game.LambdaHack.Atomic.PosAtomicRead

-- | The type representing visibility of atomic commands to factions, based
--   on the position of the command, etc. Note that the server sees and
--   smells all positions. Also note that hearing is not covered because it
--   gives very restricted information, so hearing doesn't equal seeing
--   (and we assume smelling actors get lots of data from smells).
data PosAtomic

-- | whomever sees all the positions, notices
PosSight :: LevelId -> [Point] -> PosAtomic

-- | observers and the faction notice
PosFidAndSight :: [FactionId] -> LevelId -> [Point] -> PosAtomic

-- | whomever smells all the positions, notices
PosSmell :: LevelId -> [Point] -> PosAtomic

-- | only the faction notices, server doesn't
PosFid :: FactionId -> PosAtomic

-- | faction and server notices
PosFidAndSer :: Maybe LevelId -> FactionId -> PosAtomic

-- | only the server notices
PosSer :: PosAtomic

-- | everybody notices
PosAll :: PosAtomic

-- | never broadcasted, but sent manually
PosNone :: PosAtomic

-- | Produce the positions where the atomic update takes place or, more
--   generally, the conditions under which the update can be noticed by a
--   client.
--   
--   The goal of this mechanics is to ensure that atomic commands involving
--   some positions visible by a client convey similar information as the
--   client would get by directly observing the changes of the portion of
--   server state limited to the visible positions. Consequently, when the
--   visible commands are later applied to the client's state, the state
--   stays consistent --- in sync with the server state and correctly
--   limited by visiblity. There is some wiggle room both in what "in sync"
--   and "visible" means and how they propagate through time.
--   
--   E.g., <tt>UpdDisplaceActor</tt> in a black room between two enemy
--   actors, with only one actor carrying a 0-radius light would not be
--   distinguishable by looking at the state (or the screen) from
--   <tt>UpdMoveActor</tt> of the illuminated actor, hence such
--   <tt>UpdDisplaceActor</tt> should not be observable, but
--   <tt>UpdMoveActor</tt> in similar cotext would be (or the former should
--   be perceived as the latter). However, to simplify, we assign as strict
--   visibility requirements to <tt>UpdMoveActor</tt> as to
--   <tt>UpdDisplaceActor</tt> and fall back to <tt>UpdSpotActor</tt>
--   (which provides minimal information that does not contradict state) if
--   the visibility is lower.
posUpdAtomic :: MonadStateRead m => UpdAtomic -> m PosAtomic

-- | Produce the positions where the atomic special effect takes place.
posSfxAtomic :: MonadStateRead m => SfxAtomic -> m PosAtomic

-- | Decompose an atomic action that is outside a client's visiblity. The
--   decomposed actions give less information that the original command,
--   but some of them may fall within the visibility range of the client.
--   The original action may give more information than even the total sum
--   of all actions it's broken into. E.g., <tt>UpdMoveActor</tt> informs
--   about the continued existence of the actor between moves vs popping
--   out of existence and then back in.
--   
--   This is computed in server's <tt>State</tt> from before performing the
--   command.
breakUpdAtomic :: MonadStateRead m => UpdAtomic -> m [UpdAtomic]

-- | Given the client, its perception and an atomic command, determine if
--   the client notices the command.
seenAtomicCli :: Bool -> FactionId -> Perception -> PosAtomic -> Bool

-- | Determine whether the server would see a command that has the given
--   visibilty conditions.
seenAtomicSer :: PosAtomic -> Bool
posProjBody :: Actor -> PosAtomic
singleAid :: MonadStateRead m => ActorId -> m PosAtomic
doubleAid :: MonadStateRead m => ActorId -> ActorId -> m PosAtomic
singleContainer :: MonadStateRead m => Container -> m PosAtomic
instance GHC.Classes.Eq Game.LambdaHack.Atomic.PosAtomicRead.PosAtomic
instance GHC.Show.Show Game.LambdaHack.Atomic.PosAtomicRead.PosAtomic


-- | Semantics of atomic commands shared by client and server.
--   
--   See
--   <a>https://github.com/LambdaHack/LambdaHack/wiki/Client-server-architecture</a>.
module Game.LambdaHack.Atomic.HandleAtomicWrite

-- | The game-state semantics of atomic game commands. There is no
--   corresponding definition for special effects (<tt>SfxAtomic</tt>),
--   because they don't modify <a>State</a>.
--   
--   For each of the commands, we are guaranteed that the client, the
--   command is addressed to, perceives all the positions the command
--   affects (as computed by <a>posUpdAtomic</a>). In the code for each
--   semantic function we additonally verify the client is aware of any
--   relevant items and/or actors and we throw the <tt>AtomicFail</tt>
--   exception if it's not. The server keeps copies of all clients' states
--   and, before sending a command to a client, applies it to the client's
--   state copy. If <tt>AtomicFail</tt> is signalled, the command is
--   ignored for that client. This enables simpler server code that
--   addresses commands to all clients that can see it, even though not all
--   are able to process it.
handleUpdAtomic :: MonadStateWrite m => UpdAtomic -> m ()
updCreateActor :: MonadStateWrite m => ActorId -> Actor -> [(ItemId, Item)] -> m ()
updDestroyActor :: MonadStateWrite m => ActorId -> Actor -> [(ItemId, Item)] -> m ()
updCreateItem :: MonadStateWrite m => ItemId -> Item -> ItemQuant -> Container -> m ()
updDestroyItem :: MonadStateWrite m => ItemId -> Item -> ItemQuant -> Container -> m ()
updSpotItemBag :: MonadStateWrite m => Container -> ItemBag -> [(ItemId, Item)] -> m ()
updLoseItemBag :: MonadStateWrite m => Container -> ItemBag -> [(ItemId, Item)] -> m ()
updMoveActor :: MonadStateWrite m => ActorId -> Point -> Point -> m ()
updWaitActor :: MonadStateWrite m => ActorId -> Watchfulness -> Watchfulness -> m ()
updDisplaceActor :: MonadStateWrite m => ActorId -> ActorId -> m ()
updMoveItem :: MonadStateWrite m => ItemId -> Int -> ActorId -> CStore -> CStore -> m ()
updRefillHP :: MonadStateWrite m => ActorId -> Int64 -> m ()
updRefillCalm :: MonadStateWrite m => ActorId -> Int64 -> m ()
updTrajectory :: MonadStateWrite m => ActorId -> Maybe ([Vector], Speed) -> Maybe ([Vector], Speed) -> m ()
updQuitFaction :: MonadStateWrite m => FactionId -> Maybe Status -> Maybe Status -> m ()
updLeadFaction :: MonadStateWrite m => FactionId -> Maybe ActorId -> Maybe ActorId -> m ()
updDiplFaction :: MonadStateWrite m => FactionId -> FactionId -> Diplomacy -> Diplomacy -> m ()
updTacticFaction :: MonadStateWrite m => FactionId -> Tactic -> Tactic -> m ()
updAutoFaction :: MonadStateWrite m => FactionId -> Bool -> m ()
updRecordKill :: MonadStateWrite m => ActorId -> ContentId ItemKind -> Int -> m ()
updAlterTile :: MonadStateWrite m => LevelId -> Point -> ContentId TileKind -> ContentId TileKind -> m ()
updAlterExplorable :: MonadStateWrite m => LevelId -> Int -> m ()
updSearchTile :: MonadStateWrite m => ActorId -> Point -> ContentId TileKind -> m ()
updSpotTile :: MonadStateWrite m => LevelId -> [(Point, ContentId TileKind)] -> m ()
updLoseTile :: MonadStateWrite m => LevelId -> [(Point, ContentId TileKind)] -> m ()
updAlterSmell :: MonadStateWrite m => LevelId -> Point -> Time -> Time -> m ()
updSpotSmell :: MonadStateWrite m => LevelId -> [(Point, Time)] -> m ()
updLoseSmell :: MonadStateWrite m => LevelId -> [(Point, Time)] -> m ()
updTimeItem :: MonadStateWrite m => ItemId -> Container -> ItemTimer -> ItemTimer -> m ()
updAgeGame :: MonadStateWrite m => [LevelId] -> m ()
updUnAgeGame :: MonadStateWrite m => [LevelId] -> m ()
ageLevel :: MonadStateWrite m => Delta Time -> LevelId -> m ()
updDiscover :: MonadStateWrite m => Container -> ItemId -> ContentId ItemKind -> AspectRecord -> m ()
updCover :: Container -> ItemId -> ContentId ItemKind -> AspectRecord -> m ()
updDiscoverKind :: MonadStateWrite m => Container -> ItemKindIx -> ContentId ItemKind -> m ()
discoverKind :: MonadStateWrite m => ItemKindIx -> ContentId ItemKind -> m ()
updCoverKind :: Container -> ItemKindIx -> ContentId ItemKind -> m ()
updDiscoverAspect :: MonadStateWrite m => Container -> ItemId -> AspectRecord -> m ()
discoverAspect :: MonadStateWrite m => ItemId -> AspectRecord -> m ()
updCoverAspect :: Container -> ItemId -> AspectRecord -> m ()
updDiscoverServer :: MonadStateWrite m => ItemId -> AspectRecord -> m ()
updCoverServer :: MonadStateWrite m => ItemId -> AspectRecord -> m ()
updRestart :: MonadStateWrite m => State -> m ()
updRestartServer :: MonadStateWrite m => State -> m ()
updResumeServer :: MonadStateWrite m => State -> m ()


-- | Atomic game state transformations, their representation and semantics.
--   
--   See
--   <a>https://github.com/LambdaHack/LambdaHack/wiki/Client-server-architecture</a>.
module Game.LambdaHack.Atomic

-- | Abstract syntax of atomic commands, that is, atomic game state
--   transformations.
data CmdAtomic

-- | atomic updates
UpdAtomic :: UpdAtomic -> CmdAtomic

-- | atomic special effects
SfxAtomic :: SfxAtomic -> CmdAtomic

-- | Abstract syntax of atomic updates, that is, atomic commands that
--   really change the <a>State</a>. Most of them are an encoding of a game
--   state diff, though they also carry some intentional hints that help
--   clients determine whether and how to communicate it to players.
data UpdAtomic
UpdCreateActor :: ActorId -> Actor -> [(ItemId, Item)] -> UpdAtomic
UpdDestroyActor :: ActorId -> Actor -> [(ItemId, Item)] -> UpdAtomic
UpdCreateItem :: ItemId -> Item -> ItemQuant -> Container -> UpdAtomic
UpdDestroyItem :: ItemId -> Item -> ItemQuant -> Container -> UpdAtomic
UpdSpotActor :: ActorId -> Actor -> [(ItemId, Item)] -> UpdAtomic
UpdLoseActor :: ActorId -> Actor -> [(ItemId, Item)] -> UpdAtomic
UpdSpotItem :: Bool -> ItemId -> Item -> ItemQuant -> Container -> UpdAtomic
UpdLoseItem :: Bool -> ItemId -> Item -> ItemQuant -> Container -> UpdAtomic
UpdSpotItemBag :: Container -> ItemBag -> [(ItemId, Item)] -> UpdAtomic
UpdLoseItemBag :: Container -> ItemBag -> [(ItemId, Item)] -> UpdAtomic
UpdMoveActor :: ActorId -> Point -> Point -> UpdAtomic
UpdWaitActor :: ActorId -> Watchfulness -> Watchfulness -> UpdAtomic
UpdDisplaceActor :: ActorId -> ActorId -> UpdAtomic
UpdMoveItem :: ItemId -> Int -> ActorId -> CStore -> CStore -> UpdAtomic
UpdRefillHP :: ActorId -> Int64 -> UpdAtomic
UpdRefillCalm :: ActorId -> Int64 -> UpdAtomic
UpdTrajectory :: ActorId -> Maybe ([Vector], Speed) -> Maybe ([Vector], Speed) -> UpdAtomic
UpdQuitFaction :: FactionId -> Maybe Status -> Maybe Status -> Maybe (FactionAnalytics, GenerationAnalytics) -> UpdAtomic
UpdLeadFaction :: FactionId -> Maybe ActorId -> Maybe ActorId -> UpdAtomic
UpdDiplFaction :: FactionId -> FactionId -> Diplomacy -> Diplomacy -> UpdAtomic
UpdTacticFaction :: FactionId -> Tactic -> Tactic -> UpdAtomic
UpdAutoFaction :: FactionId -> Bool -> UpdAtomic
UpdRecordKill :: ActorId -> ContentId ItemKind -> Int -> UpdAtomic
UpdAlterTile :: LevelId -> Point -> ContentId TileKind -> ContentId TileKind -> UpdAtomic
UpdAlterExplorable :: LevelId -> Int -> UpdAtomic
UpdAlterGold :: Int -> UpdAtomic
UpdSearchTile :: ActorId -> Point -> ContentId TileKind -> UpdAtomic
UpdHideTile :: ActorId -> Point -> ContentId TileKind -> UpdAtomic
UpdSpotTile :: LevelId -> [(Point, ContentId TileKind)] -> UpdAtomic
UpdLoseTile :: LevelId -> [(Point, ContentId TileKind)] -> UpdAtomic
UpdSpotEntry :: LevelId -> [(Point, PlaceEntry)] -> UpdAtomic
UpdLoseEntry :: LevelId -> [(Point, PlaceEntry)] -> UpdAtomic
UpdAlterSmell :: LevelId -> Point -> Time -> Time -> UpdAtomic
UpdSpotSmell :: LevelId -> [(Point, Time)] -> UpdAtomic
UpdLoseSmell :: LevelId -> [(Point, Time)] -> UpdAtomic
UpdTimeItem :: ItemId -> Container -> ItemTimer -> ItemTimer -> UpdAtomic
UpdAgeGame :: [LevelId] -> UpdAtomic
UpdUnAgeGame :: [LevelId] -> UpdAtomic
UpdDiscover :: Container -> ItemId -> ContentId ItemKind -> AspectRecord -> UpdAtomic
UpdCover :: Container -> ItemId -> ContentId ItemKind -> AspectRecord -> UpdAtomic
UpdDiscoverKind :: Container -> ItemKindIx -> ContentId ItemKind -> UpdAtomic
UpdCoverKind :: Container -> ItemKindIx -> ContentId ItemKind -> UpdAtomic
UpdDiscoverAspect :: Container -> ItemId -> AspectRecord -> UpdAtomic
UpdCoverAspect :: Container -> ItemId -> AspectRecord -> UpdAtomic
UpdDiscoverServer :: ItemId -> AspectRecord -> UpdAtomic
UpdCoverServer :: ItemId -> AspectRecord -> UpdAtomic
UpdPerception :: LevelId -> Perception -> Perception -> UpdAtomic
UpdRestart :: FactionId -> PerLid -> State -> Challenge -> ClientOptions -> StdGen -> UpdAtomic
UpdRestartServer :: State -> UpdAtomic
UpdResume :: FactionId -> PerLid -> UpdAtomic
UpdResumeServer :: State -> UpdAtomic
UpdKillExit :: FactionId -> UpdAtomic
UpdWriteSave :: UpdAtomic
UpdHearFid :: FactionId -> HearMsg -> UpdAtomic

-- | Symbolic representation of text messages about heard noises, sent by
--   server to clients and shown to players and used by AI.
data HearMsg
HearUpd :: Bool -> UpdAtomic -> HearMsg
HearStrike :: ContentId ItemKind -> HearMsg
HearSummon :: Bool -> GroupName ItemKind -> Dice -> HearMsg
HearTaunt :: Text -> HearMsg

-- | Abstract syntax of atomic special effects, that is, atomic commands
--   that only display special effects and don't change <a>State</a> nor
--   client state.
data SfxAtomic
SfxStrike :: ActorId -> ActorId -> ItemId -> CStore -> SfxAtomic
SfxRecoil :: ActorId -> ActorId -> ItemId -> CStore -> SfxAtomic
SfxSteal :: ActorId -> ActorId -> ItemId -> CStore -> SfxAtomic
SfxRelease :: ActorId -> ActorId -> ItemId -> CStore -> SfxAtomic
SfxProject :: ActorId -> ItemId -> CStore -> SfxAtomic
SfxReceive :: ActorId -> ItemId -> CStore -> SfxAtomic
SfxApply :: ActorId -> ItemId -> CStore -> SfxAtomic
SfxCheck :: ActorId -> ItemId -> CStore -> SfxAtomic
SfxTrigger :: ActorId -> Point -> SfxAtomic
SfxShun :: ActorId -> Point -> SfxAtomic
SfxEffect :: FactionId -> ActorId -> Effect -> Int64 -> SfxAtomic
SfxMsgFid :: FactionId -> SfxMsg -> SfxAtomic
SfxRestart :: SfxAtomic
SfxCollideTile :: ActorId -> Point -> SfxAtomic
SfxTaunt :: Bool -> ActorId -> SfxAtomic

-- | Symbolic representation of text messages sent by server to clients and
--   shown to players.
data SfxMsg
SfxUnexpected :: ReqFailure -> SfxMsg
SfxExpected :: Text -> ReqFailure -> SfxMsg
SfxFizzles :: SfxMsg
SfxNothingHappens :: SfxMsg
SfxVoidDetection :: DetectKind -> SfxMsg
SfxUnimpressed :: ActorId -> SfxMsg
SfxSummonLackCalm :: ActorId -> SfxMsg
SfxSummonTooManyOwn :: ActorId -> SfxMsg
SfxSummonTooManyAll :: ActorId -> SfxMsg
SfxSummonFailure :: ActorId -> SfxMsg
SfxLevelNoMore :: SfxMsg
SfxLevelPushed :: SfxMsg
SfxBracedImmune :: ActorId -> SfxMsg
SfxEscapeImpossible :: SfxMsg
SfxStasisProtects :: SfxMsg
SfxWaterParalysisResisted :: SfxMsg
SfxTransImpossible :: SfxMsg
SfxIdentifyNothing :: SfxMsg
SfxPurposeNothing :: SfxMsg
SfxPurposeTooFew :: Int -> Int -> SfxMsg
SfxPurposeUnique :: SfxMsg
SfxPurposeNotCommon :: SfxMsg
SfxRerollNothing :: SfxMsg
SfxRerollNotRandom :: SfxMsg
SfxDupNothing :: SfxMsg
SfxDupUnique :: SfxMsg
SfxDupValuable :: SfxMsg
SfxColdFish :: SfxMsg
SfxTimerExtended :: LevelId -> ActorId -> ItemId -> CStore -> Delta Time -> SfxMsg
SfxCollideActor :: LevelId -> ActorId -> ActorId -> SfxMsg

-- | The game-state semantics of atomic game commands. There is no
--   corresponding definition for special effects (<tt>SfxAtomic</tt>),
--   because they don't modify <a>State</a>.
--   
--   For each of the commands, we are guaranteed that the client, the
--   command is addressed to, perceives all the positions the command
--   affects (as computed by <a>posUpdAtomic</a>). In the code for each
--   semantic function we additonally verify the client is aware of any
--   relevant items and/or actors and we throw the <tt>AtomicFail</tt>
--   exception if it's not. The server keeps copies of all clients' states
--   and, before sending a command to a client, applies it to the client's
--   state copy. If <tt>AtomicFail</tt> is signalled, the command is
--   ignored for that client. This enables simpler server code that
--   addresses commands to all clients that can see it, even though not all
--   are able to process it.
handleUpdAtomic :: MonadStateWrite m => UpdAtomic -> m ()

-- | The type representing visibility of atomic commands to factions, based
--   on the position of the command, etc. Note that the server sees and
--   smells all positions. Also note that hearing is not covered because it
--   gives very restricted information, so hearing doesn't equal seeing
--   (and we assume smelling actors get lots of data from smells).
data PosAtomic

-- | whomever sees all the positions, notices
PosSight :: LevelId -> [Point] -> PosAtomic

-- | observers and the faction notice
PosFidAndSight :: [FactionId] -> LevelId -> [Point] -> PosAtomic

-- | whomever smells all the positions, notices
PosSmell :: LevelId -> [Point] -> PosAtomic

-- | only the faction notices, server doesn't
PosFid :: FactionId -> PosAtomic

-- | faction and server notices
PosFidAndSer :: Maybe LevelId -> FactionId -> PosAtomic

-- | only the server notices
PosSer :: PosAtomic

-- | everybody notices
PosAll :: PosAtomic

-- | never broadcasted, but sent manually
PosNone :: PosAtomic

-- | Produce the positions where the atomic update takes place or, more
--   generally, the conditions under which the update can be noticed by a
--   client.
--   
--   The goal of this mechanics is to ensure that atomic commands involving
--   some positions visible by a client convey similar information as the
--   client would get by directly observing the changes of the portion of
--   server state limited to the visible positions. Consequently, when the
--   visible commands are later applied to the client's state, the state
--   stays consistent --- in sync with the server state and correctly
--   limited by visiblity. There is some wiggle room both in what "in sync"
--   and "visible" means and how they propagate through time.
--   
--   E.g., <tt>UpdDisplaceActor</tt> in a black room between two enemy
--   actors, with only one actor carrying a 0-radius light would not be
--   distinguishable by looking at the state (or the screen) from
--   <tt>UpdMoveActor</tt> of the illuminated actor, hence such
--   <tt>UpdDisplaceActor</tt> should not be observable, but
--   <tt>UpdMoveActor</tt> in similar cotext would be (or the former should
--   be perceived as the latter). However, to simplify, we assign as strict
--   visibility requirements to <tt>UpdMoveActor</tt> as to
--   <tt>UpdDisplaceActor</tt> and fall back to <tt>UpdSpotActor</tt>
--   (which provides minimal information that does not contradict state) if
--   the visibility is lower.
posUpdAtomic :: MonadStateRead m => UpdAtomic -> m PosAtomic

-- | Produce the positions where the atomic special effect takes place.
posSfxAtomic :: MonadStateRead m => SfxAtomic -> m PosAtomic

-- | Decompose an atomic action that is outside a client's visiblity. The
--   decomposed actions give less information that the original command,
--   but some of them may fall within the visibility range of the client.
--   The original action may give more information than even the total sum
--   of all actions it's broken into. E.g., <tt>UpdMoveActor</tt> informs
--   about the continued existence of the actor between moves vs popping
--   out of existence and then back in.
--   
--   This is computed in server's <tt>State</tt> from before performing the
--   command.
breakUpdAtomic :: MonadStateRead m => UpdAtomic -> m [UpdAtomic]

-- | Given the client, its perception and an atomic command, determine if
--   the client notices the command.
seenAtomicCli :: Bool -> FactionId -> Perception -> PosAtomic -> Bool

-- | Determine whether the server would see a command that has the given
--   visibilty conditions.
seenAtomicSer :: PosAtomic -> Bool

-- | The monad for writing to the main game state. Atomic updates
--   (<tt>UpdAtomic</tt>) are given semantics in this monad.
class MonadStateRead m => MonadStateWrite m
modifyState :: MonadStateWrite m => (State -> State) -> m ()
putState :: MonadStateWrite m => State -> m ()

-- | Exception signifying that atomic action failed because the information
--   it carries is inconsistent with the client's state, (e.g., because the
--   client knows too little to understand the command or already deduced
--   the state change from earlier commands or is confused, amnesiac or
--   sees illusory actors or tiles). Whenever we know the failure is
--   logically impossible, we don't throw the <tt>AtomicFail</tt>
--   exception, but insert a normal assertion or <tt>error</tt> call, which
--   are never caught nor handled.
newtype AtomicFail
AtomicFail :: String -> AtomicFail


-- | Abstract syntax of responses.
--   
--   See
--   <a>https://github.com/LambdaHack/LambdaHack/wiki/Client-server-architecture</a>.
module Game.LambdaHack.Client.Response

-- | Abstract syntax of responses sent by server to an AI or UI client (or
--   a universal client that can handle both roles, which is why this type
--   is not separated into distinct AI and UI types). A response tells a
--   client how to update game state or what information to send to the
--   server.
data Response

-- | change <tt>State</tt> by performing this atomic update
RespUpdAtomicNoState :: UpdAtomic -> Response

-- | put the given <tt>State</tt>, which results from performing the atomic
--   update
RespUpdAtomic :: State -> UpdAtomic -> Response

-- | compute an AI move for the actor and send (the semantics of) it
RespQueryAI :: ActorId -> Response

-- | perform special effects (animations, messages, etc.)
RespSfxAtomic :: SfxAtomic -> Response

-- | prompt the human player for a command and send (the semantics of) it
RespQueryUI :: Response
instance GHC.Show.Show Game.LambdaHack.Client.Response.Response


-- | Descriptions of items.
module Game.LambdaHack.Client.UI.ItemDescription

-- | The part of speech describing the item.
partItem :: FactionId -> FactionDict -> Time -> ItemFull -> ItemQuant -> (Part, Part)
partItemShort :: FactionId -> FactionDict -> Time -> ItemFull -> ItemQuant -> (Part, Part)
partItemShortest :: FactionId -> FactionDict -> Time -> ItemFull -> ItemQuant -> (Part, Part)
partItemHigh :: FactionId -> FactionDict -> Time -> ItemFull -> ItemQuant -> (Part, Part)
partItemWs :: FactionId -> FactionDict -> Int -> Time -> ItemFull -> ItemQuant -> Part
partItemWsRanged :: FactionId -> FactionDict -> Int -> Time -> ItemFull -> ItemQuant -> Part
partItemShortAW :: FactionId -> FactionDict -> Time -> ItemFull -> ItemQuant -> Part
partItemMediumAW :: FactionId -> FactionDict -> Time -> ItemFull -> ItemQuant -> Part
partItemShortWownW :: FactionId -> FactionDict -> Part -> Time -> ItemFull -> ItemQuant -> Part
viewItem :: ItemFull -> AttrCharW32
itemDesc :: Bool -> FactionId -> FactionDict -> Int -> CStore -> Time -> LevelId -> ItemFull -> ItemQuant -> AttrLine

-- | The part of speech describing the item parameterized by the number of
--   effects/aspects to show.
partItemN :: FactionId -> FactionDict -> Bool -> DetailLevel -> Int -> Time -> ItemFull -> ItemQuant -> (Part, Part)
textAllPowers :: DetailLevel -> Bool -> ItemFull -> ([Text], [Text])
partItemWsR :: FactionId -> FactionDict -> Bool -> Int -> Time -> ItemFull -> ItemQuant -> Part


-- | Display game data on the screen using one of the available frontends
--   (determined at compile time with cabal flags).
module Game.LambdaHack.Client.UI.DrawM
targetDesc :: MonadClientUI m => Maybe Target -> m (Maybe Text, Maybe Text)
targetDescXhair :: MonadClientUI m => m (Maybe Text, Maybe (Text, Watchfulness))

-- | Draw the whole screen: level map and status area.
drawHudFrame :: MonadClientUI m => ColorMode -> LevelId -> m PreFrame
checkWarningHP :: UIOptions -> ActorId -> Int64 -> State -> Bool
checkWarningCalm :: UIOptions -> ActorId -> Int64 -> State -> Bool
drawFrameTerrain :: forall m. MonadClientUI m => LevelId -> m (Vector Word32)
drawFrameContent :: forall m. MonadClientUI m => LevelId -> m FrameForall
drawFramePath :: forall m. MonadClientUI m => LevelId -> m FrameForall
drawFrameActor :: forall m. MonadClientUI m => LevelId -> m FrameForall
drawFrameExtra :: forall m. MonadClientUI m => ColorMode -> LevelId -> m FrameForall
drawFrameStatus :: MonadClientUI m => LevelId -> m AttrLine
drawArenaStatus :: COps -> Level -> Int -> AttrLine
drawLeaderStatus :: MonadClientUI m => Int -> m AttrLine
drawLeaderDamage :: MonadClientUI m => Int -> ActorId -> m AttrLine
drawSelected :: MonadClientUI m => LevelId -> Int -> EnumSet ActorId -> m (Int, AttrLine)
checkWarnings :: UIOptions -> ActorId -> State -> (Bool, Bool)


-- | A set of Frame monad operations.
module Game.LambdaHack.Client.UI.FrameM

-- | Push the frame depicting the current level to the frame queue. Only
--   one line of the report is shown, as in animations, because it may not
--   be our turn, so we can't clear the message to see what is underneath.
pushFrame :: MonadClientUI m => m ()
promptGetKey :: MonadClientUI m => ColorMode -> Overlay -> Bool -> [KM] -> m KM
stopPlayBack :: MonadClientUI m => m ()

-- | Render and display animations on top of the current screen frame.
animate :: MonadClientUI m => LevelId -> Animation -> m ()
fadeOutOrIn :: MonadClientUI m => Bool -> m ()

-- | Draw the current level with the overlay on top. If the overlay is too
--   long, it's truncated. Similarly, for each line of the overlay, if it's
--   too wide, it's truncated.
drawOverlay :: MonadClientUI m => ColorMode -> Bool -> Overlay -> LevelId -> m PreFrame

-- | Render animations on top of the current screen frame.
renderFrames :: MonadClientUI m => LevelId -> Animation -> m PreFrames
resetPlayBack :: MonadClientUI m => m ()


-- | Monadic operations on slideshows and related data.
module Game.LambdaHack.Client.UI.SlideshowM

-- | Add current report to the overlay, split the result and produce,
--   possibly, many slides.
overlayToSlideshow :: MonadClientUI m => Y -> [KM] -> OKX -> m Slideshow

-- | Split current report into a slideshow.
reportToSlideshow :: MonadClientUI m => [KM] -> m Slideshow

-- | Split current report into a slideshow. Keep report unchanged.
reportToSlideshowKeep :: MonadClientUI m => [KM] -> m Slideshow

-- | Display a message. Return value indicates if the player wants to
--   continue. Feature: if many pages, only the last SPACE exits (but first
--   ESC).
displaySpaceEsc :: MonadClientUI m => ColorMode -> Text -> m Bool

-- | Display a message. Ignore keypresses. Feature: if many pages, only the
--   last SPACE exits (but first ESC).
displayMore :: MonadClientUI m => ColorMode -> Text -> m ()
displayMoreKeep :: MonadClientUI m => ColorMode -> Text -> m ()

-- | Print a yes/no question and return the player's answer. Use black and
--   white colours to turn player's attention to the choice.
displayYesNo :: MonadClientUI m => ColorMode -> Text -> m Bool
getConfirms :: MonadClientUI m => ColorMode -> [KM] -> Slideshow -> m KM

-- | Display a, potentially, multi-screen menu and return the chosen key or
--   item slot label (and the index in the whole menu so that the cursor
--   can again be placed at that spot next time menu is displayed).
--   
--   This function is the only source of menus and so, effectively, UI
--   modes.
displayChoiceScreen :: forall m. MonadClientUI m => String -> ColorMode -> Bool -> Slideshow -> [KM] -> m (Either KM SlotChar)


-- | Helper functions for both inventory management and human commands.
module Game.LambdaHack.Client.UI.HandleHelperM

-- | Message describing the cause of failure of human command.
data FailError
showFailError :: FailError -> Text
type MError = Maybe FailError
mergeMError :: MError -> MError -> MError
type FailOrCmd a = Either FailError a
failWith :: MonadClientUI m => Text -> m (FailOrCmd a)
failSer :: MonadClientUI m => ReqFailure -> m (FailOrCmd a)
failMsg :: MonadClientUI m => Text -> m MError
weaveJust :: FailOrCmd a -> Either MError a

-- | Switches current member to the next on the level, if any, wrapping.
memberCycle :: MonadClientUI m => Bool -> m MError

-- | Switches current member to the previous in the whole dungeon,
--   wrapping.
memberBack :: MonadClientUI m => Bool -> m MError
partyAfterLeader :: MonadClientUI m => ActorId -> m [(ActorId, Actor, ActorUI)]

-- | Select a faction leader. False, if nothing to do.
pickLeader :: MonadClientUI m => Bool -> ActorId -> m Bool
pickLeaderWithPointer :: MonadClientUI m => m MError
itemOverlay :: MonadClientUI m => SingleItemSlots -> LevelId -> ItemBag -> m OKX
skillsOverlay :: MonadClientRead m => ActorId -> m OKX
placesFromState :: ContentData PlaceKind -> ClientOptions -> State -> EnumMap (ContentId PlaceKind) (EnumSet LevelId, Int, Int, Int)
placeParts :: (EnumSet LevelId, Int, Int, Int) -> [Part]
placesOverlay :: MonadClientRead m => m OKX
pickNumber :: MonadClientUI m => Bool -> Int -> m (Either MError Int)

-- | Produces a textual description of items at a position.
lookAtItems :: MonadClientUI m => Bool -> Point -> ActorId -> m Text

-- | Produces a textual description of everything at the requested level's
--   position.
lookAtPosition :: MonadClientUI m => LevelId -> Point -> m Text
displayItemLore :: MonadClientUI m => ItemBag -> Int -> (ItemId -> ItemFull -> Int -> Text) -> Int -> SingleItemSlots -> m Bool
viewLoreItems :: MonadClientUI m => String -> SingleItemSlots -> ItemBag -> Text -> (Int -> SingleItemSlots -> m Bool) -> m KM
cycleLore :: MonadClientUI m => [m KM] -> [m KM] -> m ()
spoilsBlurb :: Text -> Int -> Int -> Text

-- | Produces a textual description of the tile at a position.
lookAtTile :: MonadClientUI m => Bool -> Point -> ActorId -> LevelId -> m Text

-- | Produces a textual description of actors at a position.
lookAtActors :: MonadClientUI m => Point -> LevelId -> m Text
instance GHC.Show.Show Game.LambdaHack.Client.UI.HandleHelperM.FailError


-- | UI of inventory management.
module Game.LambdaHack.Client.UI.InventoryM
data Suitability
SuitsEverything :: Suitability
SuitsSomething :: (ItemFull -> ItemQuant -> Bool) -> Suitability

-- | Let the human player choose a single, preferably suitable, item from a
--   list of items. Don't display stores empty for all actors. Start with a
--   non-empty store.
getFull :: MonadClientUI m => m Suitability -> (Actor -> ActorUI -> Skills -> ItemDialogMode -> State -> Text) -> (Actor -> ActorUI -> Skills -> ItemDialogMode -> State -> Text) -> [CStore] -> [CStore] -> Bool -> Bool -> m (Either Text ([(ItemId, ItemFullKit)], (ItemDialogMode, Either KM SlotChar)))

-- | Let a human player choose any item from a given group. Note that this
--   does not guarantee the chosen item belongs to the group, as the player
--   can override the choice. Used e.g., for applying and projecting.
getGroupItem :: MonadClientUI m => m Suitability -> Text -> Text -> [CStore] -> [CStore] -> m (Either Text ((ItemId, ItemFull), (ItemDialogMode, Either KM SlotChar)))

-- | Display all items from a store and let the human player choose any or
--   switch to any other store. Used, e.g., for viewing inventory and item
--   descriptions.
getStoreItem :: MonadClientUI m => (Actor -> ActorUI -> Skills -> ItemDialogMode -> State -> Text) -> ItemDialogMode -> m (Either Text (ItemId, ItemBag, SingleItemSlots), (ItemDialogMode, Either KM SlotChar))
instance GHC.Classes.Eq Game.LambdaHack.Client.UI.InventoryM.ItemDialogState
instance GHC.Show.Show Game.LambdaHack.Client.UI.InventoryM.ItemDialogState


-- | Semantics of <a>Game.LambdaHack.Client.UI.HumanCmd</a> client commands
--   that do not return server requests,, but only change internal client
--   state. None of such commands takes game time.
module Game.LambdaHack.Client.UI.HandleHumanLocalM
macroHuman :: MonadClientUI m => [String] -> m ()

-- | Display items from a given container store and possibly let the user
--   chose one.
chooseItemHuman :: MonadClientUI m => ItemDialogMode -> m MError
chooseItemDialogMode :: MonadClientUI m => ItemDialogMode -> m (FailOrCmd ItemDialogMode)
chooseItemProjectHuman :: forall m. (MonadClient m, MonadClientUI m) => [TriggerItem] -> m MError
chooseItemApplyHuman :: forall m. MonadClientUI m => [TriggerItem] -> m MError

-- | On top of <tt>permittedProjectClient</tt>, it also checks legality of
--   aiming at the target and projection range. It also modifies
--   <tt>eps</tt>.
psuitReq :: (MonadClient m, MonadClientUI m) => m (Either Text (ItemFull -> Either ReqFailure (Point, Bool)))
triggerSymbols :: [TriggerItem] -> [Char]
pickLeaderHuman :: MonadClientUI m => Int -> m MError
pickLeaderWithPointerHuman :: MonadClientUI m => m MError

-- | Switch current member to the next on the viewed level, if any,
--   wrapping.
memberCycleHuman :: MonadClientUI m => m MError

-- | Switch current member to the previous in the whole dungeon, wrapping.
memberBackHuman :: MonadClientUI m => m MError
selectActorHuman :: MonadClientUI m => m ()
selectNoneHuman :: MonadClientUI m => m ()
selectWithPointerHuman :: MonadClientUI m => m MError
repeatHuman :: MonadClientUI m => Int -> m ()
recordHuman :: MonadClientUI m => m ()
allHistoryHuman :: MonadClientUI m => m ()
lastHistoryHuman :: MonadClientUI m => m ()
markVisionHuman :: MonadClientUI m => m ()
markSmellHuman :: MonadClientUI m => m ()
markSuspectHuman :: MonadClient m => m ()
printScreenHuman :: MonadClientUI m => m ()

-- | End aiming mode, rejecting the current position.
cancelHuman :: MonadClientUI m => m ()

-- | Accept the current x-hair position as target, ending aiming mode, if
--   active.
acceptHuman :: (MonadClient m, MonadClientUI m) => m ()
clearTargetIfItemClearHuman :: (MonadClient m, MonadClientUI m) => m ()
itemClearHuman :: MonadClientUI m => m ()

-- | Move the xhair. Assumes aiming mode.
moveXhairHuman :: MonadClientUI m => Vector -> Int -> m MError

-- | Start aiming.
aimTgtHuman :: MonadClientUI m => m MError

-- | Cycle aiming mode. Do not change position of the xhair, switch among
--   things at that position.
aimFloorHuman :: MonadClientUI m => m ()
aimEnemyHuman :: MonadClientUI m => m ()
aimItemHuman :: MonadClientUI m => m ()

-- | Change the displayed level in aiming mode to (at most) k levels
--   shallower. Enters aiming mode, if not already in one.
aimAscendHuman :: MonadClientUI m => Int -> m MError

-- | Tweak the <tt>eps</tt> parameter of the aiming digital line.
epsIncrHuman :: (MonadClient m, MonadClientUI m) => Bool -> m ()
xhairUnknownHuman :: (MonadClient m, MonadClientUI m) => m MError
xhairItemHuman :: (MonadClient m, MonadClientUI m) => m MError
xhairStairHuman :: (MonadClient m, MonadClientUI m) => Bool -> m MError
xhairPointerFloorHuman :: MonadClientUI m => m ()
xhairPointerEnemyHuman :: MonadClientUI m => m ()
aimPointerFloorHuman :: MonadClientUI m => m ()
aimPointerEnemyHuman :: MonadClientUI m => m ()
permittedProjectClient :: MonadClientUI m => m (ItemFull -> Either ReqFailure Bool)
projectCheck :: MonadClientUI m => Point -> m (Maybe ReqFailure)

-- | Check whether one is permitted to aim (for projecting) at a target.
--   The check is stricter for actor targets, assuming the player simply
--   wants to hit a single actor. In order to fine tune trick-shots, e.g.,
--   piercing many actors, other aiming modes should be used. Returns a
--   different <tt>seps</tt> if needed to reach the target.
--   
--   Note: Simple Perception check is not enough for the check, e.g.,
--   because the target actor can be obscured by a glass wall.
xhairLegalEps :: MonadClientUI m => m (Either Text Int)
posFromXhair :: (MonadClient m, MonadClientUI m) => m (Either Text Point)
permittedApplyClient :: MonadClientUI m => m (ItemFull -> ItemQuant -> Either ReqFailure Bool)
selectAid :: MonadClientUI m => ActorId -> m ()
eitherHistory :: forall m. MonadClientUI m => Bool -> m ()

-- | End aiming mode, accepting the current position.
endAiming :: (MonadClient m, MonadClientUI m) => m ()
endAimingMsg :: MonadClientUI m => m ()

-- | Perform look around in the current position of the xhair. Does nothing
--   outside aiming mode.
doLook :: MonadClientUI m => m ()
flashAiming :: MonadClientUI m => m ()


-- | Display atomic commands received by the client.
module Game.LambdaHack.Client.UI.DisplayAtomicM

-- | Visualize atomic updates sent to the client. This is done in the
--   global state after the command is executed and after the client state
--   is modified by the command. Don't modify client state (except a few
--   fields), but only client session (e.g., by displaying messages). This
--   is enforced by types.
displayRespUpdAtomicUI :: MonadClientUI m => UpdAtomic -> m ()

-- | Display special effects (text, animation) sent to the client. Don't
--   modify client state (except a few fields), but only client session
--   (e.g., by displaying messages). This is enforced by types.
displayRespSfxAtomicUI :: MonadClientUI m => SfxAtomic -> m ()
updateItemSlot :: MonadClientUI m => Container -> ItemId -> m ()
markDisplayNeeded :: MonadClientUI m => LevelId -> m ()
lookAtMove :: MonadClientUI m => ActorId -> m ()
aidVerbMU :: MonadClientUI m => MsgClass -> ActorId -> Part -> m ()
aidVerbMU0 :: MonadClientUI m => MsgClass -> ActorId -> Part -> m ()
aidVerbDuplicateMU :: MonadClientUI m => MsgClass -> ActorId -> Part -> m Bool
itemVerbMU :: MonadClientUI m => MsgClass -> ItemId -> ItemQuant -> Part -> Container -> m ()
itemAidVerbMU :: MonadClientUI m => MsgClass -> ActorId -> Part -> ItemId -> Either (Maybe Int) Int -> CStore -> m ()
createActorUI :: MonadClientUI m => Bool -> ActorId -> Actor -> m ()
destroyActorUI :: MonadClientUI m => Bool -> ActorId -> Actor -> m ()
spotItem :: MonadClientUI m => Bool -> ItemId -> ItemQuant -> Container -> m ()
moveActor :: MonadClientUI m => ActorId -> Point -> Point -> m ()
displaceActorUI :: MonadClientUI m => ActorId -> ActorId -> m ()
moveItemUI :: MonadClientUI m => ItemId -> Int -> ActorId -> CStore -> CStore -> m ()
quitFactionUI :: MonadClientUI m => FactionId -> Maybe Status -> Maybe (FactionAnalytics, GenerationAnalytics) -> m ()
displayGameOverLoot :: MonadClientUI m => (ItemBag, Int) -> GenerationAnalytics -> m KM
displayGameOverAnalytics :: MonadClientUI m => FactionAnalytics -> GenerationAnalytics -> m KM
discover :: MonadClientUI m => Container -> ItemId -> m ()
ppSfxMsg :: MonadClientUI m => SfxMsg -> m (Maybe (MsgClass, Text))
strike :: MonadClientUI m => Bool -> ActorId -> ActorId -> ItemId -> CStore -> m ()


-- | Actor preferences for targets and actions, based on actor aspects.
module Game.LambdaHack.Client.Preferences

-- | Compute the whole <a>Benefit</a> structure, containing various facets
--   of AI item preference, for an item with the given effects and aspects.
totalUsefulness :: COps -> FactionId -> FactionDict -> ItemFull -> Benefit

-- | How much AI benefits from applying the effect. The first component is
--   benefit when applied to self, the second is benefit (preferably
--   negative) when applied to enemy. This represents benefit from using
--   the effect every <tt>avgItemDelay</tt> turns, so if the item is not
--   durable, the value is adjusted down elsewhere. The benefit includes
--   the drawback of having to use the actor's turn, except when there is
--   battle and item is a weapon and so there is usually nothing better to
--   do than to melee, or when the actor is stuck or idle or laying in wait
--   or luring an enemy from a safe distance. So there is less than
--   <tt>averageTurnValue</tt> included in each benefit, so in case when
--   turn is not spent, e.g, periodic activation or conditions, the
--   difference in value is only slight.
effectToBenefit :: COps -> FactionId -> FactionDict -> Effect -> (Double, Double)
averageTurnValue :: Double
avgItemDelay :: Double
avgItemLife :: Double
durabilityMult :: Double
organBenefit :: Double -> GroupName ItemKind -> COps -> FactionId -> FactionDict -> (Double, Int)
recBenefit :: GroupName ItemKind -> COps -> FactionId -> FactionDict -> (Double, Int)
fakeItem :: ContentId ItemKind -> ItemKind -> KindMean -> ItemFull
aspectToBenefit :: Aspect -> Double
aspectRecordToBenefit :: AspectRecord -> [Double]


-- | Handle atomic commands received by the client.
module Game.LambdaHack.Client.HandleAtomicM

-- | Client monad for saving and restarting games.
class MonadClient m => MonadClientSetup m
saveClient :: MonadClientSetup m => m ()
restartClient :: MonadClientSetup m => m ()

-- | Effect of atomic actions on client state. It is calculated with the
--   global state from after the command is executed (except where the
--   supplied <tt>oldState</tt> is used).
cmdAtomicSemCli :: MonadClientSetup m => State -> UpdAtomic -> m ()
invalidateInMelee :: MonadClient m => LevelId -> m ()
wipeBfsIfItemAffectsSkills :: MonadClient m => [CStore] -> ActorId -> m ()
tileChangeAffectsBfs :: COps -> ContentId TileKind -> ContentId TileKind -> Bool
createActor :: MonadClient m => ActorId -> Actor -> [(ItemId, Item)] -> m ()
destroyActor :: MonadClient m => ActorId -> Actor -> Bool -> m ()
addItemToDiscoBenefit :: MonadClient m => ItemId -> m ()
perception :: MonadClient m => LevelId -> Perception -> Perception -> m ()
discoverKind :: MonadClient m => ItemKindIx -> m ()
discoverKindAndAspect :: MonadClient m => ItemKindIx -> m ()
coverKind :: ItemKindIx -> m ()
coverAspectAndKind :: ItemKindIx -> m ()
discoverAspect :: MonadClient m => ItemId -> m ()
coverAspect :: ItemId -> m ()
killExit :: MonadClient m => m ()


-- | Temporary pseudo-organ (condition) definitions.
module Content.ItemKindTemporary
temporaries :: [ItemKind]


-- | Actor organ definitions.
module Content.ItemKindOrgan
organs :: [ItemKind]


-- | Definitions of items embedded in map tiles.
module Content.ItemKindEmbed
embeds :: [ItemKind]


-- | Blast definitions.
module Content.ItemKindBlast
blasts :: [ItemKind]


-- | Actor (or rather actor body trunk) definitions.
module Content.ItemKindActor
actors :: [ItemKind]


-- | Operations on the <a>Area</a> type that involve random numbers.
module Game.LambdaHack.Server.DungeonGen.AreaRnd
mkFixed :: (X, Y) -> Area -> Point -> Area

-- | Pick a random point within an area.
pointInArea :: Area -> Rnd Point

-- | Find a suitable position in the area, based on random points and a
--   predicate.
findPointInArea :: Area -> (Point -> Maybe Point) -> Int -> (Point -> Maybe Point) -> Rnd (Maybe Point)

-- | Create a void room, i.e., a single point area within the designated
--   area.
mkVoidRoom :: Area -> Rnd Area

-- | Create a random room according to given parameters.
mkRoom :: (X, Y) -> (X, Y) -> Area -> Rnd Area

-- | Pick a subset of connections between adjacent areas within a grid
--   until there is only one connected component in the graph of all areas.
connectGrid :: EnumSet Point -> (X, Y) -> Rnd [(Point, Point)]

-- | Pick a single random connection between adjacent areas within a grid.
randomConnection :: (X, Y) -> Rnd (Point, Point)

-- | The choice of horizontal and vertical orientation.
data HV
Horiz :: HV
Vert :: HV

-- | The coordinates of consecutive fields of a corridor.
type Corridor = (Point, Point, Point, Point)

-- | Try to connect two interiors of places with a corridor. Choose
--   entrances some steps away from the edges, if the place is big enough.
--   Note that with <tt>pfence == FNone</tt>, the inner area considered is
--   the strict interior of the place, without the outermost tiles.
--   
--   The corridor connects (touches) the inner areas and the turning point
--   of the corridor (if any) is outside of the outer areas and inside the
--   grid areas.
connectPlaces :: (Area, Fence, Area) -> (Area, Fence, Area) -> Rnd (Maybe Corridor)
data SpecialArea
SpecialArea :: Area -> SpecialArea
SpecialFixed :: Point -> Freqs PlaceKind -> Area -> SpecialArea
SpecialMerged :: SpecialArea -> Point -> SpecialArea

-- | Divide uniformly a larger area into the given number of smaller areas
--   overlapping at the edges.
--   
--   The list of fixed centers (some important points inside) of
--   (non-overlapping) areas is given. Incorporate those, with as little
--   disruption, as possible. Assume each of four boundaries of the cave
--   are covered by a fixed centre.
grid :: EnumMap Point (Freqs PlaceKind) -> [Point] -> Area -> (X, Y) -> ((X, Y), EnumMap Point SpecialArea)
connectGrid' :: EnumSet Point -> (X, Y) -> EnumSet Point -> EnumSet Point -> [(Point, Point)] -> Rnd [(Point, Point)]

-- | Sort the sequence of two points, in the derived lexicographic order.
sortPoint :: (Point, Point) -> (Point, Point)

-- | Create a corridor, either horizontal or vertical, with a possible
--   intermediate part that is in the opposite direction. There might not
--   always exist a good intermediate point if the places are allowed to be
--   close together and then we let the intermediate part degenerate.
mkCorridor :: HV -> Point -> Bool -> Point -> Bool -> Area -> Rnd Corridor
borderPlace :: Area -> Fence -> (Area, Area, Bool)
instance GHC.Show.Show Game.LambdaHack.Server.DungeonGen.AreaRnd.SpecialArea
instance GHC.Classes.Eq Game.LambdaHack.Server.DungeonGen.AreaRnd.HV


-- | Generation of places from place kinds.
module Game.LambdaHack.Server.DungeonGen.Place

-- | The parameters of a place. All are immutable and rolled and fixed at
--   the time when a place is generated.
data Place
Place :: ContentId PlaceKind -> Area -> TileMapEM -> TileMapEM -> Place
[qkind] :: Place -> ContentId PlaceKind
[qarea] :: Place -> Area
[qmap] :: Place -> TileMapEM
[qfence] :: Place -> TileMapEM

-- | The map of tile kinds in a place (and generally anywhere in a cave).
--   The map is sparse. The default tile that eventually fills the empty
--   spaces is specified in the cave kind specification with
--   <tt>cdefTile</tt>.
type TileMapEM = EnumMap Point (ContentId TileKind)

-- | Given a few parameters, roll and construct a <a>Place</a>
--   datastructure and fill a cave section acccording to it.
buildPlace :: COps -> CaveKind -> Bool -> ContentId TileKind -> ContentId TileKind -> AbsDepth -> AbsDepth -> Int -> Area -> Maybe Area -> Freqs PlaceKind -> Rnd Place
isChancePos :: Int -> Int -> Int -> Point -> Bool

-- | Construct a fence around an area, with the given tile group.
buildFenceRnd :: COps -> GroupName TileKind -> GroupName TileKind -> GroupName TileKind -> GroupName TileKind -> Area -> Rnd TileMapEM

-- | For <tt>CAlternate</tt> tiling, require the place be comprised of an
--   even number of whole corners, with exactly one square overlap between
--   consecutive coners and no trimming. For other tiling methods, check
--   that the area is large enough for tiling the corner twice in each
--   direction, with a possible one row/column overlap.
placeCheck :: Area -> PlaceKind -> Bool

-- | Calculate interior room area according to fence type, based on the
--   total area for the room and it's fence. This is used for checking if
--   the room fits in the area, for digging up the place and the fence and
--   for deciding if the room is dark or lit later in the dungeon
--   generation process.
interiorArea :: PlaceKind -> Area -> Maybe Area

-- | Roll a legend of a place plan: a map from plan symbols to tile kinds.
olegend :: COps -> GroupName TileKind -> Rnd (EnumMap Char (Int, Int, ContentId TileKind), EnumMap Char (ContentId TileKind))
pover :: COps -> [(Char, GroupName TileKind)] -> Rnd (EnumMap Char (Int, Int, ContentId TileKind), EnumMap Char (ContentId TileKind))

-- | Construct a fence around a place.
buildFence :: COps -> CaveKind -> Bool -> ContentId TileKind -> ContentId TileKind -> Bool -> Fence -> Area -> Rnd TileMapEM

-- | Construct a fence around an area, with the given tile kind. Corners
--   have a different kind, e.g., to avoid putting doors there.
buildFenceMap :: ContentId TileKind -> ContentId TileKind -> Area -> TileMapEM

-- | Create a place by tiling patterns.
tilePlace :: Area -> PlaceKind -> Rnd (EnumMap Point Char)
instance GHC.Show.Show Game.LambdaHack.Server.DungeonGen.Place.Place


-- | Generation of caves (not yet inhabited dungeon levels) from cave
--   kinds.
module Game.LambdaHack.Server.DungeonGen.Cave

-- | The type of caves (not yet inhabited dungeon levels).
data Cave
Cave :: ContentId CaveKind -> Area -> TileMapEM -> EnumMap Point Place -> EnumMap Point PlaceEntry -> Bool -> Cave

-- | the kind of the cave
[dkind] :: Cave -> ContentId CaveKind

-- | map area of the cave
[darea] :: Cave -> Area

-- | tile kinds in the cave
[dmap] :: Cave -> TileMapEM

-- | stair places indexed by their center
[dstairs] :: Cave -> EnumMap Point Place

-- | room entrances in the cave
[dentry] :: Cave -> EnumMap Point PlaceEntry

-- | whether the cave is dark
[dnight] :: Cave -> Bool

-- | Generate a cave using an algorithm inspired by the original Rogue, as
--   follows (in gross simplification):
--   
--   <ul>
--   <li>The available area is divided into a grid, e.g, 3 by 3, where each
--   of the 9 grid cells has approximately the same size.</li>
--   <li>In some of the 9 grid cells a room is placed at a random position
--   and with a random size, but larger than the minimum size, e.g, 2 by 2
--   floor tiles.</li>
--   <li>Rooms that are on horizontally or vertically adjacent grid cells
--   may be connected by a corridor. Corridors consist of 3 segments of
--   straight lines (either "horizontal, vertical, horizontal" or
--   "vertical, horizontal, vertical"). They end in openings in the walls
--   of the room they connect. It is possible that one or two of the 3
--   segments have length 0, such that the resulting corridor is L-shaped
--   or even a single straight line.</li>
--   <li>Corridors are generated randomly in such a way that at least every
--   room on the grid is connected, and a few more might be. It is not
--   sufficient to always connect all adjacent rooms, because not each cell
--   holds a room.</li>
--   </ul>
buildCave :: COps -> AbsDepth -> AbsDepth -> Area -> Int -> ContentId CaveKind -> (X, Y) -> EnumMap Point SpecialArea -> [Point] -> Rnd Cave
pickOpening :: COps -> CaveKind -> TileMapEM -> ContentId TileKind -> Int -> Point -> (ContentId TileKind, ContentId TileKind, ContentId PlaceKind) -> Rnd (ContentId TileKind)
instance GHC.Show.Show Game.LambdaHack.Server.DungeonGen.Cave.Cave


-- | DFOV (Digital Field of View) implemented according to specification at
--   <a>http://roguebasin.roguelikedevelopment.org/index.php?title=Digital_field_of_view_implementation</a>.
--   This fast version of the algorithm, based on PFOV, has AFAIK never
--   been described nor implemented before.
--   
--   The map is processed in depth-first-search manner, that is, as soon as
--   we detect on obstacle we move away from the viewer up to the FOV
--   radius and then restart on the other side of the obstacle. This has
--   better cache behaviour than breadth-firsts-search, where we would
--   process all tiles equally distant from the viewer in the same round,
--   because then we'd need to keep the many convex hulls and edges, not
--   just a single set, and we'd potentially traverse all of them each
--   round.
module Game.LambdaHack.Server.FovDigital

-- | Calculates the list of tiles visible from (0, 0) within the given
--   sight range.
scan :: Distance -> (PointI -> Bool) -> (Bump -> PointI) -> [PointI]

-- | Rotated and translated coordinates of 2D points, so that the points
--   fit in a single quadrant area (e, g., quadrant I for Permissive FOV,
--   hence both coordinates positive; adjacent diagonal halves of quadrant
--   I and II for Digital FOV, hence y positive). The special coordinates
--   are written using the standard mathematical coordinate setup, where
--   quadrant I, with x and y positive, is on the upper right.
data Bump
B :: Int -> Int -> Bump
[bx] :: Bump -> Int
[by] :: Bump -> Int

-- | Distance from the (0, 0) point where FOV originates.
type Distance = Int

-- | Progress along an arc with a constant distance from (0, 0).
type Progress = Int

-- | Two strict orderings of lines with a common point.
data LineOrdering

-- | Straight line between points.
data Line
Line :: Bump -> Bump -> Line

-- | Convex hull represented as a non-empty list of points.
data ConvexHull
ConvexHull :: Bump -> CHull -> ConvexHull
data CHull
CHNil :: CHull
CHCons :: Bump -> CHull -> CHull

-- | An edge (comprising of a line and a convex hull) of the area to be
--   scanned.
type Edge = (Line, ConvexHull)

-- | The contiguous area left to be scanned, delimited by edges.
type EdgeInterval = (Edge, Edge)

-- | Specialized implementation for speed in the inner loop. Not partial.
steepestInHull :: LineOrdering -> Bump -> ConvexHull -> Bump

-- | Standard <tt>foldl'</tt> over <tt>CHull</tt>.
foldlCHull' :: (a -> Bump -> a) -> a -> CHull -> a

-- | Extends a convex hull of bumps with a new bump. The new bump makes
--   some old bumps unnecessary, e.g. those that are joined with the new
--   steep bump with lines that are not shallower than any newer lines in
--   the hull. Removing such unnecessary bumps slightly speeds up
--   computation of <a>steepestInHull</a>.
--   
--   Recursion in <tt>addToHullGo</tt> seems spurious, but it's called each
--   time with potentially different comparison predicate, so it's
--   necessary.
addToHull :: LineOrdering -> Bump -> ConvexHull -> ConvexHull
addToHullGo :: LineOrdering -> Bump -> CHull -> CHull

-- | Create a line from two points.
--   
--   Debug: check if well-defined.
createLine :: Bump -> Bump -> Line

-- | Strictly compare steepness of lines <tt>(b1, bf)</tt> and <tt>(b2,
--   bf)</tt>, according to the <tt>LineOrdering</tt> given. This is
--   related to comparing the slope (gradient, angle) of two lines, but
--   simplified wrt signs to work fast in this particular setup.
--   
--   Debug: Verify that the results of 2 independent checks are equal.
steepness :: LineOrdering -> Bump -> Bump -> Bump -> Bool

-- | A pair <tt>(a, b)</tt> such that <tt>a</tt> divided by <tt>b</tt> is
--   the X coordinate of the intersection of a given line and the
--   horizontal line at distance <tt>d</tt> above the X axis.
--   
--   Derivation of the formula: The intersection point <tt>(xt, yt)</tt>
--   satisfies the following equalities:
--   
--   <pre>
--   yt = d
--   (yt - y) (xf - x) = (xt - x) (yf - y)
--   </pre>
--   
--   hence
--   
--   <pre>
--   (yt - y) (xf - x) = (xt - x) (yf - y)
--   (d - y) (xf - x) = (xt - x) (yf - y)
--   (d - y) (xf - x) + x (yf - y) = xt (yf - y)
--   xt = ((d - y) (xf - x) + x (yf - y)) / (yf - y)
--   </pre>
--   
--   General remarks: The FOV agrees with physical properties of tiles as
--   diamonds and visibility from any point to any point. A diamond is
--   denoted by the left corner of it's encompassing tile. Hero is at (0,
--   0). Order of processing in the first quadrant rotated by 45 degrees is
--   
--   <pre>
--   45678
--    123
--     @
--   </pre>
--   
--   so the first processed diamond is at (-1, 1). The order is similar as
--   for the restrictive shadow casting algorithm and reversed wrt PFOV.
--   The fast moving line when scanning is called the shallow line, and
--   it's the one that delimits the view from the left, while the steep
--   line is on the right, opposite to PFOV. We start scanning from the
--   left.
--   
--   The <a>PointI</a> (<a>Enum</a> representation of <tt>Point</tt>)
--   coordinates are cartesian. The <a>Bump</a> coordinates are cartesian,
--   translated so that the hero is at (0, 0) and rotated so that he always
--   looks at the first (rotated 45 degrees) quadrant. The
--   (<a>Progress</a>, <a>Distance</a>) cordinates coincide with the
--   <tt>Bump</tt> coordinates, unlike in PFOV.
--   
--   Debug: check that the line fits in the upper half-plane.
intersect :: Line -> Distance -> (Int, Int)

-- | Debug functions for DFOV:
--   
--   Debug: calculate steepness for DFOV in another way and compare
--   results.
_debugSteeper :: LineOrdering -> Bump -> Bump -> Bump -> Bool

-- | Debug: check if a view border line for DFOV is legal.
_debugLine :: Line -> (Bool, String)
instance GHC.Show.Show Game.LambdaHack.Server.FovDigital.ConvexHull
instance GHC.Show.Show Game.LambdaHack.Server.FovDigital.CHull
instance GHC.Show.Show Game.LambdaHack.Server.FovDigital.Line
instance GHC.Show.Show Game.LambdaHack.Server.FovDigital.Bump


-- | Field Of View scanning.
--   
--   See <a>https://github.com/LambdaHack/LambdaHack/wiki/Fov-and-los</a>
--   for discussion.
module Game.LambdaHack.Server.Fov
data FovValid a
FovValid :: a -> FovValid a
FovInvalid :: FovValid a

-- | Main perception validity map, for all factions.
type PerValidFid = EnumMap FactionId (EnumMap LevelId Bool)

-- | Visually reachable positions (light passes through them to the actor).
--   They need to be intersected with lucid positions to obtain visible
--   positions.
newtype PerReachable
PerReachable :: EnumSet Point -> PerReachable
[preachable] :: PerReachable -> EnumSet Point
data CacheBeforeLucid
CacheBeforeLucid :: PerReachable -> PerVisible -> PerSmelled -> CacheBeforeLucid
[creachable] :: CacheBeforeLucid -> PerReachable
[cnocto] :: CacheBeforeLucid -> PerVisible
[csmell] :: CacheBeforeLucid -> PerSmelled
type PerActor = EnumMap ActorId (FovValid CacheBeforeLucid)
data PerceptionCache
PerceptionCache :: FovValid CacheBeforeLucid -> PerActor -> PerceptionCache
[ptotal] :: PerceptionCache -> FovValid CacheBeforeLucid
[perActor] :: PerceptionCache -> PerActor

-- | Server cache of perceptions of a single faction, indexed by level
--   identifier.
type PerCacheLid = EnumMap LevelId PerceptionCache

-- | Server cache of perceptions, indexed by faction identifier.
type PerCacheFid = EnumMap FactionId PerCacheLid

-- | Map from level positions that currently hold item or actor(s) with
--   shine to the maximum of radiuses of the shining lights.
--   
--   Note that floor and (many projectile) actors light on a single tile
--   should be additive for <tt>FovShine</tt> to be incrementally updated.
--   
--   <tt>FovShine</tt> should not even be kept in <tt>StateServer</tt>,
--   because it's cheap to compute, compared to <tt>FovLucid</tt> and
--   invalidated almost as often (not invalidated only by
--   <tt>UpdAlterTile</tt>).
newtype FovShine
FovShine :: EnumMap Point Int -> FovShine
[fovShine] :: FovShine -> EnumMap Point Int

-- | Level positions with either ambient light or shining items or actors.
newtype FovLucid
FovLucid :: EnumSet Point -> FovLucid
[fovLucid] :: FovLucid -> EnumSet Point
type FovLucidLid = EnumMap LevelId (FovValid FovLucid)

-- | Level positions that pass through light and vision.
newtype FovClear
FovClear :: Array Bool -> FovClear
[fovClear] :: FovClear -> Array Bool
type FovClearLid = EnumMap LevelId FovClear

-- | Level positions with tiles that have ambient light.
newtype FovLit
FovLit :: EnumSet Point -> FovLit
[fovLit] :: FovLit -> EnumSet Point
type FovLitLid = EnumMap LevelId FovLit

-- | Compute positions visible (reachable and seen) by the party. A
--   position is lucid, if it's lit by an ambient light or by a weak,
--   portable light source, e.g,, carried by an actor. A reachable and
--   lucid position is visible. Additionally, positions directly adjacent
--   to an actor are assumed to be visible to him (through sound, touch,
--   noctovision, whatever).
perceptionFromPTotal :: FovLucid -> CacheBeforeLucid -> Perception
perActorFromLevel :: PerActor -> (ActorId -> Actor) -> ActorMaxSkills -> FovClear -> PerActor
boundSightByCalm :: Int -> Int64 -> Int
totalFromPerActor :: PerActor -> CacheBeforeLucid

-- | Update lights on the level. This is needed every (even enemy) actor
--   move to show thrown torches. We need to update lights even if cmd
--   doesn't change any perception, so that for next cmd that does, but
--   doesn't change lights, and operates on the same level, the lights are
--   up to date. We could make lights lazy to ensure no computation is
--   wasted, but it's rare that cmd changed them, but not the perception
--   (e.g., earthquake in an uninhabited corner of the active arena, but
--   the we'd probably want some feedback, at least sound).
lucidFromLevel :: FovClearLid -> FovLitLid -> State -> LevelId -> Level -> FovLucid

-- | Calculate the perception and its caches for the whole dungeon.
perFidInDungeon :: State -> (FovLitLid, FovClearLid, FovLucidLid, PerValidFid, PerCacheFid, PerFid)

-- | Compute positions reachable by the actor. Reachable are all fields on
--   a visually unblocked path from the actor position. Also compute
--   positions seen by noctovision and perceived by smell.
cacheBeforeLucidFromActor :: FovClear -> Actor -> Skills -> CacheBeforeLucid
shineFromLevel :: State -> LevelId -> Level -> FovShine
floorLightSources :: DiscoveryAspect -> Level -> [(Point, Int)]

-- | Compute all dynamically lit positions on a level, whether lit by
--   actors or shining floor items. Note that an actor can be blind, in
--   which case he doesn't see his own light (but others, from his or other
--   factions, possibly do).
lucidFromItems :: FovClear -> [(Point, Int)] -> [FovLucid]
litFromLevel :: COps -> Level -> FovLit
litInDungeon :: State -> FovLitLid
clearFromLevel :: COps -> Level -> FovClear
clearInDungeon :: State -> FovClearLid
lucidInDungeon :: FovClearLid -> FovLitLid -> State -> FovLucidLid

-- | Calculate perception of a faction.
perLidFromFaction :: FovLucidLid -> FovClearLid -> FactionId -> State -> (PerLid, PerCacheLid)
perceptionCacheFromLevel :: FovClearLid -> FactionId -> LevelId -> State -> PerceptionCache
type Matrix = (Int, Int, Int, Int)

-- | Perform a full scan for a given position. Returns the positions that
--   are currently in the field of view. The actor's own position is
--   considred in his field of view.
fullscan :: Int -> Point -> FovClear -> EnumSet Point
instance GHC.Classes.Eq Game.LambdaHack.Server.Fov.FovLit
instance GHC.Show.Show Game.LambdaHack.Server.Fov.FovLit
instance GHC.Classes.Eq Game.LambdaHack.Server.Fov.FovClear
instance GHC.Show.Show Game.LambdaHack.Server.Fov.FovClear
instance GHC.Classes.Eq Game.LambdaHack.Server.Fov.FovLucid
instance GHC.Show.Show Game.LambdaHack.Server.Fov.FovLucid
instance GHC.Classes.Eq Game.LambdaHack.Server.Fov.FovShine
instance GHC.Show.Show Game.LambdaHack.Server.Fov.FovShine
instance GHC.Classes.Eq Game.LambdaHack.Server.Fov.PerceptionCache
instance GHC.Show.Show Game.LambdaHack.Server.Fov.PerceptionCache
instance GHC.Classes.Eq Game.LambdaHack.Server.Fov.CacheBeforeLucid
instance GHC.Show.Show Game.LambdaHack.Server.Fov.CacheBeforeLucid
instance GHC.Classes.Eq Game.LambdaHack.Server.Fov.PerReachable
instance GHC.Show.Show Game.LambdaHack.Server.Fov.PerReachable
instance GHC.Classes.Eq a => GHC.Classes.Eq (Game.LambdaHack.Server.Fov.FovValid a)
instance GHC.Show.Show a => GHC.Show.Show (Game.LambdaHack.Server.Fov.FovValid a)


-- | Creation of items on the server. Types and operations that don't
--   involve server state nor our custom monads.
module Game.LambdaHack.Server.ItemRev

-- | The essential item properties, used for the <tt>ItemRev</tt> hash
--   table from items to their ids, needed to assign ids to newly generated
--   items. All the other meaningul properties can be derived from them.
--   Note: item seed instead of <tt>AspectRecord</tt> is not enough,
--   becaused different seeds may result in the same <tt>AspectRecord</tt>
--   and we don't want such items to be distinct in UI and elsewhere.
data ItemKnown
ItemKnown :: ItemIdentity -> AspectRecord -> Maybe FactionId -> ItemKnown

-- | Reverse item map, for item creation, to keep items and item
--   identifiers in bijection.
type ItemRev = HashMap ItemKnown ItemId
type UniqueSet = EnumSet (ContentId ItemKind)

-- | Build an item with the given kind and aspects.
buildItem :: COps -> AspectRecord -> FlavourMap -> DiscoveryKindRev -> ContentId ItemKind -> Item

-- | Roll an item kind based on given <tt>Freqs</tt> and kind rarities
newItemKind :: COps -> UniqueSet -> Freqs ItemKind -> AbsDepth -> AbsDepth -> Int -> Frequency (ContentId ItemKind, ItemKind)

-- | Given item kind frequency, roll item kind, generate item aspects based
--   on level and put together the full item data set.
newItem :: COps -> Frequency (ContentId ItemKind, ItemKind) -> FlavourMap -> DiscoveryKindRev -> AbsDepth -> AbsDepth -> Rnd (Maybe (ItemKnown, ItemFullKit))

-- | The reverse map to <tt>DiscoveryKind</tt>, needed for item creation.
--   This is total and never changes, hence implemented as vector. Morally,
--   it's indexed by <tt>ContentId ItemKind</tt> and elements are
--   <tt>ItemKindIx</tt>.
data DiscoveryKindRev
emptyDiscoveryKindRev :: DiscoveryKindRev
serverDiscos :: COps -> Rnd (DiscoveryKind, DiscoveryKindRev)

-- | Flavours assigned by the server to item kinds, in this particular
--   game. This is total and never changes, hence implemented as vector.
--   Morally, it's indexed by <tt>ContentId ItemKind</tt> and elements are
--   <tt>Flavour</tt>.
data FlavourMap
emptyFlavourMap :: FlavourMap

-- | Randomly chooses flavour for all item kinds for this game.
dungeonFlavourMap :: COps -> Rnd FlavourMap
instance Data.Binary.Class.Binary Game.LambdaHack.Server.ItemRev.FlavourMap
instance GHC.Show.Show Game.LambdaHack.Server.ItemRev.FlavourMap
instance Data.Binary.Class.Binary Game.LambdaHack.Server.ItemRev.DiscoveryKindRev
instance GHC.Show.Show Game.LambdaHack.Server.ItemRev.DiscoveryKindRev
instance GHC.Generics.Generic Game.LambdaHack.Server.ItemRev.ItemKnown
instance GHC.Classes.Eq Game.LambdaHack.Server.ItemRev.ItemKnown
instance GHC.Show.Show Game.LambdaHack.Server.ItemRev.ItemKnown
instance Data.Binary.Class.Binary Game.LambdaHack.Server.ItemRev.ItemKnown
instance Data.Hashable.Class.Hashable Game.LambdaHack.Server.ItemRev.ItemKnown


-- | Semantics of <a>Game.LambdaHack.Client.UI.HumanCmd</a> client commands
--   that return server requests. A couple of them do not take time, the
--   rest does. Here prompts and menus are displayed, but any feedback
--   resulting from the commands (e.g., from inventory manipulation) is
--   generated later on, by the server, for all clients that witness the
--   results of the commands.
module Game.LambdaHack.Client.UI.HandleHumanGlobalM

-- | Pick command depending on area the mouse pointer is in. The first
--   matching area is chosen. If none match, only interrupt.
byAreaHuman :: MonadClientUI m => (HumanCmd -> m (Either MError ReqUI)) -> [(CmdArea, HumanCmd)] -> m (Either MError ReqUI)
byAimModeHuman :: MonadClientUI m => m (Either MError ReqUI) -> m (Either MError ReqUI) -> m (Either MError ReqUI)
composeIfLocalHuman :: MonadClientUI m => m (Either MError ReqUI) -> m (Either MError ReqUI) -> m (Either MError ReqUI)
composeUnlessErrorHuman :: MonadClientUI m => m (Either MError ReqUI) -> m (Either MError ReqUI) -> m (Either MError ReqUI)
compose2ndLocalHuman :: MonadClientUI m => m (Either MError ReqUI) -> m (Either MError ReqUI) -> m (Either MError ReqUI)
loopOnNothingHuman :: MonadClientUI m => m (Either MError ReqUI) -> m (Either MError ReqUI)
executeIfClearHuman :: MonadClientUI m => m (Either MError ReqUI) -> m (Either MError ReqUI)

-- | Leader waits a turn (and blocks, etc.).
waitHuman :: MonadClientUI m => m (FailOrCmd RequestTimed)

-- | Leader waits a 1/10th of a turn (and doesn't block, etc.).
waitHuman10 :: MonadClientUI m => m (FailOrCmd RequestTimed)

-- | Leader yells or yawns, if sleeping.
yellHuman :: MonadClientUI m => m (FailOrCmd RequestTimed)
moveRunHuman :: (MonadClient m, MonadClientUI m) => Bool -> Bool -> Bool -> Bool -> Vector -> m (FailOrCmd RequestTimed)
runOnceAheadHuman :: MonadClientUI m => m (Either MError RequestTimed)
moveOnceToXhairHuman :: (MonadClient m, MonadClientUI m) => m (FailOrCmd RequestTimed)
runOnceToXhairHuman :: (MonadClient m, MonadClientUI m) => m (FailOrCmd RequestTimed)
continueToXhairHuman :: (MonadClient m, MonadClientUI m) => m (FailOrCmd RequestTimed)
moveItemHuman :: forall m. MonadClientUI m => [CStore] -> CStore -> Maybe Part -> Bool -> m (FailOrCmd RequestTimed)
projectHuman :: (MonadClient m, MonadClientUI m) => m (FailOrCmd RequestTimed)
applyHuman :: MonadClientUI m => m (FailOrCmd RequestTimed)

-- | Ask for a direction and alter a tile in the specified way, if
--   possible.
alterDirHuman :: MonadClientUI m => [TriggerTile] -> m (FailOrCmd RequestTimed)

-- | Try to alter a tile using a feature under the pointer.
alterWithPointerHuman :: MonadClientUI m => [TriggerTile] -> m (FailOrCmd RequestTimed)

-- | Display command help.
helpHuman :: MonadClientUI m => (HumanCmd -> m (Either MError ReqUI)) -> m (Either MError ReqUI)

-- | Display hint or, if already displayed, display help.
hintHuman :: MonadClientUI m => (HumanCmd -> m (Either MError ReqUI)) -> m (Either MError ReqUI)

-- | Display the dashboard.
dashboardHuman :: MonadClientUI m => (HumanCmd -> m (Either MError ReqUI)) -> m (Either MError ReqUI)
itemMenuHuman :: MonadClientUI m => (HumanCmd -> m (Either MError ReqUI)) -> m (Either MError ReqUI)
chooseItemMenuHuman :: MonadClientUI m => (HumanCmd -> m (Either MError ReqUI)) -> ItemDialogMode -> m (Either MError ReqUI)

-- | Display the main menu.
mainMenuHuman :: MonadClientUI m => (HumanCmd -> m (Either MError ReqUI)) -> m (Either MError ReqUI)

-- | Display the main menu and set <tt>swasAutomated</tt>.
mainMenuAutoOnHuman :: MonadClientUI m => (HumanCmd -> m (Either MError ReqUI)) -> m (Either MError ReqUI)

-- | Display the main menu and unset <tt>swasAutomated</tt>.
mainMenuAutoOffHuman :: MonadClientUI m => (HumanCmd -> m (Either MError ReqUI)) -> m (Either MError ReqUI)

-- | Display the settings menu.
settingsMenuHuman :: MonadClientUI m => (HumanCmd -> m (Either MError ReqUI)) -> m (Either MError ReqUI)

-- | Display the challenges menu.
challengesMenuHuman :: MonadClientUI m => (HumanCmd -> m (Either MError ReqUI)) -> m (Either MError ReqUI)
gameScenarioIncr :: MonadClient m => m ()
gameDifficultyIncr :: MonadClient m => m ()
gameWolfToggle :: MonadClient m => m ()
gameFishToggle :: MonadClient m => m ()
gameRestartHuman :: MonadClientUI m => m (FailOrCmd ReqUI)
gameQuitHuman :: MonadClientUI m => m (FailOrCmd ReqUI)
gameDropHuman :: MonadClientUI m => m ReqUI
gameExitHuman :: MonadClientUI m => m ReqUI
gameSaveHuman :: MonadClientUI m => m ReqUI
tacticHuman :: MonadClientUI m => m (FailOrCmd ReqUI)
automateHuman :: MonadClientUI m => m (FailOrCmd ReqUI)
automateToggleHuman :: MonadClientUI m => m (FailOrCmd ReqUI)
automateBackHuman :: MonadClientUI m => m (Either MError ReqUI)
areaToRectangles :: MonadClientUI m => CmdArea -> m [Maybe Area]

-- | Actor attacks an enemy actor or his own projectile.
meleeAid :: (MonadClient m, MonadClientUI m) => ActorId -> m (FailOrCmd RequestTimed)

-- | Actor swaps position with another.
displaceAid :: MonadClientUI m => ActorId -> m (FailOrCmd RequestTimed)

-- | Leader moves or searches or alters. No visible actor at the position.
moveSearchAlter :: MonadClientUI m => Bool -> Vector -> m (FailOrCmd RequestTimed)
goToXhair :: (MonadClient m, MonadClientUI m) => Bool -> Bool -> m (FailOrCmd RequestTimed)
multiActorGoTo :: (MonadClient m, MonadClientUI m) => LevelId -> Point -> RunParams -> m (FailOrCmd (Bool, Vector))
moveOrSelectItem :: forall m. MonadClientUI m => [CStore] -> CStore -> Maybe Part -> Bool -> m (FailOrCmd RequestTimed)
selectItemsToMove :: forall m. MonadClientUI m => [CStore] -> CStore -> Maybe Part -> Bool -> m (FailOrCmd (CStore, [(ItemId, ItemFullKit)]))
moveItems :: forall m. MonadClientUI m => [CStore] -> (CStore, [(ItemId, ItemFullKit)]) -> CStore -> m (FailOrCmd RequestTimed)
projectItem :: (MonadClient m, MonadClientUI m) => (CStore, (ItemId, ItemFull)) -> m (FailOrCmd RequestTimed)
applyItem :: MonadClientUI m => (CStore, (ItemId, ItemFullKit)) -> m (FailOrCmd RequestTimed)

-- | Try to alter a tile using a feature in the given direction.
alterTile :: MonadClientUI m => [TriggerTile] -> Vector -> m (FailOrCmd RequestTimed)

-- | Try to alter a tile using a feature at the given position.
--   
--   We don't check if the tile is interesting, e.g., if any embedded item
--   can be triggered, because the player explicitely requested the action.
--   Consequently, even if all embedded items are recharching, the time
--   will be wasted and the server will describe the failure in detail.
alterTileAtPos :: MonadClientUI m => [TriggerTile] -> Point -> Text -> m (FailOrCmd RequestTimed)

-- | Verify important effects, such as fleeing the dungeon.
--   
--   This is contrived for now, the embedded items are not analyzed, but
--   only recognized by name.
verifyAlters :: MonadClientUI m => LevelId -> Point -> m (FailOrCmd ())
verifyEscape :: MonadClientUI m => m (FailOrCmd ())

-- | Guess and report why the bump command failed.
guessAlter :: COps -> [TriggerTile] -> ContentId TileKind -> Text
artWithVersion :: MonadClientUI m => m [String]
generateMenu :: MonadClientUI m => (HumanCmd -> m (Either MError ReqUI)) -> [(KM, (Text, HumanCmd))] -> [String] -> String -> m (Either MError ReqUI)
nxtGameMode :: COps -> Int -> ModeKind


-- | Semantics of human player commands.
module Game.LambdaHack.Client.UI.HandleHumanM

-- | The semantics of human player commands in terms of the client monad.
--   
--   Some time cosuming commands are enabled even in aiming mode, but
--   cannot be invoked in aiming mode on a remote level (level different
--   than the level of the leader), which is caught here.
cmdHumanSem :: (MonadClient m, MonadClientUI m) => HumanCmd -> m (Either MError ReqUI)

-- | Commands that are forbidden on a remote level, because they would
--   usually take time when invoked on one, but not necessarily do what the
--   player expects. Note that some commands that normally take time are
--   not included, because they don't take time in aiming mode or their
--   individual sanity conditions include a remote level check.
noRemoteHumanCmd :: HumanCmd -> Bool
cmdAction :: (MonadClient m, MonadClientUI m) => HumanCmd -> m (Either MError ReqUI)
addNoError :: Monad m => m () -> m (Either MError ReqUI)


-- | Ways for the client to use player input via UI to produce server
--   requests, based on the client's view (visualized for the player) of
--   the game state.
module Game.LambdaHack.Client.UI

-- | Handle the move of a human player.
queryUI :: (MonadClient m, MonadClientUI m) => m RequestUI

-- | The monad that gives the client access to UI operations, but not to
--   modifying client state.
class MonadClientRead m => MonadClientUI m
getsSession :: MonadClientUI m => (SessionUI -> a) -> m a
modifySession :: MonadClientUI m => (SessionUI -> SessionUI) -> m ()
updateClientLeader :: MonadClientUI m => ActorId -> m ()
getCacheBfs :: MonadClientUI m => ActorId -> m (Array BfsDistance)
getCachePath :: MonadClientUI m => ActorId -> Point -> m (Maybe AndPath)

-- | The information that is used across a client playing session,
--   including many consecutive games in a single session. Some of it is
--   saved, some is reset when a new playing session starts. An important
--   component is the frontend session.
data SessionUI
SessionUI :: Maybe Target -> ActorDictUI -> ItemDictUI -> ItemSlots -> Maybe (CStore, CStore) -> ChanFrontend -> CCUI -> UIOptions -> Maybe AimMode -> Bool -> Maybe (ItemId, CStore, Bool) -> EnumSet ActorId -> Maybe RunParams -> History -> Point -> LastRecord -> [KM] -> EnumSet ActorId -> Int -> Bool -> Bool -> Bool -> Map String Int -> Bool -> HintMode -> Bool -> POSIXTime -> POSIXTime -> Time -> Int -> Int -> SessionUI

-- | the common xhair
[sxhair] :: SessionUI -> Maybe Target

-- | assigned actor UI presentations
[sactorUI] :: SessionUI -> ActorDictUI

-- | assigned item first seen level
[sitemUI] :: SessionUI -> ItemDictUI

-- | map from slots to items
[sslots] :: SessionUI -> ItemSlots

-- | last item move stores
[slastItemMove] :: SessionUI -> Maybe (CStore, CStore)

-- | connection with the frontend
[schanF] :: SessionUI -> ChanFrontend

-- | UI client content
[sccui] :: SessionUI -> CCUI

-- | UI options as set by the player
[sUIOptions] :: SessionUI -> UIOptions

-- | aiming mode
[saimMode] :: SessionUI -> Maybe AimMode

-- | last mouse aiming not vacuus
[sxhairMoused] :: SessionUI -> Bool

-- | selected item, if any, it's store and whether to override suitability
--   check
[sitemSel] :: SessionUI -> Maybe (ItemId, CStore, Bool)

-- | the set of currently selected actors
[sselected] :: SessionUI -> EnumSet ActorId

-- | parameters of the current run, if any
[srunning] :: SessionUI -> Maybe RunParams

-- | history of messages
[shistory] :: SessionUI -> History

-- | mouse pointer position
[spointer] :: SessionUI -> Point

-- | state of key sequence recording
[slastRecord] :: SessionUI -> LastRecord

-- | state of key sequence playback
[slastPlay] :: SessionUI -> [KM]

-- | actors that just got out of sight
[slastLost] :: SessionUI -> EnumSet ActorId

-- | player just waited this many times
[swaitTimes] :: SessionUI -> Int

-- | the player just exited AI automation
[swasAutomated] :: SessionUI -> Bool

-- | mark leader and party FOV
[smarkVision] :: SessionUI -> Bool

-- | mark smell, if the leader can smell
[smarkSmell] :: SessionUI -> Bool

-- | indices of last used menu items
[smenuIxMap] :: SessionUI -> Map String Int

-- | current level needs displaying
[sdisplayNeeded] :: SessionUI -> Bool

-- | how to show keys hints when no messages
[shintMode] :: SessionUI -> HintMode

-- | whether no report created last UI turn or the report wiped out from
--   screen
[sreportNull] :: SessionUI -> Bool

-- | this session start time
[sstart] :: SessionUI -> POSIXTime

-- | this game start time
[sgstart] :: SessionUI -> POSIXTime

-- | clips from start of session to current game start
[sallTime] :: SessionUI -> Time

-- | this game current frame count
[snframes] :: SessionUI -> Int

-- | frame count from start of session to current game start
[sallNframes] :: SessionUI -> Int

-- | Visualize atomic updates sent to the client. This is done in the
--   global state after the command is executed and after the client state
--   is modified by the command. Don't modify client state (except a few
--   fields), but only client session (e.g., by displaying messages). This
--   is enforced by types.
displayRespUpdAtomicUI :: MonadClientUI m => UpdAtomic -> m ()

-- | Display special effects (text, animation) sent to the client. Don't
--   modify client state (except a few fields), but only client session
--   (e.g., by displaying messages). This is enforced by types.
displayRespSfxAtomicUI :: MonadClientUI m => SfxAtomic -> m ()

-- | Operations for all content types, gathered together.
data CCUI
CCUI :: InputContent -> ScreenContent -> CCUI
[coinput] :: CCUI -> InputContent
[coscreen] :: CCUI -> ScreenContent

-- | Options that affect the UI of the client.
data UIOptions

-- | Modify client options with UI options.
applyUIOptions :: COps -> UIOptions -> ClientOptions -> ClientOptions

-- | Hardwired commandline arguments to process.
uCmdline :: UIOptions -> [String]

-- | Read and parse UI config file.
mkUIOptions :: COps -> Bool -> IO UIOptions

-- | Connection channel between a frontend and a client. Frontend acts as a
--   server, serving keys, etc., when given frames to display.
data ChanFrontend

-- | Initialize the frontend chosen by the player via client options.
chanFrontend :: MonadClientUI m => ScreenContent -> ClientOptions -> m ChanFrontend

-- | Add a prompt to the current report. Do not report if it was a
--   duplicate.
promptAdd :: MonadClientUI m => Text -> m ()

-- | Try to read saved client game state from the file system.
tryRestore :: MonadClientUI m => m (Maybe (StateClient, Maybe SessionUI))

-- | Let the human player issue commands until any command takes time.
humanCommand :: forall m. (MonadClient m, MonadClientUI m) => m ReqUI


-- | Semantics of responses sent by the server to clients.
module Game.LambdaHack.Client.HandleResponseM

-- | Client monad in which one can send requests to the client.
class MonadClient m => MonadClientWriteRequest m
sendRequestAI :: MonadClientWriteRequest m => RequestAI -> m ()
sendRequestUI :: MonadClientWriteRequest m => RequestUI -> m ()
clientHasUI :: MonadClientWriteRequest m => m Bool

-- | Monad for executing atomic game state transformations on a client.
class MonadClient m => MonadClientAtomic m

-- | Execute an atomic update that changes the client's <a>State</a>.
execUpdAtomic :: MonadClientAtomic m => UpdAtomic -> m ()

-- | Put state that is intended to be the result of performing an atomic
--   update by the server on its copy of the client's <a>State</a>.
execPutState :: MonadClientAtomic m => State -> m ()

-- | Handle server responses.
--   
--   Note that for clients communicating with the server over the net,
--   <tt>RespUpdAtomicNoState</tt> should be used, because executing a
--   single command is cheaper than sending the whole state over the net.
--   However, for the standalone exe mode, with clients in the same process
--   as the server, a pointer to the state set with <tt>execPutState</tt>
--   is cheaper.
handleResponse :: (MonadClientSetup m, MonadClientUI m, MonadClientAtomic m, MonadClientWriteRequest m) => Response -> m ()


-- | The main loop of the client, processing human and computer player
--   moves turn by turn.
module Game.LambdaHack.Client.LoopM

-- | Client monad in which one can receive responses from the server.
class MonadClient m => MonadClientReadResponse m
receiveResponse :: MonadClientReadResponse m => m Response

-- | The main game loop for an AI or UI client. It receives responses from
--   the server, changes internal client state accordingly, analyzes
--   ensuing human or AI commands and sends resulting requests to the
--   server. Depending on whether it's an AI or UI client, it sends AI or
--   human player requests.
--   
--   The loop is started in client state that is empty except for the
--   <tt>sside</tt> and <tt>seps</tt> fields, see <a>emptyStateClient</a>.
loopCli :: (MonadClientSetup m, MonadClientUI m, MonadClientAtomic m, MonadClientReadResponse m, MonadClientWriteRequest m) => CCUI -> UIOptions -> ClientOptions -> m ()
initAI :: MonadClient m => m ()
initUI :: (MonadClient m, MonadClientUI m) => CCUI -> m ()


-- | Semantics of responses that are sent from server to clients, in terms
--   of client state transformations, and semantics of human commands and
--   AI moves, in terms of requests to be sent from the client to the
--   server.
--   
--   See
--   <a>https://github.com/LambdaHack/LambdaHack/wiki/Client-server-architecture</a>.
module Game.LambdaHack.Client

-- | The main game loop for an AI or UI client. It receives responses from
--   the server, changes internal client state accordingly, analyzes
--   ensuing human or AI commands and sends resulting requests to the
--   server. Depending on whether it's an AI or UI client, it sends AI or
--   human player requests.
--   
--   The loop is started in client state that is empty except for the
--   <tt>sside</tt> and <tt>seps</tt> fields, see <a>emptyStateClient</a>.
loopCli :: (MonadClientSetup m, MonadClientUI m, MonadClientAtomic m, MonadClientReadResponse m, MonadClientWriteRequest m) => CCUI -> UIOptions -> ClientOptions -> m ()

-- | Requests sent by AI clients to the server. If faction leader is to be
--   changed, it's included as the second component.
type RequestAI = (ReqAI, Maybe ActorId)

-- | Possible forms of requests sent by AI clients.
data ReqAI
ReqAINop :: ReqAI
ReqAITimed :: RequestTimed -> ReqAI

-- | Requests sent by UI clients to the server. If faction leader is to be
--   changed, it's included as the second component.
type RequestUI = (ReqUI, Maybe ActorId)

-- | Possible forms of requests sent by UI clients.
data ReqUI
ReqUINop :: ReqUI
ReqUITimed :: RequestTimed -> ReqUI
ReqUIGameRestart :: GroupName ModeKind -> Challenge -> ReqUI
ReqUIGameDropAndExit :: ReqUI
ReqUIGameSaveAndExit :: ReqUI
ReqUIGameSave :: ReqUI
ReqUITactic :: Tactic -> ReqUI
ReqUIAutomate :: ReqUI

-- | Requests that take game time.
data RequestTimed
ReqMove :: Vector -> RequestTimed
ReqMelee :: ActorId -> ItemId -> CStore -> RequestTimed
ReqDisplace :: ActorId -> RequestTimed
ReqAlter :: Point -> RequestTimed
ReqWait :: RequestTimed
ReqWait10 :: RequestTimed
ReqYell :: RequestTimed
ReqMoveItems :: [(ItemId, Int, CStore, CStore)] -> RequestTimed
ReqProject :: Point -> Int -> ItemId -> CStore -> RequestTimed
ReqApply :: ItemId -> CStore -> RequestTimed

-- | Abstract syntax of responses sent by server to an AI or UI client (or
--   a universal client that can handle both roles, which is why this type
--   is not separated into distinct AI and UI types). A response tells a
--   client how to update game state or what information to send to the
--   server.
data Response

-- | change <tt>State</tt> by performing this atomic update
RespUpdAtomicNoState :: UpdAtomic -> Response

-- | put the given <tt>State</tt>, which results from performing the atomic
--   update
RespUpdAtomic :: State -> UpdAtomic -> Response

-- | compute an AI move for the actor and send (the semantics of) it
RespQueryAI :: ActorId -> Response

-- | perform special effects (animations, messages, etc.)
RespSfxAtomic :: SfxAtomic -> Response

-- | prompt the human player for a command and send (the semantics of) it
RespQueryUI :: Response

-- | Options that affect the behaviour of the client (but not game rules).
data ClientOptions
ClientOptions :: Maybe Text -> Maybe Text -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Maybe Int -> Bool -> Maybe Bool -> Bool -> Bool -> Maybe Text -> Maybe FilePath -> String -> Bool -> Bool -> Bool -> Bool -> Maybe Int -> Maybe Int -> Bool -> Bool -> Bool -> Bool -> ClientOptions

-- | Font family to use for the GTK main game window.
[sgtkFontFamily] :: ClientOptions -> Maybe Text

-- | Font file to use for the SDL2 main game window.
[sdlFontFile] :: ClientOptions -> Maybe Text

-- | Pixels to add to map cells on top of scalable font max glyph height.
--   To get symmetric padding, add an even number.
[sdlScalableSizeAdd] :: ClientOptions -> Maybe Int

-- | Pixels to add to map cells on top of fixed font max glyph height. To
--   get symmetric padding, add an even number.
[sdlBitmapSizeAdd] :: ClientOptions -> Maybe Int

-- | Font size to use for the main game window.
[sscalableFontSize] :: ClientOptions -> Maybe Int

-- | How much to log (e.g., from SDL). 1 is all, 5 is errors, the default.
[slogPriority] :: ClientOptions -> Maybe Int

-- | Maximal frames per second. This is better low and fixed, to avoid
--   jerkiness and delays that tell the player there are many intelligent
--   enemies on the level. That's better than scaling AI sofistication down
--   based on the FPS setting and machine speed.
[smaxFps] :: ClientOptions -> Maybe Int

-- | Never auto-answer all prompts, even if under AI control.
[sdisableAutoYes] :: ClientOptions -> Bool

-- | Don't show any animations.
[snoAnim] :: ClientOptions -> Maybe Bool

-- | Start a new game, overwriting the save file.
[snewGameCli] :: ClientOptions -> Bool

-- | Don't create directories and files and show time stats.
[sbenchmark] :: ClientOptions -> Bool
[stitle] :: ClientOptions -> Maybe Text
[sfontDir] :: ClientOptions -> Maybe FilePath

-- | Prefix of the save game file name.
[ssavePrefixCli] :: ClientOptions -> String

-- | Whether to use the stdout/stdin frontend.
[sfrontendTeletype] :: ClientOptions -> Bool

-- | Whether to use null (no input/output) frontend.
[sfrontendNull] :: ClientOptions -> Bool

-- | Whether to use lazy (output not even calculated) frontend.
[sfrontendLazy] :: ClientOptions -> Bool

-- | Show clients' internal debug messages.
[sdbgMsgCli] :: ClientOptions -> Bool
[sstopAfterSeconds] :: ClientOptions -> Maybe Int
[sstopAfterFrames] :: ClientOptions -> Maybe Int
[sprintEachScreen] :: ClientOptions -> Bool
[sexposePlaces] :: ClientOptions -> Bool
[sexposeItems] :: ClientOptions -> Bool
[sexposeActors] :: ClientOptions -> Bool

-- | Default value of client options.
defClientOptions :: ClientOptions

-- | Operations for all content types, gathered together.
data CCUI

-- | Options that affect the UI of the client.
data UIOptions

-- | Modify client options with UI options.
applyUIOptions :: COps -> UIOptions -> ClientOptions -> ClientOptions

-- | Hardwired commandline arguments to process.
uCmdline :: UIOptions -> [String]

-- | Read and parse UI config file.
mkUIOptions :: COps -> Bool -> IO UIOptions


-- | Server and client game state types and operations.
module Game.LambdaHack.Server.ServerOptions

-- | Options that affect the behaviour of the server (including game
--   rules).
data ServerOptions
ServerOptions :: Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Maybe (GroupName ModeKind) -> Bool -> Bool -> Maybe StdGen -> Maybe StdGen -> Bool -> Challenge -> Bool -> String -> Bool -> Bool -> ClientOptions -> ServerOptions
[sknowMap] :: ServerOptions -> Bool
[sknowEvents] :: ServerOptions -> Bool
[sknowItems] :: ServerOptions -> Bool
[sniff] :: ServerOptions -> Bool
[sallClear] :: ServerOptions -> Bool
[sboostRandomItem] :: ServerOptions -> Bool
[sgameMode] :: ServerOptions -> Maybe (GroupName ModeKind)
[sautomateAll] :: ServerOptions -> Bool
[skeepAutomated] :: ServerOptions -> Bool
[sdungeonRng] :: ServerOptions -> Maybe StdGen
[smainRng] :: ServerOptions -> Maybe StdGen
[snewGameSer] :: ServerOptions -> Bool
[scurChalSer] :: ServerOptions -> Challenge
[sdumpInitRngs] :: ServerOptions -> Bool
[ssavePrefixSer] :: ServerOptions -> String
[sdbgMsgSer] :: ServerOptions -> Bool
[sshowItemSamples] :: ServerOptions -> Bool
[sclientOptions] :: ServerOptions -> ClientOptions
data RNGs
RNGs :: Maybe StdGen -> Maybe StdGen -> RNGs
[dungeonRandomGenerator] :: RNGs -> Maybe StdGen
[startingRandomGenerator] :: RNGs -> Maybe StdGen

-- | Default value of server options.
defServerOptions :: ServerOptions
instance GHC.Show.Show Game.LambdaHack.Server.ServerOptions.ServerOptions
instance GHC.Show.Show Game.LambdaHack.Server.ServerOptions.RNGs
instance Data.Binary.Class.Binary Game.LambdaHack.Server.ServerOptions.RNGs
instance Data.Binary.Class.Binary Game.LambdaHack.Server.ServerOptions.ServerOptions


-- | Server and client game state types and operations.
module Game.LambdaHack.Server.State

-- | State with server-specific data, including a copy of each client's
--   basic game state, but not the server's basic state.
data StateServer
StateServer :: ActorTime -> ActorTime -> ActorPushedBy -> FactionAnalytics -> ActorAnalytics -> GenerationAnalytics -> EnumSet ActorId -> DiscoveryKindRev -> UniqueSet -> ItemRev -> FlavourMap -> ActorId -> ItemId -> EnumMap LevelId Int -> () -> EnumMap FactionId State -> PerFid -> PerValidFid -> PerCacheFid -> FovLucidLid -> FovClearLid -> FovLitLid -> [LevelId] -> Bool -> StdGen -> RNGs -> Bool -> Bool -> Bool -> ServerOptions -> ServerOptions -> StateServer

-- | absolute times of actors next actions
[sactorTime] :: StateServer -> ActorTime

-- | and same for actors with trajectories
[strajTime] :: StateServer -> ActorTime

-- | culprits for actors with trajectories
[strajPushedBy] :: StateServer -> ActorPushedBy

-- | various past events data for factions
[sfactionAn] :: StateServer -> FactionAnalytics

-- | various past events data for actors
[sactorAn] :: StateServer -> ActorAnalytics

-- | item creation statistics, by item lore
[sgenerationAn] :: StateServer -> GenerationAnalytics

-- | actors currently in time stasis, invulnerable to time warps until move
[sactorStasis] :: StateServer -> EnumSet ActorId

-- | reverse map, used for item creation
[sdiscoKindRev] :: StateServer -> DiscoveryKindRev

-- | already generated unique items
[suniqueSet] :: StateServer -> UniqueSet

-- | reverse id map, used for item creation
[sitemRev] :: StateServer -> ItemRev

-- | association of flavour to item kinds
[sflavour] :: StateServer -> FlavourMap

-- | stores next actor index
[sacounter] :: StateServer -> ActorId

-- | stores next item index
[sicounter] :: StateServer -> ItemId
[snumSpawned] :: StateServer -> EnumMap LevelId Int
[sundo] :: StateServer -> ()

-- | each faction state, as seen by clients
[sclientStates] :: StateServer -> EnumMap FactionId State

-- | perception of all factions
[sperFid] :: StateServer -> PerFid

-- | perception validity for all factions
[sperValidFid] :: StateServer -> PerValidFid

-- | perception cache of all factions
[sperCacheFid] :: StateServer -> PerCacheFid

-- | ambient or shining light positions
[sfovLucidLid] :: StateServer -> FovLucidLid

-- | clear tiles positions
[sfovClearLid] :: StateServer -> FovClearLid

-- | ambient light positions
[sfovLitLid] :: StateServer -> FovLitLid

-- | active arenas
[sarenas] :: StateServer -> [LevelId]

-- | whether active arenas valid
[svalidArenas] :: StateServer -> Bool

-- | current random generator
[srandom] :: StateServer -> StdGen

-- | initial random generators
[srngs] :: StateServer -> RNGs

-- | exit game loop after clip's end; usually no game save follows
[sbreakLoop] :: StateServer -> Bool

-- | exit game loop ASAP; usually with save
[sbreakASAP] :: StateServer -> Bool

-- | write savegame to file after loop exit
[swriteSave] :: StateServer -> Bool

-- | current commandline options
[soptions] :: StateServer -> ServerOptions

-- | options for the next game
[soptionsNxt] :: StateServer -> ServerOptions

-- | Position in time for each actor, grouped by level and by faction.
type ActorTime = EnumMap FactionId (EnumMap LevelId (EnumMap ActorId Time))

-- | Record who last propelled a given actor with trajectory.
type ActorPushedBy = EnumMap ActorId ActorId

-- | Initial, empty game server state.
emptyStateServer :: StateServer
updateActorTime :: FactionId -> LevelId -> ActorId -> Time -> ActorTime -> ActorTime
lookupActorTime :: FactionId -> LevelId -> ActorId -> ActorTime -> Maybe Time
ageActor :: FactionId -> LevelId -> ActorId -> Delta Time -> ActorTime -> ActorTime
instance GHC.Show.Show Game.LambdaHack.Server.State.StateServer
instance Data.Binary.Class.Binary Game.LambdaHack.Server.State.StateServer


-- | The dungeon generation routine. It creates empty dungeons, without
--   actors and without items, either lying on the floor or embedded inside
--   tiles.
module Game.LambdaHack.Server.DungeonGen

-- | Freshly generated and not yet populated dungeon.
data FreshDungeon
FreshDungeon :: Dungeon -> AbsDepth -> FreshDungeon

-- | maps for all levels
[freshDungeon] :: FreshDungeon -> Dungeon

-- | absolute dungeon depth
[freshTotalDepth] :: FreshDungeon -> AbsDepth

-- | Generate the dungeon for a new game.
dungeonGen :: COps -> ServerOptions -> Caves -> Rnd FreshDungeon
convertTileMaps :: COps -> Bool -> Rnd (ContentId TileKind) -> Maybe (Rnd (ContentId TileKind)) -> Area -> TileMapEM -> Rnd TileMap
buildTileMap :: COps -> Cave -> Rnd TileMap
anchorDown :: Y
buildLevel :: COps -> ServerOptions -> Int -> GroupName CaveKind -> Int -> AbsDepth -> [(Point, Text)] -> Rnd (Level, [(Point, Text)])
snapToStairList :: Int -> [Point] -> Point -> Either Point Point
placeDownStairs :: Text -> Bool -> ServerOptions -> Int -> CaveKind -> Area -> [Point] -> [Point] -> Rnd (Maybe Point)
levelFromCave :: COps -> Cave -> AbsDepth -> TileMap -> ([Point], [Point]) -> [Point] -> Level


-- | Basic server monads and related operations.
module Game.LambdaHack.Server.MonadServer
class MonadStateRead m => MonadServer m
getsServer :: MonadServer m => (StateServer -> a) -> m a
modifyServer :: MonadServer m => (StateServer -> StateServer) -> m ()
chanSaveServer :: MonadServer m => m (ChanSave (State, StateServer))
liftIO :: MonadServer m => IO a -> m a

-- | The monad for executing atomic game state transformations.
class MonadServer m => MonadServerAtomic m

-- | Execute an atomic command that changes the state on the server and on
--   all clients that can notice it.
execUpdAtomic :: MonadServerAtomic m => UpdAtomic -> m ()

-- | Execute an atomic command that changes the state on the server only.
execUpdAtomicSer :: MonadServerAtomic m => UpdAtomic -> m Bool

-- | Execute an atomic command that changes the state on the given single
--   client only.
execUpdAtomicFid :: MonadServerAtomic m => FactionId -> UpdAtomic -> m ()

-- | Execute an atomic command that changes the state on the given single
--   client only. Catch <a>AtomicFail</a> and indicate if it was in fact
--   raised.
execUpdAtomicFidCatch :: MonadServerAtomic m => FactionId -> UpdAtomic -> m Bool

-- | Execute an atomic command that only displays special effects.
execSfxAtomic :: MonadServerAtomic m => SfxAtomic -> m ()
execSendPer :: MonadServerAtomic m => FactionId -> LevelId -> Perception -> Perception -> Perception -> m ()
getServer :: MonadServer m => m StateServer
putServer :: MonadServer m => StateServer -> m ()
debugPossiblyPrint :: MonadServer m => Text -> m ()
debugPossiblyPrintAndExit :: MonadServer m => Text -> m ()
serverPrint :: MonadServer m => Text -> m ()
saveServer :: MonadServer m => m ()

-- | Dumps to stdout the RNG states from the start of the game.
dumpRngs :: MonadServer m => RNGs -> m ()

-- | Read the high scores dictionary. Return the empty table if no file.
restoreScore :: forall m. MonadServer m => COps -> m ScoreDict

-- | Generate a new score, register it and save.
registerScore :: MonadServer m => Status -> FactionId -> m ()

-- | Invoke pseudo-random computation with the generator kept in the state.
rndToAction :: MonadServer m => Rnd a -> m a

-- | Gets a random generator from the user-submitted options or, if not
--   present, generates one.
getSetGen :: MonadServer m => Maybe StdGen -> m StdGen


-- | Server operations for items.
module Game.LambdaHack.Server.ItemM
registerItem :: MonadServerAtomic m => ItemFullKit -> ItemKnown -> Container -> Bool -> m ItemId
randomResetTimeout :: MonadServerAtomic m => Int -> ItemId -> ItemFull -> [Time] -> Container -> m ()
embedItem :: MonadServerAtomic m => LevelId -> Point -> ContentId TileKind -> m ()
prepareItemKind :: MonadServerAtomic m => Int -> LevelId -> Freqs ItemKind -> m (Frequency (ContentId ItemKind, ItemKind))
rollItemAspect :: MonadServerAtomic m => Frequency (ContentId ItemKind, ItemKind) -> LevelId -> m (Maybe (ItemKnown, ItemFullKit))
rollAndRegisterItem :: MonadServerAtomic m => LevelId -> Freqs ItemKind -> Container -> Bool -> Maybe Int -> m (Maybe (ItemId, ItemFullKit))
placeItemsInDungeon :: forall m. MonadServerAtomic m => EnumMap LevelId [Point] -> m ()
embedItemsInDungeon :: MonadServerAtomic m => m ()

-- | Mapping over actor's items from a give store.
mapActorCStore_ :: MonadServer m => CStore -> (ItemId -> ItemQuant -> m a) -> Actor -> m ()
onlyRegisterItem :: MonadServerAtomic m => ItemKnown -> m ItemId
computeRndTimeout :: Time -> ItemFull -> Rnd (Maybe Time)
createLevelItem :: MonadServerAtomic m => Point -> LevelId -> m ()


-- | Handle atomic commands on the server, after they are executed to
--   change server <a>State</a> and before they are sent to clients.
module Game.LambdaHack.Server.HandleAtomicM

-- | Effect of atomic actions on server state is calculated with the global
--   state from after the command is executed (except where the supplied
--   <tt>oldState</tt> is used).
cmdAtomicSemSer :: MonadServer m => State -> UpdAtomic -> m ()
invalidateArenas :: MonadServer m => m ()
updateSclear :: MonadServer m => LevelId -> Point -> ContentId TileKind -> ContentId TileKind -> m Bool
updateSlit :: MonadServer m => LevelId -> Point -> ContentId TileKind -> ContentId TileKind -> m Bool
invalidateLucidLid :: MonadServer m => LevelId -> m ()
invalidateLucidAid :: MonadServer m => ActorId -> m ()
actorHasShine :: ActorMaxSkills -> ActorId -> Bool
itemAffectsShineRadius :: DiscoveryAspect -> ItemId -> [CStore] -> Bool
itemAffectsPerRadius :: DiscoveryAspect -> ItemId -> Bool
addPerActor :: MonadServer m => ActorId -> Actor -> m ()
addPerActorAny :: MonadServer m => ActorId -> Actor -> m ()
deletePerActor :: MonadServer m => ActorMaxSkills -> ActorId -> Actor -> m ()
deletePerActorAny :: MonadServer m => ActorId -> Actor -> m ()
invalidatePerActor :: MonadServer m => ActorId -> m ()
reconsiderPerActor :: MonadServer m => ActorId -> m ()
invalidatePerLid :: MonadServer m => LevelId -> m ()


-- | Debug output for requests and responses.
module Game.LambdaHack.Server.DebugM
debugResponse :: MonadServer m => FactionId -> Response -> m ()
debugRequestAI :: MonadServer m => ActorId -> m ()
debugRequestUI :: MonadServer m => ActorId -> m ()
debugShow :: Show a => a -> Text
debugPretty :: MonadServer m => FactionId -> Text -> UpdAtomic -> m ()
debugPlain :: MonadServer m => FactionId -> Text -> UpdAtomic -> m ()
data DebugAid
DebugAid :: Text -> ActorId -> FactionId -> LevelId -> Int64 -> Maybe Time -> Maybe Time -> Time -> DebugAid
[label] :: DebugAid -> Text
[aid] :: DebugAid -> ActorId
[faction] :: DebugAid -> FactionId
[lid] :: DebugAid -> LevelId
[bHP] :: DebugAid -> Int64
[btime] :: DebugAid -> Maybe Time
[btrTime] :: DebugAid -> Maybe Time
[time] :: DebugAid -> Time
debugAid :: MonadServer m => ActorId -> Text -> m Text
instance GHC.Show.Show Game.LambdaHack.Server.DebugM.DebugAid


-- | The server definitions for the server-client communication protocol.
module Game.LambdaHack.Server.ProtocolM
type CliSerQueue = MVar

-- | Connection information for all factions, indexed by faction
--   identifier.
type ConnServerDict = EnumMap FactionId ChanServer

-- | Connection channel between the server and a single client.
data ChanServer
ChanServer :: CliSerQueue Response -> CliSerQueue RequestAI -> Maybe (CliSerQueue RequestUI) -> ChanServer
[responseS] :: ChanServer -> CliSerQueue Response
[requestAIS] :: ChanServer -> CliSerQueue RequestAI
[requestUIS] :: ChanServer -> Maybe (CliSerQueue RequestUI)

-- | The server monad with the ability to communicate with clients.
class MonadServer m => MonadServerComm m
getsDict :: MonadServerComm m => (ConnServerDict -> a) -> m a
modifyDict :: MonadServerComm m => (ConnServerDict -> ConnServerDict) -> m ()
liftIO :: MonadServerComm m => IO a -> m a
putDict :: MonadServerComm m => ConnServerDict -> m ()

-- | If the <tt>AtomicFail</tt> conditions hold, send a command to client,
--   otherwise do nothing.
sendUpdate :: (MonadServerAtomic m, MonadServerComm m) => FactionId -> UpdAtomic -> m ()

-- | Send a command to client, crashing if the <tt>AtomicFail</tt>
--   conditions don't hold when executed on the client's state.
sendUpdateCheck :: (MonadServerAtomic m, MonadServerComm m) => FactionId -> UpdAtomic -> m ()
sendUpdNoState :: MonadServerComm m => FactionId -> UpdAtomic -> m ()
sendSfx :: MonadServerComm m => FactionId -> SfxAtomic -> m ()
sendQueryAI :: MonadServerComm m => FactionId -> ActorId -> m RequestAI
sendQueryUI :: (MonadServerAtomic m, MonadServerComm m) => FactionId -> ActorId -> m RequestUI
killAllClients :: (MonadServerAtomic m, MonadServerComm m) => m ()
childrenServer :: MVar [Async ()]

-- | Update connections to the new definition of factions. Connect to
--   clients in old or newly spawned threads that read and write directly
--   to the channels.
updateConn :: (MonadServerAtomic m, MonadServerComm m) => (Bool -> FactionId -> ChanServer -> IO ()) -> m ()
tryRestore :: MonadServerComm m => m (Maybe (State, StateServer))
writeQueue :: MonadServerComm m => Response -> CliSerQueue Response -> m ()
readQueueAI :: MonadServerComm m => CliSerQueue RequestAI -> m RequestAI
readQueueUI :: MonadServerComm m => CliSerQueue RequestUI -> m RequestUI
newQueue :: IO (CliSerQueue a)


-- | Sending atomic commands to clients and executing them on the server.
--   
--   See
--   <a>https://github.com/LambdaHack/LambdaHack/wiki/Client-server-architecture</a>.
module Game.LambdaHack.Server.BroadcastAtomic

-- | Send an atomic action to all clients that can see it.
handleAndBroadcast :: (MonadServerAtomic m, MonadServerComm m) => PosAtomic -> [UpdAtomic] -> CmdAtomic -> m ()
sendPer :: (MonadServerAtomic m, MonadServerComm m) => FactionId -> LevelId -> Perception -> Perception -> Perception -> m ()
handleCmdAtomicServer :: MonadServerAtomic m => UpdAtomic -> m (PosAtomic, [UpdAtomic], Bool)

-- | Messages for some unseen atomic commands.
hearUpdAtomic :: MonadStateRead m => [(ActorId, Actor)] -> UpdAtomic -> m (Maybe [ActorId])

-- | Messages for some unseen sfx.
hearSfxAtomic :: MonadServer m => [(ActorId, Actor)] -> SfxAtomic -> m (Maybe (HearMsg, [ActorId]))
filterHear :: MonadStateRead m => Point -> [(ActorId, Actor)] -> m [ActorId]
atomicForget :: FactionId -> LevelId -> Perception -> State -> [UpdAtomic]
atomicRemember :: LevelId -> Perception -> State -> State -> [UpdAtomic]


-- | Server operations common to many modules.
module Game.LambdaHack.Server.CommonM
revealItems :: MonadServerAtomic m => FactionId -> m ()
moveStores :: MonadServerAtomic m => Bool -> ActorId -> CStore -> CStore -> m ()

-- | Generate the atomic updates that jointly perform a given item move.
generalMoveItem :: MonadStateRead m => Bool -> ItemId -> Int -> Container -> Container -> m [UpdAtomic]
deduceQuits :: MonadServerAtomic m => FactionId -> Status -> m ()
deduceKilled :: MonadServerAtomic m => ActorId -> m ()
electLeader :: MonadServerAtomic m => FactionId -> LevelId -> ActorId -> m ()
setFreshLeader :: MonadServerAtomic m => FactionId -> ActorId -> m ()
updatePer :: MonadServerAtomic m => FactionId -> LevelId -> m ()
recomputeCachePer :: MonadServer m => FactionId -> LevelId -> m Perception
projectFail :: MonadServerAtomic m => ActorId -> ActorId -> Point -> Int -> Bool -> ItemId -> CStore -> Bool -> m (Maybe ReqFailure)
addActorFromGroup :: MonadServerAtomic m => GroupName ItemKind -> FactionId -> Point -> LevelId -> Time -> m (Maybe ActorId)
registerActor :: MonadServerAtomic m => Bool -> ItemKnown -> ItemFullKit -> FactionId -> Point -> LevelId -> Time -> m ActorId
discoverIfMinorEffects :: MonadServerAtomic m => Container -> ItemId -> ContentId ItemKind -> m ()
pickWeaponServer :: MonadServer m => ActorId -> m (Maybe (ItemId, CStore))
currentSkillsServer :: MonadServer m => ActorId -> m Skills
allGroupItems :: MonadServerAtomic m => CStore -> GroupName ItemKind -> ActorId -> m [(ItemId, ItemQuant)]
addCondition :: MonadServerAtomic m => GroupName ItemKind -> ActorId -> m ()
removeConditionSingle :: MonadServerAtomic m => GroupName ItemKind -> ActorId -> m Int
addSleep :: MonadServerAtomic m => ActorId -> m ()
removeSleepSingle :: MonadServerAtomic m => ActorId -> m ()
addKillToAnalytics :: MonadServerAtomic m => ActorId -> KillHow -> FactionId -> ItemId -> m ()
containerMoveItem :: MonadStateRead m => Bool -> ItemId -> Int -> Container -> Container -> m [UpdAtomic]
quitF :: MonadServerAtomic m => Status -> FactionId -> m ()

-- | Tell whether a faction that we know is still in game, keeps arena.
--   Keeping arena means, if the faction is still in game, it always has a
--   leader in the dungeon somewhere. So, leaderless factions and spawner
--   factions do not keep an arena, even though the latter usually has a
--   leader for most of the game.
keepArenaFact :: Faction -> Bool
anyActorsAlive :: MonadServer m => FactionId -> ActorId -> m Bool
projectBla :: MonadServerAtomic m => ActorId -> ActorId -> Point -> [Point] -> ItemId -> CStore -> Bool -> m ()
addProjectile :: MonadServerAtomic m => ActorId -> Point -> [Point] -> ItemId -> ItemQuant -> LevelId -> FactionId -> Time -> m ()
addActorIid :: MonadServerAtomic m => ItemId -> ItemFull -> Bool -> FactionId -> Point -> LevelId -> (Actor -> Actor) -> m ActorId
getCacheLucid :: MonadServer m => LevelId -> m FovLucid
getCacheTotal :: MonadServer m => FactionId -> LevelId -> m CacheBeforeLucid


-- | Operations for starting and restarting the game.
module Game.LambdaHack.Server.StartM
initPer :: MonadServer m => m ()
reinitGame :: MonadServerAtomic m => m ()
gameReset :: MonadServer m => ServerOptions -> Maybe (GroupName ModeKind) -> Maybe StdGen -> m State

-- | Apply options that don't need a new game.
applyDebug :: MonadServer m => m ()
sampleTrunks :: MonadServerAtomic m => Dungeon -> m GenerationAnalytics
sampleItems :: MonadServerAtomic m => Dungeon -> m GenerationAnalytics
mapFromFuns :: Ord b => [a] -> [a -> b] -> Map b a
resetFactions :: FactionDict -> ContentId ModeKind -> Int -> AbsDepth -> Roster -> Rnd FactionDict
populateDungeon :: MonadServerAtomic m => m ()

-- | Find starting postions for all factions. Try to make them distant from
--   each other. Place as many of the factions, as possible, over stairs,
--   starting from the end of the list, including placing the last factions
--   over escapes (we assume they are guardians of the escapes). This
--   implies the inital factions (if any) start far from escapes.
findEntryPoss :: COps -> LevelId -> Level -> Int -> Rnd [Point]


-- | Server operations performed periodically in the game loop and related
--   operations.
module Game.LambdaHack.Server.PeriodicM

-- | Spawn, possibly, a monster according to the level's actor groups. We
--   assume heroes are never spawned.
spawnMonster :: MonadServerAtomic m => m ()
addAnyActor :: MonadServerAtomic m => Bool -> Int -> Freqs ItemKind -> LevelId -> Time -> Maybe Point -> m (Maybe ActorId)

-- | Advance the move time for the given actor.
advanceTime :: MonadServerAtomic m => ActorId -> Int -> Bool -> m ()

-- | Advance the trajectory following time for the given actor.
advanceTimeTraj :: MonadServerAtomic m => ActorId -> m ()

-- | Add communication overhead time delta to all non-projectile, non-dying
--   faction's actors, except the leader. Effectively, this limits moves of
--   a faction on a level to 10, regardless of the number of actors and
--   their speeds. To avoid animals suddenly acting extremely sluggish
--   whenever monster's leader visits a distant arena that has a crowd of
--   animals, overhead applies only to actors on the same level. Since the
--   number of active levels is limited, this bounds the total moves per
--   turn of each faction as well.
--   
--   Leader is immune from overhead and so he is faster than other faction
--   members and of equal speed to leaders of other factions (of equal base
--   speed) regardless how numerous the faction is. Thanks to this, there
--   is no problem with leader of a numerous faction having very long UI
--   turns, introducing UI lag.
overheadActorTime :: MonadServerAtomic m => FactionId -> LevelId -> m ()

-- | Swap the relative move times of two actors (e.g., when switching a UI
--   leader). Notice that their trajectory move times are not swapped.
swapTime :: MonadServerAtomic m => ActorId -> ActorId -> m ()
updateCalm :: MonadServerAtomic m => ActorId -> Int64 -> m ()
leadLevelSwitch :: MonadServerAtomic m => m ()
rollSpawnPos :: COps -> EnumSet Point -> Bool -> Bool -> LevelId -> Level -> FactionId -> State -> Rnd (Maybe Point)


-- | Handle effects. They are most often caused by requests sent by clients
--   but sometimes also caused by projectiles or periodically activated
--   items.
module Game.LambdaHack.Server.HandleEffectM
applyItem :: MonadServerAtomic m => ActorId -> ItemId -> CStore -> m ()
kineticEffectAndDestroy :: MonadServerAtomic m => Bool -> ActorId -> ActorId -> ActorId -> ItemId -> Container -> Bool -> m ()
effectAndDestroyAndAddKill :: MonadServerAtomic m => Bool -> ActorId -> Bool -> Bool -> Bool -> ActorId -> ActorId -> ItemId -> Container -> Bool -> ItemFull -> Bool -> m ()
itemEffectEmbedded :: MonadServerAtomic m => Bool -> ActorId -> LevelId -> Point -> ItemId -> m ()
highestImpression :: MonadServerAtomic m => Actor -> m (Maybe (FactionId, Int))
dominateFidSfx :: MonadServerAtomic m => ActorId -> ActorId -> FactionId -> m Bool

-- | Drop all actor's items.
dropAllItems :: MonadServerAtomic m => ActorId -> Actor -> m ()
pickDroppable :: MonadStateRead m => Bool -> ActorId -> Actor -> m Container
data UseResult
UseDud :: UseResult
UseId :: UseResult
UseUp :: UseResult
applyKineticDamage :: MonadServerAtomic m => ActorId -> ActorId -> ItemId -> m Bool
refillHP :: MonadServerAtomic m => ActorId -> ActorId -> Int64 -> m ()
cutCalm :: MonadServerAtomic m => ActorId -> m ()
effectAndDestroy :: MonadServerAtomic m => Bool -> Bool -> Bool -> ActorId -> ActorId -> ItemId -> Container -> Bool -> ItemFull -> Bool -> m ()
imperishableKit :: Bool -> ItemFull -> Bool

-- | The source actor affects the target actor, with a given item. If any
--   of the effects fires up, the item gets identified. Even using raw
--   damage (beating the enemy with the magic wand, for example) identifies
--   the item. This means a costly <tt>UpdDiscover</tt> is processed for
--   each random timeout weapon hit and for most projectiles, but at least
--   not for most explosion particles nor plain organs. And if not needed,
--   the <tt>UpdDiscover</tt> are eventually not sent to clients. So, enemy
--   missiles that hit us are no longer mysterious until picked up, which
--   is for the better, because the client knows their charging status and
--   so can generate accurate messages in the case when not recharged. This
--   also means that thrown consumables in flasks sturdy enough to cause
--   damage are always identified at hit, even if no effect activated. So
--   throwing them at foes is a better identification method than applying.
--   
--   Note that if we activate a durable non-passive item, e.g., a spiked
--   shield, from the ground, it will get identified, which is perfectly
--   fine, until we want to add sticky armor that can't be easily taken off
--   (and, e.g., has some maluses).
itemEffectDisco :: MonadServerAtomic m => Bool -> Bool -> ActorId -> ActorId -> ItemId -> ContentId ItemKind -> ItemKind -> Container -> Bool -> [Effect] -> m UseResult

-- | Source actor affects target actor, with a given effect and it
--   strength. Both actors are on the current level and can be the same
--   actor. The item may or may not still be in the container.
effectSem :: MonadServerAtomic m => Bool -> ActorId -> ActorId -> ItemId -> Container -> Bool -> Effect -> m UseResult
effectBurn :: MonadServerAtomic m => Dice -> ActorId -> ActorId -> m UseResult
effectExplode :: MonadServerAtomic m => m () -> GroupName ItemKind -> ActorId -> ActorId -> m UseResult
effectRefillHP :: MonadServerAtomic m => Int -> ActorId -> ActorId -> m UseResult
effectRefillCalm :: MonadServerAtomic m => m () -> Int -> ActorId -> ActorId -> m UseResult
effectDominate :: MonadServerAtomic m => ActorId -> ActorId -> m UseResult
dominateFid :: MonadServerAtomic m => FactionId -> ActorId -> ActorId -> m ()
effectImpress :: MonadServerAtomic m => (Effect -> m UseResult) -> m () -> ActorId -> ActorId -> m UseResult
effectPutToSleep :: MonadServerAtomic m => m () -> ActorId -> m UseResult
effectYell :: MonadServerAtomic m => m () -> ActorId -> m UseResult
effectSummon :: MonadServerAtomic m => GroupName ItemKind -> Dice -> ItemId -> ActorId -> ActorId -> Bool -> m UseResult
effectAscend :: MonadServerAtomic m => (Effect -> m UseResult) -> m () -> Bool -> ActorId -> ActorId -> Point -> m UseResult
findStairExit :: MonadStateRead m => FactionId -> Bool -> LevelId -> Point -> m Point
switchLevels1 :: MonadServerAtomic m => (ActorId, Actor) -> m (Maybe ActorId)
switchLevels2 :: MonadServerAtomic m => LevelId -> Point -> (ActorId, Actor) -> Maybe Time -> Maybe Time -> Maybe ActorId -> m ()

-- | The faction leaves the dungeon.
effectEscape :: MonadServerAtomic m => m () -> ActorId -> ActorId -> m UseResult

-- | Advance target actor time by this many time clips. Not by actor moves,
--   to hurt fast actors more.
effectParalyze :: MonadServerAtomic m => m () -> Dice -> ActorId -> ActorId -> m UseResult
paralyze :: MonadServerAtomic m => m () -> Dice -> ActorId -> ActorId -> m UseResult

-- | Advance target actor time by this many time clips. Not by actor moves,
--   to hurt fast actors more. Due to water, so resistable.
effectParalyzeInWater :: MonadServerAtomic m => m () -> Dice -> ActorId -> ActorId -> m UseResult

-- | Give target actor the given number of tenths of extra move. Don't give
--   an absolute amount of time units, to benefit slow actors more.
effectInsertMove :: MonadServerAtomic m => m () -> Dice -> ActorId -> ActorId -> m UseResult

-- | Teleport the target actor. Note that projectiles can be teleported,
--   too, for extra fun.
effectTeleport :: MonadServerAtomic m => m () -> Dice -> ActorId -> ActorId -> m UseResult
effectCreateItem :: MonadServerAtomic m => Maybe FactionId -> Maybe Int -> ActorId -> ActorId -> CStore -> GroupName ItemKind -> TimerDice -> m UseResult

-- | Make the target actor drop items in a store from the given group. The
--   item itself is immune (any copies).
effectDropItem :: MonadServerAtomic m => m () -> ItemId -> Int -> Int -> CStore -> GroupName ItemKind -> ActorId -> m UseResult

-- | Drop a single actor's item (though possibly multiple copies). Note
--   that if there are multiple copies, at most one explodes to avoid
--   excessive carnage and UI clutter (let's say, the multiple explosions
--   interfere with each other or perhaps larger quantities of explosives
--   tend to be packaged more safely). Note also that <tt>OnSmash</tt>
--   effects are activated even if item discharged.
dropCStoreItem :: MonadServerAtomic m => Bool -> CStore -> ActorId -> Actor -> Int -> ItemId -> ItemQuant -> m ()
effectPolyItem :: MonadServerAtomic m => m () -> ItemId -> ActorId -> m UseResult
effectRerollItem :: forall m. MonadServerAtomic m => m () -> ItemId -> ActorId -> m UseResult
effectDupItem :: MonadServerAtomic m => m () -> ItemId -> ActorId -> m UseResult
effectIdentify :: MonadServerAtomic m => m () -> ItemId -> ActorId -> m UseResult
identifyIid :: MonadServerAtomic m => ItemId -> Container -> ContentId ItemKind -> ItemKind -> m ()
effectDetect :: MonadServerAtomic m => m () -> DetectKind -> Int -> ActorId -> Point -> m UseResult
effectDetectX :: MonadServerAtomic m => DetectKind -> (Point -> Bool) -> ([Point] -> m Bool) -> m () -> Int -> ActorId -> m UseResult

-- | Send the target actor flying like a projectile. If the actors are
--   adjacent, the vector is directed outwards, if no, inwards, if it's the
--   same actor, boldpos is used, if it can't, a random outward vector of
--   length 10 is picked.
effectSendFlying :: MonadServerAtomic m => m () -> ThrowMod -> ActorId -> ActorId -> Container -> Maybe Bool -> m UseResult
sendFlyingVector :: MonadServerAtomic m => ActorId -> ActorId -> Maybe Bool -> m Vector

-- | Make the target actor drop his best weapon. The item itself is immune
--   (any copies).
effectDropBestWeapon :: MonadServerAtomic m => m () -> ItemId -> ActorId -> m UseResult

-- | Activate all items with the given symbol in the target actor's
--   equipment (there's no variant that activates a random one, to avoid
--   the incentive for carrying garbage). Only one item of each stack is
--   activated (and possibly consumed). Won't activate the item itself (any
--   copies).
effectActivateInv :: MonadServerAtomic m => m () -> ItemId -> ActorId -> ActorId -> Char -> m UseResult
effectTransformContainer :: forall m. MonadServerAtomic m => m () -> ItemId -> Char -> Container -> (ItemId -> ItemQuant -> m ()) -> m UseResult
effectApplyPerfume :: MonadServerAtomic m => m () -> ActorId -> m UseResult
effectOneOf :: MonadServerAtomic m => (Effect -> m UseResult) -> [Effect] -> m UseResult
effectVerbNoLonger :: MonadServerAtomic m => Bool -> m () -> ActorId -> m UseResult
effectVerbMsg :: MonadServerAtomic m => m () -> ActorId -> m UseResult
effectComposite :: forall m. MonadServerAtomic m => (Effect -> m UseResult) -> [Effect] -> m UseResult
instance GHC.Classes.Ord Game.LambdaHack.Server.HandleEffectM.UseResult
instance GHC.Classes.Eq Game.LambdaHack.Server.HandleEffectM.UseResult


-- | Semantics of requests . A couple of them do not take time, the rest
--   does. Note that since the results are atomic commands, which are
--   executed only later (on the server and some of the clients), all
--   condition are checkd by the semantic functions in the context of the
--   state before the server command. Even if one or more atomic actions
--   are already issued by the point an expression is evaluated, they do
--   not influence the outcome of the evaluation.
module Game.LambdaHack.Server.HandleRequestM

-- | The semantics of server commands. AI always takes time and so doesn't
--   loop.
handleRequestAI :: MonadServerAtomic m => ReqAI -> m (Maybe RequestTimed)

-- | The semantics of server commands. Only the first two cases affect
--   time.
handleRequestUI :: MonadServerAtomic m => FactionId -> ActorId -> ReqUI -> m (Maybe RequestTimed)
handleRequestTimed :: MonadServerAtomic m => FactionId -> ActorId -> RequestTimed -> m Bool
switchLeader :: MonadServerAtomic m => FactionId -> ActorId -> m ()
reqMoveGeneric :: MonadServerAtomic m => Bool -> Bool -> ActorId -> Vector -> m ()
reqDisplaceGeneric :: MonadServerAtomic m => Bool -> ActorId -> ActorId -> m ()
reqAlterFail :: MonadServerAtomic m => Bool -> ActorId -> Point -> m (Maybe ReqFailure)
reqGameDropAndExit :: MonadServerAtomic m => ActorId -> m ()
reqGameSaveAndExit :: MonadServerAtomic m => ActorId -> m ()
execFailure :: MonadServerAtomic m => ActorId -> RequestTimed -> ReqFailure -> m ()
checkWaiting :: RequestTimed -> Maybe Bool

-- | This is a shorthand. Instead of setting <tt>bwatch</tt> in
--   <tt>ReqWait</tt> and unsetting in all other requests, we call this
--   once after executing a request. In game state, we collect the number
--   of server requests pertaining to the actor (the number of actor's
--   "moves"), through which the actor was waiting.
processWatchfulness :: MonadServerAtomic m => Maybe Bool -> ActorId -> m ()

-- | Clear deltas for Calm and HP for proper UI display and AI hints.
managePerRequest :: MonadServerAtomic m => ActorId -> m ()
handleRequestTimedCases :: MonadServerAtomic m => ActorId -> RequestTimed -> m ()

-- | Add a smell trace for the actor to the level. If smell already there
--   and the actor can smell, remove smell. Projectiles are ignored. As
--   long as an actor can smell, he doesn't leave any smell ever. Smell
--   trace is never left in water tiles.
affectSmell :: MonadServerAtomic m => ActorId -> m ()

-- | Actor moves or attacks. Note that client may not be able to see an
--   invisible monster so it's the server that determines if melee took
--   place, etc. Also, only the server is authorized to check if a move is
--   legal and it needs full context for that, e.g., the initial actor
--   position to check if melee attack does not try to reach to a distant
--   tile.
reqMove :: MonadServerAtomic m => ActorId -> Vector -> m ()

-- | Resolves the result of an actor moving into another. Actors on
--   unwalkable positions can be attacked without any restrictions. For
--   instance, an actor embedded in a wall can be attacked from an adjacent
--   position. This function is analogous to projectGroupItem, but for
--   melee and not using up the weapon. No problem if there are many
--   projectiles at the spot. We just attack the one specified.
reqMelee :: MonadServerAtomic m => ActorId -> ActorId -> ItemId -> CStore -> m ()
reqMeleeChecked :: forall m. MonadServerAtomic m => Bool -> ActorId -> ActorId -> ItemId -> CStore -> m ()

-- | Actor tries to swap positions with another.
reqDisplace :: MonadServerAtomic m => ActorId -> ActorId -> m ()

-- | Search and/or alter the tile.
reqAlter :: MonadServerAtomic m => ActorId -> Point -> m ()

-- | Do nothing. Wait skill 1 required. Bracing requires 2, sleep 3,
--   lurking 4.
--   
--   Something is sometimes done in <a>processWatchfulness</a>.
reqWait :: MonadServerAtomic m => ActorId -> m ()

-- | Do nothing.
--   
--   Something is sometimes done in <a>processWatchfulness</a>.
reqWait10 :: MonadServerAtomic m => ActorId -> m ()

-- | Yell<i>yawn</i>stretch/taunt. Wakes up (gradually) from sleep. Causes
--   noise heard by enemies on the level even if out of their hearing
--   range.
--   
--   Governed by the waiting skill (because everyone is supposed to have
--   it). unlike <tt>ReqWait</tt>, induces overhead.
--   
--   This is similar to the effect <tt>Yell</tt>, but always voluntary.
reqYell :: MonadServerAtomic m => ActorId -> m ()
reqMoveItems :: MonadServerAtomic m => ActorId -> [(ItemId, Int, CStore, CStore)] -> m ()
reqMoveItem :: MonadServerAtomic m => ActorId -> Bool -> (ItemId, Int, CStore, CStore) -> m ()
reqProject :: MonadServerAtomic m => ActorId -> Point -> Int -> ItemId -> CStore -> m ()
reqApply :: MonadServerAtomic m => ActorId -> ItemId -> CStore -> m ()
reqGameRestart :: MonadServerAtomic m => ActorId -> GroupName ModeKind -> Challenge -> m ()
reqGameSave :: MonadServer m => m ()
reqTactic :: MonadServerAtomic m => FactionId -> Tactic -> m ()
reqAutomate :: MonadServerAtomic m => FactionId -> m ()


-- | Server operations used when ending game and deciding whether to end.
module Game.LambdaHack.Server.EndM

-- | Continue or exit or restart the game.
endOrLoop :: (MonadServerAtomic m, MonadServerComm m) => m () -> (Maybe (GroupName ModeKind) -> m ()) -> m ()
dieSer :: MonadServerAtomic m => ActorId -> Actor -> m ()

-- | Save game on server and all clients.
writeSaveAll :: MonadServerAtomic m => Bool -> m ()
gameExit :: (MonadServerAtomic m, MonadServerComm m) => m ()


-- | The main loop of the server, processing human and computer player
--   moves turn by turn.
module Game.LambdaHack.Server.LoopM

-- | Start a game session, including the clients, and then loop,
--   communicating with the clients.
--   
--   The loop is started in server state that is empty, see
--   <a>emptyStateServer</a>.
loopSer :: (MonadServerAtomic m, MonadServerComm m) => ServerOptions -> (Bool -> FactionId -> ChanServer -> IO ()) -> m ()
factionArena :: MonadStateRead m => Faction -> m (Maybe LevelId)
arenasForLoop :: MonadStateRead m => m [LevelId]
handleFidUpd :: forall m. (MonadServerAtomic m, MonadServerComm m) => (FactionId -> m ()) -> FactionId -> Faction -> m ()

-- | Handle a clip (the smallest fraction of a game turn for which a frame
--   may potentially be generated). Run the leader and other actors moves.
--   Eventually advance the time and repeat.
loopUpd :: forall m. (MonadServerAtomic m, MonadServerComm m) => m () -> m ()

-- | Handle the end of every clip. Do whatever has to be done every fixed
--   number of clips, e.g., monster generation. Advance time. Perform
--   periodic saves, if applicable.
--   
--   This is never run if UI requested save or exit or restart and it's
--   correct, because we know nobody moved and no time was or needs to be
--   advanced and arenas are not changed. After game was saved and exited,
--   on game resume the first clip is performed with empty arenas, so arena
--   time is not updated and nobody moves, nor anything happens, but arenas
--   are here correctly updated.
endClip :: forall m. MonadServerAtomic m => (FactionId -> m ()) -> m ()

-- | Check if the given actor is dominated and update his calm.
manageCalmAndDomination :: MonadServerAtomic m => ActorId -> Actor -> m ()

-- | Trigger periodic items for all actors on the given level.
applyPeriodicLevel :: MonadServerAtomic m => m ()
handleTrajectories :: MonadServerAtomic m => LevelId -> FactionId -> m ()
hTrajectories :: MonadServerAtomic m => ActorId -> m ()

-- | Manage trajectory of a projectile.
--   
--   Colliding with a wall or actor doesn't take time, because the
--   projectile does not move (the move is blocked). Not advancing time
--   forces dead projectiles to be destroyed ASAP. Otherwise, with some
--   timings, it can stay on the game map dead, blocking path of
--   human-controlled actors and alarming the hapless human.
advanceTrajectory :: MonadServerAtomic m => ActorId -> Actor -> m ()
handleActors :: (MonadServerAtomic m, MonadServerComm m) => LevelId -> FactionId -> m Bool
hActors :: forall m. (MonadServerAtomic m, MonadServerComm m) => [ActorId] -> m Bool
restartGame :: MonadServerAtomic m => m () -> m () -> Maybe (GroupName ModeKind) -> m ()


-- | Parsing of commandline arguments.
module Game.LambdaHack.Server.Commandline

-- | Parser for server options from commandline arguments.
serverOptionsPI :: ParserInfo ServerOptions
serverOptionsP :: Parser ServerOptions


-- | Semantics of requests that are sent by clients to the server, in terms
--   of game state changes and responses to be sent to the clients.
--   
--   See
--   <a>https://github.com/LambdaHack/LambdaHack/wiki/Client-server-architecture</a>.
module Game.LambdaHack.Server

-- | Start a game session, including the clients, and then loop,
--   communicating with the clients.
--   
--   The loop is started in server state that is empty, see
--   <a>emptyStateServer</a>.
loopSer :: (MonadServerAtomic m, MonadServerComm m) => ServerOptions -> (Bool -> FactionId -> ChanServer -> IO ()) -> m ()

-- | Connection channel between the server and a single client.
data ChanServer
ChanServer :: CliSerQueue Response -> CliSerQueue RequestAI -> Maybe (CliSerQueue RequestUI) -> ChanServer
[responseS] :: ChanServer -> CliSerQueue Response
[requestAIS] :: ChanServer -> CliSerQueue RequestAI
[requestUIS] :: ChanServer -> Maybe (CliSerQueue RequestUI)

-- | Parser for server options from commandline arguments.
serverOptionsPI :: ParserInfo ServerOptions

-- | Options that affect the behaviour of the server (including game
--   rules).
data ServerOptions
ServerOptions :: Bool -> Bool -> Bool -> Bool -> Bool -> Bool -> Maybe (GroupName ModeKind) -> Bool -> Bool -> Maybe StdGen -> Maybe StdGen -> Bool -> Challenge -> Bool -> String -> Bool -> Bool -> ClientOptions -> ServerOptions
[sknowMap] :: ServerOptions -> Bool
[sknowEvents] :: ServerOptions -> Bool
[sknowItems] :: ServerOptions -> Bool
[sniff] :: ServerOptions -> Bool
[sallClear] :: ServerOptions -> Bool
[sboostRandomItem] :: ServerOptions -> Bool
[sgameMode] :: ServerOptions -> Maybe (GroupName ModeKind)
[sautomateAll] :: ServerOptions -> Bool
[skeepAutomated] :: ServerOptions -> Bool
[sdungeonRng] :: ServerOptions -> Maybe StdGen
[smainRng] :: ServerOptions -> Maybe StdGen
[snewGameSer] :: ServerOptions -> Bool
[scurChalSer] :: ServerOptions -> Challenge
[sdumpInitRngs] :: ServerOptions -> Bool
[ssavePrefixSer] :: ServerOptions -> String
[sdbgMsgSer] :: ServerOptions -> Bool
[sshowItemSamples] :: ServerOptions -> Bool
[sclientOptions] :: ServerOptions -> ClientOptions


-- | The implementation of our custom game client monads. Just as any other
--   component of the library, this implementation can be substituted.
module Implementation.MonadClientImplementation

-- | Run the main client loop, with the given arguments and empty initial
--   states, in the <tt>IO</tt> monad.
executorCli :: CCUI -> UIOptions -> ClientOptions -> COps -> Bool -> FactionId -> ChanServer -> IO ()
data CliState
CliState :: State -> StateClient -> Maybe SessionUI -> ChanServer -> ChanSave (StateClient, Maybe SessionUI) -> CliState

-- | current global state
[cliState] :: CliState -> State

-- | current client state
[cliClient] :: CliState -> StateClient

-- | UI state, empty for AI clients
[cliSession] :: CliState -> Maybe SessionUI

-- | this client connection information
[cliDict] :: CliState -> ChanServer

-- | connection to the save thread
[cliToSave] :: CliState -> ChanSave (StateClient, Maybe SessionUI)

-- | Client state transformation monad.
newtype CliImplementation a
CliImplementation :: StateT CliState IO a -> CliImplementation a
[runCliImplementation] :: CliImplementation a -> StateT CliState IO a
instance GHC.Base.Applicative Implementation.MonadClientImplementation.CliImplementation
instance GHC.Base.Functor Implementation.MonadClientImplementation.CliImplementation
instance GHC.Base.Monad Implementation.MonadClientImplementation.CliImplementation
instance Game.LambdaHack.Common.MonadStateRead.MonadStateRead Implementation.MonadClientImplementation.CliImplementation
instance Game.LambdaHack.Atomic.MonadStateWrite.MonadStateWrite Implementation.MonadClientImplementation.CliImplementation
instance Game.LambdaHack.Client.MonadClient.MonadClientRead Implementation.MonadClientImplementation.CliImplementation
instance Game.LambdaHack.Client.MonadClient.MonadClient Implementation.MonadClientImplementation.CliImplementation
instance Game.LambdaHack.Client.HandleAtomicM.MonadClientSetup Implementation.MonadClientImplementation.CliImplementation
instance Game.LambdaHack.Client.UI.MonadClientUI.MonadClientUI Implementation.MonadClientImplementation.CliImplementation
instance Game.LambdaHack.Client.LoopM.MonadClientReadResponse Implementation.MonadClientImplementation.CliImplementation
instance Game.LambdaHack.Client.HandleResponseM.MonadClientWriteRequest Implementation.MonadClientImplementation.CliImplementation
instance Game.LambdaHack.Client.HandleResponseM.MonadClientAtomic Implementation.MonadClientImplementation.CliImplementation


-- | The implementation of our custom game server monads. Just as any other
--   component of the library, this implementation can be substituted.
module Implementation.MonadServerImplementation

-- | Run the main server loop, with the given arguments and empty initial
--   states, in the <tt>IO</tt> monad.
executorSer :: COps -> CCUI -> ServerOptions -> UIOptions -> IO ()
data SerState
SerState :: State -> StateServer -> ConnServerDict -> ChanSave (State, StateServer) -> SerState

-- | current global state
[serState] :: SerState -> State

-- | current server state
[serServer] :: SerState -> StateServer

-- | client-server connection information
[serDict] :: SerState -> ConnServerDict

-- | connection to the save thread
[serToSave] :: SerState -> ChanSave (State, StateServer)

-- | Server state transformation monad.
newtype SerImplementation a
SerImplementation :: StateT SerState IO a -> SerImplementation a
[runSerImplementation] :: SerImplementation a -> StateT SerState IO a
instance GHC.Base.Applicative Implementation.MonadServerImplementation.SerImplementation
instance GHC.Base.Functor Implementation.MonadServerImplementation.SerImplementation
instance GHC.Base.Monad Implementation.MonadServerImplementation.SerImplementation
instance Game.LambdaHack.Common.MonadStateRead.MonadStateRead Implementation.MonadServerImplementation.SerImplementation
instance Game.LambdaHack.Atomic.MonadStateWrite.MonadStateWrite Implementation.MonadServerImplementation.SerImplementation
instance Game.LambdaHack.Server.MonadServer.MonadServer Implementation.MonadServerImplementation.SerImplementation
instance Game.LambdaHack.Server.ProtocolM.MonadServerComm Implementation.MonadServerImplementation.SerImplementation
instance Game.LambdaHack.Server.MonadServer.MonadServerAtomic Implementation.MonadServerImplementation.SerImplementation


-- | Game rules and assorted game setup data.
module Content.RuleKind
standardRules :: RuleContent


-- | Item definitions.
module Content.ItemKind
content :: [ItemKind]
items :: [ItemKind]
otherItemContent :: [ItemKind]


-- | Here the knot of engine code pieces, frontend and the game-specific
--   content definitions is tied, resulting in an executable game.
module TieKnot

-- | Tie the LambdaHack engine client, server and frontend code with the
--   game-specific content definitions, and run the game.
--   
--   The custom monad types to be used are determined by the
--   <tt>executorSer</tt> call, which in turn calls <tt>executorCli</tt>.
--   If other functions are used in their place- the types are different
--   and so the whole pattern of computation differs. Which of the
--   frontends is run inside the UI client depends on the flags supplied
--   when compiling the engine library. Similarly for the choice of native
--   vs JS builds.
tieKnotForAsync :: ServerOptions -> IO ()

-- | Runs tieKnotForAsync in an async and applies the main thread
--   workaround.
tieKnot :: ServerOptions -> IO ()
