是否有任何方法可以使一个变量应用于任何玩家,取决于谁在瓷砖上着陆?

2024-09-30 01:23:32 发布

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

在我的游戏中,我试图使任何发生在玩家身上的事情都只发生在该玩家身上,而不是发生在游戏中的每个人身上,所以我不会对玩家能够做的每件事复制相同的变量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")])

在我的代码中。如果有人知道一种方法,我将不胜感激,因为我只需要为每个变量创建一个变量


Tags: ofthetoyourandomopenbutdiscover
3条回答

消除许多变量的最好方法是使用循环和列表。您可以简单地添加一个列表,而不是为每个玩家添加一个变量:

#mob1 = Mob()
#mob2 = Mob()

mobs = [Mob(), Mob()]

因此,您还可以将每一个引用为列表,并在其中循环:

mobs[1]
for mob in mobs:
    print("The repr of my mob:", mob)

如果您碰巧已经编写了大部分代码,并且不想更改数百行(我们也都讨厌它:),那么可以使用带有for语句的exec循环。不推荐使用,但它可以工作,并且可以节省您重写大量代码的时间:

for value in range(1, 5): #range returns a list of numbers. In this case 1-4
    exec("""badChest%i = random.choice([mob%i, jail%i, trapped_chest%i, ("You creak open the chest to discover nothing but a pile of cobwebs")])""" % ((value,)*4))

这是一个有点大的新代码,所以让我们把它分解。首先,我使用了多行字符串(""")。这些只是不同类型的报价。如果我使用了双引号,实际字符串中的双引号会将它们取消,从而引发很多错误:

>>> "Hello world - "Joe""
SyntaxError: invalid syntax

接下来,我将python的字符串格式与%一起使用。它允许您在字符串中插入值。一些最常见的索引是%s,对于字符串,%d%i对于整数,%f对于浮点值。在一个字符串中,将这些索引放在任意位置,然后在末尾用另一个%传递它们的值:

>>> x = 5
>>> print( "Hello world, x is %i, and this is my string: %d" % (x, "strings") )
Hello world, x is 5, and this is my string: strings

接下来,我使用了列表乘法,使(value,)(逗号是元组)长四倍,因为字符串中有四个%i

>>> y = [1, 2, 3]
>>> y*3
[1, 2, 3, 1, 2, 3, 1, 2, 3]

而且exec只运行字符串,就好像它们是代码一样。总而言之,它通过1-4的range循环,对于循环的每个值,它运行此代码,但%i符号等于范围内的当前迭代:

badChest%i = random.choice([mob%i, jail%i, trapped_chest%i, ("You creak open the chest to discover nothing but a pile of cobwebs")])

这正好等于:

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")])

我认为这就是面向对象编程开始变得有用的地方。您应该编写只对指定对象执行某些操作的函数

我并没有坚持你的例子,但我为你写了一个小玩具的例子。重要的是open_trapped_cheast()将对象(玩家)作为输入:

from collections import defaultdict
import random


class Player:
    def __init__(self, name, health):
        self.name = name
        self.status = set()
        self.health = health()
        self.inventory = defaultdict(int)

    def add_item(self, item, number):
        self.inventory[item] += number


def open_trapped_chest(player):
    status = random.choice(["nothing", "poison"])
    loot_table = {
        "coins": 97,
        "rubies": 2,
        "artifact": 1,
        "cool hats": 3,
    }
    player.status.add(status)
    draws = random.randint(5, 25)
    loot = random.choices(list(loot_table.keys()),
                          list(loot_table.values()),
                          k=draws)
    for item in loot:
        player.inventory[item] += 1
hero1 = Player("Johnny", 100)
hero2 = Player("Anita", 100)

open_trapped_chest(hero1)
open_trapped_chest(hero2)

# The result is random but could something like:
print(f"{hero1.name} is affected by {hero1.status}")
# Johnny is affected by {'poison'}

print(f"{hero1.name} has the following items {dict(hero1.inventory)}")
# Johnny has the following items {'coins': 19, 'cool hats': 1, 'artifact': 1})

print(f"{hero2.name} is affected by {hero2.status}")
# Anita is affected by {'nothing'}

print(f"{hero2.name} has the following items {dict(hero2.inventory})")
# Anita has the following items {'coins': 14, 'rubies': 2})

我将为Python新手创建一个示例。 假设你有一份清单或口述

lst = [1, 2, 3]

如果你这样做

x = lst
y = lst

您没有复制lst,因为xy都引用同一个对象。通常的处理方法如下:

[lst for _ in range(10)]

这将在另一个列表中创建10个不同的lst副本

这可能无法直接回答您的问题,但对于python的新开发人员来说,这是一个常见的陷阱。请看一下python对其对象类型的引用,以便更好地了解它

相关问题 更多 >

    热门问题