#python #text-based
Вопрос:
В настоящее время я работаю над этой текстовой игрой для вводного класса python. Я не могу понять, почему некоторые части кода переносят меня в другую часть, которую я не назначал. Как будто я пошел бы на восток, а затем на север, что должно привести меня к «Скрытому складу грязи», но вместо этого привело бы меня в начальную комнату. Я знаю, что там много ошибок из-за неэффективного способа кодирования, но, пожалуйста, просто прокомментируйте, как исправить основную проблему на данный момент. Спасибо
def show_ins():
print("NEUTRALIZE THE ATAKSUKI!")
print("Team up with 6 teammates to stop the Ataksuki, or they will kill your dear friend")
print("Move commands: go South, go North, go East, go West, Exit")
print("Add teammate: get 'teammate name'")
def main():
rooms = {
'Hidden Mud Village Hall': {'South': 'The Clinic', 'West': 'The Flower Shop', 'North': 'The Bookstore',
'East': 'Yoga House'},
'The Clinic': {'North': 'Hidden Mud Village Hall', 'East': 'Weapons Depot', 'teammate': 'Lady Choyi'},
'Weapons Depot': {'West': 'The Clinic', 'teammate': 'Ten'},
'The Flower Shop': {'East': 'Hidden Mud Village Hall', 'teammate': 'Askura'},
'The Bookstore': {'South': 'Hidden Mud Village Hall', 'East': 'The Gym', 'teammate': 'Akashi'},
'The Gym': {'West': 'The Bookstore', 'teammate': 'Mighty Dude'},
'Yoga House': {'West': 'Hidden Mud Village Hall', 'North': 'Hidden Mud Warehouse', 'teammate': 'Neju'},
'Hidden Mud Warehouse': {'South': 'Yoga House', 'character': 'The Ataksuki'}
}
teammates = []
while True:
show_ins()
currentroom = 'Hidden Mud Village Hall'
command = ''
while currentroom == 'Hidden Mud Warehouse':
if teammates != ['Lady Choyi', 'Ten', 'Askura', 'Neju', 'Mighty Dude', 'Akashi']:
print('You failed. Try again.')
elif teammates == ['Lady Choyi', 'Ten', 'Askura', 'Neju', 'Mighty Dude', 'Akashi']:
print('Good job! You saved Garaa!')
while currentroom == 'Hidden Mud Village Hall':
print('------------------------------------------------------------------------------------')
print('You are currently in', currentroom)
print('Teammates: {}'.format(teammates))
command = input('Command:n')
if command not in ['go south', 'go South', 'go west', 'go West', 'go north', 'go North', 'go east', 'go East', 'exit','Exit']:
print('------------------------------------------------------------------------------------')
print('Invalid command!')
elif command in ['exit', 'Exit']:
currentroom = 'Exit'
print('Coward! Come back here!')
quit()
elif command in ['go south', 'go South']:
currentroom = 'The Clinic'
elif command in ['go west', 'go West']:
currentroom = 'The Flower Shop'
elif command in ['go north', 'go North']:
currentroom = 'The Bookstore'
elif command in ['go east', 'go East']:
currentroom = 'Yoga House'
while currentroom == 'The Clinic':
print('------------------------------------------------------------------------------------')
print('You are currently in', currentroom)
print('You see Lady Choyi')
print('Teammates: {}'.format(teammates))
command = input('Command:n')
if command not in ['go north', 'go North', 'go east', 'go East', 'exit', 'Exit', 'get lady choyi', 'get Lady Choyi']:
print('------------------------------------------------------------------------------------')
print('Invalid command!')
elif command in ['exit', 'Exit']:
currentroom = 'Exit'
print('Coward! Come back here!')
quit()
elif command in ['get lady choyi', 'get Lady Choyi']:
print('Lady Choyi has joined you')
teammates.append ('Lady Choyi')
elif command in ['go north', 'go North']:
currentroom = 'Hidden Mud Village Hall'
elif command in ['go east', 'go East']:
currentroom = 'Weapons Depot'
while currentroom == 'The Flower Shop':
print('------------------------------------------------------------------------------------')
print('You are currently in', currentroom)
print('You see Askura')
print('Teammates: {}'.format(teammates))
command = input('Command:n')
if command not in ['go east', 'go East', 'exit', 'Exit', 'get askura', 'get Askura']:
print('------------------------------------------------------------------------------------')
print('Invalid command!')
elif command in ['exit', 'Exit']:
currentroom = 'Exit'
print('Coward! Come back here!')
quit()
elif command in ['get askura', 'get Askura']:
print('Askura has joined you')
teammates.append ('Askura')
elif command in ['go east', 'go East']:
currentroom = 'Hidden Mud Village Hall'
while currentroom == 'The Bookstore':
print('------------------------------------------------------------------------------------')
print('You are currently in', currentroom)
print('You see Akashi')
print('Teammates: {}'.format(teammates))
command = input('Command:n')
if command not in ['go south', 'go South', 'go east', 'go East', 'get akashi', 'get Akashi']:
print('------------------------------------------------------------------------------------')
print('Invalid command!')
elif command in ['exit', 'Exit']:
currentroom = 'Exit'
print('Coward! Come back here!')
quit()
elif command in ['get akashi', 'get Akashi']:
print('Akashi has joined you')
teammates.append ('Akashi')
elif command in ['go south', 'go South']:
currentroom = 'Hidden Mud Village Hall'
elif command in ['go east', 'go East']:
currentroom = 'The Gym'
while currentroom == 'Yoga House':
print('------------------------------------------------------------------------------------')
print('You are currently in', currentroom)
print('You see Neju')
print('Teammates: {}'.format(teammates))
command = input('Command:n')
if command not in ['go west', 'go West', 'go north', 'go North', 'get Neju', 'get neju']:
print('------------------------------------------------------------------------------------')
print('Invalid command!')
elif command in ['exit', 'Exit']:
currentroom = 'Exit'
print('Coward! Come back here!')
quit()
elif command in ['get Neju', 'get neju']:
print('Neju has joined you')
teammates.append ('Neju')
elif command in ['go west', 'go West']:
currentroom = 'Hidden Mud Village Hall'
elif command in ['go north', 'go North']:
currentroom = 'Hidden Mud Warehouse'
while currentroom == 'Weapons Depot':
print('------------------------------------------------------------------------------------')
print('You are currently in', currentroom)
print('You see Ten')
print('Teammates: {}'.format(teammates))
command = input('Command:n')
if command not in ['go west', 'go West', 'exit', 'Exit', 'get ten', 'get Ten']:
print('------------------------------------------------------------------------------------')
print('Invalid command!')
elif command in ['exit', 'Exit']:
currentroom = 'Exit'
print('Coward! Come back here!')
quit()
elif command in ['get ten', 'get Ten']:
print('Ten has joined you')
teammates.append ('Ten')
elif command in ['go west', 'go West']:
currentroom = 'The Clinic'
while currentroom == 'The Gym':
print('------------------------------------------------------------------------------------')
print('You are currently in', currentroom)
print('You see Mighty Dude')
print('Teammates: {}'.format(teammates))
command = input('Command:n')
if command not in ['go west', 'go West', 'exit', 'Exit', 'get mighty dude', 'get Mighty Dude']:
print('------------------------------------------------------------------------------------')
print('Invalid command!')
elif command in ['exit', 'Exit']:
currentroom = 'Exit'
print('Coward! Come back here!')
quit()
elif command in ['get mighty dude', 'get Mighty Dude']:
print('Mighty Dude has joined you')
teammates.append ('Mighty Dude')
elif command in ['go west', 'go West']:
currentroom = 'The Bookstore'
main()
Ответ №1:
Непосредственная проблема, с которой вы сталкиваетесь, заключается в том, что ваш while
цикл сбрасывает текущую комнату в начале каждой итерации:
while True:
show_ins()
currentroom = 'Hidden Mud Village Hall'
...
Вместо этого вы, вероятно, захотите установить его перед циклом и разрешить изменение тела цикла currentroom
в ответ на команды:
currentroom = 'Hidden Mud Village Hall'
while True:
show_ins()
...
Ре: я знаю, что есть много ошибок и неэффективного кодирования — вот незапрошенного предложения о том, как вы могли бы написать код, который позволяет сделать из любой комнаты в любую другую комнату, используя только информацию в rooms
словаре (Т. е. без необходимости иметь отдельный «если currentroom = ‘номер'» на каждый номер):
command = input('Command:n').lower()
if command[:3] == "go ":
# this handles *any* "go" command in *any* room using the rooms dict
d = command[3:]
if d not in ["north", "south", "east", "west"]:
print("Invalid direction!")
elif d not in rooms[currentroom]:
print(f"Can't go {d} from {currentroom}.")
else:
currentroom = rooms[currentroom][d]
continue
# handle other commands
Комментарии:
1. Также
elif
должно просто бытьelse
; условие не может быть ложным, если было противоположноеif
условие.2. … Хотя условие проверяет определенную последовательность , в которой вы , вероятно, просто захотите проверить, есть ли в ней одинаковые элементы в любой последовательности; обычный способ сделать это-использовать a
set
вместо alist
или преобразоватьlist
в aset
, а затем сравнить.3. Кроме того, код используется
while
в нескольких местах , где вы явно имеете в видуif
, иначе код внутри цикла должен изменить текущую комнату, чтобыwhile
условие стало неверным; в противном случае у вас будет бесконечный цикл.