石头剪刀布这个游戏相信大家都玩过,现在让你写一个程序来模拟一下这个游戏。要求: 1.你需要输入你想输入的手势(手势用拼音输入) 2.电脑随机生成一个手势 3.比较输赢
关于手势在程序中的表达,我们可以不用字符串来表达,仅用手势的第一个字母的ASCII的序号来表示一个手势。碰巧的是这三个手势的开头都不同,所以放心的用吧。 关于电脑生成手势,其实只需要知道三个手势的首字母的ASCII码,并在三个ASCII码中随机选取一个就搞定了。 比较输赢,其实规则我们已经知道了。可以用枚举直接搞定。
import random def computerrandom(): m = random.sample([115, 106, 98], 1)[0] if m == 98: print('电脑随机选择的手势为: bu') if m == 106: print('电脑随机选择的手势为: jiandao') if m == 115: print('电脑随机选择的手势为: shitou') return m def choose(select2): if select2 == 115: handleshitou(m) elif select2 == 98: handlebu(m) elif select2 == 106: handlejiandao(m) def handleshitou(m): if m == 106: print('You win') if m == 98: print('Computer win') if m == 115: print('Your choose is the same as the computer') def handlebu(m): if m == 106: print('Computer win') if m == 98: print('Your choose is the same as the computer') if m == 115: print('You win') def handlejiandao(m): if m == 98: print('You win') if m == 115: print('Computer win') if m == 106: print('Your choose is the same as the computer') select = input('请输入你要选择的手势: ') select1 = select[0] select2 = ord(select1) m = computerrandom() choose(select2)注意一下在代码中我们用数字代表了手势,或许你会想通过数字比较来判断输赢岂不美滋滋。并不是这样的,在代码中我们用98代表布,115代表石头,106代表剪刀。试想一下如果直接比较大小会出现什么情况:115比98大,但是布是可以赢石头的!(当然可以用cmp()函数,因为cmp()函数返回值有三种情况,所以说可以判断,不过在这里既然已经知道了规则就直接枚举把,因为规则比简单)需要注意一下m是一个全局变量。
m = random.sample([115, 106, 98], 1)[0]注意一下这段代码最后的[0],如果没有[0]那么会生成一个列表,加上[0]之后就会生成一个整数。测试结果如下:
请输入你要选择的手势: shitou 电脑随机选择的手势为: shitou Your choose is the same as the computer 请输入你要选择的手势: bu 电脑随机选择的手势为: jiandao Computer win 请输入你要选择的手势: jiandao 电脑随机选择的手势为: shitou Computer win之前没有排版好,重发一下。有两个数字错了,再次修改。