Consider using a dictionary
instead of a list
. Dictionaries are ideal for maintaining counts
of things
:
from random import choice
def get_rooms(file_name):
rooms = {}
with open(file_name) as f:
for l in f:
room = l.split()
room_number = int(room[0])
rooms[room_number] = {}
for index, data in enumerate(room[1:], 1):
if index % 2:
item = data
else:
rooms[room_number][item] = int(data)
return rooms
def generate_tests(number_of_test_actions):
tests = []
for _ in range(number_of_test_actions):
tests.append((choice([1,2,3,4,5,6]),
choice(['Apple', 'Sword', 'Bow', 'Arrow', 'monkey']),
choice(['take', 'drop'])))
return tests
def take_item(room, item):
# generates and propagates KeyError exception if item not in room
room[item] -= 1
if not room[item]:
room.pop(item)
def drop_item(room, item):
if item in room:
room[item] += 1
else:
room[item] = 1
rooms = get_rooms("rooms.txt")
for room, item, action in generate_tests(10):
if action == 'take':
print('taking', item, 'from room', room, ':', rooms[room])
try:
take_item(rooms[room], item)
except KeyError:
print('-- Sorry, no', item, 'in room', room, 'to take')
else:
print('-- took', item, 'from room', room, ':', rooms[room])
elif action == 'drop':
print('dropping', item, 'in room', room, ':', rooms[room])
drop_item(rooms[room], item)
print('-- dropped', item, 'in room', room, ':', rooms[room])
rooms.txt
1 Sword 1 Apple 2
2 Apple 3
3 Bow 1 Arrow 3
4 Arrow 5
5 Bow 1
6 Arrow 10
Output
taking Apple from room 3 : {'Arrow': 3, 'Bow': 1}
-- Sorry, no Apple in room 3 to take
taking Apple from room 4 : {'Arrow': 5}
-- Sorry, no Apple in room 4 to take
dropping monkey in room 6 : {'Arrow': 10}
-- dropped monkey in room 6 : {'monkey': 1, 'Arrow': 10}
dropping Apple in room 5 : {'Bow': 1}
-- dropped Apple in room 5 : {'Apple': 1, 'Bow': 1}
taking Bow from room 3 : {'Arrow': 3, 'Bow': 1}
-- took Bow from room 3 : {'Arrow': 3}
dropping monkey in room 3 : {'Arrow': 3}
-- dropped monkey in room 3 : {'monkey': 1, 'Arrow': 3}
dropping Arrow in room 6 : {'monkey': 1, 'Arrow': 10}
-- dropped Arrow in room 6 : {'monkey': 1, 'Arrow': 11}
taking Bow from room 5 : {'Apple': 1, 'Bow': 1}
-- took Bow from room 5 : {'Apple': 1}
taking Bow from room 4 : {'Arrow': 5}
-- Sorry, no Bow in room 4 to take
taking Bow from room 5 : {'Apple': 1}
-- Sorry, no Bow in room 5 to take
collections.Counter
. – TigerhawkT3