Henry Nisce
Created October 28, 2018

Word Hack

Word hack is a word game where a random word is shuffled for the players to figure out.

28

Things used in this project

Hardware components

Echo Show (2nd Gen)
Amazon Alexa Echo Show (2nd Gen)
Display device for showing the shuffled word.
×1
Amazon Web Services Alexa Echo Button
Up to four players can participate using Alexa Echo buttons . First buzz gets the chance to answer first..
×1

Software apps and online services

Amazon Alexa AWS lambda
Code is written using Visual Studio Core ,NET 2.1 Framework . Compiled C #code is uploaded and deployed as AWS Lambda service.
AWS DynamoDB
Amazon Web Services AWS DynamoDB
More than a thousand words stored in the database and randomly chosen and reshuffled for the players to guess.
Alexa Skills Kit
Amazon Alexa Alexa Skills Kit
Skill intents and slots are created using Alexa developer console.

Story

Read more

Schematics

Testing Screen Shot

Code

word hack

C#
using System;
using System.Collections.Generic;
using Amazon.Lambda.Core;

using Alexa.NET.Response;
using Alexa.NET.Request;
using Alexa.NET.Request.Type;
using Amazon.DynamoDBv2.DataModel;
using Amazon.DynamoDBv2;
using System.Linq;
using Newtonsoft.Json;
using Alexa.NET.Response.Directive;
using Alexa.NET.Response.Directive.Templates.Types;
using Alexa.NET.Response.Directive.Templates;
using System.Threading.Tasks;
using System.Drawing.Imaging;
using System.Net.Http;
using System.IO;
using Newtonsoft.Json.Linq;
using Amazon.S3.Model;



[assembly: LambdaSerializerAttribute(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]

namespace WordHack
{
    public class Function
    {
        #region global vars
        const string title = "Word Hack";
        const string numberofPlayersText = "Please tell me number of players?";
        const string yourname = "Please tell me your alias";
        const string help = "Word Hack - is a  word guessing game where  a single word is shuffled for the player to figure out. Word is randomly selected and shown in your echo display device. You have to say the word correctly after pressing your echo button  before the timer expires. ";
        const string help2 = "To restart the game while on answer mode, you can say RESET or RESTART.";
        const string startText = "You can say PLAY? or HELP";
        const string pressTheButton = "Please press the button before you answer";//
        string sayNextText = "Please say NEXT?";
        const string numberOneToFourText = "You can say any number from one to four";
        const string backYesNo = "You can say BACK, YES or NO";
        const string SystemAdmin = "system event";
        const string selectuser = " Try to say an alias again.";
        const string backOrForwardText = "You can either say BACK or press your button to move forward";
        string goodbye = $" Thank you for playing {title}. Goodbye!";

        AsyncSearch<WordHackQuestion> questionQuery = null;
        enum Status { START, HELP, ASKPLAYERS, WAITBUTTON, READY, SURETOEND, JUGGLE, HELPJUGGLE, ASKED, WAITANSWER, ANSWERED,WAITNEXT, FINISH, BACKCONFIRM, EXIT };
        Status status = Status.START;
       DynamoDBContext dbcontext = null;
        const string firstGadget = "first";
        int questionCount = 0;
        string answer = "", prevanswer = "";
        string first, second, third, fourth;
        string lastbuzz = "";
        int playerCount = 0;
        const int timer = 15000;
        const int timerShort = timer;
        List<string> answers = null;
        int questionId = 0, timeoutCount = 0;

        SkillResponse response = new SkillResponse();
        ILambdaLogger log = null;
        IOutputSpeech innerResponse = null;
        IOutputSpeech reprompt = null;
        List<int> questioned = new List<int>();
        List<string> lastbuzzes = null;
        string question = "";
        string lastprompt = "";
        string playerToAnswer = "";
        string alexaVoice = "";
        string item = null;
        string debug = "START CODE";
        Dictionary<string, int> score = null;
        string barred = "halt,cancel,stop,next,repeat,help,hot,back,restart,resume,play,bitch,owl";
        int totalWords = 0;
        long lastTick=0;
        #endregion
   
        private void EndTheGame()
        {
            alexaVoice = goodbye;
            status = Status.START;
            var drtd = new DisplayRenderTemplateDirective
            {
                Template = new BodyTemplate7
                {
                    Token = "A2079",
                    BackButton = BackButtonVisibility.Visible,
                    BackgroundImage = new TemplateImage
                    {
                        ContentDescription = $"{title} background",
                        Sources = new List<ImageSource>
                        {
                            new ImageSource { Url=$"wordhack.jpg" }
                        }
                    },
                    Title = title,
                    Image = new TemplateImage
                    {
                        ContentDescription = "number",
                        Sources = new List<ImageSource>
                        {
                            new ImageSource { Url="thankyou.png" }
                        }
                    },
                }
            };
            response.Response.Directives.Add(drtd);
            response.Response.ShouldEndSession = true;
        }
        public async Task<SkillResponse> FunctionHandler(SkillRequest input, ILambdaContext context)
        {
            innerResponse = new PlainTextOutputSpeech();
            reprompt = new PlainTextOutputSpeech();
            try
            {
                if (answers == null)
                {
                    log = context.Logger;
                    answers = new List<string>();
                    if (!GetWords(log))
                    {

                        using (var client = new AmazonDynamoDBClient())
                        {
                            questionQuery = dbcontext.ScanAsync<WordHackQuestion>(new List<ScanCondition>() { });
                            var answerList = questionQuery.GetRemainingAsync().Result;
                            foreach (var answer in answerList)
                            {
                                var word = answer.Answer;
                                if (!barred.Contains(word.ToLower()) && word.Length < 13)
                                    answers.Add(word);
                            }
                        }
                    }
                    questioned = new List<int>();
                    lastbuzzes = new List<string>();
                    score = new Dictionary<string, int>
                    {
                        { "1",0 },
                        { "2",0 },
                        { "3",0 },
                        { "4",0 }
                    };
                    response.SessionAttributes = new Dictionary<string, object>
                    {
                        { "status", status },
                        { "questionCount", questionCount },
                        { "first", first },
                        { "second", second },
                        { "third", third },
                        { "fourth", fourth },
                        { "playerCount", playerCount },
                        { "questioned", questioned },
                        { "question", question },
                        {  "questionId", questionId },
                        {  "answer", answer },
                        { "lastbuzz", lastbuzz },
                        { "lastbuzzes", lastbuzzes },
                        {"timeoutCount", timeoutCount },
                        {"lastprompt", lastprompt },
                        {"totalWords", totalWords },
                        {"lastTick", lastTick }
                    };
                    response.Response = new ResponseBody();
                }
                debug = "level 1";
                if (input.GetRequestType() == typeof(LaunchRequest))
                {
                    alexaVoice = $"Welcome to {title} game. {startText}";
                    lastprompt = startText;
                    status = Status.START;
                    questioned.Clear();
                    response.Response.Directives.Clear();
                    totalWords = 0;
                    playerCount = 1;
                    var drtd = new DisplayRenderTemplateDirective
                    {
                        Template = new BodyTemplate2
                        {
                            Token = "A2079",
                            BackButton = BackButtonVisibility.Hidden,
                            BackgroundImage = new TemplateImage
                            {
                                ContentDescription = "word hack",
                                Sources = new List<ImageSource>
                            {
                                new ImageSource { Url=$"wordhack.jpg" }
                            }
                            },
                            Title = title
                        }
                    };
                    response.Response.Directives.Add(drtd);
                    response.Response.ShouldEndSession = false;
                }
                else if (input.GetRequestType() == typeof(IntentRequest))
                {
                    try
                    {
                        response.Response.Directives.Clear();
                        debug = "level 2";
                        var intentRequest = (IntentRequest)input.Request;
                        RestoreSession(input);
                        debug = "level 30";
                        alexaVoice = "";
                        {

                            case "AMAZON.FallbackIntent":
                                if (status == Status.JUGGLE)
                                {
                                    if (ProcessAnswer(""))
                                        await ShowWord(false);
                                    alexaVoice = "Fallback " + alexaVoice;
                                }
                                else
                                    alexaVoice = "Sorry, please repeat that";
                                break;
                            case "AMAZON.CancelIntent":
                                alexaVoice = goodbye;
                                response.Response.ShouldEndSession = true;
                                status = Status.EXIT;
                                break;
                            case "AMAZON.StopIntent":
                                alexaVoice = goodbye;
                                response.Response.ShouldEndSession = true;
                                status = Status.EXIT;
                                break;
                            case "AMAZON.HelpIntent":
                                if (status == Status.START)
                                {
                                    status = Status.HELP;
                                    ShowHelp();
                                    alexaVoice = help + help2 + "For now, please say PLAY.";
                                }
                                else if (!(status == Status.JUGGLE || status == Status.WAITANSWER))
                                    alexaVoice = help2 + lastprompt;
                                else
                                    alexaVoice = $"HELP is  not available at this stage. {lastprompt}";
                                break;
                            case "AMAZON.YesIntent":
                                if (status == Status.READY || status == Status.FINISH || status == Status.HELP || status == Status.BACKCONFIRM)
                                {
                                    questioned.Clear();
                                    questionCount = 0;
                                    for (int j = 1; j <= 4; j++)
                                        score[j.ToString()] = 0;
                                    item = AskQuestion(questioned);
                                    timeoutCount = 0;
                                    totalWords = 0;
                                    alexaVoice = $"OK. here is the first word";
                                    response.Response.Directives.Clear();
                                    SetLightColor(response, "000000");
                                    GameEngineExtensions.WhenFirstButtonDown(response, SetPlayerGadgets(playerCount), "buzzedIn", timer);
                                    await ShowWord(false);
                                    if (status != Status.HELP)
                                        status = Status.JUGGLE;
                                    else
                                    {
                                        alexaVoice = numberofPlayersText;
                                        status = Status.ASKPLAYERS;
                                        lastprompt = alexaVoice;
                                    }
                                }
                                else if (status == Status.WAITNEXT)
                                {
                                    alexaVoice = sayNextText; // + " , yesintent, waitnext";
                                    lastprompt = alexaVoice;

                                }
                                else if (status == Status.WAITBUTTON)
                                    alexaVoice = backOrForwardText;
                                else if (status == Status.SURETOEND)
                                {
                                    EndTheGame();
                                }
                                else
                                {

                                        if (ProcessAnswer("hmm"))
                                            await ShowWord(false);
                                }

                                break;
                            case "AMAZON.NoIntent":
                                if (status == Status.FINISH || status == Status.HELP)
                                {
                                    EndTheGame();

                                }
                                else
                                    if (status == Status.READY)
                                {
                                    alexaVoice = "Saying NO ends the game. Are you sure ?";
                                    status = Status.SURETOEND;
                                }
                                else if (status == Status.SURETOEND)
                                {
                                    await StartTheGame();
                                }

                                else
                                    alexaVoice = "Hmm."; status.ToString();
                                break;
                            case "PlayerCount":
                            case "PlayerCountOnly":
                                if (status == Status.ASKPLAYERS)
                                {
                                    var slot = intentRequest.Intent.Slots.FirstOrDefault();
                                    Int32.TryParse(slot.Value.Value, out playerCount);
                                    if (playerCount > 4)
                                    {
                                        alexaVoice = "Only maximum of four is allowed. Please tell me number of players?";
                                    }
                                    else
                                    {
                                        var timeout = 18000;

                                        response.AddRollCall(timeout, SetPlayers(playerCount));
                                        var text = playerCount == 2 ? "Both" : $"All {playerCount}";
                                        text = playerCount == 1 ? "" : text + " players";
                                        var text2 = playerCount == 1 ? "Player 1." : ", First buzz becomes player 1, next becomes player 2 " + (playerCount > 2 ? "and so on." : "");
                                        alexaVoice = $"{text} please press your button {text2}";
                                        SetLightBlink(response);
                                        status = Status.WAITBUTTON;
                                    }
                                }
                                break;
                            case "PlayGame":
                                if (status == Status.START || status == Status.HELP)
                                {
                                    alexaVoice = "Please tell me number of players?";
                                    status = Status.ASKPLAYERS;
                                }

                                break;
                            case "AnswerQuestionIntent":
                            case "AnswerIntent":
                                if (status == Status.WAITANSWER)
                                {
                                    status = Status.ANSWERED;
                                    var slot1 = intentRequest.Intent.Slots.FirstOrDefault().Value.Value;
                                    ProcessAnswer(slot1);
                                }
                                else //maybe saying a command
                                {
                                    var word = intentRequest.Intent.Slots.FirstOrDefault().Value.Value.ToLower();
                                    switch (word)
                                    {
                                        case "score":
                                            if (status == Status.JUGGLE || status == Status.WAITANSWER || status == Status.WAITNEXT)
                                                alexaVoice = CheckScore();
                                            else
                                                alexaVoice = $"Score not yet available. {lastprompt}";
                                            break;

                                        case "next":
                                            if (status == Status.WAITNEXT)
                                            {
                                                lastbuzzes.Clear();
                                                item = AskQuestion(questioned);
                                                debug = "32";
                                                if (item != null)
                                                {
                                                    await ShowWord(false);
                                                    alexaVoice += $" Here is the  next word";
                                                    SetLightColor(response, "000000");
                                                }
                                                else
                                                {
                                                    status = Status.FINISH;
                                                    alexaVoice += " There are no more words. " + CheckScore() + ". Do you want another set?";
                                                }
                                                GameEngineExtensions.WhenFirstButtonDown(response, SetPlayerGadgets(playerCount), "buzzedIn", timer);
                                                status = Status.JUGGLE;
                                            }

                                            else
                                            {
                                                alexaVoice = $"Sorry. That command is not available for now";
                                            }
                                            break;
                                        case "reset":
                                        case "restart":
                                            switch (status)
                                            {
                                                case Status.ASKED:
                                                case Status.WAITANSWER:
                                                case Status.JUGGLE:
                                                    alexaVoice = $"Are you sure you want to restart the game?";
                                                    status = Status.BACKCONFIRM;
                                                    break;
                                                default:
                                                    alexaVoice = $"Welcome to {title} game. {startText}";
                                                    status = Status.START;
                                                    break;

                                            }
                                            break;
                                        case "continue":
                                        case "resume":
                                            if (status == Status.JUGGLE || status == Status.WAITNEXT)
                                            {
                                                alexaVoice = $"Resuming game. {sayNextText}";
                                                lastprompt = sayNextText;
                                                response.Response.Directives.Clear();
                                                GameEngineExtensions.WhenFirstButtonDown(response, SetPlayerGadgets(playerCount), "buzzedIn", timer);
                                            }

                                            else
                                                alexaVoice = lastprompt;
                                            break;
                                        case "back":
                                            switch (status)
                                            {
                                                case Status.WAITBUTTON:
                                                case Status.READY:

                                                    alexaVoice = numberofPlayersText;
                                                    lastprompt = alexaVoice;
                                                    status = Status.ASKPLAYERS;
                                                    break;
                                                case Status.ASKPLAYERS:

                                                    alexaVoice = $"Going Back will reset to the beginning . Are you sure you want to go back?";
                                                    status = Status.BACKCONFIRM;
                                                    break;
                                                case Status.START:
                                                    alexaVoice = $"Welcome to {title} game. {startText}";
                                                    lastprompt = alexaVoice;
                                                    status = Status.START;
                                                    break;
                                                default:
                                                    alexaVoice = $"Going Back will reset to the beginning . Are you sure you want to go back?";
                                                    status = Status.BACKCONFIRM;
                                                    break;
                                            }
                                            break;
                                        default:
                                            debug = "39";
                                            response.Response.Directives.Clear();
                                            var slot1 = word.ToUpper();
                                            debug = "40";
                                            if (timeoutCount < 2)
                                                timeoutCount++;
                                            switch (status)
                                            {
                                                case Status.JUGGLE:
                                                case Status.WAITANSWER:
                                                    if (playerCount > 1)
                                                    {
                                                        debug = "41";
                                                        ProcessAnswer(slot1);
                                                        //alexaVoice += "process answer done";
                                                    }
                                                    else
                                                    {
                                                        debug = "42";
                                                        if (ProcessAnswer(slot1))
                                                            await ShowWord(false);
                                                    }
                                                    break;
                                                case Status.START:
                                                    alexaVoice = startText;
                                                    break;
                                                case Status.ASKPLAYERS:
                                                    alexaVoice = numberOneToFourText;
                                                    break;
                                                case Status.WAITBUTTON:
                                                    alexaVoice = backOrForwardText;
                                                    break;
                                            }
                                            break;
                                    }
                                   
                                }
                                break;
                            default:
                                debug = "defaultcase2";
                                if (status == Status.JUGGLE && playerCount > 1)
                                    alexaVoice = pressTheButton + "default"; // resource.HelpReprompt;

                                else if (status == Status.WAITBUTTON)
                                    alexaVoice = " I am waiting for all to press the button";

                                else if (status == Status.JUGGLE)
                                {
                                     ProcessAnswer("");
                                }
                                else if (status == Status.READY)
                                {
                                    alexaVoice = backOrForwardText;
                                }
                                else if (status == Status.ASKPLAYERS)
                                {
                                    alexaVoice = numberOneToFourText;
                                }
                                else
                                    alexaVoice = $"Sorry, I did not get that";// {status}";
                                break;
                        }
                    }
                    catch (Exception ex)
                    {
                        alexaVoice = $"{ex.Message} {ex.InnerException} while {debug}";// {status}"
                    }
                }
                else if (input.GetRequestType() == typeof(InputHandlerEventRequest))
                {
                    response.Response.Directives.Clear();
                    RestoreSession(input);

                    response.Response.ShouldEndSession = false;
                    var inputHandlerRequest = (InputHandlerEventRequest)input.Request;
                    var dictGadgets = new Dictionary<string, string>();
                    var gadgetEvent = inputHandlerRequest.Events[0];
                        switch (status)
                        {
                            case Status.READY:
                                alexaVoice = " I am all set. Are you " + (playerCount == 1 ? "" : "guys") + " ready?";
                                break;
                            case Status.WAITBUTTON:
                                if (gadgetEvent.Name == "timed out")
                                {
                                    alexaVoice = $"I havent detected {playerCount} buttons yet. All players must press their button or say restart";
                                }
                                else
                                {
                                    GameEngineExtensions.TryRollCallResult(inputHandlerRequest, out dictGadgets, SetPlayers(playerCount));
                                    alexaVoice = "OK I am all set.  Are you guys ready?";
                                    foreach (var d in dictGadgets)
                                    {
                                        if (d.Key == "first") first = d.Value;
                                        if (d.Key == "second") second = d.Value;
                                        if (d.Key == "third") third = d.Value;
                                        if (d.Key == "fourth") fourth = d.Value;
                                    }
                                    status = Status.READY;
                                }
                                break;
                            case Status.WAITANSWER:
                            case Status.JUGGLE:
                                if (gadgetEvent.Name == "timed out")
                                {
                                    if (DateTime.Now.Ticks - lastTick > 100000000)
                                    {
                                        alexaVoice = $"Time is up? ";
                                        if (status == Status.JUGGLE)
                                        {
                                            alexaVoice += $"The Correct answer is, {answer}! Please say next";
                                            status = Status.WAITNEXT;
                                        }
                                        else
                                            OthersChance();
                                    }
                                    else
                                    {
                                        //alexaVoice = "Doubtful Time out";
                                        GameEngineExtensions.WhenFirstButtonDown(response, SetPlayerGadgets(playerCount), "buzzedIn", timer);
                                    }
                               

                                }
                                else
                                {
                                       CallPlayerNumber(gadgetEvent);
                                }
                                break;
                        }
                   // }
                }
            }
            catch (Exception ex)
            {
                log.LogLine($"ERROR: {ex.Message}");
                alexaVoice = $"Sorry. I have problems processing your request  while in {status} and {debug}";
                response.Response.Directives.Clear();
                status = Status.START;
                response.Response.ShouldEndSession = true;
            }
            if (status == Status.JUGGLE)
            {
                response.Response.ShouldEndSession = null;
            }
            if (status == Status.WAITNEXT)
            {
                response.Response.ShouldEndSession = false;
            }
            if (status == Status.EXIT)
            {
                var drtd = new DisplayRenderTemplateDirective
                {
                    Template = new BodyTemplate7
                    {
                        Token = "A2079",
                        BackButton = BackButtonVisibility.Hidden,
                        BackgroundImage = new TemplateImage
                        {
                            ContentDescription = "Word Hack Background",
                            Sources = new List<ImageSource>
                        {
                            new ImageSource { Url=$"wordhack.jpg" }
                        }
                        },
                        Title = "Thank you for playing Word Hack",
                        Image = new TemplateImage
                        {
                            ContentDescription = "number",
                            Sources = new List<ImageSource>
                        {
                            new ImageSource { Url="thankyou.png" }
                        }
                        },
                    }
                };
                response.Response.Directives.Add(drtd);
            }
            (innerResponse as PlainTextOutputSpeech).Text = alexaVoice;
            response.Response.OutputSpeech = innerResponse;
            response.Version = "1.0";
            WriteSession();
            return response;
        }
        void OthersChance()
        {
            lastbuzzes.Add(lastbuzz);
            if (lastbuzzes.Count < playerCount)
            {
                alexaVoice += $" Next answer?";
                debug = "last2";
                GadgetControllerExtensions.GadgetColor(response, "FF0000", lastbuzzes.ToArray(), 8000);
                GameEngineExtensions.WhenFirstButtonDown(response, ReSetPlayerGadgets(playerCount), "buzzedIn", timerShort);
                status = Status.JUGGLE;
            }
            else
            {
                debug = "last3";
                alexaVoice += $" Correct answer is, { answer}. ";
                lastbuzzes.Clear();
                item = AskQuestion(questioned);
                debug = "last4";
                alexaVoice += CheckScore();
                if (item != null)
                {
                    alexaVoice += $"{sayNextText}";
                    lastprompt = sayNextText;
                    SetLightColor(response, "000000");
                    status = Status.WAITNEXT;
                }
                else
                {
                    debug = "last7";
                    status = Status.FINISH;
                    alexaVoice += " There are no more questions." + CheckScore() + " Do you want another set?";
                    SetLightColor(response, "00FF00");
                    response.Response.Directives.Clear();
                }
            }
        }
        private bool ProcessAnswer(string slot)
        {
            response.Response.Directives.Clear();
            if (status == Status.ANSWERED)
            {
                alexaVoice += $"{slot}, ";
                if (slot == answer.ToLower())
                {
                    var newscore = score[playerToAnswer];
                    score[playerToAnswer] = newscore + 1;
                    debug = "level 5";
                    item = AskQuestion(questioned);
                    if (item != null)
                    {
                        alexaVoice += $"That is correct. {CheckScore()} {sayNextText}";
                        lastprompt = sayNextText;
                        SetLightColor(response, "000000");
                        status = Status.WAITNEXT;
                    }
                    else
                    {
                        status = Status.FINISH;
                        alexaVoice += " There are no more questions. " + CheckScore() + " Do you want another set?";
                    }
                }
                else
                {
                    alexaVoice += "That is not correct.";// Any other answer?";
                    OthersChance();
                }
            }
            else
            {
                if (status == Status.WAITNEXT)
                {
                    alexaVoice += sayNextText;// + " Processanswer no waitanswer";
                    lastprompt = sayNextText;
                }
                else
                {
                    alexaVoice += pressTheButton;// + status.ToString();

                }
            }
            return true;

        }
        private async Task<int> StartTheGame()
        {
            questioned.Clear();
            questionCount = 0;
            for (int j = 1; j <= 4; j++)
                score[j.ToString()] = 0;
            item = AskQuestion(questioned);
            timeoutCount = 0;
            alexaVoice += $"OK. here is the first word";
            response.Response.Directives.Clear();
            await ShowWord(false);
            GameEngineExtensions.WhenFirstButtonDown(response, SetPlayerGadgets(playerCount), "timer", timer);
            return 0;
        }
        private void CallPlayerNumber(GadgetEvent gadgetEvent)
        {

            var num = "1";
            debug = "12";
            var id = gadgetEvent.InputEvents[0].GadgetId;
            debug = "16";
            if (id == second) num = "2";
            else if (id == third) num = "3";
            else if (id == fourth) num = "4";
            alexaVoice = $"Yes Player {num}?";
            playerToAnswer = num;
            status = Status.WAITANSWER;
            debug = "13";
            GameEngineExtensions.WhenFirstButtonDown(response, new[] { "none" }, "buzzedIn", timer);
            GadgetControllerExtensions.GadgetColor(response, "FF0000", SetPlayerGadgets(playerCount), 9000);
            lastbuzz = id;
        }
        private string[] ReSetPlayerGadgets(int playerCount)
        {
            string[] players = new string[playerCount];
            for (int k = 1; k <= playerCount; k++)
            {
                if (k == 1 && !lastbuzzes.Contains(first))
                    players[k - 1] = first;
                if (k == 2 && !lastbuzzes.Contains(second))
                    players[k - 1] = second;
                if (k == 3 && !lastbuzzes.Contains(third))
                    players[k - 1] = third;
                if (k == 4 && !lastbuzzes.Contains(fourth))
                    players[k - 1] = fourth;

            }
            return players;
        }
        private string[] SetPlayerGadgets(int playerCount)
        {
            string[] players = new string[playerCount];
            switch (playerCount)
            {
                case 1:
                    players[0] = first;
                    break;
                case 2:
                    players[0] = first;
                    players[1] = second;
                    break;
                case 3:
                    players[0] = first;
                    players[1] = second;
                    players[2] = third;
                    break;
                case 4:
                    players[0] = first;
                    players[1] = second;
                    players[2] = third;
                    players[3] = fourth;
                    break;
            }
            return players;
        }
        private string[] SetPlayers(int playerCount)
        {

            string[] players = new string[playerCount];
            switch (playerCount)
            {
                case 1:
                    players[0] = "first";
                    break;
                case 2:
                    players[0] = "first";
                    players[1] = "second";
                    break;
                case 3:
                    players[0] = "first";
                    players[1] = "second";
                    players[2] = "third";
                    break;
                case 4:
                    players[0] = "first";
                    players[1] = "second";
                    players[2] = "third";
                    players[3] = "fourth";
                    break;
            }
            return players;
        }
        private void SetLightBlink(SkillResponse response)
        {
            if (playerCount == 1)
                return;
            var setLight = SetLightDirective.Create(
               SetLightParameter.Create(
                   SetLightAnimation.Create(
                       100, new List<string> { "1" },
                       AnimationSegment.Create("FF0000", 500)
                       , AnimationSegment.Create("000000", 500)

                   )));

            response.Response.Directives.Add(setLight);
        }
        private void SetLightColor(SkillResponse response, string color)
        {
            if (playerCount == 1)
                return;
            var setLight = SetLightDirective.Create(
               SetLightParameter.Create(

                   SetLightAnimation.CreateSingle(
                       AnimationSegment.Create(color, 1000)

                   )));

            response.Response.Directives.Add(setLight);
        }
        private string AskQuestion(List<int> questioned)
        {
            prevanswer = answer;
            int MAXQUESTION = answers.Count;
            //questioned.ForEach(q=> log)
            if (questionCount == MAXQUESTION)
            {
                return null;

            }
            var idx = 0;
            Random rand = new Random();
            var loop = 0;
            var full = false;
            debug = "100";
            while (true)
            {
                idx = rand.Next(0, MAXQUESTION);
                //idx = questions[idx].Id;
                if (questioned.Contains(idx))
                {
                    loop++;
                    if (loop == 1000)
                    {
                        full = true;
                        debug = "102";
                        break;
                    }
                    continue;
                }
                questioned.Add(idx);
                questionCount++; ;

                break;
            }
            debug = "101";
            if (full)
            {
                return null;
            }
            debug = "102";
            var q = answers[idx];
            debug = "103";
            answer = q.ToUpper();
            question = answer;
            //alexaVoice += CheckScore();
            return q;
        }
        void RestoreSession(SkillRequest input)
        {
            questionCount = int.Parse(input.Session.Attributes["questionCount"].ToString());

            answer = input.Session.Attributes["answer"].ToString();
            playerCount = int.Parse(input.Session.Attributes["playerCount"].ToString());
            timeoutCount = int.Parse(input.Session.Attributes["timeoutCount"].ToString());
            status = (Status)Enum.Parse(typeof(Status), input.Session.Attributes["status"].ToString());
            questioned = JsonConvert.DeserializeObject<List<int>>(input.Session.Attributes["questioned"].ToString());
            debug = "333";
            question = input.Session.Attributes["question"].ToString();
            debug = "4";
            questionId = int.Parse(input.Session.Attributes["questionId"].ToString());
            debug = "5";
            lastbuzz = input.Session.Attributes["lastbuzz"].ToString();
            lastbuzzes = JsonConvert.DeserializeObject<List<string>>(input.Session.Attributes["lastbuzzes"].ToString());
            score = JsonConvert.DeserializeObject<Dictionary<string, int>>(input.Session.Attributes["score"].ToString());
            playerToAnswer = input.Session.Attributes["playerToAnswer"].ToString();
            lastprompt = input.Session.Attributes["lastprompt"].ToString();
            totalWords = int.Parse(input.Session.Attributes["totalWords"].ToString());
            lastTick = long.Parse(input.Session.Attributes["lastTick"].ToString());
        }
        void WriteSession()
        {
            response.SessionAttributes["status"] = status;
            response.SessionAttributes["questionCount"] = questionCount;
            response.SessionAttributes["timeoutCount"] = timeoutCount;
            response.SessionAttributes["answer"] = answer;
            response.SessionAttributes["first"] = first;
            response.SessionAttributes["second"] = second;
            response.SessionAttributes["third"] = third;
            response.SessionAttributes["fourth"] = fourth;
            response.SessionAttributes["playerCount"] = playerCount;
            response.SessionAttributes["questioned"] = questioned;
            response.SessionAttributes["question"] = question;
            response.SessionAttributes["questionId"] = questionId;
            response.SessionAttributes["lastbuzz"] = lastbuzz;
            response.SessionAttributes["lastbuzzes"] = lastbuzzes;
            response.SessionAttributes["score"] = score;
            response.SessionAttributes["playerToAnswer"] = playerToAnswer;
            response.SessionAttributes["lastprompt"] = lastprompt;
            response.SessionAttributes["totalWords"] = totalWords;
            response.SessionAttributes["lastTick"] = DateTime.Now.Ticks;
        }
        void LastBuzzAdd()
        {
            debug = "last 1";
            lastbuzzes.Add(lastbuzz);

            debug = "last3";
            if (lastbuzzes.Count() == playerCount)
            {
                alexaVoice += $" Correct word is, { answer}. ";
                lastbuzzes.Clear();
                item = AskQuestion(questioned);
                debug = "last4";
                if (item != null)
                {
                    status = Status.JUGGLE;
                }
                else
                {
                    debug = "last7";
                    status = Status.FINISH;
                    alexaVoice += " There are no more questions." + CheckScore() + " Do you want another set?";
                    SetLightColor(response, "00FF00");
                    response.Response.Directives.Clear();
                }
            }
            else
            {
                OthersChance();
            }


        }
        private string CheckScore()
        {
            var scoreText = "";

                scoreText = " The score is. ";
                for (int i = 1; i <= playerCount; i++)
                {
                    scoreText += $" Player {i}, {score[i.ToString()] }, ";
                }


            return scoreText;
        }
        private void ShowHelp()
        {
            var drtd = new DisplayRenderTemplateDirective
            {
                Template = new BodyTemplate2
                {
                    Token = "A2079",
                    BackButton = BackButtonVisibility.Hidden,
                    Image = new TemplateImage
                    {
                        ContentDescription = "Buzz word",
                        Sources = new List<ImageSource>
                        {
                            new ImageSource { Url=$"wordhack.jpg" }
                        }
                    },

                    Title = "Word Hack Help",
                    Content = new TemplateContent
                    {
                        Primary = new TemplateText
                        {
                            Text = help,
                            Type = "RichText"
                        },
                        Secondary = new TemplateText
...

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

Credits

Henry Nisce

Henry Nisce

1 project • 0 followers
Software Developer for more than 20 yrs specializing in desktop and web applications with hardware interfacing skills using MS devt tools .

Comments