utils.py 1.56 KB
import json
import sys
if 'esp' in sys.platform:
    from urandom import getrandbits
else:
    import random

def save_object_to_file(obj, filename):
    with open(filename, 'w', encoding='utf-8') as f:
      f.write(json.dumps(obj))

def load_object_from_file(filename):
    try:
      with open(filename, 'r', encoding='utf-8') as f:
          return json.loads(f.read())
    except Exception as e:
        print('Error opening file: ' + filename)
        print(e)
        return None

def randrange(start, stop=None):
    if 'esp' in sys.platform:
        if start == 1:
            return 0
        if stop is None:
            stop = start
            start = 0
        upper = stop - start
        bits = 0
        pwr2 = 1
        while upper > pwr2:
            pwr2 <<= 1
            bits += 1
        while True:
            r = getrandbits(bits)
            if r < upper:
                break
        return r + start
    else:
        return random.randrange(start)

def get_att(d):
    att = 0
    if 'd' in d:
        dice = d.split('d')
        for d in range(int(dice[0])):
            att += randrange(int(dice[1])) + 1
    else:
        att = int(d)
    return att
def calc_att(mud, pid, attacks, bank):
    v_att = []
    att = 0
    for attack in attacks:
        if attack['cost'] < bank:
            v_att.append(attack)
    # Select a random attack
    if len(v_att) > 0:
        attack = v_att[randrange(len(v_att))]
        att = get_att(attack['dmg'])
        mud.send_message(pid, "%s for %d" % (attack['desc'], att,))
        bank -= attack['cost']
    return att, bank