python - 如何在while循环中实现标准“A点和B点必须至少相差2”
问题描述
我遇到了关于我的石头剪刀布游戏的问题。要结束游戏,它必须具备以下两个条件:
- 一名玩家必须至少达到 5 分
- 两名球员的得分之差必须至少为 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”的标准。
解决方案
如果您希望同时满足这两个条件,则应使用and
逻辑运算符而不是or
运算符:
while (points_a < NUM_POINTS_TO_WIN and points_b < NUM_POINTS_TO_WIN) and abs(points_a - points_b) < 2:
# Here ---------------------------------------------------------------^
推荐阅读
- javascript - 使用 RSelenium 和 rvest 抓取动态 Javascript 页面
- java - 为什么选择 selector.open() 和 selector()?
- node.js - 为什么在服务器上的 POST 操作中渲染到 html 页面不起作用?
- javascript - 尝试创建搜索系统
- sql - 包含大部分相同字段的 SQL 表?
- swift - 无法转换“结果”类型的值
' 到预期的参数类型 'Result<_>' - javascript - vuetify v-menu 在打开第三方库的表单点击事件后立即关闭
- python - 使用 numpy 数组中的值从 DataFrame 创建 Pandas DataFrame 以访问数据框索引
- c++ - C++:求最大值、最小值、总和和平均值
- java - 名称的结果与概率不匹配