python 小游戲之搖骰子猜大小


最近學習Python的隨機數,邏輯判斷,循環的用法,就想找一些練習題,比如小游戲猜大小,程序思路如下:

開發環境:python2.7 , 附上源代碼如下:

搖骰子的函數,這個函數其實並不需要傳任何參數,調用后會返回三個點數結果的列表。

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

接着再用一個函數來將點數轉化成大小

def roll_result(total):
    isBig = 11 <=total <= 18
    isSmall = 3 <= total <= 10
    if isBig:
        return 'Big'
    elif isSmall:
        return 'Small'

最后,創建一個開始游戲的函數,讓用戶輸入猜大小,並且定義什么是猜對,什么是猜錯,並輸出對應的輸贏結果。

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()

完成這個小游戲之后,你就可以試着和自己設計的程序玩猜大小了。同時你也掌握了循環和條件判斷混用的方法,初步具備了設計更復雜的程序的能力了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM