VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > python入门教程 >
  • 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循环等任何循环语句,因此只会执行一次猜拳游戏。


 
import random # 引入 random 模块,用于产生随机数
 
 
 
print("欢迎来到猜拳游戏!")
 
print("请出拳:1-石头,2-剪刀,3-布")
 
 
 
# 获取用户输入,将输入转换成整型数字
 
user_input = int(input())
 
 
 
# 电脑随机出拳,使用 random.choice 随机从列表中选择一个元素
 
computer_choice = random.choice(["石头", "剪刀", "布"])
 
 
 
# 判断胜负
 
if (user_input == 1 and computer_choice == "剪刀") or \
 
(user_input == 2 and computer_choice == "布") or \
 
(user_input == 3 and computer_choice == "石头"):
 
print("你赢了!电脑出了", computer_choice)
 
elif (user_input == 1 and computer_choice == "布") or \
 
(user_input == 2 and computer_choice == "石头") or \
 
(user_input == 3 and computer_choice == "剪刀"):
 
print("你输了!电脑出了", computer_choice)
 
else:
 
print("平局!电脑出了", computer_choice)
 
 

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

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


 
# 使用字典映射实现猜拳小游戏
 
 
 
import random # 引入 random 模块,用于产生随机数
 
 
 
# 定义字典,映射石头、剪刀、布分别击败什么
 
rule_dict = {'石头': '剪刀', '剪刀': '布', '布': '石头'}
 
 
 
# 用户出拳
 
print('猜拳开始,请出拳(石头、剪刀、布):')
 
user_choice = input()
 
 
 
# 电脑出拳,从列表['石头', '剪刀', '布']中随机选择一个元素
 
computer_choice = random.choice(['石头', '剪刀', '布'])
 
print('你出了 %s ,电脑出了 %s' % (user_choice, computer_choice))
 
 
 
# 判断胜负,根据字典中定义的胜负关系进行判断
 
if rule_dict[user_choice] == computer_choice:
 
print('你赢了!')
 
elif rule_dict[computer_choice] == user_choice:
 
print('你输了!')
 
else:
 
print('平局。')
 
 

实现方式四:for循环

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


 
# 导入随机数模块
 
import random
 
 
 
# 定义字典,用于存储石头、剪刀、布之间的胜负关系
 
choices = {"石头": "剪刀", "剪刀": "布", "布": "石头"}
 
 
 
# 设置需要赢得的局数
 
rounds_to_win = 2
 
 
 
# 初始化玩家、计算机的分数
 
player_score = 0
 
computer_score = 0
 
 
 
# 进入一个循环,在每一轮游戏中:
 
for round in range(1, 4):
 
print(f"第{round}局:") # 输出当前轮次
 
computer_choice = random.choice(list(choices.keys())) # 计算机随机选择
 
player_choice = input("请出拳(石头/剪刀/布):") # 玩家输入选择
 
print(f"你出了{player_choice},电脑出了{computer_choice}。") # 输出选择
 
 
 
if player_choice == computer_choice: # 判断平局情况
 
print("平局!")
 
elif choices[player_choice] == computer_choice: # 判断玩家获胜情况
 
print("你赢了!")
 
player_score += 1 # 更新玩家得分
 
else: # 否则为计算机获胜情况
 
print("电脑赢了!")
 
computer_score += 1 # 更新计算机得分
 
 
 
print(f"当前比分:玩家 {player_score} - 电脑 {computer_score}")
 
 
 
if player_score == rounds_to_win: # 判断玩家达到赢得的局数
 
print("你赢得了比赛!")
 
break # 结束游戏循环
 
elif computer_score == rounds_to_win: # 判断计算机达到赢得的局数
 
print("电脑赢得了比赛!")
 
break # 结束游戏循环
 
 

实现方式五: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()
 
 
 

本文作者:鹅不糊涂

本文链接:https://www.cnblogs.com/Hang666/p/17472848.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。



相关教程