John
Published © Apache-2.0

Who Wants To Be The Smartest Guy? (Skill Name/Icon Changed)

Trivia Game.

BeginnerFull instructions provided2 hours787

Things used in this project

Story

Read more

Code

index.js

JavaScript
/**
 Copyright 2014-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.

 Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at

 http://aws.amazon.com/apache2.0/

 or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
 */

/**
 * This sample shows how to create a simple Trivia skill with a multiple choice format. The skill
 * supports 1 player at a time, and does not support games across sessions.
 */

'use strict';

/**
 * When editing your questions pay attention to your punctuation. Make sure you use question marks or periods.
 * Make sure the first answer is the correct one. Set at least 4 answers, any extras will be shuffled in.
 */
var questions = [
    {
"Which disease devastated livestock across the UK during 2001 ? ":[
 "Foot-in-mouth",
 "Hand-and-foot",
 "Hand-to-mouth",
 "Foot-and-mouth"
 ]
 },{
"Which of these kills its victims by constriction ? ":[
 "Anaconda",
 "Andalucia",
 "Andypandy",
 "Annerobinson"
 ]
 },{
"Which of these might be used in underwater naval operations ? ":[
 "Frogmen",
 "Newtmen",
 "Toadmen",
 "Tadpolemen"
 ]
 },{
"In the UK, VAT stands for value-added ... ? ":[
 "Tax",
 "Transaction",
 "Total",
 "Trauma"
 ]
 },{
"What are you said to do to a habit when you break it ? ":[
 "Kick it",
 "Throw it",
 "Punch it",
 "Eat it"
 ]
 },{
"Where do you proverbially wear your heart, if you show your true feelings ? ":[
 "On your sleeve",
 "On your collar",
 "On your lapel",
 "On your cuff"
 ]
 },{
"What might an electrician lay ? ":[
 "Cables",
 "Tables",
 "Gables",
 "Stables"
 ]
 },{
"What would a 'tattie picker' harvest ? ":[
 "Potatoes",
 "Raspberries",
 "Corn",
 "Apples"
 ]
 },{
"Which of these means adequate space for moving in ? ":[
 "Elbow room",
 "Foot rest",
 "Ear hole",
 "Knee lounge"
 ]
 },{
"How is a play on words commonly described ? ":[
 "Pun",
 "Pan",
 "Pin",
 "Pen"
 ]
 },{
"Which colour is used as a term to describe an illegal market in rare goods ? ":[
 "Black",
 "Blue",
 "Red",
 "White"
 ]
 },{
"Which character was first played by Arnold Schwarzenegger in a 1984 film ? ":[
 "The Terminator",
 "The Demonstrator",
 "The Instigator",
 "The Investigator"
 ]
 },{
"Which of these would a film actor like to receive ? ":[
 "Oscar",
 "Oliver",
 "Oliphant",
 "Osbert"
 ]
 },{
"In which country would you expect to be greeted with the word 'bonjour' ? ":[
 "France",
 "Italy",
 "Spain",
 "Wales"
 ]
 },{
"What name is given to the person who traditionally attends the groom on his wedding day ? ":[
 "Best man",
 "Top man",
 "Old man",
 "Poor man"
 ]
 },{
"Which word follows 'North' and 'South' to give the names of two continents ? ":[
 "America",
 "Africa",
 "Asia",
 "Australia"
 ]
 },{
"Which country is not an island ? ":[
 "Germany",
 "Madagascar",
 "Cuba",
 "Jamaica"
 ]
 },{
"Which is not the name of an English county ? ":[
 "Liverpoolshire",
 "Lancashire",
 "Leicestershire",
 "Lincolnshire"
 ]
 },{
"Which of these is a fashionable district of London ? ":[
 "Belgravia",
 "Bulgaria",
 "Belgrade",
 "Belgium"
 ]
 },{
"What name is given to a playing card with a single symbol on it ? ":[
 "Ace",
 "Whizz",
 "Hotshot",
 "Star"
 ]
 },{
"What would you normally do with a beret ? ":[
 "Wear it" ,
 "Eat it",
 "Play it",
 "Sit on it"
 ]
 },{
"Which of these is a tool for shaping and smoothing wood ? ":[
 "Plane",
 "Train",
 "Car",
 "Bike"
 ]
 },{
"What do the Americans call what we call sweets ? ":[
 "Candy" ,
 "Randy",
 "Dandy",
 "Sandy"
 ]
 },{
"Which of these is a spicy, Cajun chicken or seafood dish ? ":[
 "Gumbo",
 "Dumbo",
 "Bimbo",
 "Rambo"
 ]
 },{
"What would you expect to see at the London Aquarium ? ":[
 "Fish" ,
 "Flowers",
 "Trees",
 "Steam rollers"
 ]
 },{
"People who are in a similar unfavourable situation are said to be 'all in the same ...' ? ":[
 "Boat",
 "Car",
 "Plane",
 "Tube"
 ]
 },{
"According to the old adage, how many lives does a cat have ? ":[
 "Nine",
 "Five",
 "Seven",
 "Ten"
 ]
 },{
"Which of these is a keyboard instrument ? ":[
 "Harpsichord",
 "Ripcord",
 "Pyjama cord",
 "Sashcord"
 ]
 },{
"The former punk singer John Lydon was known on stage as Johnny ... ? ":[
 "Rotten",
 "Horrid",
 "Nasty",
 "Hateful"
 ]
 },{
"The name of which plant sounds like a greeting to 'Coronation Street's' Mrs Duckworth ? ":[
 "Aloe vera" ,
 "Hi mabel",
 "G'day june",
 "Wotcha di"
 ]
 },{
"The Nativity is the story of whose birth ? ":[
 "Jesus Christ",
 "Elvis Presley",
 "Winston Churchill",
 "John F Kennedy"
 ]
 },{
"How many moons orbit the Earth ? ":[
 "One",
 "Two",
 "Three",
 "Four"
 ]
 },{
"By what abbreviation is a compact disc commonly known ? ":[
 "CD",
 "COD",
 "CDIS",
 "COMPD"
 ]
 },{
"Which country shares a land border with the UK ? ":[
 "Ireland" ,
 "Portugal",
 "Libya",
 "Vietnam"
 ]
 },{
"The star sign Aquarius is also known as what ? ":[
 "The Water-carrier",
 "The Food-carrier",
 "The Hod-carrier",
 "The Bag-carrier"
 ]
 },{
"Which of these would be of most use if you wanted to play poker ? ":[
 "Pack of cards",
 "Bat & ball",
 "Swimming trunks",
 "Horse"
 ]
 },{
"What are said to be 'down' when things are not going well ? ":[
 "Chips",
 "Egg",
 "Bacon",
 "Beans"
 ]
 },{
"What name is given to a mound or ridge of windblown sand ? ":[
 "Dune",
 "Drone",
 "Dude",
 "Dime"
 ]
 },{
"Which part of the human body encases many of the vital organs such as the heart, lungs and liver ? ":[
 "Torso" ,
 "Head",
 "Legs",
 "Arms"
 ]
 },{
"Which of these is a weight category in professional boxing ? ":[
 "Welterweight",
 "Swelterweight",
 "Slaughterweight",
 "Daughterweight"
 ]
 },{
"Who has the authority to change a ball during a football match ? ":[
 "The referee" ,
 "Sky Sports",
 "The home team",
 "Alex Ferguson"
 ]
 },{
"If you are moving downhill over snow with a long runner attached to each foot, what are you doing ? ":[
 "Skiing",
 "Swimming",
 "Skateboarding",
 "Showjumping"
 ]
 },{
"What sort of animal is Jess, who accompanies the TV character Postman Pat ? ":[
 "Cat",
 "Dog",
 "Horse",
 "Mouse"
 ]
 },{
"A particular hazard for motorists is black ... ? ":[
 "Ice",
 "Pudding",
 "Holes",
 "Mascara"
 ]
 },{
"Which 'Dallas' spin-off saw Gary Ewing arrive in a small  Californian town ? ":[
 "Knots Landing" ,
 "Knots Patio",
 "Knots Garage",
 "Knots Porch"
 ]
 },{
"Which is a US-made soap opera ? ":[
 "Dawson's Creek",
 "Johnson's Mere",
 "Thompson's Pond",
 "Madison's Lake"
 ]
 },{
"Which of these is a discipline in both men's and women's gymnastics ? ":[
 "Floor exercises",
 "Wall exercises",
 "Ceiling exercises",
 "Roof exercises"
 ]
 },{
"Which of the following do bowlers aim to hit during a game of cricket ? ":[
 "Stumps" ,
 "Posts",
 "Hoop",
 "Net"
 ]
 },{
"Which of these applies to the shape of a soccer ball ? ":[
 "Spherical",
 "Conical",
 "Cylindrical",
 "Oval"
 ]
 },{
"Which novel by Charles Dickens was made into a film in 2002 ? ":[
 "Nicholas Nickleby",
 "Danny Dimeby",
 "Quentin Quarterby",
 "Donald Dollarby"
 ]
 },{
"A 'cuppa' is an informal term for what ? ":[
 "Cup of tea",
 "Policeman",
 "2p coin",
 "Smoked herring"
 ]
 },{
"What is the meaning of the colloquial expression 'in the bag' ? ":[
 "Almost certain",
 "Newly bought",
 "Freshly cooked",
 "Recently stolen"
 ]
 },{
"Which activity would you most associate with a mole ? ":[
 "Burrowing",
 "Climbing",
 "Swimming",
 "Flying"
 ]
 },{
"Which is not a type of antelope ? ":[
 "Gorilla",
 "Gerenuk",
 "Gemsbok",
 "Gnu"
 ]
 },{
"Which is an alternative name for members of the Society of Friends ? ":[
 "Quakers",
 "Kellogg's",
 "Special Ks",
 "Jordans"
 ]
 },{
"Which is another name for a short melodious tune ? ":[
 "Air",
 "Oxygen",
 "Nitrogen",
 "Stratosphere"
 ]
 },{
"Which of these is a large woodwind instrument ? ":[
 "Bassoon",
 "Buffoon",
 "Pantaloon",
 "Macaroon"
 ]
 },{
"In the nursery rhyme, who met a pieman ? ":[
 "Simple Simon",
 "Easy Eric",
 "Plain Peter",
 "No Frills Fred"
 ]
 },{
"Which of these is a material often used to make floor mats ? ":[
 "Rush",
 "Dash",
 "Hustle",
 "Bustle"
 ]
 },{
"In which of the following might food be stored ? ":[
 "Larder",
 "Shed",
 "Greenhouse",
 "Garage"
 ]
 },{
"What is rioja a type of ? ":[
 "Wine",
 "Bread",
 "Vegetable",
 "Nut"
 ]
 },{
"Germania was the Roman name for which modern-day European country ? ":[
 "Germany",
 "France",
 "Austria",
 "Spain"
 ]
 },{
"What was the UK's top paying attraction of 2002 ? ":[
 "London Eye",
 "London Nose",
 "London Mouth",
 "London Ear"
 ]
 },{
"Which of these is a Scottish district council ? ":[
 "Inverclyde",
 "Inverchristopher",
 "Inverclint",
 "Invercharles"
 ]
 },{
"In which town are the administrative headquarters of Kent ? ":[
 "Maidstone",
 "Lasspebble",
 "Girlrock",
 "Missgravel"
 ]
 },{
"Which of these geographical features is a mountain ? ":[
 "Kilimanjaro",
 "Danube",
 "Amazon",
 "Nile"
 ]
 },{
" Which word goes before 'States of America' to give the name of a country ? ":[
 "United",
 "Joined",
 "Agreed",
 "Harmonious"
 ]
 },{
"Which was a famous group of high-kicking stage dancers ? ":[
 "Tiller Girls",
 "Checkout Girls",
 "Cashpoint Girls",
 "Turnstile Girls"
 ]
 },{
"Which of these is a person who performs tricks that deceive the eye ? ":[
 "Illusionist" ,
 "Illustrator",
 "Illuminator",
 "Illiterate"
 ]
 },{
"Which of the following words for a coat also describes the paper cover of a book ? ":[
 "Jacket",
 "Cagoule",
 "Mackintosh",
 "Parka"
 ]
 },{
"What is hung over a horse's head for feeding ? ":[
 "Nosebag",
 "Nosegay",
 "Nosedive",
 "Nosejob"
 ]
 },{
"Something mediocre can be described as 'no great ...' ? ":[
 "Shakes",
 "Quivers",
 "Wobbles",
 "Trembles"
 ]
 },{
"What do you proverbially let down when behaving without reserve ? ":[
 "Hair",
 "Shoulders",
 "Elbows",
 "Knees"

 ]
 },{
"Which is not a species of seal ? ":[
 "Three-legged",
 "Elephant",
 "Leopard",
 "Grey"
 ]
 },{
"Which keyboard player was awarded the OBE in the 2003 Birthday Honours list ? ":[
 "Jools Holland" ,
 "Cools Belgium",
 "Drools Luxembourg",
 "Fools France"
 ]
 },{
"Which show took place between 6th-9th March 2004 at the NEC, Birmingham ? ":[
 "Crufts",
 "Toffs",
 "Cuffs",
 "Lifts"
 ]
 },{
"Harrison Ford announced in August 2003, that he would make a fourth film playing which role ? ":[
 "Indiana Jones",
 "Nevada Morgan",
 "Wyoming Williams",
 "Montana Evans"
 ]
 },{
"August 16th 2003 was the 40th anniversary of which 'Great' robbery ? ":[
 "Train" ,
 "Hovercraft",
 "Pushchair",
 "Balloon"
 ]
 },{
"Which member of the Royal Family celebrated his 19th birthday in September 2003 ? ":[
 "Prince Harry",
 "Prince Edward",
 "Prince Andrew",
 "Prince Charles"
 ]
 },{
"With which football club was David Beckham's name not linked in 2003 ? ":[
 "Scunthorpe United",
 "Barcelona",
 "AC Milan",
 "Real Madrid"
 ]
 },{
"Whose return to 'EastEnders' in 2004 sparked a 560 megawatt power surge on the national grid ? ":[
 "Dirty Den",
 "Filthy Fred",
 "Smutty Sam",
 "Grubby Gordon"
 ]
 },{
"Which patron saint's day falls on 23rd April ? ":[
 "St George",
 "St Harry",
 "St Albert",
 "St William"
 ]
 },{
"What is celebrated in Wales on 1st March ? ":[
 "St David's Day",
 "Gareth Edwards Day",
 "Tom Jones Day",
 "Richard Burton Day"
 ]
 },{
"Which adjective applied to Friday 9th April in 2004 ? ":[
 "Good",
 "Bad",
 "Ugly",
 "Indifferent"
 ]
 },{
"Which of these is a popular form of music ? ":[
 "Country & Western",
 "County & Eastern",
 "Kingdom & Northern",
 "Land & Southern"
 ]
 },{
"Which of these is a slang term for a mean person ? ":[
 "Cheapskate",
 "Cheapshark",
 "Cheapmackerel",
 "Cheaphaddock"
 ]
 },{
"Which of these is a common term for a programme of physical exercises ? ":[
 "Keep fit",
 "Stay able",
 "Remain trim",
 "Continue competent"
 ]
 },{
"What is the usual name for an establishment containing a lot of fruit machines ? ":[
 "Amusement arcade",
 "Happy house",
 "Fun folly",
 "Hilarity hall"
 ]
 },{
"Which of these means displaying advertising posters in an unauthorised place ? ":[
 "Fly-posting",
 "Ant-posting",
 "Bee-posting",
 "Wasp-posting"
 ]
 },{
"On which of these might you win a large amount of money ? ":[
 "National Lottery",
 "National Flattery",
 "National Battery",
 "National Pottery"
 ]
 },{
" What kind of envelope has a transparent section through which the address can be seen ? ":[
 "Window",
 "Fanlight",
 "Door",
 "Sunroof"
 ]
 },{
"Which of these is a type of beer ? ":[
 "Bitter",
 "Acid",
 "Tart",
 "Sour"
 ]
 },{
"What is a woman said to do with her eyelashes when she is being flirtatious ? ":[
 "Flutter",
 "Litter",
 "Platter",
 "Rotter"
 ]
 },{
"Which of these is an ice cream dessert ? ":[
 "Sundae",
 "Mondae",
 "Tuesdae",
 "Wednesdae"
 ]
 },{
"Which term means replacing a telephone receiver at the end of a call ? ":[
 "Hang up",
 "Jump up",
 "Toss up",
 "Play up"
 ]
 },{
"Which of these is a popular garden flower ? ":[
 "Carnation",
 "Busnation",
 "Trainnation",
 "Planenation"
 ]
 },{
"Which of these describes something which causes stress or anxiety ? ":[
 "Nerve-racking",
 "Knee-racking",
 "Nodule-racking",
 "Nose-racking"
 ]
 },{
"Which of these is a device often used in a séance ? ":[
 "Ouija board",
 "Ironing board",
 "Cheeseboard",
 "Circuit board"
 ]
 },{
"Which of these is a child's playground game in which participants slap each other's hands ? ":[
 "Pat-a-cake",
 "Pat-a-bap",
 "Pat-a-roll",
 "Pat-a-biscuit"
 ]
 },{
"Which of these is a term for a typically average man ? ":[
 "Joe Bloggs",
 "Joe Cole",
 "Joe Bugner",
 "Joe Strummer"
 ]
 },{
"What is the name of the instrument panel in a car ? ":[
 "Dashboard",
 "Chargeboard",
 "Sprintboard",
 "Jogboard"
 ]
 },{
"What type of protective headgear do motorcyclists wear ? ":[
 "Crash helmet",
 "Bash helmet",
 "Mash helmet",
 "Flash helmet"
 ]
 },{
"In western films, what name is given to a gang of law enforcement officers ? ":[
 "Posse",
 "Bossy",
 "Mossy",
 "Glossy"
 ]
 
 }

];

// Route the incoming request based on type (LaunchRequest, IntentRequest,
// etc.) The JSON body of the request is provided in the event parameter.
exports.handler = function (event, context) {
    try {
        console.log("event.session.application.applicationId=" + event.session.application.applicationId);

        /**
         * Uncomment this if statement and populate with your skill's application ID to
         * prevent someone else from configuring a skill that sends requests to this function.
         */

  //   if (event.session.application.applicationId !== "amzn1.echo-sdk-ams.app.933c50c2-6648-4a7e-b10c-7c336025c6a7") {
    //     context.fail("Invalid Application ID");
      //}

        if (event.session.new) {
            onSessionStarted({requestId: event.request.requestId}, event.session);
        }

        if (event.request.type === "LaunchRequest") {
            onLaunch(event.request,
                event.session,
                function callback(sessionAttributes, speechletResponse) {
                    context.succeed(buildResponse(sessionAttributes, speechletResponse));
                });
        } else if (event.request.type === "IntentRequest") {
            onIntent(event.request,
                event.session,
                function callback(sessionAttributes, speechletResponse) {
                    context.succeed(buildResponse(sessionAttributes, speechletResponse));
                });
        } else if (event.request.type === "SessionEndedRequest") {
            onSessionEnded(event.request, event.session);
            context.succeed();
        }
    } catch (e) {
        context.fail("Exception: " + e);
    }
};

/**
 * Called when the session starts.
 */
function onSessionStarted(sessionStartedRequest, session) {
    console.log("onSessionStarted requestId=" + sessionStartedRequest.requestId
        + ", sessionId=" + session.sessionId);

    // add any session init logic here
}

/**
 * Called when the user invokes the skill without specifying what they want.
 */
function onLaunch(launchRequest, session, callback) {
    console.log("onLaunch requestId=" + launchRequest.requestId
        + ", sessionId=" + session.sessionId);

    getWelcomeResponse(callback);
}

/**
 * Called when the user specifies an intent for this skill.
 */
function onIntent(intentRequest, session, callback) {
    console.log("onIntent requestId=" + intentRequest.requestId
        + ", sessionId=" + session.sessionId);

    var intent = intentRequest.intent,
        intentName = intentRequest.intent.name;

    // handle yes/no intent after the user has been prompted
    if (session.attributes && session.attributes.userPromptedToContinue) {
        delete session.attributes.userPromptedToContinue;
        if ("AMAZON.NoIntent" === intentName) {
            handleFinishSessionRequest(intent, session, callback);
        } else if ("AMAZON.YesIntent" === intentName) {
            handleRepeatRequest(intent, session, callback);
        }
    }

    // dispatch custom intents to handlers here
    if ("AnswerIntent" === intentName) {
        handleAnswerRequest(intent, session, callback);
    } else if ("AnswerOnlyIntent" === intentName) {
        handleAnswerRequest(intent, session, callback);
    } else if ("DontKnowIntent" === intentName) {
        handleAnswerRequest(intent, session, callback);
    } else if ("AMAZON.YesIntent" === intentName) {
        handleAnswerRequest(intent, session, callback);
    } else if ("AMAZON.NoIntent" === intentName) {
        handleAnswerRequest(intent, session, callback);
    } else if ("AMAZON.StartOverIntent" === intentName) {
        getWelcomeResponse(callback);
    } else if ("AMAZON.RepeatIntent" === intentName) {
        handleRepeatRequest(intent, session, callback);
    } else if ("AMAZON.HelpIntent" === intentName) {
        handleGetHelpRequest(intent, session, callback);
    } else if ("AMAZON.StopIntent" === intentName) {
        handleFinishSessionRequest(intent, session, callback);
    } else if ("AMAZON.CancelIntent" === intentName) {
        handleFinishSessionRequest(intent, session, callback);
    } else {
        throw "Invalid intent";
    }
}

/**
 * Called when the user ends the session.
 * Is not called when the skill returns shouldEndSession=true.
 */
function onSessionEnded(sessionEndedRequest, session) {
    console.log("onSessionEnded requestId=" + sessionEndedRequest.requestId
        + ", sessionId=" + session.sessionId);

    // Add any cleanup logic here
}

// ------- Skill specific business logic -------

var ANSWER_COUNT = 4;
var GAME_LENGTH = 5;
var CARD_TITLE = "Question"; // Be sure to change this for your skill.

function getWelcomeResponse(callback) {
    var sessionAttributes = {},
        speechOutput = "I will ask you " + GAME_LENGTH.toString()
            + " questions, try to get as many right as you can. Just say the number of the answer. Let's begin. ",
        shouldEndSession = false,

        gameQuestions = populateGameQuestions(),
        correctAnswerIndex = Math.floor(Math.random() * (ANSWER_COUNT)), // Generate a random index for the correct answer, from 0 to 3
        roundAnswers = populateRoundAnswers(gameQuestions, 0, correctAnswerIndex),

        currentQuestionIndex = 0,
        spokenQuestion = Object.keys(questions[gameQuestions[currentQuestionIndex]])[0],
        repromptText = "Question 1. " + spokenQuestion + " ",

        i, j;

    for (i = 0; i < ANSWER_COUNT; i++) {
        repromptText += (i+1).toString() + ". " + roundAnswers[i] + ". "
    }
    speechOutput += repromptText;
    sessionAttributes = {
        "speechOutput": repromptText,
        "repromptText": repromptText,
        "currentQuestionIndex": currentQuestionIndex,
        "correctAnswerIndex": correctAnswerIndex + 1,
        "questions": gameQuestions,
        "score": 0,
        "correctAnswerText":
            questions[gameQuestions[currentQuestionIndex]][Object.keys(questions[gameQuestions[currentQuestionIndex]])[0]][0]
    };
    callback(sessionAttributes,
        buildSpeechletResponse(CARD_TITLE, speechOutput, repromptText, shouldEndSession));
}

function populateGameQuestions() {
    var gameQuestions = [];
    var indexList = [];
    var index = questions.length;

    if (GAME_LENGTH > index){
        throw "Invalid Game Length.";
    }

    for (var i = 0; i < questions.length; i++){
        indexList.push(i);
    }

    // Pick GAME_LENGTH random questions from the list to ask the user, make sure there are no repeats.
    for (var j = 0; j < GAME_LENGTH; j++){
        var rand = Math.floor(Math.random() * index);
        index -= 1;

        var temp = indexList[index];
        indexList[index] = indexList[rand];
        indexList[rand] = temp;
        gameQuestions.push(indexList[index]);
    }

    return gameQuestions;
}

function populateRoundAnswers(gameQuestionIndexes, correctAnswerIndex, correctAnswerTargetLocation) {
    // Get the answers for a given question, and place the correct answer at the spot marked by the
    // correctAnswerTargetLocation variable. Note that you can have as many answers as you want but
    // only ANSWER_COUNT will be selected.
    var answers = [],
        answersCopy = questions[gameQuestionIndexes[correctAnswerIndex]][Object.keys(questions[gameQuestionIndexes[correctAnswerIndex]])[0]],
        temp, i;

    var index = answersCopy.length;

    if (index < ANSWER_COUNT){
        throw "Not enough answers for question.";
    }

    // Shuffle the answers, excluding the first element.
    for (var j = 1; j < answersCopy.length; j++){
        var rand = Math.floor(Math.random() * (index - 1)) + 1;
        index -= 1;

        var temp = answersCopy[index];
        answersCopy[index] = answersCopy[rand];
        answersCopy[rand] = temp;
    }

    // Swap the correct answer into the target location
    for (i = 0; i < ANSWER_COUNT; i++) {
        answers[i] = answersCopy[i];
    }
    temp = answers[0];
    answers[0] = answers[correctAnswerTargetLocation];
    answers[correctAnswerTargetLocation] = temp;
    return answers;
}

function handleAnswerRequest(intent, session, callback) {
    var speechOutput = "";
    var sessionAttributes = {};
    var gameInProgress = session.attributes && session.attributes.questions;
    var answerSlotValid = isAnswerSlotValid(intent);
    var userGaveUp = intent.name === "DontKnowIntent";

    if (!gameInProgress) {
        // If the user responded with an answer but there is no game in progress, ask the user
        // if they want to start a new game. Set a flag to track that we've prompted the user.
        sessionAttributes.userPromptedToContinue = true;
        speechOutput = "There is no game in progress. Do you want to start a new game? ";
        callback(sessionAttributes,
            buildSpeechletResponse(CARD_TITLE, speechOutput, speechOutput, false));
    } else if (!answerSlotValid && !userGaveUp) {
        // If the user provided answer isn't a number > 0 and < ANSWER_COUNT,
        // return an error message to the user. Remember to guide the user into providing correct values.
        var reprompt = session.attributes.speechOutput;
        var speechOutput = "Your answer must be a number between 1 and " + ANSWER_COUNT + ". " + reprompt;
        callback(session.attributes,
            buildSpeechletResponse(CARD_TITLE, speechOutput, reprompt, false));
    } else {
        var gameQuestions = session.attributes.questions,
            correctAnswerIndex = parseInt(session.attributes.correctAnswerIndex),
            currentScore = parseInt(session.attributes.score),
            currentQuestionIndex = parseInt(session.attributes.currentQuestionIndex),
            correctAnswerText = session.attributes.correctAnswerText;

        var speechOutputAnalysis = "";

        if (answerSlotValid && parseInt(intent.slots.Answer.value) == correctAnswerIndex) {
            currentScore++;
            speechOutputAnalysis = "correct. ";
...

This file has been truncated, please download it to see its full contents.

intent scheme

JSON
{
  "intents": [
    {
      "intent": "AnswerIntent",
      "slots": [
        {
          "name": "Answer",
          "type": "LIST_OF_ANSWERS"
        }
      ]
    },
        {
      "intent": "AnswerOnlyIntent",
      "slots": [
        {
          "name": "Answer",
          "type": "LIST_OF_ANSWERS"
        }
      ]
    },
    {
      "intent": "DontKnowIntent"
    },
    {
      "intent": "AMAZON.StartOverIntent"
    },
    {
      "intent": "AMAZON.RepeatIntent"
    },
    {
      "intent": "AMAZON.HelpIntent"
    },
    {
      "intent": "AMAZON.YesIntent"
    },
    {
      "intent": "AMAZON.NoIntent"
    },
    {
      "intent": "AMAZON.StopIntent"
    },
    {
      "intent": "AMAZON.CancelIntent"
    }
  ]
}

sample utterance

snippets
AnswerIntent the answer is {Answer}
AnswerIntent my answer is {Answer}
AnswerIntent is it {Answer}
AnswerIntent {Answer} is my answer
AnswerOnlyIntent {Answer}

AMAZON.StartOverIntent start game
AMAZON.StartOverIntent new game
AMAZON.StartOverIntent start
AMAZON.StartOverIntent start new game

DontKnowIntent i don't know
DontKnowIntent don't know
DontKnowIntent skip
DontKnowIntent i don't know that
DontKnowIntent who knows
DontKnowIntent i don't know this question
DontKnowIntent i don't know that one
DontKnowIntent dunno

Credits

John

John

2 projects • 1 follower

Comments