python2的小游戏一(解释书《易学python》的第一版Hunt the Wumpus)

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类型在于怪物所在洞穴位置进行比对最后选择输出结果值或提示玩家继续游戏。


(以上只是个人理解。本人也是刚刚入门。存在问题还望指正。)


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值