首页 > 解决方案 > 将骰子的两个结果加在一起python

问题描述

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

我的代码可能完全错误,但我希望得到一些关于如何修复它的帮助和建议(这是在 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): ")

标签: pythonpython-3.x

解决方案


您可以使用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

推荐阅读