~ryanprior/+junk/python-srd

« back to all changes in this revision

Viewing changes to sim.py

  • Committer: Ryan Prior
  • Date: 2010-12-10 22:05:08 UTC
  • Revision ID: ryanprior@gmail.com-20101210220508-8cs3nu9454hksvv2
initialĀ import

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
from srd.dnd import roll
 
2
from collections import defaultdict
 
3
from sys import stdout
 
4
simulations = 1000000
 
5
simulations_update = simulations/10
 
6
def print_sim_update(i):
 
7
  if i % simulations_update == 0 and i:
 
8
    stdout.write(".")
 
9
    stdout.flush()
 
10
 
 
11
def roll_avg(dice):
 
12
  number, die = [float(x) for x in dice.split("d")]
 
13
  return (die+1)/2 * number
 
14
 
 
15
def avg_damage(attack, ac):
 
16
  total = 0.0
 
17
  for i in xrange(0, simulations):
 
18
    total += attack.roll(ac).damage
 
19
  return round(total / float(simulations), 1);
 
20
 
 
21
def init_sort(init):
 
22
  return init[0]*10000 + init[1].init()*100 + roll("1d100")-1
 
23
 
 
24
def init_order(combatants):
 
25
  inits = []
 
26
  for i in combatants:
 
27
    init = i.init() + roll("1d20")
 
28
    inits.append((init,i))
 
29
  return sorted(inits, reverse=True, key=init_sort)
 
30
 
 
31
def determine_teams(combatants):
 
32
  teams = defaultdict(list)
 
33
  for i in combatants:
 
34
    teams[i.team].append(i)
 
35
  return teams
 
36
 
 
37
def can_fight(combatant):
 
38
  if combatant.hp > 0:
 
39
    return True
 
40
  else:
 
41
    return False
 
42
 
 
43
def bout(combatants):
 
44
  order = init_order(combatants)
 
45
  teams = determine_teams(combatants)
 
46
  winner = None
 
47
  while winner == None:
 
48
    for i in order:
 
49
      combatant = i[1]
 
50
      if not can_fight(combatant):
 
51
        for j in teams:
 
52
          if teams[j][0].team != combatant.team:
 
53
            winner = teams[j][0]
 
54
      else:
 
55
        for j in teams:
 
56
          if j != combatant.team:
 
57
            enemy = teams[j][0]
 
58
        for j in combatant.full_attack():
 
59
          enemy.hp -= j.roll(enemy.ac()).damage
 
60
      if winner != None:
 
61
        break
 
62
  return winner