6-14.
随机数。设计一个“石头、剪子、布”游戏,有时又叫“Rochambeau”,你小时候可能玩过,下面是规则。你和你的对手,在同一时间做出特定的手势,必须是下面一种:石头、剪子、布。胜利者从下面的规则产生,这个规则本身是个悖论。
(a)布包石头。
(b)石头砸剪子。
(c)剪子剪破布。在你的计算机版本中,用户输入他/她的选项,计算机找一个随机选项,然后由你的程序来决定一个胜利者或者平手。注意,最好的算法是尽量少使用if语句。
#-*- coding: utf-8 -*
import random
RCB = ['R','C','B']
win = ['RC','CB','BR']
def Stone(a):
b = random.choice(RCB)
pstr = 'Your:[ %s ] VS Computer:[ %s ] ' %(a,b)
if a == b:
print pstr,u'平局!'
elif a+b in win:
print pstr,u'你赢了:)'
else:
print pstr,u'你输了:('
def showmenu():
pr = """
(R)ock
(C)ham
(B)eau
(Q)uit
enter your RCB: """
while True:
while True:
try:
choice = raw_input(pr).strip()[0].upper()
except (EOFError,KeyboardInterrupt,IndexError):
choice = 'Q'
print '\nYou picked: [%s]' %choice
if choice not in 'RCBQ':
print 'Ivalid option, must in %s or \'Q\', try again!' %RCB
else:
break
if choice == 'Q':
break
Stone(choice)
if __name__ == '__main__':
showmenu()