2016-02-29 38 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 
相关问题