我正在用python编写一个基于tile的游戏。基本上你可以在瓷砖上放置不同的积木,一些积木可以产生或使用能量。所以,有电线。在试图弄清楚我将如何编程的电线,我决定做一个有线网络类。除了网络一分为二外,我什么都做得很好。假设有两个独立的导线网络,我用导线桥接它们之间的间隙,这样它们就连接起来了。我的代码注意到这一点,并将两个有线网络分组为一个合并的网络。但是,如果我删除了这座桥,再次创建两个单独的网络组呢?我该怎么处理?下面是我游戏的连线代码。你知道吗
class wireTemplate():
def __init__(self, image, maxPower):
self.image = pygame.transform.scale(image, (tileW,tileH))
wireTemplates.append(self)
self.maxPower = maxPower
def reproduce(self,x,y):
global wireMap
temp = copy.copy(self)
temp.rect = pygame.Rect(x*tileW,y*tileH,tileW,tileH)
temp.x = x
temp.y = y
wireMap[y][x] = temp
wires.append(temp)
didSomething = False
for i in getSurrounding(wireMap,x,y):
if i != None and i.type == "Wire":
if temp not in i.network.wires:
i.network.wires.append(temp)
temp.network = i.network
didSomething = True
#getSurrounding() returns the surrounding tiles of the
#coordinates specified.
for i2 in getSurrounding(wireMap,x,y):
if i2 != None and i2.type == "Wire":
if i.network != i2.network:
mergeNetworks(i.network,i2.network)
if not didSomething:
temp.network = wireNetwork()
temp.network.wires.append(temp)
return temp
def delete(self):
wires.remove(self)
self.network.wires.remove(self)
if self.network.wires == []: self.network.delete()
for iteration, i in enumerate(wireMap):
if self in i:
wireMap[iteration][i.index(self)] = None
class wireNetwork():
def __init__(self):
wireNetworks.append(self)
self.wires = []
self.outputs = []
self.inputs = []
self.color = pygame.Color(random.choice([0,255]),random.choice([0,255]),random.choice([0,255]),50)
def delete(self):
wireNetworks.remove(self)
您要建模的是一个图;您需要每个节点跟踪其邻居。您可以在内存中保留一个数据结构,以便快速识别两个节点是否连接(对于这一点,union-find algorithm是完美的),只要您使用该结构或继续累积连接,这是相当快的。断开连接将要求您从头开始重新构建union find数据结构,这将相对昂贵,但您有必要这样做的源数据(每个节点的邻居数据)。你知道吗
相关问题 更多 >
编程相关推荐