赞
踩
python剪刀石头布游戏
剪刀石头布是大家平时常玩的一种娱乐小游戏,这个游戏的主要目的是为了解决争议,因为三者相互制约,因此不论平局几次,总会有胜负的时候。游戏规则中,石头克剪刀,剪刀克布,布克石头。请使用python语句实现剪刀石头布游戏。具体要求如下
(1)用户输入石头剪布中任意字符串:
(2)电脑随机产生石头剪刀\布中任意字符串
(3)在每一轮中,若用户取得胜利则退出游戏,否则重新开始游戏
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()
当然可以。以下是对“剪刀石头布”游戏的代码分析:
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
函数会被调用,启动游戏。Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。