在我的游戏中,我试图使任何发生在玩家身上的事情都只发生在该玩家身上,而不是发生在游戏中的每个人身上,所以我不会对玩家能够做的每件事复制相同的变量4次
例如,我有一些类似于:
badChest1 = random.choice([mob1, jail1, trapped_chest1, ("You creak open the chest to discover nothing but a pile of cobwebs")])
badChest2 = random.choice([mob2, jail2, trapped_chest2, ("You creak open the chest to discover nothing but a pile of cobwebs")])
badChest3 = random.choice([mob3, jail3, trapped_chest3, ("You creak open the chest to discover nothing but a pile of cobwebs")])
badChest4 = random.choice([mob4, jail4, trapped_chest4, ("You creak open the chest to discover nothing but a pile of cobwebs")])
在我的代码中。如果有人知道一种方法,我将不胜感激,因为我只需要为每个变量创建一个变量
消除许多变量的最好方法是使用循环和列表。您可以简单地添加一个列表,而不是为每个玩家添加一个变量:
因此,您还可以将每一个引用为列表,并在其中循环:
如果您碰巧已经编写了大部分代码,并且不想更改数百行(我们也都讨厌它:),那么可以使用带有
for
语句的exec
循环。不推荐使用,但它可以工作,并且可以节省您重写大量代码的时间:这是一个有点大的新代码,所以让我们把它分解。首先,我使用了多行字符串(
"""
)。这些只是不同类型的报价。如果我使用了双引号,实际字符串中的双引号会将它们取消,从而引发很多错误:接下来,我将python的字符串格式与
%
一起使用。它允许您在字符串中插入值。一些最常见的索引是%s
,对于字符串,%d
或%i
对于整数,%f
对于浮点值。在一个字符串中,将这些索引放在任意位置,然后在末尾用另一个%
传递它们的值:接下来,我使用了列表乘法,使
(value,)
(逗号是元组)长四倍,因为字符串中有四个%i
:而且
exec
只运行字符串,就好像它们是代码一样。总而言之,它通过1-4的range
循环,对于循环的每个值,它运行此代码,但%i
符号等于范围内的当前迭代:这正好等于:
我认为这就是面向对象编程开始变得有用的地方。您应该编写只对指定对象执行某些操作的函数
我并没有坚持你的例子,但我为你写了一个小玩具的例子。重要的是
open_trapped_cheast()
将对象(玩家)作为输入:我将为Python新手创建一个示例。 假设你有一份清单或口述
如果你这样做
您没有复制
lst
,因为x
和y
都引用同一个对象。通常的处理方法如下:这将在另一个列表中创建10个不同的
lst
副本这可能无法直接回答您的问题,但对于python的新开发人员来说,这是一个常见的陷阱。请看一下python对其对象类型的引用,以便更好地了解它
相关问题 更多 >
编程相关推荐