Guest User

Untitled

a guest
Sep 29th, 2026
10
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.76 KB | None | 0 0
  1. from pathlib import Path
  2. import json
  3.  
  4. class RPG_Character:
  5. def __init__(self, **stats_dict):
  6. for stat in stats_dict:
  7. setattr(self, stat, stats_dict[stat])
  8.  
  9. # need to convert self.inventory
  10. # it's a list of dictionaries if we have recreated this from JSON
  11. if self.inventory and isinstance(self.inventory[0], dict):
  12. self.inventory = [Item(**kwargs) for kwargs in self.inventory]
  13.  
  14. def label2attribute(self, label):
  15. """Return the attribute value given the N character label."""
  16.  
  17. for attr in dir(self):
  18. if attr.startswith(label):
  19. return getattr(self, attr)
  20. return '~' # error, not found, return this rather than None
  21.  
  22. def __str__(self):
  23. """Return values in instance in a more compact display form.
  24.  
  25. More work, but it's easier to check output for correctness.
  26. This could be done in a better way, but this is more readable.
  27. """
  28.  
  29. result = []
  30.  
  31. # do name and inventory
  32. inv = [item.name for item in self.inventory]
  33. line = f'Name:{self.name} Inventory: {', '.join(inv)}'
  34. result.append(line)
  35.  
  36. # header line for the other attributes
  37. line = []
  38. for (label, width) in char_display:
  39. line.append(f'{label:^{width}}')
  40. result.append('|'.join(line) )
  41.  
  42. # divider line
  43. line = []
  44. for (_, width) in char_display:
  45. line.append('-' * width)
  46. result.append('+'.join(line) )
  47.  
  48. # now put the attribute values under the header line
  49. # this is a bit of a fudge, uses label2attribute() helper
  50. line = []
  51. for (label, width) in char_display:
  52. value = self.label2attribute(label)
  53. line.append(f'{value:^{width}}')
  54. result.append('|'.join(line))
  55.  
  56. result.append('') # to get ending newline
  57.  
  58. return "\n".join(result)
  59.  
  60. def add_gold(self, amount):
  61. self.gold += amount
  62.  
  63. def remove_gold(self, amount):
  64. self.gold -= amount
  65. if self.gold < 0:
  66. print("Gold amount can't be below zero.")
  67. self.gold += amount
  68.  
  69. def increase_level(self):
  70. self.level += 1
  71. self.strength += self.growth[0]
  72. self.dexterity += self.growth[1]
  73. self.agility += self.growth[2]
  74. self.endurance += self.growth[3]
  75. self.intelligence += self.growth[4]
  76. self.wisdom += self.growth[5]
  77. self.health += self.growth[6]
  78. self.mana += self.growth[7]
  79.  
  80. def add_item(self, item):
  81. self.inventory.append(item)
  82.  
  83. # probably not needed now
  84. # def show_inventory(self):
  85. # print("=====Inventory=====")
  86. # for item in self.inventory:
  87. # print(item)
  88. # print("=====Inventory=====")
  89.  
  90. def to_dict(self):
  91. # saved_inventory = []
  92. # for item in self.inventory:
  93. # saved_inventory.append(item.to_dict())
  94. return {'name': self.name,
  95. 'job': self.job,
  96. 'level': self.level,
  97. 'health': self.health,
  98. 'mana': self.mana,
  99. 'strength': self.strength,
  100. 'dexterity': self.dexterity,
  101. 'agility': self.agility,
  102. 'endurance': self.endurance,
  103. 'intelligence': self.intelligence,
  104. 'wisdom': self.wisdom,
  105. 'gold': self.gold,
  106. # use comprehension to handle inventory
  107. # 'inventory': saved_inventory
  108. 'inventory': [item.to_dict() for item in self.inventory]
  109. }
  110.  
  111.  
  112. class Item:
  113. def __init__(self, **kwargs):
  114. # handle dictionary a different way than used for RPG_Character
  115. # you decide which is better
  116. for (key, value) in kwargs.items():
  117. setattr(self, key, value)
  118. self.sell_price = self.buy_price // 4
  119.  
  120. def __str__(self):
  121. # the (f"..." f"...") thing is a way of handling lines too long
  122. return (f'Item:{self.name} Type:{self.item_type} '
  123. f'Buy:{self.buy_price} Sell:{self.sell_price}'
  124. )
  125.  
  126. def to_dict(self):
  127. return {'name': self.name,
  128. 'type': self.type, # we know it's an Item, no need for 'item_type'
  129. 'buy_price': self.buy_price,
  130. 'sell_price': self.sell_price
  131. }
  132.  
  133. def convert_dict_to_obj_inv(list_of_dicts):
  134. return [Item(**d) for d in list_of_dicts]
  135. # list_of_items = []
  136. # for temp_dict in list_of_dicts:
  137. # current_item = Item(temp_dict['name'], temp_dict['type'], temp_dict['buy_price'])
  138. # list_of_items.append(current_item)
  139. # return list_of_items
  140.  
  141. ######### start of code
  142. # it's better to keep all top-level CODE at the bottom of a file
  143. # otherwise it's hard to see where the code is in the file
  144.  
  145. path = Path('data.json')
  146. list_of_characters = []
  147.  
  148. # List of jobs
  149. warrior_class = {'job': 'Warrior', 'strength': 5, 'dexterity': 4, 'agility': 3,
  150. 'endurance': 5, 'intelligence': 3, 'wisdom': 4, 'health': 50,
  151. 'mana': 30, 'growth': [3, 2, 1, 3, 1, 2, 10, 4],
  152. 'inventory': []}
  153. rogue_class = {'job': 'Rogue', 'strength': 4, 'dexterity': 5, 'agility': 5,
  154. 'endurance': 3, 'intelligence': 4, 'wisdom': 3, 'health': 40,
  155. 'mana': 40, 'growth': [2, 3, 3, 1, 2, 1, 7, 7], 'inventory': []}
  156. mage_class = {'job': 'Mage', 'strength': 3, 'dexterity': 3, 'agility': 4,
  157. 'endurance': 4, 'intelligence': 5, 'wisdom': 5, 'health': 30,
  158. 'mana': 50, 'growth': [1, 1, 2, 2, 3, 3, 4, 10], 'inventory': []}
  159.  
  160. # character display data for .__str__()
  161. # each tuple is (<label>, <width>)
  162. # <label> MUST BE first N characters of attribute name
  163. char_display = (('job', 7), ('leve', 4), ('heal', 4), ('mana', 4), ('stre', 4),
  164. ('dext', 4), ('agil', 4), ('endu', 4), ('inte', 4), ('wisd', 4),
  165. ('gold', 4),
  166. )
  167.  
  168. # create the items
  169. # no need for 'item_type', it's an attribute of Item so no need for 'item'
  170. health_data = {'name': 'Basic Health Potion', 'type': 'Consumable',
  171. 'buy_price': 16}
  172. mana_data = {'name': 'Basic Mana Potion', 'type': 'Consumable',
  173. 'buy_price': 20}
  174. shield_data = {'name': 'Wooden Shield', 'type': 'Equipment',
  175. 'buy_price': 40}
  176.  
  177. basic_health_potion = Item(**health_data)
  178. basic_mana_potion = Item(**mana_data)
  179. wooden_shield = Item(**shield_data)
  180.  
  181. if path.exists():
  182. contents = path.read_text()
  183. temp_list_of_characters = json.loads(contents)
  184. print('File successfully retrieved')
  185.  
  186. # for character in temp_list_of_characters:
  187. # new_character = RPG_Character(**character)
  188. ## new_character.inventory = convert_dict_to_obj_inv(new_character.inventory)
  189. # list_of_characters.append(new_character)
  190. list_of_characters = [RPG_Character(**char) for char in temp_list_of_characters]
  191.  
  192. print('Retrieved characters:')
  193. for character in list_of_characters:
  194. print(character)
  195. # print(character.show_inventory())
  196. else:
  197. # Adds new characters
  198. john_data = {'name': 'John', 'gold': 50, 'level': 1}
  199. new_warrior = RPG_Character(**(warrior_class | john_data))
  200. list_of_characters.append(new_warrior)
  201. print('New warrior - John:')
  202. print(new_warrior)
  203.  
  204. new_warrior.add_gold(100)
  205. print('After adding 100 gold')
  206. print(new_warrior)
  207.  
  208. new_warrior.remove_gold(80)
  209. print('After removing 80 gold')
  210. print(new_warrior)
  211.  
  212. toby_data = {'name': 'Toby', 'gold': 50, 'level': 1}
  213. new_rogue = RPG_Character(**(rogue_class | toby_data))
  214. list_of_characters.append(new_rogue)
  215. print('New rogue - Toby:')
  216. print(new_rogue)
  217.  
  218. mage_data = {'name': 'Harris', 'gold': 50, 'level': 1}
  219. new_mage = RPG_Character(**(mage_class | mage_data))
  220. list_of_characters.append(new_mage)
  221. print('New mage - Harris:')
  222. print(new_mage)
  223.  
  224. new_mage.increase_level()
  225. print(f'After increasing level of mage {new_mage.name}')
  226. print(new_mage)
  227.  
  228. print(f'Adding health and mana potions to rogue {new_rogue.name}')
  229. new_rogue.add_item(basic_health_potion)
  230. new_rogue.add_item(basic_mana_potion)
  231.  
  232. print(f'Adding shield to warrior {new_warrior.name}')
  233. new_warrior.add_item(wooden_shield)
  234. # new_rogue.show_inventory() # due to inventory being show in the character
  235. # new_warrior.show_inventory()
  236.  
  237. print('\nFinal state of the characters')
  238. for ch in list_of_characters:
  239. print(ch)
  240. # print(list_of_characters)
  241.  
  242. contents = json.dumps([ob.to_dict() for ob in list_of_characters])
  243. path.write_text(contents)
  244. print('File saved')
  245.  
Advertisement
Add Comment
Please, Sign In to add comment