-
Notifications
You must be signed in to change notification settings - Fork 2
/
Game.hs
308 lines (289 loc) · 14.9 KB
/
Game.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE OverloadedStrings #-}
module Startups.Game where
import Startups.GameTypes
import Startups.Utils
import Startups.Base
import Startups.Cards
import Startups.CardList
import Startups.PrettyPrint
import Control.Lens
import Control.Monad
import Control.Applicative
import Control.Monad.Error (throwError)
import System.Random (randomR)
import qualified Data.Map as M
import qualified Data.MultiSet as MS
import Data.Monoid
import Data.List.Split (chunksOf)
import Data.Maybe (fromMaybe)
import Data.Traversable (for)
-- | This is the initialization function. The state should be initialized
-- with the correct list of players, but the player state or discard pile
-- can be arbitrary, as they will be initialized here.
--
-- It ensures some invariants, such as :
-- * all players have the first stage of their company in their card list
-- * all players have a valid left and right neighbor
initGame :: GameStateOnly m => m ()
initGame = do
discardpile .= []
pidlst <- playerList >>= shuffle
companies <- shuffle [Facebook .. Microsoft]
let leftNeighbors = tail (concat $ repeat pidlst)
rightNeighbors = last pidlst : concat (repeat pidlst)
playerInformation = getZipList ((,,,) <$> ZipList pidlst
<*> ZipList leftNeighbors
<*> ZipList rightNeighbors
<*> ZipList companies)
forM_ playerInformation $ \(pid, ln, rn, company) -> do
side <- (\x -> if x == 0 then A else B) <$> getRandom 2
let profile = CompanyProfile company side
playermap . ix pid %= (pCompany .~ profile)
. (pCards .~ [getResourceCard profile Project])
. (pFunds .~ 3)
. (pNeighborhood .~ (ln, rn))
. (pCompanyStage .~ Project)
-- | A simple wrapper for getting random numbers.
getRandom :: GameStateOnly m => Int -> m Int
getRandom x = do
gen <- use rnd
let (o, gen') = randomR (0,x - 1) gen
rnd .= gen'
return o
-- | A helper function that retrieves the player list
playerList :: GameStateOnly m => m [PlayerId]
playerList = map fst . itoList <$> use playermap
-- | This shuffles a list of values, using the randomRoll function.
shuffle :: (GameStateOnly m, Eq a) => [a] -> m [a]
shuffle [] = return []
shuffle xs = do
n <- getRandom (length xs)
let x = xs !! n
xs' = filter (/= x) xs
rest <- shuffle xs'
return (x : rest)
-- | Shuffle the cards corresponding to an age, and deal them in hands of
-- 7 cards.
dealCards :: GameStateOnly m => Age -> m (M.Map PlayerId [Card])
dealCards age = do
playerlst <- playerList
let agecards = filter (\c -> c ^? cAge == Just age && correctPlayerCount c) allcards
correctPlayerCount = (== Just True) . preview (cMinplayers . to (<= fromIntegral playerCount))
communityCount = playerCount + 2
playerCount = length playerlst
com <- if age == Age3
then take communityCount <$> shuffle communities
else return []
M.fromList . zip playerlst . chunksOf 7 <$> shuffle (com <> agecards)
-- | A helper for retrieving the player state.
getPlayerState :: NonInteractive m => PlayerId -> m PlayerState
getPlayerState pid = preuse (playermap . ix pid) >>= \m -> case m of
Nothing -> throwError ("Could not retrieve" <+> showPlayerId pid <+> "state")
Just x -> return x
-- | This transforms an exchange with a pair of neighbors with a list of
-- collected resources, and money to distribute with these neighbors.
--
-- The money is not immediately added to the neighbor to prevent a race
-- condition where a player could try an exchange that is more expensive
-- than what he owns, hoping some other player with exchange something with
-- him.
resolveExchange :: NonInteractive m => PlayerId -> Exchange -> m (MS.MultiSet Resource, AddMap PlayerId Funding)
resolveExchange pid exch = mconcat . M.elems <$> itraverse resolveExchange' exch
where
resolveExchange' neigh reslist = do
stt <- use playermap
let cost = getSum $ reslist ^. folded . to (Sum . getExchangeCost pid neigh stt)
playermoney = fromMaybe 0 (stt ^? ix pid . pFunds)
neighname = stt ^. ix pid . neighbor neigh
neigresources = stt ^. ix neighname . to (availableResources Exchange)
when (cost > playermoney) (throwError (showPlayerId pid <+> "tried to perform an exchange without enough funding"))
unless (any (reslist `MS.isSubsetOf`) neigresources) (throwError (showPlayerId pid <> "'s neighbor doesn't have enough resources"))
playermap . ix pid . pFunds -= cost
pure (reslist, AddMap (M.singleton neighname cost))
-- | Try to play a card, with some extra resources, provided that the
-- player has enough.
playCard :: NonInteractive m => Age -> PlayerId -> MS.MultiSet Resource -> Card -> m ()
playCard age pid extraResources card = do
-- compute available resources
playerState <- getPlayerState pid
-- remove the chosen card from the card list, and remove the money from
-- the player account
let Cost _ fundCost = card ^. cCost
let -- this tests whether a player has the opportunity capability ready
hasOpportunity = has (cardEffects . _Opportunity . ix age) playerState && has cType card
-- checks if a player has enough resources to play a card
enoughResources = fundCost <= playerState ^. pFunds && isAffordable playerState extraResources card
-- checks if a card is free (owns another card that permits free
-- construction)
isFree = case card ^? cName of
Just n -> freeConstruction playerState ^. contains n
Nothing -> False
-- checks if a player can build a given card. This is in the 'let'
-- part to take advantage of guards.
checkPrice | enoughResources = playermap . ix pid . pFunds -= fundCost
| isFree = return ()
| hasOpportunity = playermap . ix pid . cardEffects . _Opportunity . at age .= Nothing
| otherwise = throwError (showPlayerId pid <+> "tried to play a card he did not have the resources for.")
checkPrice
-- add the card to the player hand
playermap . ix pid . pCards %= (card :)
-- | This resolve the action played by the player, returning the new hand
-- (with the played card removed) and each player funding variation
-- (resulting from exchanges, or cards played). The final element in the
-- tuple is the card that actually got played. It might be :
-- * Nothing, for a card drop
-- * Just a card, for the card that got played
-- * Just a wonder stage
--
-- The reason it is done that way is that card payouts must be computed
-- after all other actions have been performed.
resolveAction :: NonInteractive m => Age -> PlayerId -> ([Card], (PlayerAction, Exchange)) -> m ([Card], AddMap PlayerId Funding, Maybe Card)
resolveAction age pid (hand, (PlayerAction actiontype card, exch)) = do
-- check that the player didn't cheat
unless (card `elem` hand) (throwError (showPlayerId pid <+> "tried to play a card that was not in his hand:" <+> shortCard card))
-- resolve the exchanges
(extraResources, payout) <- resolveExchange pid exch
-- and now process the effect
let newhand = filter (/= card) hand
(cardp, extrapay) <- case actiontype of
Drop -> discardpile %= (card :) >> return (Nothing, 3)
Play -> playCard age pid extraResources card >> return (Just card, 0)
BuildCompany -> do
stt <- getPlayerState pid
let profile = stt ^. pCompany
curstage = stt ^. pCompanyStage
maxstage = getMaxStage profile
nextstage = succ curstage
ccard = getResourceCard profile nextstage
when (curstage == maxstage) (throwError (showPlayerId pid <+> "tried to increase the company stage beyond the limit."))
playermap . ix pid . pCompanyStage %= succ
playCard age pid extraResources ccard
return (Just ccard, 0)
return (newhand, payout <> AddMap (M.singleton pid extrapay), cardp)
-- | Play the end of age poaching.
resolvePoaching :: GameStateOnly m => Age -> m ()
resolvePoaching age = do
plyrs <- use playermap
let poachingScores = fmap (view (cardEffects . _Poaching)) plyrs
ifor_ plyrs $ \pid pstt -> do
let scores = pstt ^.. pNeighborhood . traverse . to (\p -> cmpScore $ view (ix p) poachingScores) . traverse
curScore = poachingScores ^. ix pid
cmpScore s | s > curScore = Just Defeat
| s < curScore = Just $ Victory age
| otherwise = Nothing
playermap . ix pid . pPoachingResults <>= scores
-- | Play a turn :
-- * Ask the player what he'd like to do with the proposed hand.
-- * Remove the card the player chose from the hand, and play it.
--
-- Not that all cards effects are revealed simultaneously, and all cards
-- that let player gain money must be played after all cards are played.
playTurn :: Age -> Turn -> M.Map PlayerId [Card] -> GameMonad (M.Map PlayerId [Card])
playTurn age turn rawcardmap = do
stt <- use id
-- compute the list of players that are playing this turn. Only players
-- with the Efficiency power will be able to play the 7th turn.
let cardmap = if turn == 7
then M.filterWithKey (\pid _ -> has (playerEffects pid . _Efficiency) stt) rawcardmap
else rawcardmap
convertCards crds = case crds ^? _NonEmpty of
Just n -> return n
Nothing -> throwError "We managed to get an empty hand to play, this should never happen"
-- first gather all decisions
decisions <- ifor cardmap $ \pid crds -> (crds,) <$> (convertCards crds >>= playerDecision age turn pid)
actionRecap (fmap snd decisions)
results <- itraverse (resolveAction age) decisions
-- first add the money gained from exchanges
ifor_ (results ^. traverse . _2) $ \pid payout ->
playermap . ix pid . pFunds += payout
-- then add the money gained from cards
ifor results $ \pid (hand, _, card) -> do
void $ for card $ \c -> do
f <- getCardFunding pid c <$> use playermap
playermap . ix pid . pFunds += f
return hand
-- | Rotates the player hands, at the end of each turn.
rotateHands :: Age -> M.Map PlayerId [Card] -> GameMonad (M.Map PlayerId [Card])
rotateHands age cardmap = itraverse rotatePlayer cardmap
where
rotatePlayer pid _ = do
-- get the identifier of the correct neighbor
neighid <- use (playermap . ix pid . neighbor direction)
-- get his hand
return (cardmap ^. ix neighid)
direction = if age == Age2
then NLeft
else NRight
-- | Play a whole age
playAge :: Age -> GameMonad ()
playAge age = do
cards <- dealCards age
let turnPlay crds turn = do
ncrds <- playTurn age turn crds
-- The 7th turn is a hack for the efficiency capacity. In that
-- case, the hands should not be rotated as the rules stipulate
-- that the player can play the two cards he has in hands.
if turn == 6
then return ncrds
else rotateHands age ncrds
remaining <- foldM turnPlay cards [1 .. 7]
discardpile <>= toListOf (traverse . traverse) remaining
-- now for recycling
pm <- itoList <$> use playermap
let recyclers = pm ^.. traverse . filtered (has (_2 . cardEffects . _Recycling)) . _1
forM_ recyclers $ \pid -> do
stt <- use id
case stt ^? discardpile . _NonEmpty of
Just nedp -> do
generalMessage (showPlayerId pid <+> "is going to use his recycle ability.")
card <- askCardSafe age pid nedp "Choose a card to recycle (play for free)"
generalMessage (showPlayerId pid <+> "recycled" <+> shortCard card)
playermap . ix pid . pCards %= (card :)
discardpile %= filter (/= card)
Nothing -> tellPlayer pid (emph "The discard pile was empty, you can't recycle.")
-- resolve the "military" part
resolvePoaching age
-- | Resolves the effect of the CopyCommunity effect that let a player copy
-- an arbitrary community card from one of his neighbors.
checkCopyCommunity :: GameMonad ()
checkCopyCommunity = use playermap >>= itraverse_ checkPlayer
where
checkPlayer pid stt = when (has (cardEffects . _CopyCommunity) stt) $ do
-- get the violet cards from both neighbors
mvioletCards <- forM (stt ^.. pNeighborhood . traverse) $ \nid ->
toListOf (pCards . traverse . filtered (has (cType . _Community))) <$> getPlayerState nid
let violetCards = concat mvioletCards
case violetCards ^? _NonEmpty of
Just nevc -> do
generalMessage (showPlayerId pid <+> "is going to use his community copy ability.")
card <- askCardSafe Age3 pid nevc "Which community would you like to copy ?"
generalMessage (showPlayerId pid <+> "copied" <+> shortCard card)
playermap . ix pid . pCards %= (card:)
Nothing -> tellPlayer pid (emph "There were no violet cards bought by your neighbors. You can't use your copy capacity.")
victoryPoints :: GameStateOnly m => m (M.Map PlayerId (M.Map VictoryType VictoryPoint))
victoryPoints = use playermap >>= itraverse computeScore
where
computeScore pid playerState = do
let poaching = (PoachingVictory, playerState ^. pPoachingResults . traverse . to poachScore)
poachScore Defeat = -1
poachScore (Victory Age1) = 1
poachScore (Victory Age2) = 3
poachScore (Victory Age3) = 5
funding = (FundingVictory, fromIntegral (playerState ^. pFunds `div` 3))
scienceTypes = playerState ^.. cardEffects . _RnD
scienceJokers = length (playerState ^.. cardEffects . _ScientificBreakthrough)
research = (RnDVictory, scienceScore scienceTypes scienceJokers)
stt <- use playermap
let cardPoints = playerState ^.. pCards . traverse . to (\c -> getCardVictory pid c stt) . folded
return $ M.fromListWith (+) $ poaching : funding : research : cardPoints
-- | The main game function, runs a game. The state must be initialized in
-- the same way as the 'initGame' function.
playGame :: GameMonad (M.Map PlayerId (M.Map VictoryType VictoryPoint))
playGame = do
initGame
mapM_ playAge [Age1 .. Age3]
checkCopyCommunity
victoryPoints