首页 > 编程语言 >Python实现猜拳小游戏的多种方式

Python实现猜拳小游戏的多种方式

时间:2023-06-11 13:33:34浏览次数:38  
标签:count computer 猜拳 Python win choice 小游戏 user print

简介

猜拳小游戏是一个经典的小游戏项目,也是初学者学习编程的必要练手题目之一。在 Python 中,我们可以使用多种方式来实现一个简单的猜拳小游戏。

本文将依次介绍六种Python实现猜拳小游戏的方法,包括:使用 if-else 条件语句、使用 random 模块、使用字典映射胜负关系、for循环、while循环、函数。知识点依次堆加,这些方式各有优缺点,但无论哪种方式,都能够帮助初学者熟悉 Python 的编码语法和逻辑思维,更好地理解 Python 的基本数据类型、控制语句等内容;对于专业人士,可以根据具体需求进行选择。

实现方式一:使用 if-else 条件语句

不能使用while循环和for循环还有随机数模块,因此电脑的出拳方式的生成只能通过计算得到,而该算法只能模拟随机数的一部分特性,因此在实际应用中可能存在一定的问题。

注意,这个程序中没有使用while循环或for循环等任何循环语句,因此只会执行一次猜拳游戏。

# 定义常量
ROCK = 1
PAPER = 2
SCISSORS = 3

# 输出欢迎信息
print("欢迎来到猜拳游戏!")
print("游戏规则:")
print("1. 石头胜剪刀")
print("2. 剪刀胜布")
print("3. 布胜石头")

# 定义得分变量
player_score = 0
computer_score = 0
tie_count = 0

# 让玩家输入出拳方式
player_choice = int(input("请输入您的出拳方式(1:石头,2:剪刀,3:布):"))

# 判断玩家的选择
if player_choice == ROCK:
    print("你出了石头")
elif player_choice == PAPER:
    print("你出了剪刀")
else:
    print("你出了布")

# 生成电脑的出拳方式
computer_choice = ((player_score + computer_score + tie_count) % 3) + 1

# 输出电脑的选择
if computer_choice == ROCK:
    print("电脑出了石头")
elif computer_choice == PAPER:
    print("电脑出了剪刀")
else:
    print("电脑出了布")

# 判断输赢并输出结果
if player_choice == ROCK:
    if computer_choice == ROCK:
        print("平局")
        tie_count += 1
    elif computer_choice == PAPER:
        print("电脑获胜")
        computer_score += 1
    else:
        print("你获胜")
        player_score += 1
elif player_choice == PAPER:
    if computer_choice == ROCK:
        print("你获胜")
        player_score += 1
    elif computer_choice == PAPER:
        print("平局")
        tie_count += 1
    else:
        print("电脑获胜")
        computer_score += 1
else:
    if computer_choice == ROCK:
        print("电脑获胜")
        computer_score += 1
    elif computer_choice == PAPER:
        print("你获胜")
        player_score += 1
    else:
        print("平局")
        tie_count += 1

# 输出得分情况
print(f"您的得分:{player_score},电脑的得分:{computer_score},平局次数:{tie_count}")

实现方式二:使用 random 模块

在使用if语句的基础上通过引入 Python 的 random 模块,实现电脑随机产生手势的功能。

注意,这个程序中没有使用while循环或for循环等任何循环语句,因此只会执行一次猜拳游戏。

# 使用 random 模块实现猜拳小游戏

import random

# 按照石头剪刀布的胜负规则判断输赢
def who_win(user_input, computer_input):
    win_list = [["石头","剪刀"], ["剪刀","布"], ["布","石头"]]
    if user_input == computer_input:
        return 0
    elif [user_input,computer_input] in win_list:
        return 1
    else:
        return -1

while True:
    # 玩家输入手势
    user_choice = input("请选择(石头/剪刀/布):")

    # 随机生成电脑的手势
    computer_choice = random.choice(["石头", "剪刀", "布"])
    print("电脑选择:", computer_choice)

    # 判断胜负
    result = who_win(user_choice, computer_choice)

    if result == 0:
        print("平局,再来一局!")
    elif result == 1:
        print("你赢了!")
    else:
        print("你输了!")

    # 是否再来一局
    play_again = input("是否再来一局?(y/n)")
    if play_again.lower() != "y":
        break

实现方式三:使用字典映射胜负关系

使用if语句与随机数模块和一个字典来映射石头剪刀布的胜负规则,并根据用户和计算机输入的选项对应的键值找到其胜出的选项

# 使用字典映射实现猜拳小游戏

import random

# 定义一个字典,表示石头剪刀布的胜负关系
dict = {"石头": "剪刀", "剪刀": "布", "布": "石头"}

while True:
    # 玩家输入手势
    user_choice = input("请选择(石头/剪刀/布):")

    # 随机生成电脑的手势
    computer_choice = random.choice(["石头", "剪刀", "布"])
    print("电脑选择:", computer_choice)

    # 判断胜负
    if dict[user_choice] == computer_choice:
        print("你赢了!")
    elif user_choice == computer_choice:
        print("平局!")
    else:
        print("你输了!")

    # 是否再来一局
    play_again = input("是否再来一局?(y/n)")
    if play_again.lower() != "y":
        break

实现方式四:for循环

这种实现方式使用if语句、随机数模块和一个字典来映射石头剪刀布的胜负规则,并使用for循环来实现猜拳小游戏

import random  
  
# 定义石头剪刀布的胜负规则  
rules = {  
    "rock": {  
        "scissors": "你赢了!",  
        "paper": "你输了!"  
    },  
    "paper": {  
        "rock": "你赢了!",  
        "scissors": "你输了!"  
    },  
    "scissors": {  
        "paper": "你赢了!",  
        "rock": "你输了!"  
    }  
}  

# 循环玩5局游戏  
for i in range(5):  
    # 生成随机选择  
    player_choice = random.choice(["rock", "paper", "scissors"])  
    computer_choice = random.choice(["rock", "paper", "scissors"])  
    print("你的选择:{}".format(player_choice))  # 输出玩家选择  
    print("电脑的选择:{}".format(computer_choice))  # 输出电脑选择  
  
    # 判断胜负关系并输出结果  
    if player_choice == computer_choice:  
        print("平局!")  # 如果玩家和电脑选择一样,则平局  
    elif rules[player_choice][computer_choice] == "你赢了!":  
        print(rules[player_choice][computer_choice])  # 如果玩家选择战胜电脑选择,则输出玩家胜利信息  
    else:  
        print(rules[computer_choice][player_choice])  # 如果电脑选择战胜玩家选择,则输出电脑胜利信息 

实现方式五:while循环

在原有基础上进行修改,将for循环替换为while循环;

  1. 增加了用户交互环节,让用户可以选择自己出拳或者输入r随机出拳的功能;
  2. 记录了游戏结果统计变量(比如用户胜利场数、电脑胜利场数和回合数),并在游戏结束时打印比分结果;
  3. 在满足三局两胜的条件时结束游戏,并询问用户是否再次开启游戏;
import random

# 定义一个字典,用于映射石头剪刀布的胜负规则
rps_dict = {'石头': '剪刀', '剪刀': '布', '布': '石头'}

# 初始化用户选择和电脑选择
user_choice = None
computer_choice = None

# 初始化游戏结果统计变量
user_win_count = 0
computer_win_count = 0
round_count = 0

# 使用while循环实现猜拳小游戏
while True:
    # 打印提示信息
    print("欢迎来到猜拳游戏!")
    print("请输入石头、剪刀或布(输入r表示随机选择):")

    # 获取用户输入
    user_input = input().strip().lower()

    # 如果用户输入为r,则随机选择石头、剪刀或布
    if user_input == 'r':
        computer_choice = random.choice(list(rps_dict.values()))

    # 如果用户输入为有效的选项,则将其转换为对应的值并赋值给user_choice和computer_choice
    elif user_input in list(rps_dict.keys()):
        user_choice = user_input
        computer_choice = rps_dict[user_input]

    # 如果用户输入无效,则提示错误信息并继续循环
    else:
        print("输入无效,请重新输入!")
        continue

    # 判断胜负并输出结果
    if user_choice == computer_choice:
        print("平局!")
    elif (user_choice == '石头' and computer_choice == '剪刀') or \
         (user_choice == '剪刀' and computer_choice == '布') or \
         (user_choice == '布' and computer_choice == '石头'):
        print("恭喜你,你赢了!")
        user_win_count += 1
    else:
        print("很遗憾,你输了。")
        computer_win_count += 1

    # 打印本局游戏的结果
    print(f"你出了{user_choice},电脑出了{computer_choice}")
    print(f"当前比分:你 {user_win_count} - {computer_win_count} 电脑\n")

    # 增加回合数并判断是否达到三局两胜的条件
    round_count += 1
    if user_win_count == 2:
        print("你已经获得三局两胜了,你赢了!")
        break
    elif computer_win_count == 2:
        print("很遗憾,电脑获得了三局两胜,你输了!")
        break

    # 根据用户的选择决定是否继续游戏
    replay = input("是否再玩一局?(y/n)").strip().lower()
    if replay != 'y':
        break

# 询问用户是否再次开启游戏
play_again = input("是否再次开启游戏?(y/n)").strip().lower()
if play_again == 'y':
    exec(open(__file__).read())
else:
    print("游戏结束!")

实现方式六:函数

对while循环的代码进行重构使用函数进行优化

import random
from time import sleep

# 定义一个字典,用于映射石头剪刀布的胜负规则
rps_dict = {'石头': {'name': '石头', 'defeat': '布'},
            '剪刀': {'name': '剪刀', 'defeat': '石头'},
            '布': {'name': '布', 'defeat': '剪刀'}}

# 清屏函数,用于在每次输出前清空屏幕
def clear_screen():
    print('\033c', end='')

# 美化输出函数,用于打印美观的输出界面
def print_beautiful(message):
    print('='*50)
    print(f"{message:^50}")
    print('='*50)

# 获取用户输入函数,用于获取用户选择
def get_user_choice():
    while True:
        user_input = input("请选择 石头、剪刀、布:")
        if user_input not in rps_dict:
            print_beautiful("选择无效,请重新选择")
        else:
            break
    return rps_dict[user_input]

# 电脑随机选择函数
def get_computer_choice():
    return random.choice(list(rps_dict.values()))

# 判断胜负函数
def judge(user_choice, computer_choice):
    if user_choice == computer_choice:
        result = "平局!"
        winner = None
    elif user_choice['defeat'] == computer_choice['name']:
        result = "很遗憾,你输了。"
        winner = 'computer'
    else:
        result = "恭喜你,你赢了!"
        winner = 'user'
    return result, winner

# 打印结果函数
def print_result(result, user_choice, computer_choice):
    print_beautiful(result)
    sleep(1)
    print(f"你出了【{user_choice['name']}】,电脑出了【{computer_choice['name']}】")

# 根据胜负结果更新胜利次数函数
def update_win_count(winner, win_count):
    if winner == 'user':
        win_count['user'] += 1
    elif winner == 'computer':
        win_count['computer'] += 1

# 打印当前比分函数
def print_score(win_count):
    print(f"当前比分:你 {win_count['user']} - {win_count['computer']} 电脑\n")

# 判断是否达成胜利条件函数
def check_victory(win_count):
    if win_count['user'] == 2:
        print_beautiful("恭喜你,你已经获得三局两胜了,你赢了!")
        return True
    elif win_count['computer'] == 2:
        print_beautiful("很遗憾,电脑获得了三局两胜,你输了!")
        return True
    else:
        return False

# 再玩一局函数
def ask_replay():
    while True:
        replay = input("是否再玩一局?(y/n)").strip().lower()
        if replay not in ['y', 'n']:
            print_beautiful("输入无效,请重新输入")
        else:
            break
    return replay == 'y'

# 游戏结束函数
def game_over():
    print_beautiful("游戏结束!")
    sleep(2)

# 主函数,实现游戏逻辑
def main():
    clear_screen()
    print_beautiful("欢迎来到猜拳游戏!")
    win_count = {'user': 0, 'computer': 0}

    while True:
        user_choice = get_user_choice()
        computer_choice = get_computer_choice()

        result, winner = judge(user_choice, computer_choice)
        print_result(result, user_choice, computer_choice)
        update_win_count(winner, win_count)
        print_score(win_count)

        if check_victory(win_count):
            if not ask_replay():
                break
            else:
                win_count = {'user': 0, 'computer': 0}
                clear_screen()
            
    game_over()

if __name__ == '__main__':
    main()

标签:count,computer,猜拳,Python,win,choice,小游戏,user,print
From: https://www.cnblogs.com/Hang666/p/17472848.html

相关文章

  • python数组避坑操作(比如删除数组中的所有0)
    一、演示坑tracks=[0,0,0,1,1,1]fortrackintracks:iftrack==0:tracks.remove(track)print(tracks)#[0,1,1,1]发现:有一个0没有被删去,why???二、这次遍历时,带上索引打印tracks=[0,0,0,1,1,1]forindex,trackinenumerate(tracks......
  • python变量前的星号
    变量前单星号表示将参数转化成元组变量前双星号表示将参数转化成字典函数传参顺序从左到右(一般):位置参数、默认参数、单星号参数、关键字传参、双星号参数传参解压功能单星号对list或元组进行解压,输入的参数不是一个list或元组,而是其中的元素。双星号对字典进......
  • python整型/字符串/浮点 地址
    相同整数/浮点数/字符串-同一内存地址不同整数/浮点数/字符串-不同内存地址......
  • 日报 python
    (一)、中国大学排名数据分析与可视化;(写到实验报告中)【源代码程序】importrequestsfrombs4importBeautifulSoupasbsimportpandasaspdfrommatplotlibimportpyplotasplt  defget_rank(url):   count=0   rank=[]   headers={     ......
  • 盘点一个Python自动化办公过程中Excel数据为空的处理
    大家好,我是皮皮。一、前言前几天在Python群,粉丝问了一个Python自动化办公的问题,这里拿出来给大家分享下。这个问题相信很多人都会遇到,原始Excel数据中,这个【编号】列一般是有相关数据的,但是如果没有的话,就先写为“暂无编号”,如下图所示:后来发现通过Python代码,将其写入到word文件,不......
  • 盘点一个Python网络爬虫问题
    大家好,我是皮皮。一、前言前几天在Python最强王者群【刘桓鸣】问了一个Python网络爬虫的问题,这里拿出来给大家分享下。他自己的代码如下:importrequestskey=input("请输入关键字")res=requests.post(url="https://jf.10086.cn/cmcc-web-shop/search/query",data=......
  • 【视频】随机波动率SV模型原理和Python对标普SP500股票指数预测|数据分享|附代码数据
    全文链接:http://tecdat.cn/?p=22546最近我们被客户要求撰写关于随机波动率SV模型的研究报告,包括一些图形和统计输出。什么是随机波动率?随机波动率(SV)是指资产价格的波动率是变化的而不是恒定的“随机”一词意味着某些变量是随机确定的,无法精确预测。在金融建模的背景下,随......
  • 用Python白嫖WPS付费功能:把PPT转为 1张 长图,1行代码搞定
    大家好,这里是程序员晚枫,小红薯也叫这个名。读者群......
  • Python爬虫--BOSS直聘网Python相关职业招聘信息
    一、选题的背景为什么要选择此选题?要达到的数据分析目标是什么?从社会、经济、技术、数据来源等方面进行描述(200字以内)(10分)   最近Python大热,Python在数据分析、后端开发、人工智能、运维、全栈开发等多方面都具有得天独厚的优势。在一些行业爬虫工程师,人工智能,爬虫工程......
  • Python网络爬虫对汽车团购报名的爬取及分析
    一、选题背景 现如今汽车已逐步进入家庭中,对于一些准备购入新车的家庭,犹豫不决,不知道现在市场上与车友们推荐的哪些车,此次爬虫项目将对网上的团购排名进行爬取,更能简单直观的让大家依据个人情况来挑选自己中意的车辆详情。二、设计方案1.主题式网络爬虫名称  《python网络......