基于文本的游戏
继承人我的代码基于文本的游戏
direction = 0
while direction != ("quit"):
direction = input("> ")
if direction[0:4] != "quit" and direction != "go north" and direction != "go south" and direction != "go east" and direction != "go west" and direction != "go up" and direction != "go down" and direction[0:4] != "look":
if direction[0:2] == "go" and direction[3:] == (""):
print("please tell me more")
else:
print("huh?")
elif direction[0:1] == "go" and direction != "north" and direction != "south" and direction != "east" and direction != "west" and direction != "up" and direction != "down":
print ("please tell me more")
elif direction[0:4] == "quit":
print ("OK ... but a small part of you may never leave until you have personally saved Muirfieland from the clutches of evil .. Bwahahahahahah (sinister laugh).")
elif direction[0:4] == "look":
print ("You see nothing but endless void stretching off in all directions ...")
else:
print ("You wander of in the direction of " + direction)
我尝试添加到我的代码 这一点,如果第一个字是公认的,但第二个不是,它会与回应: “对不起,我怕我不能这样做“ 即时只是有麻烦让我的代码一点点,任何帮助将不胜感激谢谢。
所以快速分析...你让文本解析器其工作过程如下:
- 获取“命令”的第一个字,如果我们不知道这个词的用户使用无效的输入不 - >通知并重新启动
- 如果用户使用已知的“命令”,解析它的参数(如:
go north
,go south
),并让“嵌套”功能拍摄参数的照顾
注意“主解析功能”并不需要知道go()
参数是否有效,进行验证,以go()
它只是代表的责任。
所以我认为你应该建立code (class)这样的:
class Game:
# Initialize internal variables, method automatically called on g = Game()
def __init__(self):
self._exit = False
# Array of known commands, used in run, basically maps commands
# to function and it says: if will get 'go' execute self._go
self._commands = {
'go': self._go,
'quit': self._quit
}
# Array of go sub commands, used by _go
self._commands_go = {
'north': self._go_north
# ...
}
# Mathod for parsing command, if it gets "comamnd" returns ("command",None)
# if "command arg1 arg2" returns ("command", "arg1 arg2")
@staticmethod
def parse_command(string):
string = str(string)
index = string.find(' ')
if index < 0:
return (string, None)
return (string[:index], string[index+1:])
# This is main method; the only one which should be called from outside
# It will just read data from input in never ending loop and parse commands
def run(self):
while not self._exit:
src = input('> ')
(command,args) = Game.parse_command(src)
# Do we have this command, execute it
if command in self._commands:
self._commands[command](args)
else:
print('I\'m sorry I don\'t known command {}, try one of these:'.format(command))
print('\n'.join(self._commands.keys()))
#######################################################
# All game commands go here
#######################################################
def _quit(self,args):
self._exit = True
print('Bye bye')
# Movement handling, will get executed when user types 'go ...' nad '...' will be in arg
def _go(self,args):
# No argument
if args is None:
print('Go excepts one of these:', '; '.join(self._commands_go.keys()))
return False
# Split sub command anr arguments
(command,args) = Game.parse_command(args)
if command not in self._commands_go:
print('Go excepts one of these:', '; '.join(self._commands_go.keys()))
return False
if args is not None:
print('Too many arguments for go')
return False
self._commands_go[command](args)
return True
# Go north
def _go_north(self, args):
print('Going north')
game = Game()
game.run()
这将允许您:
- 建立复杂的嵌套命令
- 建美好和可读命令层次结构(
inventory item 123 update use potion 345
)而不是难以阅读的一组复杂条件 - 构建功能别名
go north
可以使用别名为gn
加入'gn': self._go_north
到_commands
- 构建可重用的参数解析
(item_id, action, args) = self._parse_item_action(args)
- 采取面向对象编程的优点(没有全局变量,一切都将是类属性,意外变量覆盖的风险较低)
如果你需要分析goasdf
作为go
,你可以只是简单:
for i in self._commands:
if input.startswirh(i):
return self._commands[i](...)
print('Invalid command')
return False
注:我没有测试代码,它只是我的头。
即时通讯对不起,我只是一个非常业余的编码器,因为你可以看到...即时通讯有点难以理解你的代码,以及它是如何作品,你会介意把它拆分多一点给我,并解释它 – user2232076
@ user2232076我已经添加了一些评论,但首先阅读[python类和对象](http://docs.python.org/3.2/ tutorial/classes.html),然后提出直接的问题:) – Vyktor
非常感谢您向我展示了这一点,它实际上已经极大地扩展了我对python的了解,现在剩下的只是很少的小镊子。 – user2232076
你的代码看起来相当混乱给我,这里只是一个简单的代码的版本:
flag = 0
count = 0
direction = 0
while direction != ("quit"):
direction = input("> ")
count += 1
if recognised and count == 1: # word is recognised
flag = 1
print "whatever you want..."
elif (not recognised) and count == 2 and flag == 1:
flag = 0
print "sorry, im afraid i cant do that"
else:
flag = 1
print "second is recognised or whatever you want..."
在我的代码,我给自己定一个标志,如果第一猜测是公认的递增计数也。第二个猜测,我只是检查标志和计数的价值。
不怎么相对与您的代码,但是,当你可以代替获取用户输入,分割它,所以它变成一个列表和比较的第一个字,则第二所以它可能是像
user = user_input("> ")
user = user.split()
if user[0] == "look"
if user[1] == "left"
do something
if user[1] == "right"
do something
else
print ("sorry, im afraid i cant do that")
不知道这是你在找什么,虽然
简单地说,我认为你需要学习更多的代码,让自己在这里变得更容易,尽管也许类有点多,而且我不是这个意思一个侮辱的方式。
作为一个简单的开始,我建议使用in关键字而不是==。
例如:
if "north" in direction:
do something
这将“有所作为”如果输入是北,北,北上,北上请等等。
解决您的问题,所以你的代码可以使用这样的事情:
input = ("> ")
if "go" in input and not ("north" in input and "south" in input...):
print "That is not a direction you can go in."
等。 “而不是(...)”部分可以重写得更整洁,但我写它是为了显示发生的事情更容易。
truthcase = None
directions = ["north", "south", ...]
for i in directions:
if i not in input:
continue
else:
truthcase = True
truthcase = False
if "go" in input and not truthcase:
print something
希望这会有所帮助。
你的意思是“被识别”是什么意思?你的代码中有太多的条件,哪一个被识别? –
由公认的我的意思是如果theres一个单词thats不意味着在那里例如“去”是一个公认的词,但“efwqef”不是。 所以用于例如用户输入 去fwqefuqwe 它会说对不起,我不能那样做 – user2232076