python 游戏(猜数字)
Posted 呆萌小朋友
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 游戏(猜数字)相关的知识,希望对你有一定的参考价值。
1. 构造猜数字核心函数
import random
def guess_core(guess_min,guess_max,guess_counrt):
‘‘‘猜数字核心判断函数
:param guess_min 范围的开始
:param guess_max 范围的结束
:param guess_counrt 猜数字的次数‘‘‘
print(‘请猜出%d~%d之间的任意一个数字你有%d次机会‘%(guess_min,guess_max,guess_counrt))
random_number = random.randint(guess_min, guess_max)
count=guess_counrt
while count:
count -= 1
user_nubmer=number_judge(input(‘请猜:‘))
if user_nubmer==random_number:
print(‘恭喜你猜对了‘)
break
elif not count:
print(‘Game Over‘)
elif user_nubmer > random_number:
print(‘太大在猜一次 (机会%d次)‘%count)
elif user_nubmer < random_number:
print(‘太小在猜一次 (机会%d次)‘%count)
print(‘答案是:%s‘ % random_number)
2. 构造用户外壳函数
def guess_number():
‘‘‘猜数字函数‘‘‘
print(‘欢迎来到猜数字游戏‘)
guess_min = number_judge(input(‘输入开始数字:‘))
guess_max = number_judge(input(‘输入结束数字:‘))
guess_counrt = number_judge(input(‘输入猜取次数:‘))
while True:
guess_core(guess_min, guess_max, guess_counrt)
flag=input(‘结束游戏按 N:‘)
if flag==‘N‘ or flag==‘n‘:
break
default_guess=input(‘重新输入范围按 Y:‘)
if default_guess==‘Y‘ or default_guess==‘y‘:
guess_min = number_judge(input(‘输入开始数字:‘))
guess_max = number_judge(input(‘输入结束数字:‘))
guess_counrt = number_judge(input(‘输入猜取次数:‘))
3. 构造输入判断函数
def number_judge(number):
‘‘‘判断输入数字输入函数‘‘‘
if number.isdigit():
return int(number)
else:
while True:
test=input(‘请输入整数数字:‘)
if test.isdigit():
break
return int(test)
4. 调用执行
guess_number()
以上是关于python 游戏(猜数字)的主要内容,如果未能解决你的问题,请参考以下文章