from random import random def getInputs(): probA = float(input("请输入选手A的能力值(0-1): ")) probB = float(input("请输入选手B的能力值(0-1): ")) return probA,probB def simOneGame(probA, probB): scoreA, scoreB = 0, 0 serving = "A" i=1 while not gameOver(scoreA, scoreB): serving=switchServing(i,serving) i+=1 if serving is "A": if random() < probA: scoreA += 1 else: scoreB += 1 else: if random() < probB: scoreB += 1 else: scoreA += 1 print(scoreA,'--',scoreB) def gameOver(scoreA,scoreB): if scoreA==10 and scoreB ==10: return False elif scoreA ==12 or scoreB==12: return True else: return scoreA==11 or scoreB==11 def switchServing(i,serving): if i%5 == 0 and i>0: if serving is 'A': serving='B' else: serving='A' return serving def Winner(scoreA,scoreB): if scoreA ==12 or scoreB==12: if scoreA == 12: return'A' else: return'B' def simOneChampion(): B=0; A=0; round=1 probA,probB= getInputs(); while True: print('第{}局'.format(round)) r=simOneChampion(probA,probB) round+= 1 if r is 'A': A+= 1 else: B+= 1 if A==2: print('A获胜') break elif B == 2: print('B获胜') break else: continue simOneChampion()这段代码有什么错误
时间: 2024-02-14 18:13:02 浏览: 123
simple-http-utilities:简单的http包装库
这段代码中有几个错误:
1. 在 simOneGame 函数中,缺少 return 语句,导致该函数不返回任何值。
2. 在 switchServing 函数中,只有当 i%5 == 0 且 i>0 时才会切换发球权,但是在第一局比赛开始前,i 的值为 1,没有进入切换发球权的逻辑。可以在 simOneGame 函数中先将 serving 设置为 "A",然后在第一次循环前调用一次 switchServing 函数。
3. 在 Winner 函数中,如果比赛还没有结束,该函数不返回任何值。
4. 在 simOneChampion 函数中,调用 simOneChampion 函数时应该传入 probA 和 probB 两个参数,而不是只传入 probA。另外,应该将 simOneChampion 函数的调用放在一个 while 循环中,以便可以连续进行多局比赛。
下面是修改后的代码:
```python
from random import random
def getInputs():
probA = float(input("请输入选手A的能力值(0-1): "))
probB = float(input("请输入选手B的能力值(0-1): "))
return probA, probB
def simOneGame(probA, probB):
scoreA, scoreB = 0, 0
serving = "A"
i = 1
serving = switchServing(i, serving)
while not gameOver(scoreA, scoreB):
i += 1
serving = switchServing(i, serving)
if serving == "A":
if random() < probA:
scoreA += 1
else:
scoreB += 1
else:
if random() < probB:
scoreB += 1
else:
scoreA += 1
print(scoreA, "--", scoreB)
return Winner(scoreA, scoreB)
def gameOver(scoreA, scoreB):
if scoreA == 10 and scoreB == 10:
return False
elif scoreA == 12 or scoreB == 12:
return True
else:
return scoreA == 11 or scoreB == 11
def switchServing(i, serving):
if i % 5 == 0:
if serving == "A":
serving = "B"
else:
serving = "A"
return serving
def Winner(scoreA, scoreB):
if scoreA == 12:
return "A"
elif scoreB == 12:
return "B"
else:
return None
def simOneChampion():
B = 0
A = 0
round = 1
while True:
print("第{}局".format(round))
r = simOneGame(probA, probB)
round += 1
if r == "A":
A += 1
elif r == "B":
B += 1
if A == 2:
print("A获胜")
break
elif B == 2:
print("B获胜")
break
probA, probB = getInputs()
simOneChampion()
```
阅读全文