from random import choice
cave_numbers = range(1,21)
wumpus_location = choice(cave_numbers)
player_location = choice(cave_numbers)
while player_location == wumpus_location:
player_location = choice(cave_numbers)
print "Welcome to Hunt the Wunpus!"
print "You can see", len(cave_numbers), "caves"
print "To play, just type the number"
print "of the cave you wish to enter next"
while True:
print "You are in cave", player_location
if (player_location == wumpus_location - 1 or player_location == wumpus_location + 1):
print "I smell a wumpus!"
print "which cave next?"
player_input = raw_input(">")
if (not player_input.isdigit() or int(player_input) not in cave_numbers):
print player_input, "is not a cave"
else:
player_location = int(player_input)
if player_location == wumpus_location:
print "Aargh ! You got eaten by a wumpus!"
break
第一行类似于c中的include,其引入一个模块random在下面程序使用random中的range方法生成一个在包含1到21之间的数值的数组(列表)。
而choice方法则是返回一个在列表中的随机项在这里主要返回的值是在1到21之间。通过range和choice方法的一起使用来获得一个随机数的值。
在开头要注意的是怪物和主角所在的位置不能出现相同值这会使得游戏在开始的时候就结束退出。
在第十行使用了一个len函数用于返回字符串长度在这里是用于对range方法产生的数据长度的处理可以方便玩家的有关交互动作。
下面是死循环部分:首先程序输出玩家所在的洞穴位置比对洞穴位置与怪物所在洞穴位置后给出相关提示,通过使用raw_input方法来获取一个用户输入。先判断用户输入的值是否在原先的范围内而后转换成int类型在于怪物所在洞穴位置进行比对最后选择输出结果值或提示玩家继续游戏。
(以上只是个人理解。本人也是刚刚入门。存在问题还望指正。)