2012-02-21 63 views
1

嘿傢伙即時通訊有一個問題,試圖編程出一套邏輯。我想做一個Go(棋盤遊戲)的問題。我想讓我的程序做的事情是在一個xml文件中讀取,這個文件代表了一個人可以完成這個謎題的一系列步驟,或者甚至是一個死路一條。所以在XML它看起來像製作一個動態序列

<Step x="4" y="5"> 
    <Response x="4" y="6" /> 
    <Step x="3" y="6" victory="true"> 
    </Step> 
</Step> 
<!-- This is a dead end --> 
<Step x="4" y="4"> 
    <Response x="4" y="5" /> 

    <Step x="5" y="5" defeat="true"></Step> 
    <Step x="6" y="4" defeat="true"></Step> 
</Step> 

我的想法是:把在我的XML處理器(IM使用SAX)使用步驟類來存儲一個步驟內形成臺階各種各樣的鏈接列表,但我不能概念化我將如何運行在列表中。有沒有人有這樣乾淨的做法? *注意我需要逐步運行,如果步驟不存在,請將它們稱爲錯誤,並讓它們再次嘗試,但我願意將我的xml更改爲所需的任何內容。

回答

2

名單我不是從你的問題完全確定是否您遇到的XML或Java表示問題。我假設後者。

表示Go等遊戲中的連續播放序列可以使用n元樹來完成。樹中的每個節點代表一個移動,並且所有可能的移動響應都是它的子節點。這將匹配您的XML表示。

下面是介紹如何實現n元樹(從這個SO問題採取:k-ary Trees in Java)兩個環節

編輯,這裏的大致我如何解析文檔來創建一棵樹(你將不得不創建自己的Tree類,我假設這裏是基本的樹方法)。

class MyDocumentHandler { 
    // The tree we are building 
    private Tree tree; 
    // The current element we are parsing 
    private TreeNode current; 

    public void startDocument() { 
     // At the beginning of the document, create a new empty tree 
     tree = new Tree(); 
     // The current node is the root 
     current = tree; 
    } 

    public void startElement(String uri, String localName, String qName, Attributes attributes) { 
     // Process the new element, read its attributes etc. to create the new TreeNode 
     TreeNode child = new TreeNode(); 
     // Add the newly created node to the current element 
     current.addChild(child); 

     // The current element is now the child 
     current = child; 
    } 

    public void endElement(String uri, String localName, String qName) { 
     // When the current element ends, then return to its parent 
     current = current.getParent(); 
    } 
} 

您可以看到連續調用beginElement和endElement將如何創建與您的文檔具有相同結構的樹。

+0

多數民衆贊成什麼即時尋找,但我的鬥爭是真正如何我可以讀入一棵樹。例如,薩克斯帕爾斯進入第一步,將其放入樹中,然後進行第二步,它如何知道將其放入老樹中?我想我可以開始計算我採取的步驟,但那麼當我第二次採取這一措施時呢?我怎麼知道把它放進第一棵樹或第二棵樹或第三棵樹? – 2012-02-21 16:46:30

+0

@Umimi>我添加了一個剪輯給你如何做到這一點的基礎知識。希望你能夠把它整理出來。 – ARRG 2012-02-21 18:46:07

+0

謝謝你,這對我來說是非常有用的東西 – 2012-02-21 22:44:12

0

看起來你想存儲可能的步驟和響應樹?

我會用player = player1(或player2)創建一個類Step。

<Step player="p1" x="4" y="5"> 
    <Step player="p2" x="4" y="6"> 
     <Step player="p1" x="3" y="6" victory="true" /> 
    </Step> 
    <Step player="p2" x="4" y="3"> 
     <Step player="p1" x="3" y="6"> 
//some more steps 
     </Step> 
    </Step> 
</Step> 

或只是步驟

<Step player="p1" x="4" y="5"> 
<Step player="p2" x="4" y="4"> 
...