Python游戏循环问题:显示结束信息且不退出程序
问题解决与代码优化建议
核心问题解决(Garden房间结束逻辑)
你遇到的问题是进入Garden房间后,添加break会导致程序直接关闭,无法看到结束消息。这是因为程序执行break后会立即终止,没有留给用户查看消息的时间。解决方法是在显示胜负消息后,添加一个等待用户输入的步骤,再跳出循环:
修改主循环中的Garden判断部分:
while True: # 处理进入Garden房间的胜负逻辑 if current_room == 'Garden': if len(inventory) == 6: print('Congratulations you have defeated The Giant Serpent and saved the tea party!') print('Thank you for playing!') else: print('\nOh dear! You did not collect all of the items!') print('You were eaten by The Giant Serpent and the party was ruined!') print('Thank you for playing!') # 等待用户输入,避免程序直接关闭 input("按回车键退出游戏...") break # 跳出循环,结束游戏 # 以下为原循环中的房间状态打印、输入处理逻辑 print(f'You are in the {current_room}') print('Inventory:', inventory) if current_room != 'Garden' and 'item' in rooms[current_room]: print(f'You see the {rooms[current_room]["item"]}') print('------------------------------') move = input('Enter your move: ').strip().lower().split() # 后续输入处理逻辑...
这样修改后,玩家进入Garden房间看到胜负消息后,需要按回车键才会退出程序,确保能看到结束提示。
代码优化建议
1. 修复拼写错误
将Strong Sheild改为Strong Shield,避免玩家输入时出现匹配问题。
2. 封装胜负判断逻辑
把Garden房间的胜负判断抽成单独函数,让主代码更简洁:
def check_game_end(inventory): if len(inventory) == 6: print('Congratulations you have defeated The Giant Serpent and saved the tea party!') print('Thank you for playing!') else: print('\nOh dear! You did not collect all of the items!') print('You were eaten by The Giant Serpent and the party was ruined!') print('Thank you for playing!') input("按回车键退出游戏...")
然后在主循环中调用:
if current_room == 'Garden': check_game_end(inventory) break
3. 避免修改原始rooms字典
原代码中del rooms[current_room]['item']会修改原始数据,若后续要支持重新开始游戏,会导致物品丢失。可以创建字典副本使用:
from copy import deepcopy def main(): rooms = { # 原rooms定义... } rooms_copy = deepcopy(rooms) # 使用副本,不修改原始数据 # 后续操作都用rooms_copy
4. 输入处理优化
- 处理空输入:避免用户直接按回车导致的索引错误
move = input('Enter your move: ').strip().lower().split() if not move: print('Invalid move, please try again') continue - 严格匹配物品名称:原代码用
in判断会导致部分匹配,改为完全匹配:elif move[0] == 'get' and ' '.join(move[1:]) == rooms_copy[current_room]['item']:
5. 使用f-string优化打印格式
替换字符串拼接和format,让代码更易读:
print(f'You are in the {current_room}') print(f'You see the {rooms_copy[current_room]["item"]}')
6. 增加无效移动的容错处理
修改move_between_rooms函数,避免无效方向导致的KeyError:
def move_between_rooms(current_room, direction, rooms): # 若方向无效,返回原房间 return rooms[current_room].get(direction, current_room)
完整优化后的代码
from copy import deepcopy def main_menu(): print("Tea Party Take Over Game") print("Collect 6 items to win the game, or be eaten by the giant serpent.") print("Move commands: go South, go North, go East, go West") print("Add to Inventory: get 'item name'") def move_between_rooms(current_room, direction, rooms): return rooms[current_room].get(direction, current_room) def get_item(current_room, rooms, inventory): inventory.append(rooms[current_room]['item']) rooms[current_room]['item'] = None # 标记物品已拾取,不删除键 def check_game_end(inventory): if len(inventory) == 6: print('Congratulations you have defeated The Giant Serpent and saved the tea party!') print('Thank you for playing!') else: print('\nOh dear! You did not collect all of the items!') print('You were eaten by The Giant Serpent and the party was ruined!') print('Thank you for playing!') input("按回车键退出游戏...") def main(): rooms = { 'Main Hall': {'North': 'Library', 'East': 'Dining room', 'South': 'Greenhouse', 'West': 'Storage'}, 'Library': {'South': 'Main Hall', 'East': 'Artifact Collection', 'item': 'Potion Book'}, 'Artifact Collection': {'West': 'Library', 'item': 'Serpent Sword'}, 'Dining room': {'West': 'Main Hall', 'North': 'Kitchen', 'item': 'Strong Shield'}, 'Kitchen': {'South': 'Dining room', 'item': 'Potion Ingredients'}, 'Greenhouse': {'North': 'Main Hall', 'East': 'Garden', 'item': 'Healing Herb'}, 'Garden' : {'West': 'Greenhouse'}, 'Storage': {'East': 'Main Hall', 'item': 'Small Cauldron'} } rooms_copy = deepcopy(rooms) inventory = [] current_room = "Main Hall" main_menu() while True: if current_room == 'Garden': check_game_end(inventory) break print(f'You are in the {current_room}') print('Inventory:', inventory) if current_room != 'Garden' and 'item' in rooms_copy[current_room] and rooms_copy[current_room]['item'] is not None: print(f'You see the {rooms_copy[current_room]["item"]}') print('------------------------------') move_input = input('Enter your move: ').strip().lower() if not move_input: print('Invalid move, please try again') continue move = move_input.split() if len(move) >= 2 and move[0] == 'go': direction = move[1].capitalize() new_room = move_between_rooms(current_room, direction, rooms_copy) if new_room == current_room: print('Invalid direction, please try again') else: current_room = new_room continue elif len(move) >= 2 and move[0] == 'get': item_name = ' '.join(move[1:]).title() if current_room != 'Garden' and 'item' in rooms_copy[current_room] and rooms_copy[current_room]['item'] == item_name: print(f'You pick up the {item_name}') print('------------------------------') get_item(current_room, rooms_copy, inventory) else: print('That item is not here!') continue else: print('Invalid move, please try again') continue if __name__ == "__main__": main()
内容的提问来源于stack exchange,提问作者alyssamessier
相关产品推荐
相关产品推荐

