python实现简单石头剪刀布游戏

作者:眼不痛请看我 时间:2023-03-08 03:23:44 

前言:

相信大家在童年或者生活中都玩过石头剪刀布这个游戏,这个游戏需要两个及以上的人。而今天,网上也实现了石头剪刀布的游戏。通过初步学习python,也学会了如何编写这个游戏。

目标:

利用python判断语句实现石头剪刀布的游戏。

思路:

假设剪刀(0),石头(1),布(2),那么如何才能获胜呢?

python实现简单石头剪刀布游戏

那么根据这个表格可以初步写出代码:


if user == 0 and computer == 0:
print("平局")
elif user == 0 and computer == 1:
print("玩家胜")
elif user == 0 and computer == 2:
print("电脑胜")
elif user == 1 and computer == 0:
print("电脑获胜")
elif user == 1 and computer == 1:
print("平局")
elif user == 1 and computer == 2:
print("玩家胜")
elif user == 2 and computer == 0:
print("玩家胜")
elif user == 2 and computer == 1:
print("电脑胜")
elif user == 2 and computer == 2:
print("平局")

当我们写完这串代码,我们不难发现,这样写代码太麻烦了,谁都怕麻烦,所以,我们可以根据这之中的规律写出更短的代码。

python实现简单石头剪刀布游戏

根据上表,我们可以很轻松的发现规律:


1.if user-computer == -2 or user-computer == 1 时,是玩家胜出
2.if user-computer == -1 or user-computer == 2 时,是电脑胜出
3.if user-computer == 0 时,是平局

那么精简后的部分代码如下:


if user == computer:
print("玩家是%s,电脑是%s,平局"%(usr,com))
elif user - computer == -1 or user - computer == 2:
print("玩家是%s,电脑是%s,玩家输"%(usr,com))
else:
print("玩家是%s,电脑是%s,玩家胜"%(usr,com))

因为电脑是随机的,我们并不知道,所以需要调用random 完整的代码如下:


import random
computer = random.randint(0,2)
user = int(input("剪刀(0),石头(1),布(2):"))
#判断电脑出的是石头,剪刀,还是布
if computer == 0:
com = "剪刀"
elif computer == 1:
com = "石头"
else:
com = "布"
#判断玩家出的石头,剪刀,还是布
if user == 0:
usr = "剪刀"
elif user == 1:
usr = "石头"
else:
usr = "布"
#结果并输出
if user == computer:
print("玩家是%s,电脑是%s,平局"%(usr,com))
elif user - computer == -1 or user - computer == 2:
print("玩家是%s,电脑是%s,玩家输"%(usr,com))
else:
 print("玩家是%s,电脑是%s,玩家胜"%(usr,com))

效果演示图如下:

python实现简单石头剪刀布游戏

来源:https://blog.csdn.net/c1429163893/article/details/120885245

标签:python,石头剪刀布,游戏
0
投稿

猜你喜欢

  • python实现括号匹配的思路详解

    2023-08-24 16:50:30
  • Safari显示网页字体为超级无敌难看的宋体的原因

    2008-04-20 16:49:00
  • 从零开始写jQuery框架

    2008-12-24 13:37:00
  • ASP实现防止网站被采集代码

    2011-03-25 10:40:00
  • 再说淘宝的评价和信用机制

    2008-07-10 12:43:00
  • Python tkinter模块弹出窗口及传值回到主窗口操作详解

    2023-09-27 23:03:05
  • 正确认识MySQL对服务器端光标的限制

    2008-12-03 15:52:00
  • 404页面设计一样可以闪光

    2007-08-19 15:09:00
  • python字符串连接方法分析

    2021-12-24 16:27:10
  • 一文带你掌握Python中文词频统计

    2022-11-17 21:02:00
  • 如何使用Python的Requests包实现模拟登陆

    2022-10-07 03:12:26
  • 详细解读Python的web.py框架下的application.py模块

    2021-06-24 22:28:47
  • Zen Coding: 一种快速编写HTML/CSS代码[译]

    2009-12-16 12:53:00
  • 讲解数据库管理系统必须提供的基本服务

    2009-01-04 14:33:00
  • 编写Python脚本来实现最简单的FTP下载的教程

    2022-11-12 01:25:45
  • Python基于time模块求程序运行时间的方法

    2023-07-27 15:59:03
  • 数据库理论:学习基于SQL数据库的算法

    2009-01-13 13:38:00
  • 开发心得--写给想学Javascript朋友的一点经验之谈

    2009-02-25 11:42:00
  • 关于Internet Explorer 8

    2009-03-22 15:40:00
  • 分享216色网页拾色器(调色板)

    2007-09-27 12:33:00
  • asp之家 网络编程 m.aspxhome.com