python - python 将骰子的两个结果相加

标签 python python-3.x

我是Python的绝对初学者,但我真的很想挑战自己。我想创建一个游戏,为每个玩家(目前是两个玩家)掷骰子两次。骰子的结果相加,如果是偶数则加 10 分,如果是奇数则减去 5 分。玩家最多可以玩 5 轮。到目前为止,我已将代码保留在 while 循环内,并导入 random 来“掷”骰子,但我不知道如何将随机结果添加在一起。

我的代码可能完全错误,但我希望得到一些有关如何修复它的帮助和建议(这是在 python 3 上完成的)

我的代码:

person1_name = input("What is your name: ")
person2_name = input("What is your name: ")

import random
number = random.randint(1,6)
rounds = "yes"
while rounds == "yes":
    print(person1_name, "- 1st roll = ",number, " and 2nd roll = ",number)
    total_1 = number + number
    if total_1 % 2 == 0:
        total_1 = total_1 + 10
        print(person1_name," has ",total_1, "points")
    else:
        total_1 = total_1 - 5
        print(person1_name, " has ",total_1, "points")
    print(person2_name, "- 1st roll = ",number, "and 2nd roll = ",number)
    total_2 = number + number
    if total_2 % 2 == 0:
        total_2 = total_2 + 10
        print(person2_name," has ",total_2, "points")
    else:
        total_2 = total_2 - 5
        print(person2_name," has ",total_2, "points")
    rounds = input("Do you want to play again (yes/no): ")

最佳答案

您可以使用random.choices()直接得到总和.

sum_dices = sum(random.choices(range(1,7),k=2))

或直接检查:

if sum(random.choices(range(1,7),k=2)) % 2:
     pass
else:
     pass

关于python - python 将骰子的两个结果相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52245623/

相关文章:

python - 将数据帧写入 csv 按列

python - 名称错误 : global name 'MySQLdb' is not defined

python - 使用 scikit 限制线性回归预测值

python - Python 3 中 max([a for a in [1,2]]) 和 max(a for a in [1,2]) 的区别

python - NumPy 数组的阈值像素索引

python - 在本地(非 Azure)docker 实例中使用来自 Azure feed 的 python 包

python - 如何在 ipython notebook 中显示图表

python - 每隔两个元素向列表添加一个元素

python - 如何使用boto3更新dynamodb中一个项目的几个属性

python-3.x - 使用 Google Cloud Endpoints 时如何重启 Flask 服务器?