-
Notifications
You must be signed in to change notification settings - Fork 5
/
battle_engine.py
353 lines (295 loc) · 12.4 KB
/
battle_engine.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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
#!/usr/bin/python
import math
import random
import factories.monster_factory
from commands.use_potion_command import UsePotionCommand
from util.helpers import triangular
from items.unique_items import lowLevelFindableUniques
from items.unique_items import highLevelFindableUniques
from items.unique_items import eliteLevelFindableUniques
import constants
def battle(player, context, monsters = None):
"""
The battle engine of Lord of the Rings.
@param player: The player object.
@param context: Context constant for battle engine. Battle engine
behaves differently
in different contexts. Battles are either random battles
or story-based battles (e.g., boss battles).
@param monsters: An optional parameter used for story-based battles.
Consists of the list of monsters to fight.
@return: True if battle was won; False otherwise.
Differences between random battles and story-based battles:
-Random battles: monster factory called by battle engine and monsters are
supplied by monster factory. Player can run successfully in random battles.
-Story-based battles: monsters must be supplied through the "monsters"
parameter. Player cannot run from battle.
"""
#Battle setup
output = _battleSetup(player, context)
if context == constants.BattleEngineContext.RANDOM:
bonusDifficulty = output[0]
monsters = output[1]
#If no monsters are spawned
if len(monsters) == 0:
return
else:
bonusDifficulty = output
earnings = [0, 0]
#Main battle sequence
while len(monsters) != 0:
#Display enemy monsters
print "Monsters:"
for monster in monsters:
print "\t%s: %s" % (monster.getName(), monster.getDescription())
print ""
#Solicit user input
choice = None
acceptable = ["attack", "use potion", "run", "explode"]
while choice not in acceptable:
choice = raw_input("You may: 'attack', 'use potion', 'run.' ")
#Player attack option
if choice == 'attack':
earnings = _playerAttackPhase(player, monsters, bonusDifficulty, earnings)
#Use potion option
elif choice == "use potion":
_usePotion(player)
#Run option
elif choice == "run":
if context == constants.BattleEngineContext.RANDOM:
if random.random() < constants.BattleEngine.RUN_PROBABILITY_SUCCESS:
print "You ran away succesfully!"
print ""
return True
else:
print "Your path is blocked!"
else:
print "Your path is blocked!"
#Code - eliminates all enemies
elif choice == "explode":
monsters = []
earnings = [0, 0]
#Break between player and monster phases
raw_input("Press enter to continue. ")
print ""
#Monsters attack phase
continueBattle = _monsterAttackPhase(player, monsters)
#Escape sequence given battle loss
if not continueBattle:
print ""
print "Gandalf bails you out."
player.heal(1)
return False
#Battle end sequence - loot received
_endSequence(player, earnings)
return True
def _battleSetup(player, context):
"""
Generates variables for battle engine and prints battle
splash screen.
"""
#For random battles
if context == constants.BattleEngineContext.RANDOM:
#Create variables
location = player.getLocation()
region = location.getRegion()
bonusDifficulty = location.getBattleBonusDifficulty()
#Spawn monsters
monsterCount = _monsterNumGen(player)
monsters = factories.monster_factory.getMonsters(monsterCount, region,
bonusDifficulty)
#Declare battle
print "Zonkle-tronks! Wild monsters appeared!"
print ""
return bonusDifficulty, monsters
#For story-based battles
elif context == constants.BattleEngineContext.STORY:
#Create variables
location = player.getLocation()
region = location.getRegion()
bonusDifficulty = location.getBattleBonusDifficulty()
#Display splash screen
print """
()==[:::::::::::::> ()==[:::::::::::::> ()==[:::::::::::::>
"""
return bonusDifficulty
else:
errorMsg = "_battleSetup given invalid context parameter."
raise AssertionError(errorMsg)
def _monsterNumGen(player):
"""
Helper function used to determine the number of monsters to spawn.
Default spawn comes from a parameter supplied by space. A normal
distribution is applied to introduce variation.
@param player: Player object.
@return: Number of monsters to spawn.
"""
location = player.getLocation()
region = location.getRegion()
bonusDifficulty = location.getBattleBonusDifficulty()
#Calculate region spawn
if region == constants.RegionType.ERIADOR:
monsterCount = (1 + bonusDifficulty) * constants.RegionBaseSpawn.ERIADOR
elif region == constants.RegionType.BARROW_DOWNS:
monsterCount = (1 + bonusDifficulty) * constants.RegionBaseSpawn.BARROW_DOWNS
elif region == constants.RegionType.HIGH_PASS:
monsterCount = (1 + bonusDifficulty) * constants.RegionBaseSpawn.HIGH_PASS
elif region == constants.RegionType.ENEDWAITH:
monsterCount = (1 + bonusDifficulty) * constants.RegionBaseSpawn.ENEDWAITH
elif region == constants.RegionType.MORIA:
monsterCount = (1 + bonusDifficulty) * constants.RegionBaseSpawn.MORIA
elif region == constants.RegionType.RHOVANION:
monsterCount = (1 + bonusDifficulty) * constants.RegionBaseSpawn.RHOVANION
elif region == constants.RegionType.ROHAN:
monsterCount = (1 + bonusDifficulty) * constants.RegionBaseSpawn.ROHAN
elif region == constants.RegionType.GONDOR:
monsterCount = (1 + bonusDifficulty) * constants.RegionBaseSpawn.GONDOR
elif region == constants.RegionType.MORDOR:
monsterCount = (1 + bonusDifficulty) * constants.RegionBaseSpawn.MORDOR
else:
errorMsg = "Invalid region - region base monster determination."
raise AssertionError(errorMsg)
#Apply normal distribution to introduce variation
standardDeviation = monsterCount/constants.BattleEngine.STANDARD_DEVIATION
monsterCount = random.normalvariate(monsterCount, standardDeviation)
monsterCount = max(math.floor(monsterCount), 1)
monsterCount = int(monsterCount)
return monsterCount
def _playerAttackPhase(player, monsters, bonusDifficulty, earnings):
"""
When the user gets to attack a single monster object.
If monster health is reduced to zero, monster is removed
from battle.
Additionally, experience and money is calculated for winnings.
@param player: The player object.
@param monsters: The list of monster objects.
@param earnings: 2-element tuple caring battle earnings. First element
is money earned and second is experience received.
Earnings needs to be passed in between successive
function calls to update battle earnings.
@return: 2-element tuple carrying battle earnings.
First element is money earned, second
element is experience received.
"""
#Starting battle earnings
money = earnings[0]
experience = earnings[1]
#Solicit attack target
target = raw_input("Whom? ")
print ""
#Find monster object
for monster in monsters:
if monster.getName() == target:
#Carry out attack
player.attack(monster)
print ("%s did %s damage to %s!" % (player.getName(),
player.getTotalAttack(), monster.getName()))
#If monster is still alive
if monster.getHp() > 0:
print ("%s has %s hp remaining." % (monster.getName(),
monster.getHp()))
#If monster has died
else:
print "%s" % monster.getDeathString()
#Generate earnings from winning battle
expIncrease = monster.getExperience() * (1 + bonusDifficulty)
experience += expIncrease
money += math.floor(expIncrease/constants.BattleEngine.MONEY_CONSTANT)
#Remove monster from monsters list
for monster in monsters:
if monster.getName() == target:
monsters.remove(monster)
#No need to keep iterating through monsters
break
#No need to keep iterating through monsters
break
else:
print "%s looks at you in confusion." % player.getName()
return money, experience
def _usePotion(player):
"""
Creates an additional UsePotionCommand object
for battle purposes only and then executes the
action sequence of this usePotion.
@param player: The player object.
"""
usePotionCmd = UsePotionCommand(" ", " ", player)
usePotionCmd.execute()
def _monsterAttackPhase(player, monsters):
"""
Monster attack phase - when monsters attack player.
@param player: The player object.
@param monsters: The offending list of monsters.
@return: True if battle is to continue. False
otherwise.
"""
#Monsters attack
for monster in monsters:
monster.attack(player)
print ("%s %s for %s damage!" % (monster.getName(),
monster.getAttackString(), monster.getAttack()))
print "%s has %s HP remaining." % (player.getName(), player.getHp())
#Battle ends
if player.getHp() == 0:
print ""
return False
if monsters:
raw_input("Press enter to continue. ")
print ""
#Battle continuation
return True
def _itemFind(player, experience):
"""
Calculates whether player finds an item and which item he finds.
@param player: The player object.
@param experience: The experience gained from the battle.
"""
location = player.getLocation()
#Item find for low-level uniques
lowLevel = triangular(constants.ItemFind.lowLevel)
if experience > lowLevel and lowLevelFindableUniques:
item = random.choice(lowLevelFindableUniques)
print "You found %s!" % item.getName()
if not player.addToInventory(item):
location.addItem(item)
#Item find for high-level uniques
highLevel = triangular(constants.ItemFind.highLevel)
if experience > highLevel and highLevelFindableUniques:
item = random.choice(highLevelFindableUniques)
print "You found %s!" % item.getName()
if not player.addToInventory(item):
location.addItem(item)
#Item find for elite-level uniques
eliteLevel = triangular(constants.ItemFind.eliteLevel)
if experience > eliteLevel and eliteLevelFindableUniques:
item = random.choice(eliteLevelFindableUniques)
print "You found %s!" % item.getName()
if not player.addToInventory(item):
location.addItem(item)
def _endSequence(player, earnings):
"""
Battle cleanup:
-Victory sequence displayed.
-Player experience and money increase.
@param player: The player object.
@param earnings: 2-element tuple: first element is
money and second is experience.
"""
money = earnings[0]
experience = earnings[1]
#Calculate splash screen variables
victoryDeclaration = "Enemies are vanguished!"
gainsDeclaration = ("%s gains %s %s and %s experience!"
% (player.getName(), money, constants.CURRENCY, experience))
lengthBar = len(gainsDeclaration)
victoryDeclaration = victoryDeclaration.center(lengthBar)
bar = "$" * lengthBar
#Victory sequence
print bar
print victoryDeclaration
print gainsDeclaration
_itemFind(player, experience)
player.increaseMoney(money)
player.increaseExperience(experience)
print bar
print ""