module Exercise08 where import Data.Bits import Data.List import System.Random (Random, mkStdGen, randomIO, randoms) -- Player is either 1 or -1 type Player = Int -- A field is just an Int value where the absolute gives the number of pieces on the field -- and the sign corresponds to the player -- e.g. -3 would mean there are three blobs in this field of player -1 type Field = Int type Row = [Field] type Column = [Field] -- boards are rectangles represented as a list of rows type Board = [Row] -- A position on the board is represented as (row, column) -- (0,0) is the top left corner, coordinate values increase towards the bottom right type Pos = (Int, Int) -- A size represented as (height,width) type Size = (Int, Int) -- A strategy takes the player who's move it is, optionally takes a list of double values -- to allow for probabilistic strategies, takes the current board and gives back the position -- of the move the player should do type Strategy = [Double] -> Player -> Board -> Pos -- A stateful strategy can additionally pass some object between invocations type StatefulStrategyFunc a = a -> [Double] -> Player -> Board -> (Pos, a) -- first value is the state object to pass to the first invocation of each game type StatefulStrategy a = (a, StatefulStrategyFunc a) defaultSize :: (Int, Int) defaultSize = (9, 6) -- Some useful helper functions row :: Board -> Int -> Row row = (!!) column :: Board -> Int -> Column column = row . transpose width :: Board -> Int width (x : _) = length x width _ = 0 height :: Board -> Int height = length size :: Board -> Size size b = (height b, width b) getCell :: Pos -> Board -> Field getCell (y, x) b = b !! y !! x -- pretty print a single cell showCell :: Field -> String showCell c = "- +" !! succ (signum c) : show (abs c) -- pretty print the given board showBoard :: Board -> String showBoard = unlines . map (unwords . map showCell) -- print a board to the console printBoard :: Board -> IO () printBoard = putStr . showBoard -- check if a position is one a board of the given size isValidPos :: Size -> Pos -> Bool isValidPos (r, c) (y, x) = y >= 0 && y < r && x >= 0 && x < c {- x.1 -} -- Check if the given player can put an orb on the given position canPlaceOrb :: Player -> Pos -> Board -> Bool canPlaceOrb p (y, x) b | p > 0 = row b y !! x >= 0 | p < 0 = row b y !! x <= 0 -- Check if the given player has won the game, -- you can assume that the opponent has made at least one move before hasWon :: Player -> Board -> Bool hasWon p b | p > 0 = all (all (>= 0)) b | p < 0 = all (all (<= 0)) b -- the list of neighbors of a cell neighbors :: Size -> Pos -> [Pos] neighbors (r, c) (y, x) = pos where pos = if y /= r -1 then (y + 1, x) : pos2 else pos2 pos2 = if y /= 0 then (y -1, x) : pos3 else pos3 pos3 = if x /= c -1 then (y, x + 1) : pos4 else pos4 pos4 = [(y, x - 1) | x /= 0] -- update a single position on the board -- f: function that modifies the number of orbs in the cell -- p: player to whom the updated cell should belong updatePos :: (Int -> Int) -> Player -> Pos -> Board -> Board updatePos f p (y, x) b = newb where newb = take y b ++ [newrow] ++ drop (y + 1) b newrow = take x (row b y) ++ [neworb] ++ drop (x + 1) (row b y) neworb | p > 0 = if getCell (y, x) b > 0 then f (getCell (y, x) b) else f $abs (getCell (y, x) b) | p < 0 = if getCell (y, x) b > 0 then negate (f (getCell (y, x) b)) else negate (f $abs (getCell (y, x) b)) {- x.2 -} -- place an orb for the given player in the given cell putOrb :: Player -> Pos -> Board -> Board putOrb p (y, x) b = checkoverflow where update = updatePos (1 +) p (y, x) b neigh = neighbors (size b) (y, x) deleted = take y update ++ [newrow] ++ drop (y + 1) update newrow = take x (row update y) ++ [0] ++ drop (x + 1) (row update y) loop bo [] = bo loop bo (x : xs) = if hasWon p bo then bo else loop (putOrb p x bo) xs checkoverflow = if abs (getCell (y, x) update) == length neigh && not (hasWon p update) then loop deleted neigh else update {- x.3 -} {-WETT-} -- Your strategy strategy :: Strategy strategy rando p b = if not (null placed) then far else putcorner where far = if countMine p (putOrb p faraway b) all > myorbsum + 1 then faraway else putcorner putcorner = if not (null corners) then head corners else later later = if not (null attacklater) && not (null $head attacklater) then head $ head attacklater else sideTwo sideTwo = if not (null $sides b p) then head (sides b p) else head randomy all = [(x, y) | x <- [0 .. height b -1], y <- [0 .. width b -1]] placed = filter (isMine p b) all oppo = filter (isMine (negate p) b) all myorbsum = sum $ map (\x -> abs (getCell x b)) placed faraway = foldl1 (\x y -> if countMine p (putOrb p x b) all > countMine p (putOrb p y b) all then x else y) placed corners = filter (\x -> getCell x b == 0 && oppoCanAttack x b p) ((height b -1, width b -1) : (0, 0) : (height b -1, 0) : [(0, width b -1)]) attacklater = map (\x -> placeBeside x b p) oppo randomy = filter (\x -> canPlaceOrb p x b) all countMine :: Int -> Board -> [Pos] -> Int countMine p b all = sum $ map (\x -> abs (getCell x b)) (filter (isMine p b) all) oppoCanAttack :: Pos -> Board -> Int -> Bool oppoCanAttack pos b p = null $filter (\a -> not (canPlaceOrb p a b) && length (neighbors (size b) a) -1 == abs (getCell a b)) (neighbors (size b) pos) sides :: Board -> Int -> [Pos] sides b p = filter (\x -> canPlaceOrb p x b && oppoCanAttack x b p && abs (getCell x b) < length (neighbors (size b) x) -1) blanks where blanks = concat [(x, y) : [(w, z)] | x <- [0, 2 .. height b -1], w <- [1, 3 .. height b -1], z <- [1, 3 .. width b -1], y <- [0, 2 .. width b -1]] placeBeside :: Pos -> Board -> Int -> [Pos] placeBeside pos b p = filter (\a -> length (neighbors (size b) a) - abs (getCell a b) <= length (neighbors (size b) pos) - abs (getCell pos b) && oppoattack (neighbors (size b) a)) neigh where neigh = filter (\x -> canPlaceOrb p x b) (neighbors (size b) pos) oppoattack n = null $filter (\a -> not (canPlaceOrb p a b) && length (neighbors (size b) a) - abs (getCell a b) < length (neighbors (size b) pos) - abs (getCell pos b)) n neighborOppo :: Pos -> Board -> Int -> Bool neighborOppo pos b p | p > 0 = any (\a -> getCell a b < 0) (neighbors (size b) pos) | p < 0 = any (\a -> getCell a b > 0) (neighbors (size b) pos) isMine :: Int -> Board -> Pos -> Bool isMine p b pos | p > 0 && getCell pos b > 0 = True | p < 0 && getCell pos b < 0 = True | otherwise = False -- adds state to a strategy that doesn't use it wrapStrategy :: Strategy -> StatefulStrategy Int wrapStrategy strat = (0, \s r p b -> (strat r p b, succ s)) -- the actual strategy submissions -- if you want to use state modify this instead of strategy -- additionally you may change the Int in this type declaration to any type that is usefully for your strategy strategyState :: StatefulStrategy Int strategyState = wrapStrategy strategy {-TTEW-} -- Simulate a game between two strategies on a board of the given size and -- returns the state of the board before each move together with the player that won the game play :: [Int] -> Size -> StatefulStrategy a -> StatefulStrategy b -> [(Board, Pos)] play rss (r, c) (isa, sa) (isb, sb) = go rss isa sa isb sb 1 0 (replicate r (replicate c 0)) where -- type signature is necessary, inferred type is wrong! go :: [Int] -> a -> StatefulStrategyFunc a -> b -> StatefulStrategyFunc b -> Player -> Int -> Board -> [(Board, Pos)] go (rs : rss) stc sc stn sn p n b | won = [] | valid = (b, m) : go rss stn sn st' sc (- p) (succ n) (putOrb p m b) | otherwise = [] where won = n > 1 && hasWon (- p) b (m, st') = sc stc (mkRandoms rs) p b valid = isValidPos (size b) m && canPlaceOrb p m b -- Play a game and print it to the console playAndPrint :: Size -> StatefulStrategy a -> StatefulStrategy b -> IO () playAndPrint size sa sb = do seed <- randomIO -- let seed = 42 let moves = play (mkRandoms seed) size sa sb putStr $ unlines (zipWith showState moves $ cycle ['+', '-']) ++ "\n" ++ (case length moves `mod` 2 of 1 -> "Winner: +"; 0 -> "Winner: -") ++ "\n" ++ "View at https://vmnipkow16.in.tum.de/christmas2020/embed.html#i" ++ base64 (1 : t size ++ concatMap (t . snd) moves) ++ "\n" where showState (b, pos) p = showBoard b ++ p : " places at " ++ show pos ++ "\n" t (a, b) = [a, b] mkRandoms :: Random a => Int -> [a] mkRandoms = randoms . mkStdGen base64 :: [Int] -> String base64 xs = case xs of [] -> "" [a] -> f1 a : f2 a 0 : "==" [a, b] -> f1 a : f2 a b : f3 b 0 : "=" a : b : c : d -> f1 a : f2 a b : f3 b c : f4 c : base64 d where alphabet = (!!) "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" f1 a = alphabet $ shiftR a 2 f2 a b = alphabet $ shiftL (a .&. 3) 4 .|. shiftR b 4 f3 b c = alphabet $ shiftL (b .&. 15) 2 .|. shiftR c 6 f4 c = alphabet $ c .&. 63