python模拟石头剪刀布

标签 python simulation

我想编写一个函数 simul(),它接受一个整数并模拟 Player1 和 Player2 之间的 n 轮剪刀石头布。赢得最多回合的玩家赢得 n 轮比赛,平局可能出现。

例子:

simul(1) Player1

simul(1) Tie

simul(100) Player2

我写过:

def rps():   
 lst['R', 'P', 'S']
 p1=random.choice(lst)
 p2=random.choice(lst)
 if p1+p2=='RS' or p1+p2=='PR' or p1+p2=='SP':
      return '-1'
 elif p1+p2=='RP' or p1+p2=='PS' or p1+p2=='SR':
      return '1'
 else:
      return '0'

def simul(n):
 total=0
 for i in range(n):
      if rps()==-1:
           total+=-1
      elif rps()==1:
           total+=1
      else:
           total+=0
 if total<0:
      print('Player1')
 elif total==0:
      print('Tie')
 else:
      print('Player2')

但是,当我运行 simul() 代码时,我得到的唯一结果是“Tie”。我该如何解决??

最佳答案

在函数 rps() 中你返回的是 strings,但是在函数 simul() 中你比较的是 rps()整数

由于您使用的是 -1、0 和 1,因此您应该返回整数。

def rps():   
    lst['R', 'P', 'S']
    p1=random.choice(lst)
    p2=random.choice(lst)
    if p1+p2 == 'RS' or p1+p2 == 'PR' or p1+p2 == 'SP':
        return -1
    elif p1+p2 == 'RP' or p1+p2 == 'PS' or p1+p2 == 'SR':
        return 1
    else:
        return 0

注意:Python使用'single quotes', "double quotes" and """triple quotes""" 识别字符串。

关于python模拟石头剪刀布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23774291/

相关文章:

python - 使用 python-telegram-bot 按下开始时如何使用内联键盘发送 gif?

Python,我正在尝试创建这种参数 -active=YES

linux - 模拟 USB 设备以实现自动化

algorithm - 表示通过有向图传播的信号

java - 如何实例化 Anylogic block /对象 (INode)

python - 如何在我的页面之间共享导航栏?应用引擎 python Jinja2

python - 创建没有重复的树

python - 将内联注释移动到上一行

python - 蛋白质结构和网格的蒙特卡洛模拟

python - Python 中的几何布朗运动模拟