Hackster is hosting Hackster Holidays, Ep. 6: Livestream & Giveaway Drawing. Watch previous episodes or stream live on Monday!Stream Hackster Holidays, Ep. 6 on Monday!
John
Published © MIT

Chess Facts

The skill provides some facts about the game of chess which not many chess players may be aware of.

BeginnerShowcase (no instructions)1 hour922

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 simple sample has no external dependencies or session management, and shows the most basic
 * example of how to create a Lambda function for handling Alexa Skill requests.
 *
 * Examples:
 * One-shot model:
 *  User: "Alexa, ask Space Geek for a space fact"
 *  Alexa: "Here's your space fact: ..."
 */

/**
 * App ID for the skill
 */
var APP_ID =undefined; //OPTIONAL: replace with "amzn1.echo-sdk-ams.app.[your-unique-value-here]";

/**
 * Array containing space facts.
 */
var FACTS = [
"The number of possible unique chess games is much greater than the number of electrons in the universe. The number of electrons is estimated to be about 10^79, while the number of unique chess games is 10^120.",
"The longest chess game theoretically possible is 5,949 moves.",
"The longest time for a Castling move to take place was the match game between Bobotsor vs. Irkov in 1966: 46. 0-0.",
"As late as 1561, Castling was two moves. You had to play R-KB1 on one move and K-KN1 on the next move.",
"The word Checkmate in Chess comes from the Persian phrase 'Shah Mat' which means 'the King is dead.'",
"Blathy, Otto (1860-1939), credited for creating the longest Chess Problem, mate in 290 moves.",
"The Police raided a Chess Tournament in Cleveland in 1973, arrested the Tournament director and confiscated the Chess sets on charges of allowing gambling (cash prizes to winners) and possession of gambling devices (the Chess sets).",
"The number of possibilities of a Knight's tour is over 122 million.",
"The longest official chess game lasted 269 moves (I. Nikolic - Arsovic, Belgrade 1989) and ended in a draw.",
"From the starting position, there are eight different ways to Mate in two moves and 355 different ways to Mate in three moves.",
"The new Pawn move, advancing two squares on its first move instead of one, was first introduced in Spain in 1280.",
"Dr. Emanuel Lasker from Germany retained the World Chess Champion title for more time than any other player ever: 26 years and 337 days.",
"In 1985, the Soviet player Garry Kasparov became the youngest World Chess Champion ever at the age of 22 years and 210 days.",
"The first Chessboard with alternating light and dark squares appears in Europe in 1090.",
"During the 1972 Fischer-Spassky match in Rekjavik, the Russians linked Spassky's erratic play with Fischer's chair. The Icelandic organization put a 24-hour Police guard around the chair while chemical and x-ray tests were performed on the chair. Nothing unusual was found.",
"The first mechanical Chess Clock was invented by Thomas Wilson in 1883. Prior to that, Sandglasses were used. Sandglasses were first used in London in 1862. The present day push-button Clock was first perfected by Veenhoff in 1900.",
"The folding Chess board was originally invented in 1125 by a Chess-playing priest. Since the Church forbids priests to play Chess, he hid his Chess board by making one that looked simply like two books lying together.",
"The worst performance by a player was Macleod of Canada who lost 31 games in the New York double-round robin of 1889.",
"Frank Marshall (1877-1944) was the first American to defeat a Soviet player in an international tournament in New York, 1924. He reigned as U.S. Champion for 30 years, but only defended his title once when he defeated Ed Lasker (5-4) in 1923. He was the first master to play more than 100 games simultaneously.",
"In 1985, Eric Knoppert played 500 games of 10-minute Chess in 68 hours.",
"Albert Einstein was a good friend of World Chess Champion Emanuel Lasker. In an interview with the New York Times in 1936 Albert said, 'I do not play any games. There is no time for it.  When I get through work I do not want anything which requires the working of the mind.' He did take up Chess in his later life.",
"There were 72 consecutive Queen moves in the Mason-Mackenzie game at London in 1882.",
"The record of moves without capture is of 100 moves during the Match between Thorton and M. Walker in 1992.",
"Rookies or, players in their first year, are named after the Rook in Chess.  Rooks generally are the last pieces to be moved into action, and the same goes for Rookies.",
"A Computer Program named Deep Thought beat an International Grand Master for the first time in November 1988 in Long Beach, California.",
"Blindfold chess is an impressive skill that many stronger chess players possess.  It certainly requires a keen ability to see the board clearly, which can get difficult after many moves.  The record was set in 1960 in Budapest by Hungarian Janos Flesch, who played 52 opponents simultaneously while blindfolded – he won 31 of those games.",
"There are well over 1,000 different openings, including variations within larger openings/defenses that one can learn.",
"Chess is often cited by psychologists as an effective way to improve memory function.  Also allowing the mind to solve complex problems and work through ideas, it is no wonder that chess is recommended in the fight against Alzheimer’s.  Some contend that it can increase one’s intelligence, though that is a more complex topic. The effects of chess on young individuals had led to chess being introduced in school districts and various countries.  It has been shown to improve children’s grades and other positive effects as well.",
"FIDE stands for Fédération Internationale des Échecs, which literally translates into World Chess Federation.",
"The second book ever printed in the English language was about chess!",
"The first computer program for playing chess was developed in 1951, by Alan Turing.  However, no computer was powerful enough to process it, so Turing tested it by doing the calculations himself and playing according to the results, taking several minutes per move.",
"The oldest recorded chess game in history is from the 900s, between a historian from Baghdad and his student.",
"The oldest surviving complete chess sets were found on the Isle of Lewis, in northern Scotland, and dates to the 12th century.  They were probably made in Iceland or Norway, and their appearance was used in Harry Potter and the Sorcerer’s Stone for the wizard chess pieces.",
"About 600,000,000 (Six hundred million) people know how to play chess worldwide!",
"In many languages, the Pawn is a foot soldier, but in German and Spanish, it’s a peasant or farmer, instead!",
"The reason why traditional chess pieces don’t look like actual soldiers, bishops, and kings is because before the game reached Europe, it passed through the Islamic world.  Islam forbids making statues of animals or people, so chess pieces became vague-looking.  When the game spread to Christian Europe, the pieces didn’t change much.",
"Chess began in India during the Gupta Empire, spreading to the Persian Sassanid Empire, and then to the Middle East after Muslims conquered Persia.  From there, it spread to Europe and Russia.",
"Initially, the Queen could only move one square at a time, diagonally.  Later, she could move two squares at a time, diagonally.  It wasn’t until Reconquista Spain, with its powerful queen Isabella, that the Queen became the strongest piece on the board.",
"In Shatranj, the predecessor to chess, the Queen was a minister or vizier, and still is in many languages.",
"There are even more chess facts possible than the unique chess games (see #1)."
];

/**
 * The AlexaSkill prototype and helper functions
 */
var AlexaSkill = require('./AlexaSkill');

/**
 * SpaceGeek is a child of AlexaSkill.
 * To read more about inheritance in JavaScript, see the link below.
 *
 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript#Inheritance
 */
var Fact = function () {
    AlexaSkill.call(this, APP_ID);
};

// Extend AlexaSkill
Fact.prototype = Object.create(AlexaSkill.prototype);
Fact.prototype.constructor = Fact;

Fact.prototype.eventHandlers.onSessionStarted = function (sessionStartedRequest, session) {
    //console.log("onSessionStarted requestId: " + sessionStartedRequest.requestId + ", sessionId: " + session.sessionId);
    // any initialization logic goes here
};

Fact.prototype.eventHandlers.onLaunch = function (launchRequest, session, response) {
    //console.log("onLaunch requestId: " + launchRequest.requestId + ", sessionId: " + session.sessionId);
    handleNewFactRequest(response);
};

/**
 * Overridden to show that a subclass can override this function to teardown session state.
 */
Fact.prototype.eventHandlers.onSessionEnded = function (sessionEndedRequest, session) {
    //console.log("onSessionEnded requestId: " + sessionEndedRequest.requestId + ", sessionId: " + session.sessionId);
    // any cleanup logic goes here
};

Fact.prototype.intentHandlers = {
    "GetNewFactIntent": function (intent, session, response) {
        handleNewFactRequest(response);
    },

    "AMAZON.HelpIntent": function (intent, session, response) {
        response.ask("You can say tell me a Chess fact, or, you can say exit... What can I help you with?", "What can I help you with?");
    },

    "AMAZON.StopIntent": function (intent, session, response) {
        var speechOutput = "Goodbye";
        response.tell(speechOutput);
    },

    "AMAZON.CancelIntent": function (intent, session, response) {
        var speechOutput = "Goodbye";
        response.tell(speechOutput);
    }
};

/**
 * Gets a random new fact from the list and returns to the user.
 */
function handleNewFactRequest(response) {
    // Get a random space fact from the space facts list
    var factIndex = Math.floor(Math.random() * FACTS.length);
    var randomFact = FACTS[factIndex];

    // Create speech output
    var speechOutput = "Here's your fact: " + randomFact;
    var cardTitle = "Your Chess Fact";
    response.tellWithCard(speechOutput, cardTitle, speechOutput);
}

// Create the handler that responds to the Alexa Request.
exports.handler = function (event, context) {
    // Create an instance of the SpaceGeek skill.
    var fact = new Fact();
    fact.execute(event, context);
};

AlexaSkill.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.
*/

'use strict';

function AlexaSkill(appId) {
    this._appId = appId;
}

AlexaSkill.speechOutputType = {
    PLAIN_TEXT: 'PlainText',
    SSML: 'SSML'
}

AlexaSkill.prototype.requestHandlers = {
    LaunchRequest: function (event, context, response) {
        this.eventHandlers.onLaunch.call(this, event.request, event.session, response);
    },

    IntentRequest: function (event, context, response) {
        this.eventHandlers.onIntent.call(this, event.request, event.session, response);
    },

    SessionEndedRequest: function (event, context) {
        this.eventHandlers.onSessionEnded(event.request, event.session);
        context.succeed();
    }
};

/**
 * Override any of the eventHandlers as needed
 */
AlexaSkill.prototype.eventHandlers = {
    /**
     * Called when the session starts.
     * Subclasses could have overriden this function to open any necessary resources.
     */
    onSessionStarted: function (sessionStartedRequest, session) {
    },

    /**
     * Called when the user invokes the skill without specifying what they want.
     * The subclass must override this function and provide feedback to the user.
     */
    onLaunch: function (launchRequest, session, response) {
        throw "onLaunch should be overriden by subclass";
    },

    /**
     * Called when the user specifies an intent.
     */
    onIntent: function (intentRequest, session, response) {
        var intent = intentRequest.intent,
            intentName = intentRequest.intent.name,
            intentHandler = this.intentHandlers[intentName];
        if (intentHandler) {
            console.log('dispatch intent = ' + intentName);
            intentHandler.call(this, intent, session, response);
        } else {
            throw 'Unsupported intent = ' + intentName;
        }
    },

    /**
     * Called when the user ends the session.
     * Subclasses could have overriden this function to close any open resources.
     */
    onSessionEnded: function (sessionEndedRequest, session) {
    }
};

/**
 * Subclasses should override the intentHandlers with the functions to handle specific intents.
 */
AlexaSkill.prototype.intentHandlers = {};

AlexaSkill.prototype.execute = function (event, context) {
    try {
        console.log("session applicationId: " + event.session.application.applicationId);

        // Validate that this request originated from authorized source.
        if (this._appId && event.session.application.applicationId !== this._appId) {
            console.log("The applicationIds don't match : " + event.session.application.applicationId + " and "
                + this._appId);
            throw "Invalid applicationId";
        }

        if (!event.session.attributes) {
            event.session.attributes = {};
        }

        if (event.session.new) {
            this.eventHandlers.onSessionStarted(event.request, event.session);
        }

        // Route the request to the proper handler which may have been overriden.
        var requestHandler = this.requestHandlers[event.request.type];
        requestHandler.call(this, event, context, new Response(context, event.session));
    } catch (e) {
        console.log("Unexpected exception " + e);
        context.fail(e);
    }
};

var Response = function (context, session) {
    this._context = context;
    this._session = session;
};

function createSpeechObject(optionsParam) {
    if (optionsParam && optionsParam.type === 'SSML') {
        return {
            type: optionsParam.type,
            ssml: optionsParam.speech
        };
    } else {
        return {
            type: optionsParam.type || 'PlainText',
            text: optionsParam.speech || optionsParam
        }
    }
}

Response.prototype = (function () {
    var buildSpeechletResponse = function (options) {
        var alexaResponse = {
            outputSpeech: createSpeechObject(options.output),
            shouldEndSession: options.shouldEndSession
        };
        if (options.reprompt) {
            alexaResponse.reprompt = {
                outputSpeech: createSpeechObject(options.reprompt)
            };
        }
        if (options.cardTitle && options.cardContent) {
            alexaResponse.card = {
                type: "Simple",
                title: options.cardTitle,
                content: options.cardContent
            };
        }
        var returnResult = {
                version: '1.0',
                response: alexaResponse
        };
        if (options.session && options.session.attributes) {
            returnResult.sessionAttributes = options.session.attributes;
        }
        return returnResult;
    };

    return {
        tell: function (speechOutput) {
            this._context.succeed(buildSpeechletResponse({
                session: this._session,
                output: speechOutput,
                shouldEndSession: true
            }));
        },
        tellWithCard: function (speechOutput, cardTitle, cardContent) {
            this._context.succeed(buildSpeechletResponse({
                session: this._session,
                output: speechOutput,
                cardTitle: cardTitle,
                cardContent: cardContent,
                shouldEndSession: true
            }));
        },
        ask: function (speechOutput, repromptSpeech) {
            this._context.succeed(buildSpeechletResponse({
                session: this._session,
                output: speechOutput,
                reprompt: repromptSpeech,
                shouldEndSession: false
            }));
        },
        askWithCard: function (speechOutput, repromptSpeech, cardTitle, cardContent) {
            this._context.succeed(buildSpeechletResponse({
                session: this._session,
                output: speechOutput,
                reprompt: repromptSpeech,
                cardTitle: cardTitle,
                cardContent: cardContent,
                shouldEndSession: false
            }));
        }
    };
})();

module.exports = AlexaSkill;

Credits

John

John

2 projects • 1 follower

Comments