1. 構造猜數字核心函數 2. 構造用戶外殼函數 3. 構造輸入判斷函數 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()
python學習途徑
本游戲參考書本 <<Python游戲編程快速上手>>
友情推薦: 猿人學Python【https://www.yuanrenxue.com/】 由一群工作十餘年的老程式員結合實際工作經驗所寫的Python教程。