首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在不完成循环的情况下进入或退出循环?(Lua)

如何在不完成循环的情况下进入或退出循环?(Lua)
EN

Stack Overflow用户
提问于 2016-03-01 03:37:44
回答 2查看 327关注 0票数 0

我想为OpenComputers (我的世界模式)编写一个曼卡拉游戏,它使用Lua。然而,Mancala要求必须进入中间的主循环(六个罐子可供选择),退出中间的循环(将最后一块石头放入一个空的罐子中),并从循环中进入循环(将最后一块石头放入罐子中,必须从该罐子中拾取所有石头)。

我可以很容易地在两边做mancalas,使用一个boolean,一个玩家要去的地方,和一个if语句。

对于那些不熟悉曼卡拉的人,我有一个快速流程图来解释我的问题:http://imgur.com/WubW1pC

我的一个想法是这样的伪代码:

代码语言:javascript
复制
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

我不知道下一步该怎么走。

EN

回答 2

Stack Overflow用户

发布于 2016-03-01 04:11:27

正如您所描述的,退出和进入循环的唯一方法是使用Lua协程的yieldresume方法。coroutine.yield允许您退出当前的协程/函数,但会保持其状态不变,因此后续的coroutine.resume调用将从执行yield的确切位置继续进行。yield还可以返回值,resume可以提供值,这允许构建更复杂的逻辑,而不仅仅是从特定点恢复执行。

您可能需要查看Chapter 9 in Programming in Lua以了解有关协程的详细信息。

票数 1
EN

Stack Overflow用户

发布于 2016-03-01 07:50:21

我不打算审查Mancala的实现,关于退出循环,比如'break‘逻辑,

你可以用老方法来做:

代码语言:javascript
复制
function(stones, pot)    
    shouldIterate = true    
    while stones > 0 and shouldIterate do
        if pot == 6 then
            shouldIterate = false
        end
        pot = pot + 1
    end
end
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35708109

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档