#看了前面几个章节,对python最基础的语法有了一定了解。写个程序来验证一下
#程序名:猜大小
#按投骰子的规则来猜大小,用户有初始资金1000,每次下注一定金额,直至用户输光、赢够10000或主动退出游戏
import random #使用random库
import sys #使用sys库
#定义函数GetPointsResult,取3个随机数(1-6)求和,返回相应的判断结果 和 具体数值
def GetPointsResult():
a = random.randrange(1,7) #取值范围(a,b),其实是a到b-1
b = random.randrange(1,7)
c = random.randrange(1,7)
total = [a,b,c]
if 11 <= sum(total) <= 18:
return 'big',total #1个return返回2个值
else:
return 'small',total
#定义函数GetInptu,获取用户输入,直到获取到正确输入为止(否则一直死循环)
# 根据用户输入退出程序或返回用户输入值
def GetInptu():
while True:
choices = ['big','small','bye']
userselect = input('Pleae guess and input \'Big\' or \'Small\',if you want to quit,input \'Bye\':')
userselect = userselect.lower()
if userselect in choices:
break
else:
print('Please input the right choice!')
if userselect=='bye':
print('Bye~~~See you next time!')
sys.exit()
else:
userbet = input('How much you wanna bet ? -- ')
return userselect,float(userbet)
def GameStart(money):
print('\n')
print('<<< ****** Welcome,Game Start ****** >>>') # 显示欢迎词
print('<<< You have money ${} , Enjoy!! >>>'.format(money));
pointsresult, pointsvalue = GetPointsResult() # 调用函数,因为这个函数return了2个值,所以左侧用两个变量来接收,按顺序
pointsresult = pointsresult.lower() # 转换为全部小写
userguess, bet = GetInptu()
userguess = userguess.lower()
if bet>money:
print('You have no enough money ,you can bet max ${} this time.'.format(money))
GameStart(money)
if pointsresult == userguess:
print('Oh yeah ! The points are {},You guess {},You win and earned ${}'.format(pointsvalue, userguess, bet))
money = money + bet
if money > 10000:
print('Oh~~~~Rich man,you earned more than $10000 and you must leave or kill you!')
sys.exit()
else:
GameStart(money)
else:
print('Sorry ! The points are {},You guess {},You lost ${}!'.format(pointsvalue, userguess, bet))
money = money - bet
if money > 0:
GameStart(money)
else:
print('Sorry,you have lost all money, game over!')
sys.exit()
usermoney = 1000;
GameStart(usermoney)
python练手程序之猜大小
最新推荐文章于 2024-04-23 16:18:12 发布