python 实现21根火柴游戏

Posted 学python的蜗牛

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 实现21根火柴游戏相关的知识,希望对你有一定的参考价值。

游戏规则::有21根火柴,人和计算机轮流拿,人先拿(输入拿几根)计算机后拿,每次至少1根最多4根,拿到最后一根火柴的算输,要确保计算机一定可以获胜

tips:保证计算机最后能拿到20,所以就不能取16~19之间,只能取到15,以此类推,计算机取的火柴数必须使总数到达5,10,15和20。

代码如下:

rint("规则:一次自能取1~4根火柴,最后取到21为输家")
#total代表取出的火柴总数
total = 0
while True:
    person = int(input('人取多少根火柴: '))       #person表示人取出的火柴数
    total += person
    print(f'当前取出火柴总数为{total},还剩下{21 - total}')
    if total < 5:
        computer = 5 - total                        # computer表示计算机取出的火柴数
        total += computer
        print(f'计算机拿{computer}根')
        print(f'当前取出火柴总数为{total},还剩下{21 - total}')
    elif total < 10 :
        computer = 10 - total
        total += computer
        print(f'计算机拿{computer}根')
        print(f'当前取出火柴总数为{total},还剩下{21 - total}')
    elif total < 15:
        computer = 15 - total
        total += computer
        print(f'计算机拿{computer}根')
        print(f'当前取出火柴总数为{total},还剩下{21 - total}')
    elif total < 20 :
        computer = 20 - total
        total += computer
        print(f'计算机拿{computer}根')
        print(f'当前取出火柴总数为{total},还剩下{21 - total}')
    else:
        print("游戏结束")
        break

结果如下:

以上是关于python 实现21根火柴游戏的主要内容,如果未能解决你的问题,请参考以下文章