本文主要介紹如何用Python設計一個經典小游戲:猜大小。
在這個游戲中,將用到前面我介紹過的所有內容:變量的使用、參數傳遞、函數設計、條件控制和循環等,做個整體的總結和復習。
游戲規則:
初始本金是1000元,默認賠率是1倍,贏了,獲得一倍金額,輸了,扣除1倍金額。
程序運行結果是這樣的:

現在,我們來梳理下思路。
梳理清楚思路后,接下來開始敲代碼。
搖骰子:
定義roll_dice函數,3個骰子,循環次數numbers為3,骰子點數points初始值為空,這里的參數傳遞用到的是之前講到的關鍵詞參數傳遞。
隨機數生成用import random來實現。Python中最方便的就是有很多強大的庫支持,現在我們可以直接導入一個random的內置庫,用它來生成隨機數。如:
1 import random2 point = random.randrange(1,7)3 # random.randrange(1,7)生成1-6的隨機數4 print(point)
print(point)后可以看到打印出的隨機數,每次運行結果都是隨機的。
接下來我們看下搖骰子這部分的完整代碼:
import randomdef roll_dice(numbers = 3,points = None): print('----- 搖骰子 -----') if points is None: points = [] # points為空列表,后續可以插入新值到該列表 while numbers > 0: point = random.randrange(1,7) points.append(point) # 用append()方法將point數值插入points列表中 numbers = numbers - 1 # 完成一次,numbers減1,當小于等于0時不再執行該循環 return points定大?。?/strong>
11≤骰子總數≤18為大,3≤骰子總數≤10為小,代碼如下:
def roll_result(total): isBig = 11 <= total <=18 isSmall = 3 <= total <= 10 if isBig: return '大' elif isSmall: return '小'
玩游戲:
初始本金1000元,默認賠率1倍;贏了,獲得一倍金額,輸了,扣除1倍金額;本金為0時,游戲結束。
def start_game(): your_money = 1000 while your_money > 0: print('----- 游戲開始 -----') choices = ['大','小'] # choices賦值為大和小,用戶需輸入二者之一為正確 your_choice = input('請下注,大 or 小:') your_bet = input('下注金額:') if your_choice in choices: points = roll_dice() # 調用roll_dice函數 total = sum(points) # sum為相加,將3個骰子的結果相加 youWin = your_choice == roll_result(total) if youWin: print('骰子點數:',points) print('恭喜,你贏了 {} 元,你現在有 {} 元本金'.format(your_bet,your_money + int(your_bet))) # your_bet是字符串格式,這里需要轉化為int類型進行計算 your_money = your_money + int(your_bet) # 最新本金 else: print('骰子點數:',points) print('很遺憾,你輸了 {} 元,你現在有 {} 元本金'.format(your_bet, your_money - int(your_bet))) your_money = your_money - int(your_bet) else: print('格式有誤,請重新輸入') # 如果輸入的不是choices列表中的大或小,則為格式有誤 else: print('游戲結束')start_game()到這里,我們就完成了該游戲三大部分的設計,大家一定要仔細思考,梳理設計思路,動手敲出代碼才好。
最后,附【猜大小】游戲的完整代碼:
import randomdef roll_dice(numbers = 3,points = None): print('----- 搖骰子 -----') if points is None: points = [] while numbers > 0: point = random.randrange(1,7) points.append(point) numbers = numbers - 1 return pointsdef roll_result(total): isBig = 11 <= total <=18 isSmall = 3 <= total <= 10 if isBig: return '大' elif isSmall: return '小'def start_game(): your_money = 1000 while your_money > 0: print('----- 游戲開始 -----') choices = ['大','小'] your_choice = input('請下注,大 or ?。?#39;) your_bet = input('下注金額:') if your_choice in choices: points = roll_dice() total = sum(points) youWin = your_choice == roll_result(total) if youWin: print('骰子點數:',points) print('恭喜,你贏了 {} 元,你現在有 {} 元本金'.format(your_bet,your_money + int(your_bet))) your_money = your_money + int(your_bet) else: print('骰子點數:',points) print('很遺憾,你輸了 {} 元,你現在有 {} 元本金'.format(your_bet, your_money - int(your_bet))) your_money = your_money - int(your_bet) else: print('格式有誤,請重新輸入') else: print('游戲結束')start_game()以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持VEVB武林網!
新聞熱點
疑難解答