python关于石头剪刀布的一道题

题目

石头剪刀布这个游戏相信大家都玩过,现在让你写一个程序来模拟一下这个游戏。要求:
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

之前没有排版好,重发一下。有两个数字错了,再次修改。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值