Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

Untitled

By: a guest on Oct 30th, 2011  |  syntax: Python  |  size: 1.62 KB  |  views: 19  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. from math import ceil
  2.  
  3. ARMOR = 0
  4. DAMAGE = 1
  5. RANGE = 2
  6. TYPES = (ARMOR, DAMAGE, RANGE)
  7.  
  8. STATS = [# hp, dmg, range, cost
  9.         (8, 2, 0, 1.00), # armor
  10.         (6, 6, 1, 1.75), # damage
  11.         (4, 4, 2, 2.50)] # range
  12.  
  13. def getCostFromHP(army_hp):
  14.     return sum(STATS[t][3] * (army_hp[t] / float(STATS[t][0])) for t in TYPES)
  15.  
  16. def getDamage(att_hp, distance):
  17.     """Compute total damage done by attacker."""
  18.     dmg = 0
  19.     for t in TYPES:
  20.         units = ceil(att_hp[t] / float(STATS[t][0]))
  21.         if STATS[t][2] >= distance:
  22.             dmg += units * STATS[t][1]
  23.     return dmg
  24.  
  25. def applyDamage(def_hp, dmg):
  26.     """Apply dmg to defender's units."""
  27.     for t in TYPES:
  28.         if def_hp[t] >= dmg:
  29.             def_hp[t] -= dmg
  30.             break
  31.         else:
  32.             dmg -= def_hp[t]
  33.             def_hp[t] = 0
  34.  
  35. def simulate(a_units, b_units):
  36.     """
  37.    Simulates battle between two armys and returns the score.
  38.    Accepts army in this format: [armored, damage, ranged]
  39.    """
  40.    
  41.     turn = 0
  42.    
  43.     a_hp = [STATS[t][0] * a_units[t] for t in TYPES]
  44.     b_hp = [STATS[t][0] * b_units[t] for t in TYPES]
  45.     a_cost = sum(STATS[t][3] * a_units[t] for t in TYPES)
  46.     b_cost = sum(STATS[t][3] * b_units[t] for t in TYPES)
  47.    
  48.     while any(a_hp) and any(b_hp):
  49.         a_dmg = getDamage(a_hp, 2 - turn)
  50.         b_dmg = getDamage(b_hp, 2 - turn)
  51.  
  52.         applyDamage(a_hp, b_dmg)
  53.         applyDamage(b_hp, a_dmg)
  54.        
  55.         turn += 1
  56.  
  57.     if any(b_hp): # if b won...
  58.         return - getCostFromHP(b_hp) / float(b_cost)
  59.     else:
  60.         return getCostFromHP(a_hp) / float(a_cost)
  61.