python 游戏(猜数字)
程序员文章站
2022-07-05 15:09:20
1. 构造猜数字核心函数 2. 构造用户外壳函数 3. 构造输入判断函数 方法1 方法2 4. 调用执行 ......
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. 构造输入判断函数
方法1
def number_judge(number):
'''判断输入数字输入函数'''
if number.isdigit():
return int(number)
else:
while true:
test=input('请输入整数数字:')
if test.isdigit():
break
return int(test)
方法2
def number_judge(number):
'''判断输入数字输入函数'''
while not number.isdigit():
number = input('请输入整数数字:')
return int(number)
4. 调用执行
guess_number()