Made rich console global and all print methods now use it.

This commit is contained in:
Chris Davoren 2023-07-16 09:39:00 +10:00
parent 13073df432
commit 2fd9b573e5
1 changed files with 56 additions and 61 deletions

View File

@ -5,8 +5,7 @@ import datetime
import csv import csv
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
import rich import rich.console
from rich.console import Console
# Only "normal storage" is used to insert requested items # Only "normal storage" is used to insert requested items
normal_storage_ids = [82, 632] normal_storage_ids = [82, 632]
@ -17,6 +16,8 @@ storage_ids = {
3062: {"name": "Body storage", "capacity": 20}, 3062: {"name": "Body storage", "capacity": 20},
} }
console = rich.console.Console(highlight=False)
# A single item with its code, name, and quantity # A single item with its code, name, and quantity
class Item: class Item:
@ -97,7 +98,6 @@ class Character:
with open(trait_filename, 'r') as trait_file: with open(trait_filename, 'r') as trait_file:
trait_reader = csv.reader(trait_file, delimiter='\t') trait_reader = csv.reader(trait_file, delimiter='\t')
for row in trait_reader: for row in trait_reader:
print(row)
cls.trait_ids[int(row[0])] = row[1].strip() cls.trait_ids[int(row[0])] = row[1].strip()
if cls.condition_ids is None: if cls.condition_ids is None:
@ -160,14 +160,11 @@ class Character:
new_char.is_clone = True new_char.is_clone = True
new_char.tag['name'] = new_name new_char.tag['name'] = new_name
new_skills = [s.copy() for s in self.skills] new_char.skills = [s.copy() for s in self.skills]
new_attributes = [a.copy() for a in self.attributes] new_char.attributes = [a.copy() for a in self.attributes]
new_char.skills = new_skills
new_char.attributes = new_attributes
return new_char return new_char
def print_summary(self): def print_summary(self):
console = Console(highlight=False)
console.print("Name: [bright_cyan]{}[/]".format(self.name)) console.print("Name: [bright_cyan]{}[/]".format(self.name))
console.print() console.print()
console.print("Skills:") console.print("Skills:")
@ -248,7 +245,7 @@ class GameData:
ship_name = "UNNAMED (?fogged)" ship_name = "UNNAMED (?fogged)"
if ship_tag.has_attr('sname'): if ship_tag.has_attr('sname'):
ship_name = ship_tag['sname'] ship_name = ship_tag['sname']
# print(ship_name) # console.print(ship_name)
# Forgotten - why did I specify owner as required here - what ships don't have owners? # Forgotten - why did I specify owner as required here - what ships don't have owners?
owner_node = ship_tag.find('settings', owner=True) owner_node = ship_tag.find('settings', owner=True)
@ -272,7 +269,7 @@ class GameData:
item_quantity = int(s_tag['inStorage']) item_quantity = int(s_tag['inStorage'])
item = Item(item_code, item_name, item_quantity) item = Item(item_code, item_name, item_quantity)
storage_area.add_item(item) storage_area.add_item(item)
# print("{:4}: {} - {}".format(item_code, item_name, item_quantity)) # console.print("{:4}: {} - {}".format(item_code, item_name, item_quantity))
# Step 4 - Character data # Step 4 - Character data
for character_list in ship_tag.find_all('characters'): for character_list in ship_tag.find_all('characters'):
@ -339,7 +336,7 @@ class GameData:
for character in ship.characters: for character in ship.characters:
# Cloned character tags have to be added to the list # Cloned character tags have to be added to the list
if character.is_clone: if character.is_clone:
print("ADDING CLONED CHARACTER") console.print("ADDING CLONED CHARACTER")
charlist_tag = ship.tag.find('characters') charlist_tag = ship.tag.find('characters')
charlist_tag.append(character.tag) charlist_tag.append(character.tag)
@ -391,7 +388,6 @@ class GameData:
return return
def print_detailed_character_summary(self): def print_detailed_character_summary(self):
console = Console(highlight=False)
for ship in self.ships: for ship in self.ships:
console.print("Listing characters for ship [magenta]{}[/] (owned by [bright_cyan]{}[/], state [bright_cyan]{}[/]):".format(ship.name, ship.owner, ship.state)) console.print("Listing characters for ship [magenta]{}[/] (owned by [bright_cyan]{}[/], state [bright_cyan]{}[/]):".format(ship.name, ship.owner, ship.state))
if len(ship.characters) == 0: if len(ship.characters) == 0:
@ -409,7 +405,6 @@ class GameData:
console.print() console.print()
def print_detailed_item_summary(self): def print_detailed_item_summary(self):
console = Console(highlight=False)
for ship in self.ships: for ship in self.ships:
rich.print("Inventory for ship [#aa00ff]{}[/] (owned by [bright_cyan]{}[/], state [bright_cyan]{}[/]):".format(ship.name, ship.owner, ship.state)) rich.print("Inventory for ship [#aa00ff]{}[/] (owned by [bright_cyan]{}[/], state [bright_cyan]{}[/]):".format(ship.name, ship.owner, ship.state))
if len(ship.storage_areas) == 0: if len(ship.storage_areas) == 0:
@ -442,18 +437,18 @@ class GameData:
console.print() console.print()
def print_summary(self): def print_summary(self):
print("Start game summary:") console.print("Start game summary:")
print(" Player currency: {}".format(self.player.currency)) console.print(" Player currency: {}".format(self.player.currency))
print(" Number of ships: {}".format(len(self.ships))) console.print(" Number of ships: {}".format(len(self.ships)))
for ship in self.ships: for ship in self.ships:
print(" {} (owner {}, state {})".format(ship.name, ship.owner, ship.state)) console.print(" {} (owner {}, state {})".format(ship.name, ship.owner, ship.state))
print(" Contains {} storage area(s):".format(len(ship.storage_areas))) console.print(" Contains {} storage area(s):".format(len(ship.storage_areas)))
for index, storage_area in enumerate(ship.storage_areas): for index, storage_area in enumerate(ship.storage_areas):
print(" Storage area {} - contains {} item(s) - occupancy {} unit(s)".format(index, len(storage_area.items), storage_area.get_total_occupancy())) console.print(" Storage area {} - contains {} item(s) - occupancy {} unit(s)".format(index, len(storage_area.items), storage_area.get_total_occupancy()))
print(" Has {} character(s):".format(len(ship.characters))) console.print(" Has {} character(s):".format(len(ship.characters)))
for char in ship.characters: for char in ship.characters:
print(" {}".format(char.name)) console.print(" {}".format(char.name))
# char.print_summary() # char.print_summary()
@ -461,30 +456,30 @@ def characters(soup):
for character in soup.find_all('characters'): for character in soup.find_all('characters'):
c_elems = character.find_all('c') c_elems = character.find_all('c')
if len(c_elems) > 0: if len(c_elems) > 0:
print('Found some appropriate c-tags') console.print('Found some appropriate c-tags')
for char_c in c_elems: for char_c in c_elems:
# print(char_c['name']) # console.print(char_c['name'])
if 'name' in char_c.attrs: if 'name' in char_c.attrs:
print(char_c['name']) console.print(char_c['name'])
# We have found a character tag! # We have found a character tag!
# ---- SKILL UPRGRADING # ---- SKILL UPRGRADING
skill_tag = char_c.find('skills') skill_tag = char_c.find('skills')
print(skill_tag) console.print(skill_tag)
# Experimental changing # Experimental changing
for sk_tag in skill_tag.find_all('s'): for sk_tag in skill_tag.find_all('s'):
sk_tag['level'] = '5' sk_tag['level'] = '5'
sk_tag['mxn'] = '8' sk_tag['mxn'] = '8'
if 'mxp' in sk_tag.attrs: if 'mxp' in sk_tag.attrs:
sk_tag['mxp'] = '8' sk_tag['mxp'] = '8'
print(skill_tag) console.print(skill_tag)
# ---- ATTRIBUTE UPGRADING # ---- ATTRIBUTE UPGRADING
attribute_tag = char_c.find('attr') attribute_tag = char_c.find('attr')
print(attribute_tag) console.print(attribute_tag)
for a_tag in attribute_tag.find_all('a'): for a_tag in attribute_tag.find_all('a'):
a_tag['points'] = '6' a_tag['points'] = '6'
print(attribute_tag) console.print(attribute_tag)
def inventory(soup, add_code, add_quantity): def inventory(soup, add_code, add_quantity):
@ -496,16 +491,16 @@ def inventory(soup, add_code, add_quantity):
result = line.split() result = line.split()
code = int(result[0]) code = int(result[0])
name = ' '.join(result[1:]) name = ' '.join(result[1:])
# print(code, name) # console.print(code, name)
id_dict[code] = name id_dict[code] = name
# print(id_dict) # console.print(id_dict)
print("You have requested that {} unit(s) of {} be added to existing storage of this item (storage site will be selected at random)".format(add_quantity, id_dict[add_code])) console.print("You have requested that {} unit(s) of {} be added to existing storage of this item (storage site will be selected at random)".format(add_quantity, id_dict[add_code]))
item_tracking = {} item_tracking = {}
print('-----') console.print('-----')
storage_space_counter = 1 storage_space_counter = 1
@ -519,20 +514,20 @@ def inventory(soup, add_code, add_quantity):
for inv_tag in ship_tag.find_all('inv'): for inv_tag in ship_tag.find_all('inv'):
if inv_tag.parent.name != 'feat': if inv_tag.parent.name != 'feat':
continue continue
print('Storage space {}'.format(storage_space_counter)) console.print('Storage space {}'.format(storage_space_counter))
print() console.print()
quantity_total = 0 quantity_total = 0
for s_tag in inv_tag.find_all('s'): for s_tag in inv_tag.find_all('s'):
item_code = int(s_tag['elementaryId']) item_code = int(s_tag['elementaryId'])
item_quantity = int(s_tag['inStorage']) item_quantity = int(s_tag['inStorage'])
item_name = id_dict[item_code] item_name = id_dict[item_code]
print("{:4}: {} - {}".format(item_code, item_name, item_quantity)) console.print("{:4}: {} - {}".format(item_code, item_name, item_quantity))
if item_code == add_code and not added_quantity: if item_code == add_code and not added_quantity:
print(" Updating quantity with requested amount...") console.print(" Updating quantity with requested amount...")
item_quantity += add_quantity item_quantity += add_quantity
s_tag['inStorage'] = item_quantity s_tag['inStorage'] = item_quantity
added_quantity = True added_quantity = True
print(" Item quantity is now {}".format(s_tag['inStorage'])) console.print(" Item quantity is now {}".format(s_tag['inStorage']))
quantity_total += item_quantity quantity_total += item_quantity
if item_code not in item_tracking: if item_code not in item_tracking:
@ -540,18 +535,18 @@ def inventory(soup, add_code, add_quantity):
else: else:
item_tracking[item_code] = item_tracking[item_code] + item_quantity item_tracking[item_code] = item_tracking[item_code] + item_quantity
print() console.print()
print('Total use of storage space {}: {}'.format(storage_space_counter, quantity_total)) console.print('Total use of storage space {}: {}'.format(storage_space_counter, quantity_total))
storage_space_counter += 1 storage_space_counter += 1
print('-----') console.print('-----')
print('Item total summary:') console.print('Item total summary:')
print() console.print()
for item in item_tracking.items(): for item in item_tracking.items():
item_code = item[0] item_code = item[0]
item_name = id_dict[item_code] item_name = id_dict[item_code]
item_quantity = item[1] item_quantity = item[1]
print('{:4} - {} - {}'.format(item_code, item_name, item_quantity)) console.print('{:4} - {} - {}'.format(item_code, item_name, item_quantity))
def give_money(soup, amount): def give_money(soup, amount):
@ -578,8 +573,8 @@ def list_ships(soup):
owner_node = ship_tag.find('settings', owner=True) owner_node = ship_tag.find('settings', owner=True)
ship_owner = owner_node['owner'] ship_owner = owner_node['owner']
ship_state = owner_node['state'] ship_state = owner_node['state']
print('Ship found: {} owned by {} (state: {})'.format(ship_name, ship_owner, ship_state)) console.print('Ship found: {} owned by {} (state: {})'.format(ship_name, ship_owner, ship_state))
# print(settings_node) # console.print(settings_node)
def parse_item_file(filename): def parse_item_file(filename):
@ -614,29 +609,29 @@ def main():
parser.add_argument('--replace_original', required=False, action='store_true', help='Replace original file instead of creating edited alternative. Renames original for backup, but USE WITH CAUTION') parser.add_argument('--replace_original', required=False, action='store_true', help='Replace original file instead of creating edited alternative. Renames original for backup, but USE WITH CAUTION')
args = parser.parse_args() args = parser.parse_args()
# print(args) # console.print(args)
print("--- Space Haven Saved Game Inspector ---") console.print("--- Space Haven Saved Game Inspector ---")
print() console.print()
filename = args.filename filename = args.filename
# print(filename) # console.print(filename)
full_text = "" full_text = ""
for line in open(filename): for line in open(filename):
full_text += line full_text += line
# print(full_text) # console.print(full_text)
soup = BeautifulSoup(full_text, "xml") soup = BeautifulSoup(full_text, "xml")
Item.load_ids('item_ids.tsv') Item.load_ids('item_ids.tsv')
print("Item code database successfully loaded.") console.print("Item code database successfully loaded.")
print() console.print()
Character.load_ids('char_skills.tsv', 'char_attributes.tsv', 'char_traits.tsv', 'char_conditions.tsv') Character.load_ids('char_skills.tsv', 'char_attributes.tsv', 'char_traits.tsv', 'char_conditions.tsv')
print("Character code database successfully loaded.") console.print("Character code database successfully loaded.")
print() console.print()
game_data = GameData(soup) game_data = GameData(soup)
game_data.populate() game_data.populate()
@ -664,10 +659,10 @@ def main():
if args.add_item_set: if args.add_item_set:
item_list = parse_item_file(args.add_item_set[0]) item_list = parse_item_file(args.add_item_set[0])
# print(item_list) # console.print(item_list)
print("Items to be added:") console.print("Items to be added:")
for (item_code, item_quantity) in item_list: for (item_code, item_quantity) in item_list:
print("{} : {}".format(Item.get_name_from_code(item_code), item_quantity)) console.print("{} : {}".format(Item.get_name_from_code(item_code), item_quantity))
game_data.add_item(item_code, item_quantity) game_data.add_item(item_code, item_quantity)
edits_made = True edits_made = True
@ -693,13 +688,13 @@ def main():
if edits_made: if edits_made:
if args.replace_original: if args.replace_original:
print('Renaming original file') console.print('Renaming original file')
datetime_suffix = datetime.datetime.now().strftime('%Y-%m-%d-%H%M_%S_%f') datetime_suffix = datetime.datetime.now().strftime('%Y-%m-%d-%H%M_%S_%f')
new_filename = args.filename + "-" + datetime_suffix new_filename = args.filename + "-" + datetime_suffix
# print(datetime_suffix) # console.print(datetime_suffix)
os.rename(args.filename, new_filename) os.rename(args.filename, new_filename)
print('Now rewriting game file with new information') console.print('Now rewriting game file with new information')
text = soup.prettify() text = soup.prettify()
# Delete XML header - game doesn't have it # Delete XML header - game doesn't have it
sansfirstline = '\n'.join(text.split('\n')[1:]) sansfirstline = '\n'.join(text.split('\n')[1:])
@ -707,7 +702,7 @@ def main():
f = open(args.filename, 'w') f = open(args.filename, 'w')
f.write(sansfirstline) f.write(sansfirstline)
f.close() f.close()
print('Complete.') console.print('Complete.')
else: else:
text = soup.prettify() text = soup.prettify()
# Delete XML header - game doesn't have it # Delete XML header - game doesn't have it