I’m pretty new to python and I’m trying to make an inventory for a text RPG game I’m making if you could help me figure this out id super appreciate it!
JavaScript
x
42
42
1
class PlayerAttributes:
2
inventory = []
3
def __init__(self, name, inventory):
4
self.name = name
5
self.inventory = inventory # LIST
6
class Item:
7
def __init__(self, item_name, damage):
8
self.item_name = item_name
9
self.damage = damage
10
11
class Weapons(Item):
12
weapon_1 = Item("Me Sword", 100)
13
14
15
Player_1 = PlayerAttributes("Bob", [])
16
17
def get_name():
18
Player_1.name = input("Enter name here: ").capitalize()
19
commands()
20
21
def stats():
22
print("Name = " + str(Player_1.name), "n",
23
"Inventory: ")
24
for x in Player_1.inventory:
25
print(str(x.item_name))
26
27
def commands():
28
prompt = None
29
prompt_choices = {"stats", "quit", "give"}
30
while prompt not in prompt_choices:
31
prompt = input("Enter Command: ").lower()
32
if prompt == "stats":
33
stats()
34
commands()
35
elif prompt == "quit":
36
quit()
37
elif prompt == "give":
38
Player_1.inventory.append(Weapons.weapon_1)
39
commands()
40
41
get_name()
42
Current output if I enter Test as name then, giveX3, stats
JavaScript
1
11
11
1
Enter name here: Test
2
Enter Command: give
3
Enter Command: give
4
Enter Command: give
5
Enter Command: stats
6
Name = Test
7
Inventory:
8
Me Sword
9
Me Sword
10
Me Sword
11
Desired output if I enter Test as name then, giveX8, stats Also would like to do a new line after every 4 Items have been shown
JavaScript
1
14
14
1
Enter name here: Test
2
Enter Command: give
3
Enter Command: give
4
Enter Command: give
5
Enter Command: give
6
Enter Command: give
7
Enter Command: give
8
Enter Command: give
9
Enter Command: give
10
Enter Command: stats
11
Name = Test
12
Inventory: Me Sword, Me Sword, Me Sword, Me Sword #loop after 4 items
13
Me Sword, Me Sword, Me Sword, Me Sword
14
If you have any suggestions I’d really appreciate the help! P.S it does not have to be a for loop but I do not want to have to print every weapon index in order to get them in that output
Advertisement
Answer
You can use slicing and join
:
JavaScript
1
16
16
1
def stats():
2
items = [item.item_name for item in Player_1.inventory]
3
4
print(f"Name = {Player_1.name}")
5
6
if not items: # if empty list
7
print("Inventory is empty.")
8
return
9
10
for i in range(0, len(items), 4):
11
if i == 0:
12
print("Inventory: ", end='')
13
else:
14
print(" ", end='') # for non-first lines
15
print(', '.join(items[i:i+4]))
16
Output:
JavaScript
1
11
11
1
Enter name here: foo
2
Enter Command: give
3
Enter Command: give
4
Enter Command: give
5
Enter Command: give
6
Enter Command: give
7
Enter Command: stats
8
Name = Foo
9
Inventory: Me Sword, Me Sword, Me Sword, Me Sword
10
Me Sword
11