Skip to content

Instantly share code, notes, and snippets.

@Vashy
Last active March 12, 2019 22:55
Show Gist options
  • Save Vashy/2dbfbaeb5b88a3c4c62c10e8b4ea8fc0 to your computer and use it in GitHub Desktop.
Save Vashy/2dbfbaeb5b88a3c4c62c10e8b4ea8fc0 to your computer and use it in GitHub Desktop.
RPG equip cost calculator
#!/usr/bin/env python3
"""Usage: python3 calculate.py "path/to/file"
PRE: input file format example. csv-like file:
unitary cost, moltiplicator (optional), name or descriptor
Scrolls
12,5 5x Mage Armor scroll (CL1)
12,5 2x Shield scroll (CL1)
37,5 2 Shield scroll (CL3)
12,5 2x Reduce Person Scroll (CL1)
12.5 Enlarge Person Scroll (CL1)
12.5 Silent Image (CL1)
75 Protection from Good (CL3)
75 2x See Invisibility (CL3)
75 Gust of Wind (CL3)
75 2x Invisibility (CL3)
75 1x Disguise Other (CL3)
75 1x Alter Self (CL3)
75 2x Cat’s Grace (CL3)
75 Bear’s Endurance (CL3)
187.5 1x Clay Skin (CL5)
187.5 1x Shrink Item (CL5)
187.5 1x Fly (CL5)
187.5 1x Haste (CL5)
350 1x Invisibility, Greater (CL7)
Wands
750 Wand
"""
import argparse
import re
def remove_trailing_x(arg):
"""Return an `arg`'s copy without the trailing final x."""
if arg[-1] == 'x':
return arg[:-1]
return arg
def convert_to_float_or_1(arg):
"""Return `float(arg)`, or 1 if the cast fails."""
try:
value = float(arg)
return value
except ValueError:
return 1.0
# Match for records, form '132 1x item name and stuff'
re_record = re.compile(r'\d*[\.,]?\d+\s+\d*x?[ \t]*.*|\d+')
# Match for sections, normal text
re_section = re.compile(r'[\w \t\d]+')
# Parse filename, CLI argument
parser = argparse.ArgumentParser()
parser.add_argument("file")
args = parser.parse_args()
try:
with open(args.file, "r") as f:
value = f.readlines()
except FileNotFoundError:
print('File "%s" does not exist' % args.file)
exit(-1)
tot = 0.0 # Total
tots = {} # Total for each category
key = '' # Default Key
for line in value:
if len(line) > 0.0:
match_record = re_record.match(line)
match_section = re_section.match(line)
if match_record:
# print('Matched record: ' + match_record.group()) # Debugging
line = line.split()
line[0] = line[0].replace(',', '.')
line[1] = remove_trailing_x(line[1])
if key != '': # Not in the default case
arg_1 = convert_to_float_or_1(line[1])
tots[key] += float(line[0]) * arg_1
tot += float(line[0]) * arg_1
elif match_section:
# print('Matched section: ' + match_section.group()) # Debugging
key = line.rstrip()
tots[key] = 0.0
# Total
print() # Beautify
result = 'Total: %.2f' % (tot)
print(result)
print('-' * len(result)) # Beatify
print() # Beatify
# Categories, sorted by value (descending order)
for key, value in sorted(tots.items(), key=lambda x: x[1], reverse=True):
if value > 0:
print('%s: %.2f' % (key, value))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment