python - 将骰子的两个结果加在一起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): ")
解决方案
您可以使用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
推荐阅读
- laravel - 使用单选按钮进行条件验证,当单选按钮值为“是”时需要另一个输入,否则可以为空
- javascript - 如何使用nodejs mysql从html中的表单传递id
- java - 如何通过 Activator 激活 AEM bundel?
- android - 如何获取可上传的文件路径链接
- c++ - opencv 4.0 无法保存视频
- sql - BigQuery:如何计算过去 2 天不同访问者的运行计数
- java - 垃圾收集(本地参考)
- php - isset($_POST['submit']) 未在按钮单击时触发
- javascript - html 线图显示设备状态所需的建议
- java - TextView textView = (TextView) findViewById(R.id.textView) 是向上转换还是向下转换?