为战斗模拟器生成随机数

Generating Random Numbers for a Combat Simulator

我正在尝试创建一个非常基本的战斗模拟器。这是我的代码:

import random
#from random import * I had, at one time, created a D20 generator that used the * function. I have since removed it in favor of using randint()
sword = 0
D20 = 0

class Hero:

    def swing_and_hit(sword, D20):

        sword = D20
        print(D20)
        if sword >= 10:
            print("You have defeated the Villian!")

        elif sword  < 10:
            print("You have died!")

D20 = randint(1,20)
Adventurer = Hero
#Adventurer.D20_Func()  Ignore this...aborted effort to try something
Adventurer.swing_and_hit(sword, D20)

每次我在 http://pythontutor.com/visualize.html#mode=edit 运行 时,随机数生成器输出 13。我不明白为什么会这样……有什么想法吗?我已经尝试将随机数生成嵌套在函数 swing_and_hit 中,每次我 运行 程序时它仍然生成相同的数字。

我认为每次生成相同数字的随机数生成器是 pythontutor.com 的怪癖。我每次只用这个代码就得到 17:

import random
print(random.randint(1, 20))

如果您必须使用网站来 运行 您的代码,请尝试 repl.it

这似乎是 "feature" in Pythontutor 以确保不同的人会看到相同的结果 运行 相同的代码。 (我总是 17)

无论他们是否将其定义为一项功能,它都可能被破坏 - 随机数应该是随机的。

只需在您自己的计算机上安装 Python,然后开始使用 - 如果您使用的是 Windows(如果不是,则从 http://python.org 下载不到 20MB您已经安装了 Python)。有交互式解释器,甚至还有一个与语言一起安装的简单开发环境——你没有动机用一个网络实现来伤害自己,这可能对一些代码的小组研究有好处,或者反思每个可变步骤中的内容循序渐进。 Python 交互式环境比您在此站点上获得的 "click to run" 动态得多。