Answer the question
In order to leave comments, you need to log in
What does the sessionStorage[user_id]['attempt'] parameter do?
In the task, the player must guess the city from the picture. Now, based on the task, we are writing another program. The
question is this: in the play_game function there is a line attempt = sessionStorage[user_id]['attempt'] (there is also
sessionStorage[user_id]['attempt'] = 1 in the code above) for what does it answer?
I tried to find it in Alice's documentation, but something went wrong)
from flask import Flask, request
import logging
import json
import random
app = Flask(__name__)
logging.basicConfig(level=logging.INFO)
cities = {
'москва': [
'1533899/a828508baf125f948521', '965417/b41b381f2e55c93b8e27'
],
'нью-йорк': [
'1533899/6a3ef6d0598589925c1f', '1540737/4415d6c9d377b216599e'
],
'париж': [
'1521359/555d1246d51f21bca1d0', '1652229/227cfc25581e379aad08'
]
}
sessionStorage = {}
@app.route('/post', methods=['POST'])
def main():
logging.info('Request: %r', request.json)
response = {
'session': request.json['session'],
'version': request.json['version'],
'response': {
'end_session': False
}
}
handle_dialog(response, request.json)
logging.info('Request: %r', response)
return json.dumps(response)
def handle_dialog(res, req):
user_id = req['session']['user_id']
if req['session']['new']:
res['response']['text'] = 'Привет! Назови свое имя!'
sessionStorage[user_id] = {
'first_name': None,
'game_started': False
}
return
first_name = get_first_name(req)
if sessionStorage[user_id]['first_name'] is None:
if first_name is None:
res['response']['text'] = 'Не раслышала имя. Повтори!'
else:
sessionStorage[user_id]['first_name'] = first_name
sessionStorage[user_id]['guessed_cities'] = []
res['response']['text'] = 'Приятно познакомиться, ' + first_name.title() + '. Я Алиса. ' \
'Отгадаешь город по фото?'
res['response']['buttons'] = [
{
'title': 'Да',
'hide': True
},
{
'title': 'Нет',
'hide': True
},
{
'title': 'Помощь',
'hide': True
}
]
else:
if not sessionStorage[user_id]['game_started']:
if 'да' in req['request']['nlu']['tokens']:
if len(sessionStorage[user_id]['guessed_cities']) == 3:
res['response']['text'] = 'Ты отгадал все города!'
res['end_session'] = True
else:
sessionStorage[user_id]['game_started'] = True
sessionStorage[user_id]['attempt'] = 1
play_game(res, req)
elif 'нет' in req['request']['nlu']['tokens']:
res['response']['text'] = 'Ну и ладно!'
res['end_session'] = True
elif req['request']['original_utterance'].lower() == 'помощь':
res['response']['text'] = 'Это игра по отгадыванию городов. ' \
'Назови город по предложенной картинке ^_^'
else:
res['response']['text'] = 'Не понял ответа! Так да или нет?'
res['response']['buttons'] = [
{
'title': 'Да',
'hide': True
},
{
'title': 'Нет',
'hide': True
},
{
'title': 'Помощь',
'hide': True
}
]
elif req['request']['original_utterance'].lower() == 'помощь':
res['response']['text'] = 'Это текст помомщи. Будь смелее и продолжи общение.'
else:
play_game(res, req)
def play_game(res, req):
user_id = req['session']['user_id']
attempt = sessionStorage[user_id]['attempt']
if attempt == 1:
city = list(cities.keys())[random.randint(0, 2)]
while (city in sessionStorage[user_id]['guessed_cities']):
city = list(cities.keys())[random.randint(0, 2)]
sessionStorage[user_id]['city'] = city
res['response']['card'] = {}
res['response']['card']['type'] = 'BigImage'
res['response']['card']['title'] = 'Что это за город?'
res['response']['card']['image_id'] = cities[city][attempt - 1]
res['response']['buttons'] = [
{
'title': 'Помощь',
'hide': True
}
]
else:
city = sessionStorage[user_id]['city']
if get_city(req) == city:
res['response']['text'] = 'Правильно! Сыграем еще?'
res['response']['buttons'] = [
{
'title': 'Да',
'hide': True
},
{
'title': 'Нет',
'hide': True
},
{
'title': 'Помощь',
'hide': True
}
]
sessionStorage[user_id]['guessed_cities'].append(city)
sessionStorage[user_id]['game_started'] = False
return
else:
res['response']['text'] = 'Неправильно'
if attempt == 3:
res['response']['text'] = 'Вы пытались. Это ' + city.title() + '. Сыграем еще?'
res['response']['buttons'] = [
{
'title': 'Да',
'hide': True
},
{
'title': 'Нет',
'hide': True
},
{
'title': 'Помощь',
'hide': True
}
]
sessionStorage[user_id]['game_started'] = False
sessionStorage[user_id]['guessed_cities'].append(city)
return
else:
res['response']['card'] = {}
res['response']['card']['type'] = 'BigImage'
res['response']['card']['title'] = 'Неправильно. Вот тебе дополнительное фото'
res['response']['card']['image_id'] = cities[city][attempt - 1]
res['response']['buttons'] = [
{
'title': 'Помощь',
'hide': True
}
]
sessionStorage[user_id]['attempt'] += 1
def get_city(req):
for entity in req['request']['nlu']['entities']:
if entity['type'] == 'YANDEX.GEO':
if 'city' in entity['value'].keys():
return entity['value']['city']
else:
return None
return None
def get_first_name(req):
for entity in req['request']['nlu']['entities']:
if entity['type'] == 'YANDEX.FIO':
if 'first_name' in entity['value'].keys():
return entity['value']['first_name']
else:
return None
return None
if __name__ == '__main__':
app.run()
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question