python小游戏(二)——dragon realm
游戏规则是在1和2中挑选一个数字,代表一个山洞,山洞中有不同的老虎,有一个好的,有一个坏的,选了之后会产生不同结果:
源代码如下:
import random
import time
def displayintr():
print ("you are in a land full of dragons.In front of you ,you see two caves.In one cave,the draon is friendly,and will share his treasure with you.The other dragon is greedy and hungry,and you will eat you on sight")
print()
def chosecave():
cave=''
while cave != '1' and cave != '2':
print('which cave will you go into(1 or 2)')
cave=input()
return cave
def checkcave(chosencave):
print ('you approch the cave')
time.sleep(2)
print('It is dark and spookly....')
time.sleep(2)
print('a large dragon jumps out in front of you !He opens his jaws and ...')
print()
time.sleep(2)
friendlycave=random.randint(1,2)
if chosencave==str(friendlycave):
print('gives you his treasure')
else:
print('gobbles you down in one bite')
playagain='yes'
while playagain=='yes' or playagain=='y':
displayintr()
cavenumber=chosecave()
checkcave(cavenumber)
print ('do you want to play again(yes or no)')
playagain=input()
首先这里用到了两个模块,一个事random,另外一个是time
定义了三个函数,目的是便于重复引用。
其中需要关注的三个点是:
第一个函数chosecave()中,return cave 返回值,这个语句一定不能写在while循环中,不然将导致输入验证不起作用
第二个是在主程序的第一个语句是playagain=yes保证了第一个是直接执行下面的函数,从而进行游戏。
第三个是在函数中引用了time模块,让游戏变得更加有趣一点。