Table of Contents
Today I am going to explain many important concepts through Alexa gaming skill. At the end of this tutorial we shall a functioning Alexa gaming skill.
What we are going to make ?
Quiz Game - Alexa skill development / Custom Alexa skill
What are the features Alexa quiz game have ?
- Multiplayer
- Repeat Question
- Score handling
- Declare winner and loser based on the score
- Resume the game and continue a game
- Help(which instruct users how to play a game)
We will implement the below user interaction model/flow
User: Alexa open "sports trivia quiz"
Alexa: Welcome to the sports trivia quiz, You are going to face many challenging questions of GK. First, tell me how many players want to play quiz? maximum of five players are allowed at a time.
User: Two players are going to play
Alexa: Okay I note down that two players are going to play. Tell me the name of player 1.
User: chirag
Alexa: okay player 1 is Chirag. Tell me the name of the next player
User: gautam
Alexa: player 2 is Gautam. okay, All set. Are you ready for the Quiz?
User: Yes
Alexa: Here is the first question for player one, Tell me what is the capital of India? A. Mumbai B. Chennai C. Delhi D. Ahmedabad
User: can you please repeat the question
Alexa: Tell me what is the capital of India? A. Mumbai B. Chennai C. Delhi D. ahmedabad
User: My answer is c(Do not need to specify Delhi here Alexa just need option)
Alexa: You are absolutely correct. Chirag, Your current score is 10 points. Let's move on to the next question for player two. Tell me which is the largest desert in the world? A. Sahara B. Arabian C. Arctic D. kalhari
User: I will go with b
Alexa: oops! sorry, you are wrong this time. The correct answer is "a. Sahara".
Now it will repeat until Alexa ask five questions to each player and at the it will declare a winner based on the scores.
Alexa: Congrats Chirag, your final score is 50 points. You play very well.
Technology Stack : Flask-ask, Alexa and Amazon web services - Aws Lambda ( Lambda function )
To get a basic idea about how to create a flask application. You can follow this link
Before we start coding, we first need to have a better idea about the following things.
- What is the invocation name? What is the use of it?
- What are utterances?
- What are the intents? How to design intents?
- What are the slots? How to design slots for this skill?
Let's go through each of the above questions and get a better idea about that.
What is the invocation name? What is the use of it ?
Each Alexa skill has a unique identity. We have to define a name for our Alexa skill. We can launch our application through the invocation name.
Go to invocation tab and set a unique innovation name for your skill.
What are utterances ? It is set of all possible user answers
What are the intents ? How to create intents? How to design intents ?
- It is set of utterances
- Go to your skills where you can find the create intent button. Click it and name it whatever you want and then define utterances in it.
- When we are designing intents. It's best practice to design a new intent for each feature.
- In this skill, we want to provide a feature like restart a game.
- Now think about its utterances which could be like starting over, restart quiz, start a new game, etc. And for that, we need to create intent like NewGameIntent or RestartGameIntent
I hope now you are clear how you can create intent in Alexa. In this skill, we required some intents which you can see in the following image.
What are the slots ? How to create slots? How to design slots ?
- It is a set of dynamic values which is used in utterances
- We can add it just by clicking the add button of slot types and then name it whatever we want.
- In Alexa quiz skill we are giving multi-user feature. So to achieve that feature we can think like at the beginning of the quiz Alexa will ask you how many players are going to play? Right. In response, the user can give any number of response like four or five players are going to play. So here we know that numbers are common and repetitive part and it has to be any kind of number. So to handle the response of user we should create slot type of numbers instead of creating different utterances for each player. In this case, we will use a built-in slot type of Alexa which is “AMAZON.NUMBER” which covers all numbers and then define slot name into corresponding intent.
As we have now set up necessary Alexa things. Let's start building the alexa app.
Alexa skill experience with Python - Let's start coding
Create flask ask project if you don’t know how to do it. Refer to this link.
Coding Part
Create flask ask project if you don’t know how to do it. Refer to this link.
Project Structure
Define project structure as follows:
alexa_challenges
speech_assets
- en_IN.json
- challenges.py
- constants.py
- data.py
- logger.py
- responses.py
- utils.py
- .gitignore
- README.md
- requirements.txt
Details of project files
challenges.py: It is the main file of our project where our main logic are going to be written.
constants.py: In this file we will define all constants which we will set in this skill.
data.py: This file contains logic to generate data for quiz. Like function for generating question and answers.
logger.py: It is used to manage log of our skill which is very useful for debugging the skill.
responses.py: It will contain all responses which we will use in this skill.
utils.py: It is used to define helper functions.
speechassets/enIN.json: It will contain whole json data of skill.
requirements.txt: It will contain all requirements of this project or skill.
If you are not getting an idea about any file then don’t worry for now! At the end of this blog I have added github link where you can get all source code so that you can see project structure and files etc.
Create alexa_quiz folder and create challenges.py, constants.py, responses.py and utils.py in it.
challenges.py
from flask_ask import Ask, request, session, question, statement, delegate, audio, current_stream
from responses import RESPONSE
app = Flask(__name__)
ask = Ask(app, "/")
@ask.launch
def launch():
speech_text = RESPONSE['WELCOME_MSG']
return question(speech_text).reprompt(speech_text).simple_card('TRT QUIZ', speech_text)
So in the above code, we simply pass a welcome message to the launch intent. So whenever a user invokes skill using invocation name “sports trivia quiz” then Alexa respond with this welcome message.
reesponses.py
RESPONSE = {
'WELCOME_MSG': 'Welcome to the TRT QUIZ, You are going to face many challenging questions of GK. First tell me how many players want to play quiz? maximum five players are allowed at a time.'
}
You can define helper methods in utils.py. I will not explain each intent and function if I will explain each intent and function then this blog is going to be very long. Instead of that, I am sharing my GitHub code from which you can take reference and make your gaming skills from scratch.
Clone whole project from this link.
Now use python3.6 and install all requirements of the project using the following command $ pip install -r requirements.txt
Just one thing is remaining which is copy JSON data of intent and slots. In Alexa challenges project which you have cloned from a link, It has speech_assets folder in which you find JSON file which contains all intents, slots, and utterances. Now just copy the whole content and paste it in Alexa JSON editor and then click build model button.
Now the magic will happen. All intents and slots will be created automatically. So behind the scenes, It takes JSON data and creates intent and slots according to that data.
In my code, you will see I have used one concept throughout the skill which is sending data from one intent to others. You can consider it as sending data from one endpoint to another endpoint and maintain it in session. So that I can use that data over to different endpoints or intents. Using it we can achieve multiplayer, repeat question, etc.
In flask-ask we used session.attributes to achieve it. For more details refer to this link.
One more thing I want to add here which is important for gaming skill is to resume the game at user left off last time which is going to be very useful right? For that you can implement database integration into your skill and store question answers dataset and users information to your DB and then the user can resume the game from where they left off. Isn’t it awesome!
To run a project using the following command: $ python challenges.py
Now you need to take server endpoint and paste it in Alexa endpoint section. For that, you can use ngrok so you can test it locally.
And that’s it. All things are done. Now you can play Alexa quiz game from your Alexa app. You just need to login into Alexa app using your Alexa developer account credentials.
How to achieve functionalities ?
1 Multiplayer: First of all you should know that how we can manage data into session because in many features we are going to use session data(In flask ask we can store session data using session.attributes). For multiplayer, we can get players count from the response of the user in playerscount intent. Then store it into session data and set dynamic responses in the result of playerscount intent. Like in response we are asking “Tell me the name of first players” and then if user will give his name in response then alexa will call players name intent where we will check players count if players count is two then we will give response like “player 1 is xyz now tell me the name of the next player” and if player count is 1 then we will give response like “player 1 is xyz. Okay all set. Let’s begin the quiz...” I hope you get the logic behind the multiplayers!
Code Snippet:
@ask.intent('PlayerCountIntent')
def count_players(players_count):
try:
info_logger('********* IN PLAYER COUNT INTENT *************')
info_logger('players count: {}'.format(players_count))
quiz_instance = Quiz(session.attributes)
speech_text = quiz_instance.count_players_responses(int(players_count))
except Exception as e:
error_logger(e)
speech_text = RESPONSE['ERROR_MSG']
return question(speech_text).reprompt(speech_text).simple_card('Quiz', speech_text)
@ask.intent('PlayersNameIntent')
def handle_players_info(name):
try:
info_logger('********* IN PLAYER NAME INTENT *************')
info_logger(request)
info_logger('players name: '+name)
quiz_instance = Quiz(session.attributes)
if quiz_instance.track_player_count():
return question(quiz_instance.track_player_count())
elif 'next_intent' in session.attributes.keys():
return question(RESPONSE['ALEXA_MISSUNDERSTOOD'])
elif request.intent['confirmationStatus'] == "DENIED":
return question(RESPONSE['ASK_NAME_AGAIN'])
speech_text = quiz_instance.players_info(name)
except Exception as e:
error_logger(e)
speech_text = RESPONSE['ERROR_MSG']
return question(speech_text).reprompt(speech_text).simple_card('Quiz', speech_text)
2 Repeat Question: It is also achieved with session data. Whenever alexa ask question we just need to put that question into session and when user ask for repeat question then alexa will call repeat question intent in which we will return the last question which we have stored in session data.
Code snippet:
@ask.intent('RepeatQuestionIntent')
def repeat_question():
try:
info_logger('********* IN REPEAT QUESTION INTENT *************')
info_logger('repeat question: '+session.attributes['question'])
speech_text = session.attributes['question']
except Exception as e:
error_logger(e)
speech_text = RESPONSE['ERROR_MSG']
return question(speech_text).reprompt(speech_text).simple_card('Question', speech_text)
3 Score handling: Now assume two players are playing the quiz and when first player gives a correct answer of question then increase 10 points of player 1 and put it in the session data. If player 2 gives wrong answer then do nothing just give losing answer message. It will repeat until the end of the quiz.
Code snippet:
def check_answer(self, answer, user_answer):
'''Check user answer is correct or not and update score accordingly.'''
correct_option = list(answer.keys())[0]
if user_answer.lower() in correct_option.lower():
players = self.attr['players']
current_player = players[str(self.attr['counter'] % self.attr['total_players'])]
current_player['score'] += 10
response = RESPONSE['CORRECT_ANS_MSG'].format(name=current_player['name'],
score=current_player['score'])
speech_text = self.response_with_music(SOUNDS['positive_response'], response)
else:
response = RESPONSE['WRONG_ANS_MSG'].format(
ans=correct_option+' '+self.attr['quiz_data'][self.attr['question']][correct_option])
speech_text = self.response_with_music(SOUNDS['negative_response'], response)
return speech_text
4 Declare a winner based on the score: In previous functionality we managed score of multiple users in session so at the end at last answer of last user we can declare winner based on score data which is stored in session.
Code snippet:
def get_winner(self):
players = self.attr['players']
player_score = { value['name']:value['score'] for key,value in players.items()
if type(value) != int}
winners_list = [key for key, value in player_score.items()
if value == max(player_score.values())]
max_score = max(player_score.values())
return winners_list, max_score
5 Resume the game and continue a game: We can store our session data to mongo db and then when user will invoke alexa quiz skill then we will ask user that he/she wants to continue their previous game and if they want to continue game then we can fetch whole session data and continue quiz using that data which make sense right. This will give an awesome experience to the user.
6 Help(which instruct users how to play a game): In each alexa skill we should define help intent in which we can define guidelines of that skill. So whenever user ask for help or guidance then we alexa will call helpintent and give response accordingly.
Code snippet:
@ask.intent('AMAZON.HelpIntent')
def help():
info_logger('********* IN AMAZON HELP INTENT *************')
speech_text = RESPONSE['HELP_MSG']
return question(speech_text).reprompt(speech_text).simple_card('GUIDE', speech_text)
responses.py where all responses are defined
RESPONSE = {
'ALEXA_MISSUNDERSTOOD': 'Sorry, I couldn\' t get your answer. can you please repeat your answer \
in different way. like i think option or i guess option then give appropriate option.',
'ASK_NAME_AGAIN': 'can you tell me your name again?',
'ASK_READY_MSG': 'Okay then let me know when you feel you are ready for quiz.',
'CORRECT_ANS_MSG': 'You are absolutely correct. {name}, Your current score is {score} points.',
'CURRENT_SKILL': 'You are already in the demo quiz.',
'ERROR_MSG': 'Sorry I can not understand this or maybe something goes wrong for further help \
you can say help me or guide me',
'FALLBACK_MSG': 'Something goes wrong, It seems that you speak something wrong. you should give\
answer like, I think option or I guess option or I will go with option then choose \
appropriate option',
'GET_SINGLE_PLAYER_MSG': 'Hey {name}, Are you ready for the Quiz?',
'GET_MULTI_PLAYER_MSG': 'okay player {number} is {name}. Tell me the name of next player.',
'GET_LAST_PLAYER_MSG': 'player {number} is {name}. okay All set. Are you ready \
for the Quiz?',
'HELP_MSG': 'In this quiz game you first need to specify how many players are going to play \
then give their names one by one after that alexa will ask you questions one by one \
also verify your answers and give you scores accordingly. you can give answer like, I \
think or I guess or i will go with then choose approprirate option. You can choose \
particular category by saying ask me question regarding and then choose any category from \
Entertainment, Science, Mythology, Sports, Geography, History, Politics, Art, Celebrities, \
Animals, and Vehicles. you can also continue quiz after 5 questions if you wanna play \
further.',
'HINT_ANSWER_PATTERN': 'You have to give an answer like, I think option or I guess option or \
I will go with option and then give appropriate option. I hope this will help you.',
'HINT_PLAYER_NAME': 'You should give player name like, abc here or \
I am abc or you can directly give your name.',
'INVALID_CATEGORY': 'sorry but you have to choose category from Entertainment, Science, \
Mythology, Sports, Geography, History, Politics, Art, Celebrities, Animals, and Vehicles.',
'MULTI_WIN_MSG': '{name} have {score} points. so game is tie. Would you like to play further?',
'NO_PLAYERS_MSG': 'At least one player have to play quiz. Without any player quiz can\ 't be\
played.',
'ONE_PLAYER_MSG': 'okay great. Tell me your name please.',
'PLAYERS_OUT_OF_RANGE': 'maximum five players are allowed at a time. so you need to choose \
players between one to five.',
'PLAYBACK_SPEED': 'okay I have set my playback speed {speed}',
'SINGLE_WIN_MSG': 'Congrats {name}, you final score is {score} points. You play very well. \
Would you like to continue?',
'STOP_MSG': 'Okay see you soon.',
'TRACK_PLAYERS_COUNT': 'First Tell me how many players are going to play?',
'TRACK_PLAYER_NAME': 'First Tell me name of player please?',
'VALID_PLAYERS_MSG': 'Okay I note down that {number} players are going to play. \
Tell me the name of player 1. ',
'WELCOME_MSG': 'Welcome to the TRT QUIZ, You are going to face many challenging questions of \
GK. First tell me how many players want to play quiz? maximum five players are \
allowed at a time.',
'WRONG_ANS_MSG': 'oops! sorry you are wrong this time. The correct answer is {ans}. ',
}
### Source Code
Get full source code from this [link](https://github.com/thirdrocktechkno/Alexaquiz).
13 Best Alexa Skills in 2020 That Every Echo User Must Try
Read MoreThird Rock Techkno is a leading IT services company. We are a top-ranked web, voice and mobile app development company with over 10 years of experience. Client success forms the core of our value system.
We have expertise in the latest technologies including angular, react native, iOs, Android and more. Third Rock Techkno has developed smart, scalable and innovative solutions for clients across a host of industries.
Our team of dedicated developers combine their knowledge and skills to develop and deliver web and mobile apps that boost business and increase output for our clients.