-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgamestate.py
333 lines (304 loc) · 13.4 KB
/
gamestate.py
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
import collections
import random
from actions import *
import util
import copy
class GameState:
def __init__( self, prevState = None ):
"""
Generates a new state by copying information from its predecessor.
"""
if prevState is None:
self.players = []
self.numPlayers = 0
self.playerTurn = 0
self.currentAction = None
self.playerExchange = None
self.playerChallenge = None
self.playerBlock = None
self.playerTarget = None
self.punishedPlayers = []
self.deck = []
self.inactiveInfluences = collections.Counter()
self.pastActions = [] #list of counters, one for each player
self.nextActionType = None # can be 'action', 'block', 'challenge', 'discard'
self.challengeSuccess = None
self.blockPhaseOccured = False
self.actionStack = []
self.playersCanAct = []
else:
self.players = list(prevState.players)
self.numPlayers = prevState.numPlayers
self.playerTurn = prevState.playerTurn
self.currentAction = prevState.currentAction
self.playerExchange = prevState.playerExchange
self.playerChallenge = prevState.playerChallenge
self.playerBlock = prevState.playerBlock
self.playerTarget = prevState.playerTarget
self.punishedPlayers = list(prevState.punishedPlayers)
self.deck = list(prevState.deck)
self.inactiveInfluences = collections.Counter(prevState.inactiveInfluences)
self.pastActions = list(prevState.pastActions)
self.nextActionType = prevState.nextActionType
self.challengeSuccess = prevState.challengeSuccess
self.actionStack = list(prevState.actionStack)
self.playersCanAct = list(prevState.playersCanAct)
self.blockPhaseOccured = prevState.blockPhaseOccured
def __eq__( self, other ):
"""
Allows two states to be compared.
"""
# def __hash__( self ):
# """
# Allows states to be keys of dictionaries.
# """
def __str__( self ):
return """
Players: %r
Number Players: %r
Player Turn: %r
Current Action: %r
Next Action Type: %r
Player Block: %r
Player Challenge: %r
Challenge Success: %r
Player Target: %r
Player Exchange: %r
Punished Players: %r
Past Actions: %r
Deck: %r
Inactive Influences: %r
""" % ([str(player) for player in self.players], self.numPlayers, self.playerTurn, self.currentAction, \
self.nextActionType, self.playerBlock, self.playerChallenge, self.challengeSuccess, self.playerTarget, \
self.playerExchange, self.punishedPlayers, self.pastActions, self.deck, self.inactiveInfluences)
def detailedStr(self):
out = str(self)
out += """
Challenge Success: %r
Block Phase Occured: %r
Players:
""" % (self.challengeSuccess, self.blockPhaseOccured)
for p in self.players:
out += '\n\t%s\n\t\tInactive Influences: %s\n\t\tRevealed Influences: %s\n\t\tPossible Influences: %s' % (p, p.inactiveInfluences, p.revealedInfluences, p.possibleInfluences)
out += '\n\tAction Stack:'
for a in self.actionStack:
out += '\n\t\t%s' % a
out += '\n\tPlayers that can act: %r' % self.playersCanAct
out += '\n\tPossible actions for each player:'
for p in range(len(self.players)):
astring = ''
for a in self.getAllActions(p):
astring += '\n\t\t\t%s' % a
out += '\n\t\t%d: %s' % (p, astring)
return out
def initialize( self, numPlayers=4 ):
"""
Creates an initial game state given a number of players.
"""
self.numPlayers = numPlayers
self.deck = ['ambassador', 'assassin', 'captain', 'contessa', 'duke'] * 3
random.shuffle(self.deck)
for i in range(numPlayers):
nextInfluences = self.deck[0:2]
self.deck = self.deck[2:]
s = PlayerState(i, nextInfluences) #initalizes player state with index number and two cards to have
self.players.append(s)
self.playerTurn = random.randint(0, self.numPlayers - 1)
self.playersCanAct.append(self.playerTurn)
self.nextActionType = 'action'
def getLegalActions( self, playerIndex=0 ):
playerState = self.players[playerIndex]
if len(playerState.influences) == 0:
return [None]
if self.nextActionType == 'action':
indexList = [x.playerIndex for x in self.players if len(x.influences) > 0 and x.playerIndex != playerIndex]
if self.playerTurn != playerIndex:
return []
result = ['income', 'foreign aid']
if playerState.coins >= 10:
return util.ActionGenerator(['coup'], playerIndex=playerIndex, otherPlayers=indexList)
if playerState.coins >= 7:
result += ['coup']
#now, we look at Influences
for influence in playerState.influences:
if influence in util.influenceToAction:
if influence != 'assassin' or playerState.coins >= 3:
result.append(util.influenceToAction[influence])
return util.ActionGenerator(result, playerIndex=playerIndex, otherPlayers=indexList)
elif self.nextActionType == 'block':
#if the action is steal or assassination, then only the target can block
#if action is foreign aid, anyone can block
if self.playerTurn == playerIndex:
return [None]
if self.currentAction == 'foreign aid' or (self.currentAction in ['steal', 'assassinate'] and playerIndex == self.playerTarget):
for influence in playerState.influences:
if self.currentAction in util.blockToInfluence and influence in util.blockToInfluence[self.currentAction]:
return util.ActionGenerator(['block'], playerIndex=playerIndex) + [None]
return [None]
elif self.nextActionType == 'challenge':
if self.currentAction not in util.basicActions and ((self.playerBlock is not None and playerIndex != self.playerBlock) \
or (self.playerBlock is None and playerIndex != self.playerTurn)):
return util.ActionGenerator(['challenge'], playerIndex=playerIndex) + [None]
else:
return [None]
elif self.nextActionType == 'discard':
return util.ActionGenerator(['discard'], playerIndex=playerIndex, numInfluences=len(self.players[playerIndex].influences))
def getBluffActions( self, playerIndex=0 ):
playerState = self.players[playerIndex]
if len(playerState.influences) == 0:
return []
if self.nextActionType == 'action':
indexList = [x.playerIndex for x in self.players if len(x.influences) > 0 and x.playerIndex != playerIndex]
if self.playerTurn != playerIndex:
return []
if playerState.coins >= 10:
return []
result = []
for influence in util.influenceList:
if influence not in playerState.influences:
if influence in util.influenceToAction:
if influence != 'assassin' or playerState.coins >= 3:
result.append(util.influenceToAction[influence])
return util.ActionGenerator(result, playerIndex=playerIndex, otherPlayers=indexList)
elif self.nextActionType == 'block':
if self.playerTurn == playerIndex:
return []
if self.currentAction == 'foreign aid' or (self.currentAction in ['steal', 'assassinate'] and playerIndex == self.playerTarget):
canBlock = False
for influence in util.influenceList:
if influence in util.blockToInfluence[self.currentAction] and influence in playerState.influences:
canBlock = True
if canBlock:
return []
else:
return util.ActionGenerator(['block'], playerIndex=playerIndex)
else:
return []
elif self.nextActionType == 'challenge':
return []
elif self.nextActionType == 'discard':
return []
def getAllActions(self, playerIndex): # be less hacky
return self.getLegalActions(playerIndex) + self.getBluffActions(playerIndex)
def continueTurn(self):
nextState = self.deepCopy()
#print 'nextState:', nextState
if self.nextActionType == 'discard':
nextState = nextState.resolveActions()
nextState.punishedPlayers = [x for x in nextState.punishedPlayers if len(nextState.players[x].influences)>0]
nextState.playersCanAct = list(set(nextState.punishedPlayers))
if len(nextState.punishedPlayers) == 0:
nextState = nextState.finishTurn()
elif self.nextActionType == 'challenge':
if self.playerChallenge is not None:
nextState = nextState.resolveTopAction()
if not self.blockPhaseOccured and not self.challengeSuccess:
nextState.blockPhaseOccured = True
nextState.nextActionType = 'block'
nextState.playersCanAct = [p for p in range(nextState.numPlayers) if len(nextState.players[p].influences) != 0 and p != nextState.playerTurn]
# if nextState.currentAction not in util.blocks else []
else:
nextState = nextState.resolveActions()
nextState.nextActionType = 'discard'
nextState.playersCanAct = list(set(nextState.punishedPlayers))
elif self.nextActionType == 'block' and self.blockPhaseOccured == True:
nextState = nextState.resolveActions()
nextState.nextActionType = 'discard'
nextState.playersCanAct = list(set(nextState.punishedPlayers))
elif self.nextActionType == 'block' or self.nextActionType == 'action':
nextState.nextActionType = 'challenge'
nextState.playersCanAct = [p for p in range(nextState.numPlayers) if len(nextState.players[p].influences) != 0 and p != nextState.playerTurn]
# if nextState.currentAction not in util.basicActions else []
while len(nextState.playersCanAct) == 0:
nextState = nextState.continueTurn()
return nextState
def resolveActions(self):
nextState = self.deepCopy()
while len(nextState.actionStack) > 0:
nextAction = nextState.actionStack.pop()
nextState = nextAction.resolve(nextState)
return nextState
def resolveTopAction(self):
nextState = self.deepCopy()
nextAction = nextState.actionStack.pop()
nextState = nextAction.resolve(nextState)
return nextState
def finishTurn(self):
nextState = self.deepCopy()
nextState.nextActionType = 'action'
nextState.currentAction = None
nextState.playerChallenge = None
nextState.playerBlock = None
nextState.playerTarget = None
nextState.playerExchange = None
nextState.punishedPlayers = []
nextState.challengeSuccess = None
nextState.blockPhaseOccured = False
while True:
nextState.playerTurn = (nextState.playerTurn + 1) % nextState.numPlayers
if len(nextState.players[nextState.playerTurn].influences) > 0:
break
nextState.playersCanAct = [nextState.playerTurn]
return nextState
# Returns:
# Dictionary{ Player -> ([list of influences], boolean hasInfluence}
# nextState can follow self if:
# if hasInfluence: Player must have at least one influence in list
# if not hasInfluence: Player must not have any influences in list
def requiredInfluencesForState(self, nextState):
requiredInfluences = {}
if self.nextActionType == 'action':
requiredInfluences[self.playerTurn] = (util.actionToInfluence[nextState.currentAction], True) if nextState.currentAction in util.actionToInfluence else ([], True)
elif self.nextActionType == 'block' and nextState.playerBlock is not None:
requiredInfluences[nextState.playerBlock] = (util.blockToInfluence[self.currentAction], True) if self.currentAction in util.blockToInfluence else ([], True)
elif self.nextActionType == 'challenge' and nextState.playerChallenge is not None:
if self.playerBlock == None:
requiredInfluences[self.playerTurn] = (util.actionToInfluence[self.currentAction], not nextState.challengeSuccess) if self.currentAction in util.actionToInfluence else ([], False)
else:
requiredInfluences[self.playerBlock] = (util.blockToInfluence[self.currentAction], not nextState.challengeSuccess) if self.currentAction in util.blockToInfluence else ([], False)
return requiredInfluences
def isOver( self ):
activePlayers = [1 for player in self.players if len(player.influences) > 0]
return sum(activePlayers) <= 1
def printState(self):
print self
def deepCopy( self ):
# return GameState(self)
return copy.deepcopy(self)
def generateSuccessorStates(self, action, playerIndex):
if action is None:
newState = self.deepCopy()
newState = newState.continueTurn()
return [newState]
if self.nextActionType == 'challenge':
successState = self.deepCopy()
successState = action.choose(successState)
successState.actionStack[-1].challengeSuccess = True
successState = successState.continueTurn()
failState = self.deepCopy()
failState = action.choose(successState)
failState.actionStack[-1].challengeSuccess = False
failState = failState.continueTurn()
return [successState, failState]
else:
# other RNG..... exchange???
newState = self.deepCopy()
newState = action.choose(newState)
newState = newState.continueTurn()
return [newState]
class PlayerState:
"""
PlayerStates hold the state of a player (index, Influences etc).
"""
def __init__( self, index, influences ):
self.playerIndex = index
self.influences = influences
self.coins = 2
self.inactiveInfluences = []
self.revealedInfluences = []
self.possibleInfluences = collections.Counter({influence: 1 for influence in util.influenceList})
def __str__( self ):
return str(self.playerIndex) + ': ' + str(self.influences) + ' (%d coins)' % self.coins
# def __eq__( self, other ):
# def __hash__(self):
# def copy( self ):