随机数战斗模拟器

2024-03-29 09:37:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个函数来模拟一场战斗。到目前为止,我有一个列表和一些东西,随机挑选其中一个我在另一个帖子中找到的。我似乎不能用if语句打印出“Hit!或“闪避!或“暴击!“当它选择了相应的单词,因为它给出了一个语法错误的任何原因。有人能帮我吗?如何才能生成if语句?在

Health = 10
dodge = 1
dmg = 1
hit = dmg + 1
crhit = hit * 2

def fight():
    while 1 == 1:
        global Health
        global dodge
        global hit
        global dmg
        chances = [hit, hit, dodge, crhit, hit]
        from random import choice
fight()

Tags: 函数列表if语句单词global帖子health
2条回答

您只有导入函数选择,您仍然需要调用它:

from random import choice # This makes it so we can use the function in the script.
Health = 10
dodge = 1
dmg = 1
hit = dmg + 1
crhit = hit * 2
def fight():
    while 1:
        mychoice = choice(chances) # We call the function. It gets a random value from the list
        if mychoice == hit: # Create an if/elif for each possible outcome
            dostuff()
        elif ...
fight()

然后可以使用if/elif结构来处理每个选项

另外,这些global语句也不需要,因为实际上您并没有修改变量本身(除非您打算稍后再修改)。在

while 1 == 1可以简单地写成while 1,因为它也可以被认为是True。在

你不能从cd3}中得到一个完整的{cd3}元素,因为你不能从cd3}中得到一个。您只需编写三个if-elif语句来检查每个语句。简短的例子(你应该从这里得到答案)

>>> varOne = 2
>>> varTwo = 3
>>> varThree = 4
>>> from random import choice
>>> testVar = choice([varOne, varTwo, varThree])
>>> if testVar == varOne:
       print 'abc'
    elif testVar == varTwo:
       print 'def'
    else:
       print 'ghi'


abc

相关问题 更多 >