Javascript中的简单关卡设计:如何在第N个问题后询问用户是否要继续游戏?

Simple level design in Javascript: How to ask user if they want to continue the game after Nth questions?

我第一次在 javascript 构建 Alexa 游戏作为练习。

玩家给出线索后猜动物。

如果玩家想继续玩,我想在第 6 个(或多长时间)问题后给出选项。

例如,我有 30 个相同级别的问题,但想要有 5 个级别(或真正的回合)。所以我想在他们进入下一个级别之前问第 6 个问题。

这是我当前的代码,它没有计数器,它一直运行直到问题 运行 结束。

我知道 python 你可以保留一个计数器并检查它何时达到某个数字,但是,我仍然是新手 javascript 并且一般来说都是编码。任何关于我应该做什么的建议都将不胜感激。

function nextAnimal(handlerInput) {
    var speakOutput = ""
    
    //if the previous guess was correct, respond postively
    if(getAnimalIndex(handlerInput) >= 0) {
        if(isGuessCorrect(handlerInput)) { //skip the first animal
            speakOutput += generatePositiveResponse();
        }
    }
    
    //increment animalIndex
    incrementAnimalIndex(handlerInput)
    var currAnimal = getCurrAnimal(handlerInput)
    
    //check if index has reached MAX_ANIMALS
    if(getAnimalIndex(handlerInput) === MAX_ANIMALS) {
        setGameState(handlerInput, "askingActions") //move on to actions
        return nextAction(handlerInput)
    } else {
        //ask the next animal
        speakOutput += currAnimal.question
        return handlerInput.responseBuilder
            .speak(speakOutput)
            .reprompt(currentAnimal.hint)
            .withShouldEndSession(false)
            .withStandardCard(currentAnimal.cardTitle, currAnimal.cardContent, currAnimal.image)
            .getResponse();
    }
}


//move on to the next action in the game 
function nextAction(handlerInput) {
    var speakOutput = ""
    
    //if the previous guess was correct, respond positively
    if(getActionIndex(handlerInput) >= 0) { //skip the first action
        if(isGuessCorrect(handlerInput)) {
            speakOutput += generatePositiveResponse();
        }
    }

无论是Python还是JS,首先要了解的是每次与客户的交互都是不同的运行你的脚本(尤其是Lambda)。所以你的计数器需要在交互之间存储。最简单的方法是使用 Alexa SDK 的内置会话存储。

像这样提取值。如果它是会话的开始并且您没有存储任何东西,它将是一个空对象。

var session_vars = handlerInput.attributesManager.getSessionAttributes();

您可以添加任何您想要的属性作为对象的属性。

session_vars.counter = 1;

玩家每回答一个问题,就加1。然后存储起来。

handlerInput.attributesManager.setSessionAttributes(session_vars);

如果要在会话之间存储,请使用持久属性适配器。

https://developer.amazon.com/en-US/docs/alexa/alexa-skills-kit-sdk-for-nodejs/manage-attributes.html