【问题标题】:Python text based game room to room movement基于 Python 文本的游戏房间到房间移动
【发布时间】:2021-04-09 22:09:59
【问题描述】:

您好,我是使用 python 编码和创建基于文本的游戏的新手。我正在编写代码以从一个房间移动到另一个房间。我需要一些帮助来清理我到目前为止所做的事情。我通过一个即时反馈程序运行它并获得了这些提示,但不确定如何纠正它:

  • Great Hall 字符串是主词典中的一个键。修改代码,使其不是主字典中的键。
  • 它说它无法对我的代码进行分类(不确定这是什么意思)
  • 将多个打印命令整合到一个函数中
  • 使用非复杂条件使条件更简单
  • 更好的做法是使用 while True: 和 break 保留字在需要停止循环时停止循环

数据设置

rooms = {'Great Hall': {'name': 'Great Hall', 'South': 'Bedroom', 'North': 'Dungeon', 'West': 
'Library', 'East': 'Kitchen'},
     
'Bedroom': {'name': 'Bedroom', 'East': 'Cellar', 'North': 'Great Hall'},
      
'Cellar': {'name': 'Cellar', 'West': 'Bedroom'},
     
'Library': {'name': 'Library', 'East': 'Great Hall'},
    
'Kitchen': {'name': 'Kitchen', 'West': 'Great Hall', 'North': 'Dining Room'},
     
'Dining Room': {'name': 'Dining Room', 'South': 'Kitchen'},
     
'Dungeon': {'name': 'Dungeon', 'South': 'Great Hall', 'East': 'Gallery'},
    
'Gallery': {'name': 'Gallery', 'West': 'Dungeon'},
    
}

directions = ['North', 'South', 'East', 'West']

current_room = rooms['Great Hall']

游戏循环

while True:

# display current location

print()

print('You are in the {}.'.format(current_room['name']))

# get user input
command = input('\nWhat direction do you want to go? ').strip()
# movement
if command in directions:
    if command in current_room:
        current_room = rooms[current_room[command]]
    else:
        # bad movement
        print("You can't go that way.")
# Exit game
elif command.lower() in ('q', 'quit'):
    break
# bad command
else:
    print("I don't understand that command.")

【问题讨论】:

  • 第一个建议是使用f strings,它们更容易阅读
  • 我也不认为这是一个合适的问题
  • @ClMend 他的代码没有问题,也不是一般问题,因此根据 SO(据我所知)它不被认为是一个好问题,它更适合代码审查

标签: python


【解决方案1】:

顺便说一句,您将在 Code Review Stack Exchange 上获得更多帮助。 https://codereview.stackexchange.com/

首先,您的代码不起作用 - While 循环中的代码没有缩进。

这会抛出一个错误:

while True:
print("hi")

这不会:

while True:
    print("hi")
  • 更好的做法是使用 while True: 和 break 保留字在需要停止循环时停止循环

您似乎已经在使用它,但由于您的缩进错误,它没有注意到它。

  • Great Hall 字符串是主词典中的一个键。修改代码,使其不是主字典中的键。

这可能意味着制作多个字典而不是将它们全部放在一个中,但这并不重要,所以我不知道它为什么会抱怨。

  • 它说它不能对我的代码进行分类(不确定这是什么意思) 我也没有;请提供一些上下文。

  • 将多个打印命令合并到一个函数中

现在这已经失控了。我不知道为什么它告诉你这样做,但你可以使用一个元组:

def printstuff(x):
    for i in x:
        print(i)

printstuff((5,5,3,85,"hi"))
# will print:
# 5
# 5
# 3
# 85
# hi 
  • 使用非复杂条件使条件更简单

不知道这意味着什么。再次,请提供上下文。

另外,正如评论所说,使用 f-strings(仅限 python 3.6+)会让你的生活变得更轻松。这个:

hello = "hello world"
print("\n{}".format(hello))

可以缩短为:

hello = "hello world"
print(f"\n{hello}")

\n 将充当空白的print() 调用)

【讨论】:

  • 感谢您的提示。至于为其中一些项目提供更多背景信息,我希望我可以,但这就是它给我的所有信息。另外,很抱歉没有正确输入代码。我有正确的缩进,它确实适用于 pycharm。
猜你喜欢
  • 1970-01-01
  • 2015-10-31
  • 1970-01-01
  • 1970-01-01
  • 2020-08-14
  • 1970-01-01
  • 1970-01-01
  • 2017-07-11
  • 1970-01-01
相关资源
最近更新 更多