1. 程式人生 > >Python入門——石頭剪刀布程式

Python入門——石頭剪刀布程式

概述:

如果你和我一樣是一個有著其他語言基礎的程式設計者,那我想這個小程式對於你來說是小case。由於本人初學Python,就先拿這個熟悉熟悉一下語法,就不再是以前大家都愛用的Hello World了。

流程圖:


程式碼如下:

import random

# define a function for get winner
# 1: Scissor
# 2: Stone
# 3: Cloth
def get_winner(you, me):
    if you == me:
        return 0
    
    if you == 1:
        if me == 2:
            return -1
        else:
            return 1

    if you == 2:
        if me == 1:
            return 1
        else:
            return -1

    if you == 3:
        if me == 2:
            return 1
        else:
            return -1

# define a function for get Label for finger
def get_lable(finger):
    if finger == 1:
        return "Scissor"
    elif finger == 2:
        return "Stone"
    else:
        return "Cloth"

you = raw_input("Your Finger is:")
while int(you) > 0:
    you = int(you) % 3
    
    if you == 0:
        you = 3

    me = random.randint(1, 3)
    print "your finger is %s and my finger is %s" % (get_lable(you), get_lable(me))
    
    result = get_winner(you, me)
    
    if result == -1:
        print "I Win."
    elif result == 1:
        print "You Win."
    else:
        print "No winner."
    
    you = raw_input("Your Finger is:")

print "END"