2016-02-29 41 views
0

我想爲OpenComputers(minecraft mod)編寫一個Mancala遊戲,並使用Lua。然而,Mancala需要不得不進入中間的主循環(六個盆可供選擇),退出中間的循環(將最後一塊石頭放在空鍋子中),然後從循環內部進入循環(放入鍋中的最後一塊石頭,必須從該鍋拿起所有的石頭)。如何在沒有完成的情況下進入或退出循環? (Lua)

我可以很容易地做兩側的mancalas,與玩家去布爾值和if語句。

我有一個快速的圖來說明我的問題,對於那些不熟悉的寶石棋:http://imgur.com/WubW1pC

我有一個想法是這樣的僞代碼:

declare pots1[0,4,4,4,4,4,4], pots2[0,4,4,4,4,4,4] //pots1[0] and pots2[0] are that player's mancala 

function side1(pot,player) //pot is the pot chosen by the player 
    declare stones = pots1[pot] 
    pots1[pot] = 0 

    do 
     pot = pot + 1 
     stones = stones - 1 
     pots1[pot] = pots1[pot] + 1 
    while stones > 0 and pot < 6 

    if pot == 6 and stones > 0 and player //If stones were dropped in pot 6 and player1 is playing, drop stone in his mancala 
     pots1[0] = pots1[0] + 1 
     stones = stones - 1 

    if stones == 0 //If player1 is out of stones, check the pot for more stones. Pick up all stones in pot and continue. 
     if pots1[pot] > 1 

我不知道在哪裏從這裏出發。

回答

1

退出並進入循環的唯一方法就是使用Lua協程的yieldresume方法。 coroutine.yield允許您退出當前的協同程序/功能,但完全保留其狀態,因此後續的coroutine.resume呼叫將從執行yield的確切位置繼續。 yield也可以返回值並且resume可以提供值,這允許構建比從特定點恢復執行更復雜的邏輯。

您可能想要檢查Chapter 9 in Programming in Lua以瞭解協程的詳細信息。

+0

如果我使用協程.yield,我可以在沒有簡歷的情況下再次調用函數/循環嗎? – Nachtara

+0

是的,但它顯然與恢復協程有不同的效果。這將是一個**不同的**調用相同的功能。 –

+0

這很好,這個程序沒有必要返回到它在循環中停留的地方。不過,如果我再也不回去,會不會造成內存泄漏? – Nachtara

0

我不會審查寶石棋執行, 關於退出循環,如「休息」的邏輯,

你可以在舊的方式做到這一點:

function(stones, pot)  
    shouldIterate = true  
    while stones > 0 and shouldIterate do 
     if pot == 6 then 
      shouldIterate = false 
     end 
     pot = pot + 1 
    end 
end 
相關問題