基于文本的游戏输入

时间:2015-03-16 21:03:24

标签: python user-input

我可能只是愚蠢,但我真的无法弄清楚这一点。我正在制作基于文本的游戏,为了模拟不同场景中的角色移动,我使用了以下代码:

 import random

 north = ("There is a path to the North. ")
 south = ("There is a path to the South. ") 
 east  = ("There is a path to the East. ")
 west = ("There is a path to the West. ")

 nsew = [north, south, east, west]

 print ("You find yourself in a woodland clearing. ")

 print (random.choice(nsew))
 print (random.choice(nsew))
 print (random.choice(nsew))
 print (random.choice(nsew))

 direction = input("Which way do you go? ")

这应该从列表中打印四个随机项目。我希望能够做到这样的事情:

if direction == ("North"):
    print ("You decide to go North.")

但是每个都有一个if语句,所以如果用户键入“east”,程序将回复“你决定去东方”

谢谢

2 个答案:

答案 0 :(得分:1)

import random

paths = []
tiaptt = "There is a path to the "
nsew = ["north", "south", "east", "west"]
amount = random.randrange(1,4)


for path in random.sample(nsew,amount):
    print tiaptt+path
    paths.append(path.lower())

direction = raw_input("Which way do you go? ")

try:
    index = paths.index(direction.lower())
    print "You have chosen to go %s"%paths[index]
except:
    print "You have chosen a wrong direction"
希望这会有所帮助。它适用于python 2.7,如果你使用3+,你可能想把我的raw_input改为输入。并在印刷品周围加上()。

print ("You have chosen to go %s"%paths[index])

答案 1 :(得分:0)

嗯,首先阅读用户输入,将所有字母设置为小写,然后将结果字符串与“' north',' south'' east&#39进行比较;和' west'。