笨办法学Python(三十五)

本文深入解析Python习题35,详细介绍了如何运用if语句、函数及列表创建一个简单的文本冒险游戏。从代码解读到游戏地图绘制,再到常见错误修正,全面涵盖习题要点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

习题 35: 分支和函数

    你已经学会了 if 语句、函数、还有列表。现在你要练习扭转一下思维了。把下面的代码写下来,看你是否能弄懂它实现的是什么功能。

 1 from sys import exit
 2 
 3 def gold_room():
 4     print  "This room is full of gold. How much do you take?"
 5 
 6     next = raw_input("> ")
 7     if "0" in next or "1" in next:
 8         how_much = int(next)
 9     else:
10         dead("Man, learn to type a number.")
11 
12     if how_much < 50:
13         print "Nice, you're not greedy,you win!"
14         exit(0)
15     else:
16         dead("You greedy bastard!")
17 
18 
19 def bear_room():
20     print "There is a bear here."
21     print "The bear has a bunch of honey."
22     print "The fat bear is in front of another door."
23     print "How are you going to move the bear?"
24     bear_moved = False 
25 
26     while True:
27         next = raw_input("> ")
28 
29         if next == "take honey":
30             dead("The bear looks at you then slaps your face off.")
31         elif next == "taunt bear" and not bear_moved:
32             print "The bear has moved frome the door. You can go through it now."
33             bear_moved = True
34         elif next == "taunt bear" and bear_moved:
35             dead("The bear gets pissed off and chews your leg off.")
36         elif next == "open door" and bear_moved:
37             gold_room()
38         else:
39             print "I got no idea what that means."
40 
41 
42 def cthulhu_room():
43     print "Here you see the great evil Cthulhu."
44     print "He, it, whatever stares at you and you go insane."
45     print "Do you flee for your life or eat your head?"
46 
47     next = raw_input("> ")
48 
49     if "flee" in next:
50         start()
51     elif "head" in next:
52         dead("Well that was tasty!")
53     else:
54         cthulhu_room()
55 
56 
57 def dead(why):
58     print why, "Good job!"
59     exit(0)
60 
61 def start():
62     print "You are in a dark room."
63     print "There is a door to your right and left."
64     print "Which one do you take?"
65 
66     next = raw_input("> ")
67 
68     if next == "left":
69         bear_room()
70     elif next == "right":
71         cthulhu_room()
72     else:
73         dead("You stumble around the room until you starve.")
74 
75 
76 start()        
View Code

你应该看到的结果

    下面是我玩游戏的过程:

 

 

加分习题

  1. 把这个游戏的地图画出来,把自己的路线也画出来。
  2. 改正你所有的错误,包括拼写错误。
  3. 为你不懂的函数写注解。记得文档注解该怎么写吗?
  4. 为游戏添加更多元素。通过怎样的方式可以简化并且扩展游戏的功能呢?
  5. 这个 gold_room 游戏使用了奇怪的方式让你键入一个数字。这种方式会导致什么样的 bug? 你可以用比检查 0、1 更好的方式判断输入是否是数字吗?int() 这个函数可以给你一些头绪。

习题练习

5.

Python函数-int()

转载于:https://www.cnblogs.com/yllinux/p/7506402.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值