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
函数会被调用,启动游戏。 - 如果此脚本被作为模块导入,则不会自动启动游戏。