【问题标题】:How to save/store random number temporarily?如何临时保存/存储随机数?
【发布时间】:2019-07-10 03:58:43
【问题描述】:

我正在创建一个 Yahzee 游戏,我希望它暂时保存“骰子”掷骰。

import random

roll = random.randint(0, 6)
print("Dice 1: " + roll)
print("Dice 2: " + roll)
input = "Save die?"
if input == "Dice 2":
    print("Dice 1: " + roll)
    # Print Dice 2's number above, below

它应该输出:

Dice 1: 3
Dice 2: 6
Save Die? Die 2
Dice 1: 2
Dice 2: 6

如何让它保存号码,所以我可以使用它,但是在 6 次移动、5 次滚动和选择游戏之后,它会被删除。

【问题讨论】:

  • 您只滚动一次,如果您需要存储每一卷,它会保存在 roll 变量中,使用列表来存储所有滚动值。
  • @AlbinPaul,但我想在接下来的 5 次内再次拨打该号码,但不会更改
  • @SpartanGolf,尝试运行您的代码并自己修复错误。不如学编程……
  • 使用 2 个不同的变量,每个骰子一个:roll1roll2。将int 转换为str 以进行打印。使用input() 函数,不要将变量命名为input

标签: python python-2.7 python-2.x


【解决方案1】:

我不知道什么是 Yahzee 游戏,但我认为您需要像 list 这样的简单数据结构来保存您的结果并在必要时清空列表。

import random

results = []
move_num = 6
while True:
    for i in range(move_num):
        dices = [random.randint(0, 6), random.randint(0, 6)]
        print('Dice 1: {}'.format(dices[0]))
        print('Dice 2: {}'.format(dices[1]))
        decision = int(input('Save die?'))
        if decision in [1, 2]:
            results.append(dices[decision-1])
        else:
            print('wrong dice number')
    print('results are {}'.format(results))
    results.clear()

我不懂游戏规则,希望对你有帮助。

【讨论】:

  • 你应该让OP自己找到答案。他/她甚至没有尝试过自己的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-28
  • 2021-02-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多