-- | Types and functions for manipulating tiles.
module Hs2048.Tile
    ( Tile
    , empty
    , parse
    , rank
    , render
    , score
    ) where

{- |
    Represents a tile on the game board. Can be empty (@Nothing@) or can have a
    value (@Just n@). By convention, a tile's value is always a power of 2.
-}
type Tile = Maybe Int

{- |
    Returns the empty tile.

    >>> empty
    Nothing
-}
empty :: Tile
empty :: Tile
empty = Tile
forall a. Maybe a
Nothing

{- |
    Parses a string as a tile. This is the inverse of 'render'.

    >>> parse "-"
    Nothing
    >>> parse "2"
    Just 2
-}
parse :: String -> Tile
parse :: String -> Tile
parse String
"-" = Tile
forall a. Maybe a
Nothing
parse String
s = Int -> Tile
forall a. a -> Maybe a
Just (String -> Int
forall a. Read a => String -> a
read String
s)

{- |
    Calculates the rank of a tile.

    >>> rank Nothing
    0
    >>> rank (Just 2)
    1
    >>> rank (Just 2048)
    11
-}
rank :: Tile -> Int
rank :: Tile -> Int
rank Tile
Nothing = Int
0
rank (Just Int
n) = Double -> Int
forall b. Integral b => Double -> b
forall a b. (RealFrac a, Integral b) => a -> b
floor (Double -> Double -> Double
forall a. Floating a => a -> a -> a
logBase Double
b Double
n')
  where
    b :: Double
b = Double
2 :: Double
    n' :: Double
n' = Int -> Double
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
n

{- |
    Renders a tile as a string. This is the inverse of 'parse'.

    >>> render Nothing
    "-"
    >>> render (Just 2)
    "2"
-}
render :: Tile -> String
render :: Tile -> String
render Tile
Nothing = String
"-"
render (Just Int
n) = Int -> String
forall a. Show a => a -> String
show Int
n

{- |
    Calculates the score of a tile.

    >>> score Nothing
    0
    >>> score (Just 2)
    0
    >>> score (Just 2048)
    20480
-}
score :: Tile -> Int
score :: Tile -> Int
score Tile
Nothing = Int
0
score t :: Tile
t@(Just Int
n) = Int
n Int -> Int -> Int
forall a. Num a => a -> a -> a
* (Tile -> Int
rank Tile
t Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1)