我已经制作了一个寻宝游戏,我需要它,这样一旦一个包含宝箱的广场被访问了3次,它就变成了一个“土匪”。 为了统一访问宝箱的次数,我在TreasureChestCoordinates列表中添加了许多相同的坐标。然后我计划有一个if语句,这样如果任何一个坐标写入3次,所有3个将被删除并放入“强盗”列表中。 这是该部分的草案代码:
# Treasure Chests Collecting Coins #
if (x,y) in TreasureCoords[0:(TCNumber -1)]:
print("You have landed on a treasure chest! You can visit it 2 more times before it becomes a bandit.")
CoinCollection = CoinCollection + 10
TreasureCoords.append(x,y)
#if TreasureCoords.count(any item) > 3:
#remove all copies of item from list
#add item to bandit list
x,y表示用户当前所在的坐标.CoinCollection是一个单独的变量,当用户登陆宝箱或强盗时会发生变化。顺便说一下,坐标的数量是无限的,因为用户先前决定了在游戏里。 那么,我如何复制我的坐标列表,一旦它们在列表中3次删除它们并将它们放入新的列表中?我认为这是最简单的方法来“计算”用户在广场上的次数,并将宝箱更改为强盗。
答案 0 :(得分:1)
首先......您不需要在列表中搜索三次出现的任何坐标。这太浪费了。如果在发生这种情况后将其删除,那么唯一可能出现三次的坐标就是您刚刚访问过的坐标。
如果确实希望按照您的问题所示进行操作,请执行while (x,y) in TreasureCoords: TreasureCoords.remove((x,y))
之类的操作。但是,使用dict
可能会更容易。你甚至可以避免使用单独的变量。假设ItemCoords
最初填充了代表未经访问的宝箱的坐标:
ItemCoords[(x,y)] = 0 # add a treasure
...然后你可以看看宝藏被访问了多少次:
visits = ItemCoords.get((x,y), None)
if visits is None:
pass # nothing there
else if visits > 3:
fightBandit() # ...or whatever
else:
print("You have landed on a treasure chest! You can visit it %i more times before it becomes a bandit." % (2 - visits))
CoinCollection += 10
ItemCoords[(x,y)] += 1
这仍然过于简单化。你可能想要一种更加面向对象的方法,正如Christian所暗示的那样:
class Treasure:
def __init__(x,y):
self.x = x
self.y = y
self.visits = 0
def visit():
print("You have landed on a treasure chest! You can visit it %i more times before it becomes a bandit." % (2 - visits))
CoinCollection += 10
if visits == 3:
world[(self.x, self.y)] = Bandit(self.x, self.y)
class Bandit:
def __init__(x,y):
self.x = x
self.y = y
def visit():
# Replace this with whatever happens when the player meets a bandit
print("You have been eaten by a grue.")
sys.exit(0)
# Initialize the world
for n in range(NumberOfTreasure):
# get x,y somehow, e.g. random
world[(x,y)] = Treasure(x,y)
# ...code for player wandering around...
here = world.get((x,y), None)
if here is not None:
here.visit()
答案 1 :(得分:0)
我认为这是一个对象有益的情况 - 而不是跟踪有关同一事物的事实的单独列表,使用存储所有相关信息的对象列表。
看起来像这样:
class Monster(object):
#define like you like it
pass
class Treasure(object):
def init(x, y):
self.x = x
self.y = y
self.visits = 0
def visit():
self.visits += 1
if self.visits >= 3:
return Monster()
else:
return 10
calling code:
treasure = Treasure(1,1)
rv = treasure.visit()
if isinstance(rv, Monster):
# lets the monster rip him to shreds
else:
CoinCollection +=treasure.visit()