Python入门小游戏:剪刀石头布

经过前几天的学习,相信小白们已经对Python有了初步的了解和掌握了。

下面,教你们一个入门小游戏,石头剪刀布。

在这个游戏里,我们用到了一个循环:for循环,引用了一个random库。

我们知道,石头剪刀布的游戏规则,石头赢剪刀,剪刀赢布,布赢石头,那么,在Python代码中,它们应该怎么表示呢,我们一起来看。

from random import randint
userWin = 0
computerWin = 0
deuce = 0
# enmerate 列举 枚举
for index,value in enumerate(range(3)):
    # index 代表编号 value 代表值
    userNum = input('请输入数字:')
    userNum = int(userNum)
    computerNum = randint(0,2)

首先我们看这几行代码,开头引用了一个random库中的randint,

我们定义了“玩家赢“”电脑赢“和”平局“,那么,我们如何去输入呢。

看下面,我们会发现一行for in结构的代码:for in结构就是循环结构,循环也叫迭代。

range为范围,index是编号。

我们定义电脑输出值的范围是(0,2)也就是0,1,2.

    if userNum - computerNum == -1 or userNum - computerNum == 2:
        print('第{}局玩家胜利!'.format(index + 1))
        userWin += 1
    elif userNum - computerNum == 0 :
        print('第{}局平局'.format(index + 1))
        deuce += 1
    else:
        print('第{}局电脑胜!'.format(index + 1))
        computerWin += 1
    print('-----------第{}局结束------------'.format(index + 1))

接下来用if语句来判断猜拳的胜负,不难看出此中的逻辑关系,接着下一步,

    if computerWin == 2:
        print('电脑胜利!')
        break
    elif userWin == 2:
        print('玩家胜利!')
        break
    else:
        if deuce == 3:
            print('平局了!')
        elif deuce == 1 and userWin - computerNum == 0 and index == 2:
            print('平局了!')
        elif deuce == 2 and index == 2:
            if userWin - computerWin == 1:
                print('玩家胜利!')
            else:
                print('电脑胜利!')

设置三局两胜制,这里一定要考虑到所有的情况,才能确保不出现bug。

好了,废话少说,下面源码献给你们,尽情享受Python的乐趣吧!

from random import randint
userWin = 0
computerWin = 0
deuce = 0
# enmerate 列举 枚举
for index,value in enumerate(range(3)):
    # index 代表编号 value 代表值
    userNum = input('请输入数字:')
    userNum = int(userNum)
    computerNum = randint(0,2)

    if userNum - computerNum == -1 or userNum - computerNum == 2:
        print('第{}局玩家胜利!'.format(index + 1))
        userWin += 1
    elif userNum - computerNum == 0 :
        print('第{}局平局'.format(index + 1))
        deuce += 1
    else:
        print('第{}局电脑胜!'.format(index + 1))
        computerWin += 1
    print('-----------第{}局结束------------'.format(index + 1))

    if computerWin == 2:
        print('电脑胜利!')
        break
    elif userWin == 2:
        print('玩家胜利!')
        break
    else:
        if deuce == 3:
            print('平局了!')
        elif deuce == 1 and userWin - computerNum == 0 and index == 2:
            print('平局了!')
        elif deuce == 2 and index == 2:
            if userWin - computerWin == 1:
                print('玩家胜利!')
            else:
                print('电脑胜利!')



  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值