【python小项目】python剪刀石头布游戏

在这里插入图片描述


python剪刀石头布游戏



1. 项目要求

剪刀石头布是大家平时常玩的一种娱乐小游戏,这个游戏的主要目的是为了解决争议,因为三者相互制约,因此不论平局几次,总会有胜负的时候。游戏规则中,石头克剪刀,剪刀克布,布克石头。请使用python语句实现剪刀石头布游戏。具体要求如下

(1)用户输入石头剪布中任意字符串:
(2)电脑随机产生石头剪刀\布中任意字符串
(3)在每一轮中,若用户取得胜利则退出游戏,否则重新开始游戏


2. 代码实现

import random

def computer_choice():
    """电脑随机产生选择"""
    return random.choice(['石头', '剪刀', '布'])

def game_result(user, computer):
    """判断游戏结果"""
    if user == computer:
        return "平局"
    elif (user == '石头' and computer == '剪刀') or \
         (user == '剪刀' and computer == '布') or \
         (user == '布' and computer == '石头'):
        return "用户胜"
    else:
        return "电脑胜"

def play_game():
    """主游戏逻辑"""
    while True:
        user_input = input("请输入石头、剪刀或布:")
        if user_input not in ['石头', '剪刀', '布']:
            print("输入错误,请重新输入!")
            continue

        comp_input = computer_choice()
        print(f"电脑选择了:{comp_input}")

        result = game_result(user_input, comp_input)
        print(result)

        if result == "用户胜":
            print("恭喜您赢了!")
            break
        else:
            print("请重新开始游戏!")

if __name__ == "__main__":
    play_game()


3. 代码分析

当然可以。以下是对“剪刀石头布”游戏的代码分析:

import random

代码分析

  • 导入random模块,这是为了后续随机生成电脑的选择。
def computer_choice():
    """电脑随机产生选择"""
    return random.choice(['石头', '剪刀', '布'])

代码分析

  • computer_choice函数模拟了电脑的随机选择。通过使用random.choice函数从列表['石头', '剪刀', '布']中随机选取一个元素作为结果。
def game_result(user, computer):
    """判断游戏结果"""
    if user == computer:
        return "平局"
    elif (user == '石头' and computer == '剪刀') or \
         (user == '剪刀' and computer == '布') or \
         (user == '布' and computer == '石头'):
        return "用户胜"
    else:
        return "电脑胜"

代码分析

  • game_result函数根据玩家和电脑的选择判断游戏结果。
  • 如果玩家和电脑的选择相同,结果是“平局”。
  • 通过一系列条件检查,判断玩家是否胜出。如玩家选择’石头’且电脑选择’剪刀’,则玩家胜出。
  • 如果不满足上述条件,电脑则胜出。
def play_game():
    """主游戏逻辑"""
    while True:
        user_input = input("请输入石头、剪刀或布:")
        if user_input not in ['石头', '剪刀', '布']:
            print("输入错误,请重新输入!")
            continue

        comp_input = computer_choice()
        print(f"电脑选择了:{comp_input}")

        result = game_result(user_input, comp_input)
        print(result)

        if result == "用户胜":
            print("恭喜您赢了!")
            break
        else:
            print("请重新开始游戏!")

代码分析

  • play_game函数是游戏的主逻辑。
  • 使用一个while循环来确保游戏继续进行,直到玩家胜出为止。
  • 获取玩家的输入并检查其有效性。
  • 获取电脑的随机选择并显示。
  • 使用game_result函数判断游戏结果,并根据结果输出相应消息。
  • 如果玩家胜出,结束游戏;否则,继续下一轮。
if __name__ == "__main__":
    play_game()

代码分析

  • 当此脚本被直接运行时,play_game函数会被调用,启动游戏。
  • 如果此脚本被作为模块导入,则不会自动启动游戏。
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值