Python实现猜拳小游戏的多种方式
简介
猜拳小游戏是一个经典的小游戏项目,也是初学者学习编程的必要练手题目之一。在 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循环;
- 增加了用户交互环节,让用户可以选择自己出拳或者输入r随机出拳的功能;
- 记录了游戏结果统计变量(比如用户胜利场数、电脑胜利场数和回合数),并在游戏结束时打印比分结果;
- 在满足三局两胜的条件时结束游戏,并询问用户是否再次开启游戏;
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()
Python实现猜拳小游戏的多种方式的更多相关文章
- Python开发转盘小游戏
Python开发转盘小游戏 Python 一 原理分析 Python开发一个图形界面 有12个选项和2个功能键 确定每个按钮的位置 每个按钮的间隔相同 点击开始时转动,当前选项的背景颜色为红色,其他 ...
- C#之winform 猜拳小游戏
C#之winform 猜拳小游戏 1.建立项目文件 2.进行界面布局 2.1 玩家显示(控件:label) 2.2 显示玩家进行选择的控件(控件:label) 2.3 电脑显示(控件:label) ...
- Java猜拳小游戏(剪刀、石头、布)
1.第一种实现方法,调用Random数据包,直接根据“1.2.3”输出“剪刀.石头.布”.主要用了9条输出判断语句. import java.util.Random; import java.util ...
- 用Python实现童年小游戏贪吃蛇
贪吃蛇作为一款经典小游戏,早在 1976 年就面世了,我最早接触它还是在家长的诺基亚手机中.
- 教你用Python自制拼图小游戏,一起来制作吧
摘要: 本文主要为大家详细介绍了python实现拼图小游戏,文中还有示例代码介绍,感兴趣的小伙伴们可以参考一下. 开发工具 Python版本:3.6.4 相关模块: pygame模块: 以及一些Pyt ...
- python 小鸡飞行小游戏
python 小鸡飞行小游戏 用空格键控制小鸡飞行 代码 import pygame.freetype import sys import random pygame.init() screen = ...
- 用Java编写的猜拳小游戏
学习目标: 熟练掌握各种循环语句 例题: 代码如下: // 综合案例分析,猜拳案例 // isContinue为是否开始游戏时你所输入的值 char isContinue; //y为开始,n为借宿 S ...
- 利用Python完成一个小游戏:随机挑选一个单词,并对其进行乱序,玩家要猜出原始单词
一 Python的概述以及游戏的内容 Python是一种功能强大且易于使用的编程语言,更接近人类语言,以至于人们都说它是“以思考的速度编程”:Python具备现代编程语言所应具备的一切功能:Pytho ...
- python 面向对象编程 - 小游戏
面向对象写的小游戏 欢迎玩耍 class Omnicience: camp = 'Omniscience' def __init__(self, name, atk=100, hp=1000, mp= ...
- python学习-6 猜拳小游戏
import random # 调用随机数模块 pc = random.randint(1,3) # 产生1-3的随机数 print("来玩个猜拳游戏吧!") a = '石头' b ...
随机推荐
- 如何快速在Ubuntu上搭建python环境?
如何快速在Ubuntu上搭建python环境? 一.准备好python源码包 使用curl命令获取python源码包的过程很缓慢且容易失败,因此提前去官网下载好后放在本地是最好的办法. 二.启动镜像并 ...
- day128:MySQL进阶:MySQL安装&用户/权限/连接/配置管理&MySQL的体系结构&SQL&MySQL索引和执行计划
目录 1.介绍和安装 2.基础管理 2.1 用户管理 2.2 权限管理 2.3 连接管理 2.4 配置管理 3.MySQL的体系结构 4.SQL 5.索引和执行计划 1.介绍和安装 1.1 数据库分类 ...
- Looper 源码分析
//可以看到我们的Looper是存放在线程独有的ThreadLocal进行隔离的 //也就是每个线程独有一份Looper static final ThreadLocal<Loope ...
- 互联网常用API收集
百度车联网API:http://lbsyun.baidu.com/index.php?title=car
- numpy常用的操作
以下是NumPy中一些常用的操作及其相应的代码示例: 创建NumPy数组: import numpy as np # 从Python列表创建一维数组 a = np.array([1, 2, 3, 4, ...
- COIG:开源四类中文指令语料库
CHINESE OPEN INSTRUCTION GENERALIST: A PRELIMINARY RELEASE 论文:https://arxiv.org/pdf/2304.07987v1.pdf ...
- 深入理解python虚拟机:程序执行的载体——栈帧
深入理解python虚拟机:程序执行的载体--栈帧 栈帧(Stack Frame)是 Python 虚拟机中程序执行的载体之一,也是 Python 中的一种执行上下文.每当 Python 执行一个函数 ...
- js给元素设置样式
一.style 利用 "[元素].style.[CSS属性名] = [属性值]" 的方法 1 var Box = document.getElementById('box') 2 ...
- .net 6 使用 NEST 查询,时间字段传值踩坑
0x01业务描述 说明: 同事搭建的业务系统,最开始使用 log4net 记录到本地日志. 然后多个项目为了日志统一,全部记录在 Elasticsearch ,使用 log4net.Elastic ...
- Spring源码:Bean的生命周期(二)
前言 让我们继续讲解Spring的Bean实例化过程.在上一节中,我们已经讲解了Spring是如何将Bean定义加入到IoC容器中,并使用合并的Bean定义来包装原始的Bean定义.接下来,我们将继续 ...