Test19-用循环语句、if语句和函数做一个小游戏

本文通过实战小游戏,深入浅出地讲解Python中的if、for、while语句及函数定义,演示如何运用这些基本元素构建游戏逻辑。游戏包含多个场景,玩家的选择将决定最终结局。同时,文章详细解析了exit()和int()函数的使用,帮助读者理解Python流程控制与数据类型转换。

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

Python系列之笨方法学Python是我学习《笨方法学Python》—Zed A. Show著
的学习思路和理解,如有不如之处,望指出!!!

这一节我们用前面学习过的if语句、for语句、while语句和def定义函数等来做一个小游戏

源代码

# ex35.py

from sys import exit

def gold_room():
	print "this room is full of gold.How much do you take?"
	next=raw_input("> ")
	if "0" in next or "1" in next:
		how_much=int(next)
	else:
		dead("man,learn to type a number.")
	if how_much<50:
		print "Nice,you're not greedy,you win!"
		exit(0)
	else:
		dead("You greedy bastard!")
		
def bear_room():
	print "there is a bear here."
	print "The bear has a bunch of honey."
	print "the fat bear is in front of another door."
	print "How are you going to move the bear?"
	bear_moved=False
	while True:
		next=raw_input("> ")
		if next=="take honey":
			dead("the bear looks at you then slaps your face off.")
		elif next=="taunt bear" and not bear_moved:
			print "The bear has moved from the door.You can go through it now."
			bear_moved=True
		elif next=="taunt bear" and bear_moved:
			dead("the bear gets pissed off and chews your leg off.")
		elif next=="open door" and bear_moved:
			gold_room()
		else:
			print "I got no idea what that means."
			
def cthulhu_room():
	print "here you see the great evil Cthulhu."
	print "He,it,whatever stares at you and you go insane."
	print "Do you flee for your life or eat your head?"
	next=raw_input("> ")
	if "flee" in next:
		start()
	elif "head" in next:
		dead("well that was tasty!")
	else:
		cthulhu_room()
		
def dead(why):
	print why,"Good job!"
	exit(0)
def start():
	print "You are in a dark room."
	print "there is a door to your right and left."
	print "which one do you take?"
	next=raw_input("> ")
	if next=="left":
		bear_room()
	elif next=="right":
		cthulhu_room()
	else:
		dead("you stumble around the room until you starve.")
start()

这是一个选择的小游戏,每次不同的选择都会有不同的结果

建议仔细看这个代码,搞清楚逻辑关系

你可以看到的结果

本节需要注意的知识

  1. exit()语句

exit()可以中断某个程序,而其中的数字参数则用来表示程序是否遇到错误而中断。
exit(0)表示程序是正常退出的
exit(1)表示发生了错误,可以用不一样的数字代表不同的错误结果。
比如,你可以用exit(100)来表示另一种和exit(2)exit(1)不同的错误

  1. int()指令

int() 函数用于将一个字符串或数字转换为整型。

语法

class int(x, base=10)

参数

  • x – 字符串或数字。
  • base – 进制数,默认十进制。

示例

>>>int()               # 不传入参数时,得到结果0
0
>>> int(3)
3
>>> int(3.6)
3
>>> int('12',16)        # 如果是带参数base的话,12要以字符串的形式进行输入,12 为 16进制
18
>>> int('0xa',16)  
10  
>>> int('10',8)  
8
  1. 为什么写while True

这样可以创建一个无限循环


这是**《笨方法学Python》**的第十九篇文章

希望自己可以坚持下去

希望你也可以坚持下去

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值