来源:http://blog.csdn.net/sun7545526/article/details/8138603
需求:设计一个”石头,剪子,布”游戏,有时又叫”Rochambeau”,你小时候可能玩过,下面是规则.你和你的对手,在同一时间做出特定的手势,必须是下面一种手势:石头,剪子,布.胜利者从
下面的规则中产生,这个规则本身是个悖论.
(a) 布包石头.
(b)石头砸剪子,
(c)剪子剪破布.在你的计算机版本中,用户输入她/他的选项,计算机找一个随机选项,然后由你
的程序来决定一个胜利者或者平手.注意:最好的算法是尽量少的使用 if 语句.
曾经实现过一个java版本的,用的思路是通过Enum分发的方式来实现,那种实现方式灵活性相对较强,但是代码量还是较多.现在正在学习python,所以用python实现了一个简单的版本,代码的数量上还是有明显的减少[本人是新手,不足请指教]:
''' demonstrate Stone, Stainless, Paper game Created on 2012-11-1 @author: Eric ''' import random; #elementA-->DRAW WIN LOST COMPETE_RESULT = {"Stone":["Stone", "Stainless", "Paper"], "Stainless":["Stainless", "Paper", "Stone"], "Paper":["Paper", "Stone", "Stainless"]}; SIGN = {0:"Stone", 1:"Stainless", 2:"Paper"} RESULTS = {0:"DRAW", 1:"WIN", 2:"LOST"}; def rochambeauGame(): print('''0:STONE 1:STAINLESS 2:Paper 3:quit '''); while True: userSign = input("please input your userSign number:"); if int(userSign) in (1, 2, 3, 0): if userSign == 0: exit(); else: userSignResults = COMPETE_RESULT[SIGN[int(userSign)]]; pcSign = SIGN[int(genereteRandomPCSign())]; print("User Sign:" + SIGN[int(userSign)] + " PC Sign:" + pcSign + " \n####result is: user " + RESULTS[userSignResults.index(pcSign)]); else: print("please input correctly order"); #generate a random number,[0,2] def genereteRandomPCSign(): return random.randrange(3); if __name__ == '__main__': rochambeauGame();