0

我写了一个对象PathGraph,它实现了一个Nodes 的图形和各种有用的功能,我打算用它来在一个简单的塔防游戏中进行寻路。我还编写了一个Path实现 Dijkstra 算法的类,并且每个非静态游戏单元都有一个Path.

我遇到的问题是,当我运行应用程序时,代码会执行代码以初始化单元,并在此过程中为每个蠕动初始化路径,然后再构建 PathGraph 对象(使用 Eclipse Scala 调试器和 println 语句确认) . 然而不幸的是,生成路径的代码需要初始化PathGraph对象,特别是path变量(var以便在地图更新时我可以指向新路径等)。

我应该如何用我的代码解决这个问题?PathGraph 代码粘贴在下面以供参考。

object PathGraph {
  private val graph:Array[Array[Node]] = buildAndFillGraph()

  //val nodeDist:Double = MainGame.pixelsPerIteration
  val nodeDist = .5
  val numXNodes = (MainGame.gamePanelWidth.toDouble / nodeDist).toInt
  val numYNodes = (MainGame.gamePanelHeight.toDouble / nodeDist).toInt
  val defaultInfinity = 99999

  //build every Nodes adjacent nodes
  val angle = 45
  val minHeight = 0
  val minWidth = 0
  val maxHeight = MainGame.gamePanelSize.height //game panel y value starts at 0 at TOP
  val maxWidth = MainGame.gamePanelSize.width
  val numPossibleAdjacentNodes = 360 / angle //360 degrees, 45 degree angle between every potentially adjacent Node
  val hypotenuseLength = math.sqrt((nodeDist * nodeDist) + (nodeDist * nodeDist))



  def buildGraphArray(): Array[Array[Node]] = {
    println("numXNodes/nodeDist.toInt: " + (numXNodes.toDouble / nodeDist).toInt + "\n")
    //build every Node in the graph
    val lgraph = 
      (for (x <- 0 until (numXNodes / nodeDist).toInt) yield {
      (for (y <- 0 until (numYNodes / nodeDist).toInt) yield {
        new Node(x.toDouble * nodeDist, y.toDouble * nodeDist)//gives lgraph(x,y) notation
      }).toArray //convert IndexedSeqs to Arrays
    }).toArray//again

    lgraph
  }

  def buildAndFillGraph():Array[Array[Node]] = {
    val lgraph = buildGraphArray()//Ar[Ar[Node]]
    println("lgraph built")
    lgraph.map(x => x.map(y => y.setAdjacentNodes(lgraph)))
    //set the adjacent nodes for all nodes in the array
    if (lgraph.size != numXNodes*numYNodes) println("numXNodes*numYNodes: " + numXNodes*numYNodes)
    else MainGame.pathGraphBuilt = true
    lgraph

  }

  def getGraph() = graph

  def toBuffer(): mutable.Buffer[Node] = graph.flatten.toBuffer

  def toArray(): Array[Node] = graph.flatten
}
4

1 回答 1

1

您可以做一些事情来改进代码:

  • 不要使用静态变量。你PathGraph应该是一个类,而不是一个对象。MainGame. pathGraphBuilt也是一个静态变量,您可以用构建器替换 - 请参阅下一点。

  • 使用构建器模式来区分构建的事物最终结果。您的 PathGraph 逻辑将主要进入构建器。这些方面的东西:

-

case class PathGraphBuilder(nodeDist: Double, numXNodes: Double /* and so on */) {
  def apply: PathGraph = buildAndFillGraph
  def buildGraphArray = ...
  def buildAndFillGraph = ...
}

class PathGraph(underlyingGraph: Array[Array[Node]]) {
  def toBuffer(): mutable.Buffer[Node] = underlyingGraph.flatten.toBuffer

  def toArray(): Array[Node] = underlyingGraph.flatten
}
于 2013-09-26T01:11:58.613 回答