最近學習Python的隨機數,邏輯判斷,循環的用法,就想找一些練習題,好比小遊戲猜大小,程序思路以下:html
開發環境:python2.7 , 附上源代碼以下:python
搖骰子的函數,這個函數其實並不須要傳任何參數,調用後會返回三個點數結果的列表。app
import random def roll_dice(numbers=3,points=None): print ('<<<<< ROLL THE DICE! >>>>>') if points is None: points = [] while numbers > 0: point = random.randint(1,6) points.append(point) numbers = numbers-1 return points
接着再用一個函數來將點數轉化成大小dom
def roll_result(total): isBig = 11 <=total <= 18 isSmall = 3 <= total <= 10 if isBig: return 'Big' elif isSmall: return 'Small'
最後,建立一個開始遊戲的函數,讓用戶輸入猜大小,而且定義什麼是猜對,什麼是猜錯,並輸出對應的輸贏結果。python2.7
def start_game(): print ('<<<<< GAME STARTS! >>>>>') choices=['Big','Small'] your_choice=raw_input('Big or Small') if your_choice in choices: points = roll_dice() total = sum(points) youWin = your_choice == roll_result(total) if youWin: print('The points are',points,'You win !') else: print('The points are',points,'You lose !') else: print('Invalid Words') start_game() start_game()
完成這個小遊戲以後,你就能夠試着和本身設計的程序玩猜大小了。同時你也掌握了循環和條件判斷混用的方法,初步具有了設計更復雜的程序的能力了。函數