<p>我有两个while循环,它们占用了我代码中的大量空间。我想知道是否有人知道如何合并它们,使我的代码更整洁和更小,因为我甚至不知道从哪里开始。我环顾四周,找不到如何合并两个几乎相同的循环。希望有人能帮我。我发现了一个非常类似的问题,但对我来说,答案没有意义,因为代码不工作,我试图修复它。这是密码。你知道吗</p>
<pre><code>for i in range(5):
while True:
print(" ")
input("Press enter to roll player 1 ")
print("Rolling dice!")
roll1=random.randint(1,6)
roll2=random.randint(1,6)
print(roll1)
print(roll2)
total=(roll1 + roll2)
print("Your total is:" ,total)
score1=score1 +total
if roll1 is roll2:
if total in even:
score1=score1 +10
print(score1)
print("You rolled a double. Roll again.")
continue
elif total in odd:
score1-score1 -5
print(score1)
print("You rolled a double. Roll again.")
continue
elif total in even:
score1=score1 +10
print(score1)
break
elif total in odd:
score1=score1 -5
print(score1)
break
if score1<0:
print("Player 1, you went under 0. Game over.")
break
while True:
print(" ")
input("Press enter to roll player 2 ")
print("Rolling dice!")
roll1=random.randint(1,6)
roll2=random.randint(1,6)
print(roll1)
print(roll2)
total=(roll1 + roll2)
print("Your total is:" ,total)
score2=score2 +total
if roll1 is roll2:
if total in even:
score2=score2 +10
print(score2)
print("You rolled a double. Roll again.")
continue
elif total in odd:
score2=score2 -5
print(score2)
print("You rolled a double. Roll again.")
continue
elif total in even:
score2=score2 +10
print(score2)
break
elif total in odd:
score2=score2 -5
print(score2)
break
if score2<0:
print("Player 2, you went under 0. Game over.")
break
</code></pre>
<p>正如你所看到的,他们实际上是完全相同的除了球员1到球员2和得分1到得分2。如何简化此代码?你知道吗</p>