首页 > 解决方案 > 如何在while循环中实现标准“A点和B点必须至少相差2”

问题描述

我遇到了关于我的石头剪刀布游戏的问题。要结束游戏,它必须具备以下两个条件:

我已经制作了其中一个分数必须至少为 5 的部分。此外,尝试将差异条件放在 While-loop 行中,但无济于事。如果一名玩家达到 5 或一名玩家的差值超过 2,则这样做会使游戏结束。标准说,两者都需要满足,而不仅仅是一个或另一个。剪刀石头布编码已经由权威机构给出。

import play_rock_paper_scissors as play_rps

NUM_POINTS_TO_WIN = 5

num_rounds_played = 0
points_a = 0 
points_b = 0 

while (points_a < NUM_POINTS_TO_WIN and points_b < NUM_POINTS_TO_WIN) or \
abs(points_a - points_b)<2:


    winner = play_rps.play()
    print('Outcome of round', num_rounds_played,':',winner)
    num_rounds_played += 1
    if winner == 'a':
        points_a += 1
    elif winner == 'b':
        points_b += 1


print('Number of rounds played =',num_rounds_played) 

print('A has won',points_a,'rounds')
print('B has won',points_b,'rounds') 

我希望输出类似于:

[1] A: 2 B: 5
[2] A: 5 B: 3
[3] A: 0 B: 5

但实际输出是:

[1] A: 6 B: 8
[2] A: 2 B: 4
[3] A: 9 B: 11

不满足“不能超过 5”的标准。

标签: pythonpython-3.xwhile-loop

解决方案


如果您希望同时满足这两个条件,则应使用and逻辑运算符而不是or运算符:

while (points_a < NUM_POINTS_TO_WIN and points_b < NUM_POINTS_TO_WIN) and abs(points_a - points_b) < 2:
# Here ---------------------------------------------------------------^

推荐阅读