Невозможно заставить оператор if работать в текстовой игре.Python

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Невозможно заставить оператор if работать в текстовой игре.

Сообщение Anonymous »

Следующий код реализует текстовую игру. Игра состоит из пещеры и нескольких комнат внутри нее, где игрок может перемещаться и получать предметы.
Однако я не могу добраться до кода под if current_room == "Логово злодея": , даже если я успешно доберусь до комнаты Логова Злодея.

Код: Выделить всё

def display_instructions():
# print a main menu and the commands
print('Welcome to Colossal Cave Adventure Remake')
print('Move commands: South, North, East, West')
print('Collect 9 items before encountering the Dragon or be eaten by the Dragon.')
print('Move commands: South, North, East, West, Exit & Get Item')
print('To add item to inventory use: Get item')

display_instructions()

# The starting room
current_room = 'Cave Entrance'
inventory = []
move = ''
directions = ['North', 'South', 'East', 'West', 'Exit', 'Get Item']
item_key = 'item'
villain = 'Dragon'

# Define room connections
rooms = {
'Cave Entrance': {'South': 'Troll Region', 'North': 'Giants Room', 'East': 'Magnificent Caverns', 'West': 'Pearl Room' },
'Giants Room': {'item': 'Golden Eggs', 'East': 'Hall of Mists', 'West': 'Forest Region', 'South': 'Cave Entrance'},
'Hall of Mists': {'item': 'Diamonds', 'West': 'Giants Room'},
'Forest Region': {'item': 'Magic Staff', 'South': 'Volcano Region', 'East': 'Giants Room'},
'Volcano Region': {'item': 'Ring of Doom', 'North': 'Forest Region'},
'Pearl Room': {'item': 'Magic Pearl', 'East': 'Cave Entrance', 'North': 'Pirates Room'},
'Pirates Room': {'item': 'Pirates Chest', 'South': 'Pearl Room'},
'Magnificent Caverns': {'item':'Trident', 'South': 'Plover Room', 'West': 'Cave Entrance'},
'Plover Room': {'item': 'Emeralds', 'North': 'Magnificent Caverns'},
'Troll Region': {'item': 'Golden Chain', 'North': 'Cave Entrance', 'East': "Villain's Lair"},
"Villain's Lair": {'villain': 'Dragon', 'West': 'Troll Region'} # Villain's Lair
}

def user_status():  # indicate room and inventory contents
print('\n-------------------------')
print(f'You are in the {current_room}.')
print(f'Your inventory is {inventory}.')

if 'item' in rooms[current_room]:
print(f"In this room you see {rooms[current_room]['item']}.")
else:
print("This room is empty.")

print('-------------------------------')

#While loop for game play
while move != 'Exit':
user_status()

move = str(input('Make a move, Get item or Exit to quit: \n')).title().strip()

if move not in directions:
print('Invalid Input. Try Again!')
continue

# Code to get item
if move == 'Get Item':
if 'item' in rooms[current_room]:
inventory.append(rooms[current_room]['item'])
# Delete item from dictionary
del rooms[current_room]['item']
else:
print("There's no item here.")

#if encounter villain in room
if current_room == "Villain's Lair":
# If You Lose
if len(inventory) < 9:
print('You lost the fight with the Dragon.')
break
#If You Win
else:
print('You won! You beat the Dragon! Congratulations!')
break

# If you want to exit game
elif move == 'Exit':
print("You've exited the game. Bye! Thanks for playing!")
break

# If Move Is Right Direction
if move in rooms[current_room]:
current_room = rooms[current_room][move]
else:
# If Wrong Direction
print("You have a wall in the way. Try again")
При запуске программы следующие действия в указанном порядке приведут игрока в Логово Злодея с пустым инвентарем, так что, по крайней мере, Вы проиграли битву с Драконом.< /code> должно появиться сообщение: Мне нужно, чтобы игрок выигрывал или проигрывал при входе в зависимости от количества предметов в инвентаре. Когда я вхожу в логово злодея, код вообще ничего не делает, просто печатает статус, но никаких других сообщений об успехе или ошибке не появляется.
Может кто-нибудь сказать мне, почему код внутри «проблемного» если не работает?

Подробнее здесь: https://stackoverflow.com/questions/792 ... based-game
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»