2015-01-18 2 views
0

저는 타일 기반의 게임을 파이썬으로 작성하고 있습니다. 기본적으로 타일에 다른 블록을 배치 할 수 있으며 일부는 능력을 생성하거나 사용합니다. 그래서, 철사가 있습니다. 와이어를 프로그래밍하는 방법을 알아 내려고 시도한 후에 wireNetwork 클래스를 만들기로 결정했습니다. 네트워크가 두 개로 나뉘어져있는 경우를 제외하고는 모든 것이 잘 작동하고 멋지게 작동합니다. 두 개의 분리 된 유선 네트워크가 있다고 가정하고, 유선과 유선 사이의 간격을 연결하여 연결되도록합니다. 내 코드는 두 개의 와이어 네트워크를 하나의 병합 된 네트워크로 분류하고 그룹화합니다. 하지만 두 개의 개별 네트워크 그룹을 다시 만들고 브리지를 삭제하려면 어떻게해야합니까? 어떻게 처리할까요? 아래에 내 게임의 배선 코드가 있습니다.내 게임의 논리 배선

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) 

답변

2

모델링하는 것은 그래프입니다. 각 노드는 이웃 노드를 추적해야합니다. 두 노드가 연결되어 있는지 여부를 빠르게 확인할 수 있도록 메모리에 데이터 구조를 유지할 수 있습니다 (이 경우 union-find algorithm은 완벽합니다). 구조를 사용 중이거나 연결을 계속 누적하는 한 매우 빠릅니다. 연결이 끊어지면 처음부터 union-find 데이터 구조를 다시 빌드해야하는데, 이는 상대적으로 비용이 많이 들지만 그렇게하기 위해 필요한 소스 데이터 (각 노드의 인접 데이터)가 있어야합니다.