From: sabadev Date: Sun, 31 Jan 2021 23:58:25 +0000 (-0500) Subject: Added collision detection for enemies. X-Git-Url: http://sabadev.xyz:4321/?a=commitdiff_plain;h=4767087c07390a6a61869e258a48fece10a25eab;p=avoidance.git Added collision detection for enemies. --- diff --git a/src/Game.hs b/src/Game.hs index 8639345..b5d3ce2 100644 --- a/src/Game.hs +++ b/src/Game.hs @@ -2,6 +2,7 @@ module Game (gameSettings, G.getStdGen, G.playGame) where import Data.Bifunctor (bimap) import Data.Char (toUpper) +import Data.Maybe (listToMaybe) import System.Random (Random(..)) import qualified Terminal.Game as G @@ -101,7 +102,7 @@ handleTick state@(State { stateScreen = GameScreen }) = do let stateAfterEnemies = handleEnemies state let oldPlayer = statePlayer state let player = moveCharacter (entityDirection oldPlayer) oldPlayer - let box = handleCollision player (stateBox stateAfterEnemies) + let box = handleCollision player $ handleCollisions (stateEnemy stateAfterEnemies) (stateBox stateAfterEnemies) let newScore = stateScore stateAfterEnemies + 1 if isOutOfBounds box then stateAfterEnemies { stateScreen = TitleScreen } else stateAfterEnemies { statePlayer = player, stateBox = box, stateScore = newScore, stateDifficulty = div newScore 200 + 1 } @@ -202,6 +203,13 @@ willCollide :: Direction -> G.Coords -> G.Coords -> Bool willCollide Stop _ _ = False willCollide _ first second = first == second +handleCollisions :: [Character Enemy] -> Character Box -> Character Box +handleCollisions enemies box = do + let matchingEnemy = listToMaybe $ filter (\enemy -> willCollide (entityDirection enemy) (entityCoords enemy) (entityCoords box)) enemies + case matchingEnemy of + Nothing -> box + Just enemy -> moveCharacter (entityDirection enemy) box + handleCollision :: Character t -> Character Box -> Character Box handleCollision (Character { entityCoords = coords, entityDirection = direction }) box | willCollide direction coords (entityCoords box) = moveCharacter direction box