2 回答
TA贡献1821条经验 获得超6个赞
您的 if 语句非常有利于 p1 获胜。我希望 'p2' 获胜的示例代码,因为 p2 具有优越的颜色:
colour1 = 'b'
colour2 = 'r'
num1 = 2
num2 = 1
if(colour1 == "r")and(colour2 == "b"):
print("p1")
elif(colour1 == "b")and(colour2 == "y"):
print("p1")
elif(colour1 == "y")and(colour2 == "r"):
print("p1")
elif num1 > num2:
print("p1")
else:
print("p2")
>>> p1
玩家 1 在这里获胜,因为没有检查玩家 2 是否具有更好的颜色。要正确检查正确的获胜者,您可以将 if 语句修改为以下逻辑:
colour1 = 'b'
colour2 = 'r'
num1 = 2
num2 = 1
if (colour1 == "r" and colour2 == "b") or (colour1 == "b" and colour2 == "y") or (colour1 == "y" and colour2 == "r"):
print("p1")
elif (colour2 == "r" and colour1 == "b") or (colour2 == "b" and colour1 == "y") or (colour2 == "y" and colour1 == "r"):
print("p2")
elif num1 > num2:
print("p1")
else:
print("p2")
>>> p2
您可以在其中将最后一个 elif 和 else 重构为以下代码行:
colour1 = 'b'
colour2 = 'r'
num1 = 2
num2 = 1
if (colour1 == "r" and colour2 == "b") or (colour1 == "b" and colour2 == "y") or (colour1 == "y" and colour2 == "r"):
print("p1")
elif (colour2 == "r" and colour1 == "b") or (colour2 == "b" and colour1 == "y") or (colour2 == "y" and colour1 == "r"):
print("p2")
else:
print("p1" if num1 > num2 else "p2")
>>> p2
TA贡献1887条经验 获得超5个赞
首先,玩你的游戏很有趣。其次,正如我所怀疑的,错误总是出在多个 if 语句中,这特别棘手,因为您认为自己是彻底的,并且在 ned 中它会咬你!
为了清楚起见,让我们举个例子:
p1Card = y8 ,p2Card = b1
让我们运行它:
if(colour1 == "r")and(colour2 == "b") # False
winner = ("p1")
elif(colour1 == "b")and(colour2 == "y")# False
winner = ("p1")
elif(colour1 == "y")and(colour2 == "r")# False
winner = ("p1")
elif num1 > num2: # True
winner = ("p1")
else:
winner = ("p2")
因此,赢家 P1 而它应该是 P2。有多种方法可以避免这种情况,但这应该留给您自己解决:)
添加回答
举报