Ejemplo n.º 1
0
def progressStory(battle):
    logger.info('progressing story')
    battleId = battle['questBattleId']
    response = {}
    # check if it's the last battle in a chapter
    if battleId in nextChapter:
        clearedChapterId = int(str(battle['questBattleId'])[2:4])
        clearedChapter = dt.getUserObject('userChapterList', clearedChapterId)
        clearedChapter['cleared'] = True
        clearedChapter['clearedAt'] = nowstr()

        if nextChapter[battleId] is not None:
            logger.info('battleId in nextChapter')
            startNewChapter(nextChapter[battleId], response)

        response['userChapterList'] = response.get('userChapterList',
                                                   []) + [clearedChapter]
        dt.setUserObject('userChapterList', clearedChapterId, clearedChapter)

    # check if it's the last battle in a secton
    if battleId in nextSection:
        clearedSectionId = battle['questBattle']['sectionId']
        clearedSection = dt.getUserObject('userSectionList', clearedSectionId)
        clearedSection['cleared'] = True
        clearedSection['clearedAt'] = nowstr()

        if 'clearReward' in clearedSection['section']:
            response = obtainReward(clearedSection['section']['clearReward'],
                                    response)

        # TODO: make challenge quests work as well
        addChallengeQuests(clearedSectionId, response)

        if nextSection[battleId] is not None:
            logger.info('battleId in nextSection')
            for nextSectionId in nextSection[battleId]:
                startNewSection(nextSectionId, response)

        response['userSectionList'] = response.get('userSectionList',
                                                   []) + [clearedSection]
        dt.setUserObject('userSectionList', clearedSectionId, clearedSection)

    # when it's not the last battle, get the next battle
    if battleId + 1 in dt.masterBattles:  # not sure if this heuristic is always the case
        newBattle, exists = newtil.createUserQuestBattle(battleId + 1)
        if not exists:
            response['userQuestBattleList'] = response.get(
                'userQuestBattleList', []) + [newBattle]
            dt.setUserObject('userQuestBattleList', battleId + 1, newBattle)

    return response
Ejemplo n.º 2
0
def createUserEnemy(enemyId):
    return {
        'userId': dt.userId,
        'createdAt': nowstr(),
        'enemyId': enemyId,
        'enemy': dt.masterEnemies[enemyId]
    }, dt.getUserObject('userEnemyList', enemyId) is not None
Ejemplo n.º 3
0
def save():
    body = flask.request.json

    # sometimes, when you continue to edit a team, the deckType isn't sent at all,
    # so we have to store it
    # not sure if the request ever doesn't have a deckType on the first time you edit a team
    if 'deckType' in body:
        deckType = body['deckType']
        dt.saveJson('data/user/deckType.json',{'deckType': body['deckType']})
    else:
        deckType = dt.readJson('data/user/deckType.json')['deckType']

    userDeck = dt.getUserObject('userDeckList', deckType)
    if userDeck is None:
        userDeck = {'createdAt': nowstr(), 'userId': dt.userId, 'deckType': deckType}
    
    userDeck['name'] = body['name']
    
    if 'questPositionHelper' in body.keys():
        userDeck['questPositionHelper'] = body['questPositionHelper']
    if 'episodeUserCardId' in body.keys():
        userDeck['questEpisodeUserCardId'] = body['episodeUserCardId']
    if 'formationSheetId' in body.keys():
        userDeck['formationSheetId'] = body['formationSheetId']
        
    userFormation = dt.getUserObject('userFormationSheetList', body['formationSheetId'])
    if userFormation is None:
        flask.abort(400, description='{"errorTxt": "Trying to use a nonexistent formation","resultCode": "error","title": "Error"}')

    userDeck['formationSheet'] = userFormation['formationSheet']

    keys = set(userDeck.keys())
    for key in keys:
        if key.startswith('questPositionId') or key.startswith('userCardId') or key.startswith('userPieceId'):
            del userDeck[key]        

    for i, positionId in enumerate(body['questPositionIds']):
        userDeck['questPositionId'+str(i+1)] = positionId
    
    for i, cardId in enumerate(body['userCardIds']):
        userDeck['userCardId'+str(i+1)] = cardId

    for i, pieceIdList in enumerate(body['userPieceIdLists']):
        numSlots = dt.getUserObject('userCardList', userDeck['userCardId'+str(i+1)])['revision'] + 1
        numMemoriaAssigned = 0
        for j, pieceId in enumerate(pieceIdList):
            userDeck['userPieceId0'+str(i+1)+str(j+1)] = pieceId
            numMemoriaAssigned += 1
            if numMemoriaAssigned >= numSlots:
                break

    dt.setUserObject('userDeckList', deckType, userDeck)
    gameUser = dt.setGameUserValue('deckType', deckType)
    
    return flask.jsonify({
        'resultCode': 'success',
        'userDeckList': [userDeck],
        'gameUser': gameUser
    })
Ejemplo n.º 4
0
def createUserFormation(formationId):
    formation = dt.masterFormations[formationId]
    return {
        "userId": dt.userId,
        "formationSheetId": formationId,
        "createdAt": nowstr(),
        "formationSheet": formation
    }, dt.getUserObject('userFormationSheetList', formationId) is not None
Ejemplo n.º 5
0
def createUserDoppel(doppelId):
    doppel = dt.masterDoppels[doppelId]
    return {
        "userId": dt.userId,
        "doppelId": doppelId,
        "doppel": doppel,
        "createdAt": nowstr()
    }, dt.getUserObject('userDoppelList', doppelId) is not None
Ejemplo n.º 6
0
def receiveReward(challenge):
    response = {}
    for reward in challenge['challenge']['rewardCodes'].split(','):
        response = dt.updateJson(response, obtainItem(reward))
    challenge['receivedAt'] = nowstr()
    dt.setUserObject('userDailyChallengeList', challenge['challengeId'],
                     challenge)
    return response
Ejemplo n.º 7
0
def createUserChapter(chapterId):
    return {
        "chapter": dt.masterChapters[chapterId],
        "chapterId": chapterId,
        "cleared": False,
        "createdAt": nowstr(),
        "userId": dt.userId
    }, dt.getUserObject('userChapterList', chapterId) is not None
Ejemplo n.º 8
0
def createUserMeguca(charaId, card=None):
    userCardId = str(uuid1())
    masterCard = dt.masterCards[charaId]
    chara = masterCard['chara']

    if card is None:
        card = masterCard['cardList'][0]['card']
    userCard = {
        "id": userCardId,
        "userId": dt.userId,
        "cardId": card['cardId'],
        "displayCardId": card['cardId'],
        "revision": 0,
        "attack": card['attack'],
        "defense": card['defense'],
        "hp": card['hp'],
        "level": 1,
        "experience": 0,
        "magiaLevel": 1,
        "enabled": True,
        "customized1": False,
        "customized2": False,
        "customized3": False,
        "customized4": False,
        "customized5": False,
        "customized6": False,
        "createdAt": nowstr(),
        "card": card
    }
    userChara = {
        "userId": dt.userId,
        "charaId": charaId,
        "chara": chara,
        "bondsTotalPt": 0,
        "userCardId": userCardId,
        "lbItemNum": 0,
        "visualizable": True,
        "commandVisualType": "CHARA",
        "commandVisualId": charaId,
        "live2dId": "00",
        "createdAt": nowstr()
    }
    userLive2d, _ = createUserLive2d(charaId, '00', 'Magical Girl')
    userLive2d['defaultOpened'] = True
    return userCard, userChara, userLive2d
Ejemplo n.º 9
0
def createUserSection(sectionId):
    return {
        "userId": dt.userId,
        "sectionId": sectionId,
        "section": dt.masterSections[sectionId],
        "canPlay": True,
        "cleared": False,
        "createdAt": nowstr()
    }, dt.getUserObject('userSectionList', sectionId) is not None
Ejemplo n.º 10
0
def createUserItem(item):
    return {
        "userId": dt.userId,
        "itemId": item['itemCode'],
        "environmentId": "COMMON",
        "quantity": 0,
        "total": 0,
        "item": item,
        "createdAt": nowstr()
    }
Ejemplo n.º 11
0
def createUserQuestBattle(battleId):
    return {
        "userId": dt.userId,
        "questBattleId": battleId,
        "questBattle": dt.masterBattles[battleId],
        "cleared": False,
        "missionStatus1": "NON_CLEAR",
        "missionStatus2": "NON_CLEAR",
        "missionStatus3": "NON_CLEAR",
        "rewardDone": False,
        "createdAt": nowstr()
    }, dt.getUserObject('userQuestBattleList', battleId) is not None
Ejemplo n.º 12
0
def regist():
    adventureId = flask.request.json['adventureId']
    newAdventure = {
        "adventureId": adventureId,
        "createdAt": nowstr(),
        "skipped": False,
        "userId": dt.userId
    }
    dt.setUserObject('userQuestAdventureList', adventureId, newAdventure)
    return flask.jsonify({
        "userQuestAdventureList": [newAdventure]
    })
Ejemplo n.º 13
0
def addStory(charaId):
    existingSections = dt.listUserObjectKeys('userSectionList')
    validSections = dt.masterSections.keys()
    userSectionDict = {}
    for i in range(4):
        sectionId = int('3{0}{1}'.format(charaId, i+1))
        if sectionId in existingSections: continue
        if sectionId in validSections:
            userSectionDict[sectionId] = {
                "userId": dt.userId,
                "sectionId": sectionId,
                "section": dt.masterSections[sectionId],
                "canPlay": str(sectionId).endswith('1'),
                "cleared": False,
                "createdAt": nowstr()
            }

    existingBattles = dt.listUserObjectKeys('userQuestBattleList')
    validBattles = dt.masterBattles.keys()
    userQuestBattleDict = {}
    for i in range(4):
        for j in range(3):
            battleId = int('3{0}{1}{2}'.format(charaId, i+1, j+1))
            if battleId in existingBattles: continue
            if battleId in validBattles:
                userQuestBattleDict[battleId] = {
                    "userId": dt.userId,
                    "questBattleId": battleId,
                    "questBattle": dt.masterBattles[battleId],
                    "cleared": False,
                    "missionStatus1": "NON_CLEAR",
                    "missionStatus2": "NON_CLEAR",
                    "missionStatus3": "NON_CLEAR",
                    "rewardDone": False,
                    "createdAt": nowstr()
                }
    
    dt.batchSetUserObject('userSectionList', userSectionDict)
    dt.batchSetUserObject('userQuestBattleList', userQuestBattleDict)
    return list(userSectionDict.values()), list(userQuestBattleDict.values())
Ejemplo n.º 14
0
def createUserGachaGroup(groupId):
    return {
        "userId": dt.userId,
        "gachaGroupId": groupId,
        "count": 0,
        "paid": 0,
        "totalCount": 0,
        "dailyCount": 0,
        "weeklyCount": 0,
        "monthlyCount": 0,
        "currentScheduleId": 20,
        "resetCount": 0,
        "createdAt": nowstr()
    }
Ejemplo n.º 15
0
def createUserLive2d(charaId, live2dId, description):
    return {
        "userId": dt.userId,
        "charaId": charaId,
        "live2dId": live2dId,
        "live2d": {
            "charaId": charaId,
            "live2dId": live2dId,
            "description": description,
            "defaultOpened": False,
            "voicePrefixNo": live2dId
        },
        "createdAt": nowstr()
    }, dt.getUserObject('userLive2dList',
                        int(str(charaId) + str(live2dId))) is not None
Ejemplo n.º 16
0
def getGift(giftId, amount):
    userGift = dt.getUserObject('userGiftList', giftId)
    if userGift is None:
        newGift = dt.masterGifts[giftId]
        newGift['rankGift'] = 'RANK_' + str(newGift['rank'])
        userGift = {
            "userId": dt.userId,
            "giftId": giftId,
            "quantity": amount,
            "createdAt": nowstr(),
            "gift": newGift
        }
    userGift['quantity'] += amount
    dt.setUserObject('userGiftList', giftId, userGift)
    return {'userGiftList': [userGift]}
Ejemplo n.º 17
0
def clearDaily(challengeIds):
    dailyChallenges = []
    for challengeId in challengeIds:
        dailyChallenge = dt.getUserObject('userDailyChallengeList',
                                          challengeId)
        if dailyChallenge['clearedCount'] < dailyChallenge['challenge'][
                'count']:
            dailyChallenge['clearedCount'] += 1
            if dailyChallenge['clearedCount'] >= dailyChallenge['challenge'][
                    'count']:
                dailyChallenge['clearedAt'] = nowstr()
            dt.setUserObject('userDailyChallengeList', challengeId,
                             dailyChallenge)
            dailyChallenges.append(dailyChallenge)
    return dailyChallenges
Ejemplo n.º 18
0
def clearBattle(battle):
    userBattle = dt.getUserObject('userQuestBattleList',
                                  battle['questBattleId'])
    if userBattle is None: return None

    now = nowstr()
    userBattle['cleared'] = True
    if 'firstClearedAt' not in userBattle:
        userBattle['firstClearedAt'] = now
    userBattle['lastClearedAt'] = now
    userBattle['clearCount'] = userBattle.get('clearCount', 0) + 1

    dt.setUserObject('userQuestBattleList', battle['questBattleId'],
                     userBattle)
    return userBattle
Ejemplo n.º 19
0
def handlePage(endpoint):
    response = dt.readJson('data/events.json')
    response['currentTime'] = homu.nowstr()

    args = flask.request.args.get('value')
    if args is not None:
        args = re.sub(r'&timeStamp=\d+', '', args) \
                .replace('value=', '') \
                .split(',')
    else:
        args = []
    if endpoint in specialCases.keys():
        specialCases[endpoint](response)
    
    if endpoint=='ResumeBackground':
        logger.info('resuming')

    addArgs(response, args, 'TopPage' in endpoint) # login if it's TopPage
    return flask.jsonify(response)
Ejemplo n.º 20
0
def createUserPiece(pieceId):
    found = False
    for userPiece in dt.readJson('data/user/userPieceList.json'):
        if userPiece['pieceId'] == pieceId:
            found = True
    piece = dt.masterPieces[pieceId]
    return {
        "id": str(uuid1()),
        "userId": dt.userId,
        "pieceId": piece['pieceId'],
        "piece": piece,
        "level": 1,
        "experience": 0,
        "lbCount": 0,
        "attack": piece['attack'],
        "defense": piece['defense'],
        "hp": piece['hp'],
        "protect": False,
        "archive": False,
        "createdAt": nowstr()
    }, found
Ejemplo n.º 21
0
def createUserMemoria(pieceId):
    piece = dt.masterPieces[pieceId]

    userPieceId = str(uuid1())
    userPiece = {
        "id": userPieceId,
        "userId": dt.userId,
        "pieceId": piece['pieceId'],
        "piece": piece,
        "level": 1,
        "experience": 0,
        "lbCount": 0,
        "attack": piece['attack'],
        "defense": piece['defense'],
        "hp": piece['hp'],
        "protect": False,
        "archive": False,
        "createdAt": nowstr()
    }
    dt.setUserObject('userPieceList', userPieceId, userPiece)
    return userPiece
Ejemplo n.º 22
0
def arenaFreeRank(response):
    # Assumes there are at least three enemies possible, no error checking
    enemies = random.sample(os.listdir('data/arenaEnemies'), k=3)
    enemyInfo = [dt.readJson('data/arenaEnemies/'+enemy)['opponentUserArenaBattleInfo'] for enemy in enemies]

    response['userArenaBattleMatch'] = {
		"userId": "0571792e-f615-11ea-bdf5-024ec58565ab",
		"arenaBattleType": "FREE_RANK",
		"userRatingPoint": calculateArenaRating(),
		"opponentUserId1": enemyInfo[0]['userId'],
		"opponentUserArenaBattleInfo1": enemyInfo[0],
		"opponentUserId2": enemyInfo[1]['userId'],
		"opponentUserArenaBattleInfo2": enemyInfo[1],
		"opponentUserId3": enemyInfo[2]['userId'],
		"opponentUserArenaBattleInfo3": enemyInfo[2],
		"opponentUserIdList": [],
		"matchedAt": homu.nowstr(),
		"expiredAt": (datetime.now()+timedelta(minutes=15)).strftime('%Y/%m/%d %H:%M:%S'),
		"enable": True,
		"isNew": False
	}
Ejemplo n.º 23
0
def makeLoginBonus(lastLoginBonusDate, response):
    loginBonusCount = (dt.getGameUserValue('loginBonusCount') % 7) + 1
    if datetime.now().date().weekday() == 0:
        loginBonusCount = 1

    lastMonday, nextMonday = homu.thisWeek()
    if homu.strToDateTime(lastLoginBonusDate).date() < lastMonday:
        loginBonusCount = 1

    dt.setGameUserValue('loginBonusGetAt', homu.nowstr())
    dt.setGameUserValue('loginBonusPattern', 'S1') # no clue how to get the other patterns, even from JP, or if this even matters...
    dt.setGameUserValue('loginBonusCount', loginBonusCount)

    bonuses = dt.readJson('data/loginBonusList.json')
    currBonus = bonuses[loginBonusCount-1]
    for rewardCode in currBonus['rewardCodes'].split(','):
        loginItems = obtainItem(rewardCode)
        response = dt.updateJson(response, loginItems)
    response['loginBonusList'] = bonuses

    response['loginBonusPeriod'] = lastMonday.strftime('%m/%d') + '〜' + nextMonday.strftime('%m/%d')
Ejemplo n.º 24
0
def save():
    body = flask.request.json

    targetUserPieceSet = dt.getUserObject('userPieceSetList', body['setNum'])
    if targetUserPieceSet is None:
        targetUserPieceSet = {
            "createdAt": nowstr(),
            'userId': dt.userId,
            'setNum': body['setNum']
        }

    targetUserPieceSet['name'] = body['name']
    for i, id in enumerate(body['userPieceIdList']):
        targetUserPieceSet['userPieceId' + str(i + 1)] = id

    dt.setUserObject('userPieceSetList', body['setNum'], targetUserPieceSet)

    response = {
        'resultCode': 'success',
        'userPieceSetList': [targetUserPieceSet]
    }
    return flask.jsonify(response)
Ejemplo n.º 25
0
def login():
    logger.info('logging in')
    response = {}

    user = dt.readJson('data/user/user.json')

    nowstr = homu.nowstr()
    if datetime.now().date() > datetime.strptime(user['todayFirstAccessDate'], homu.DATE_FORMAT).date():
        logger.info('new day')

        dt.setUserValue('loginDaysInRow', user['loginDaysInRow'])
        dt.setUserValue('todayFirstAccessDate', nowstr)
        dt.setUserValue('dataPatchedAt', nowstr)

        yuitil.resetDaily()
    
    dt.setUserValue('loginCount', user['loginCount'] + 1)
    dt.setUserValue('penultimateLoginDate', user['lastLoginDate'])
    dt.setUserValue('lastLoginDate', nowstr)
    dt.setUserValue('lastAccessDate', nowstr)
    dt.setUserValue('indexingTargetDate', nowstr)

    dt.setGameUserValue('announcementViewAt', nowstr)
    return response
Ejemplo n.º 26
0
def arenaStart(response):
    body = flask.request.json

    chosenTeam = dt.getUserObject('userDeckList', 21)
    if chosenTeam is None:
        flask.abort(
            400,
            '{"errorTxt": "You don\'t have a mirrors team...","resultCode": "error","title": "Error"}'
        )

    chosenFormation = dt.getUserObject('userFormationSheetList',
                                       chosenTeam['formationSheetId'])
    if chosenFormation is None:
        flask.abort(
            400,
            '{"errorTxt": "You don\'t have that formation.","resultCode": "error","title": "Error"}'
        )

    battleId = str(uuid1())
    userQuestBattleResult = {
        "battleType": "ARENA",
        "bondsPt1": 0,
        "bondsPt2": 0,
        "bondsPt3": 0,
        "bondsPt4": 0,
        "bondsPt5": 0,
        "bondsPt6": 0,
        "bondsPt7": 0,
        "bondsPt8": 0,
        "bondsPt9": 0,
        "clearedMission1": False,
        "clearedMission2": False,
        "clearedMission3": False,
        "connectNum": 0,
        "continuedNum": 0,
        "createdAt": nowstr(),
        "deadNum": 0,
        "deckType": 21,
        "diskAcceleNum": 0,
        "diskBlastNum": 0,
        "diskChargeNum": 0,
        "doppelNum": 0,
        "enemyNum": 0,
        "episodeUserCardId": chosenTeam['questEpisodeUserCardId'],
        "exp": 0,
        "follow": True,
        "follower": True,
        "formationSheetId": chosenTeam['formationSheetId'],
        "formationSheet": chosenFormation,
        "id": battleId,
        "level": dt.getUserValue('level'),
        "magiaNum": 0,
        "nativeClearTime": 0,
        "questBattleStatus": "CREATED",
        "riche": 0,
        "serverClearTime": 0,
        "skillNum": 0,
        "turns": 0,
        "userId": dt.userId
    }

    for i in range(5):
        numberedId = 'userCardId' + str(i + 1)
        if numberedId in chosenTeam:
            userQuestBattleResult['userCardId' + str(chosenTeam[
                'questPositionId' + str(i + 1)])] = chosenTeam[numberedId]

    userArenaBattle = dt.readJson('data/user/userArenaBattle.json')
    userArenaBattleResult = dt.readJson('data/user/userArenaBattleResult.json')
    if userArenaBattleResult is None:
        userArenaBattleResult = {"numberOfConsecutiveWins": 0}
    userArenaBattleResult.update({
        "userQuestBattleResultId": battleId,
        "userId": dt.userId,
        "opponentUserId": body['opponentUserId'],
        "arenaBattleType": "FREE_RANK",
        "arenaBattleStatus": "CREATED",
        "arenaBattleOpponentType": "SAME",
        "point": userArenaBattle['freeRankArenaPoint'],
        "createdAt": nowstr()
    })

    response.update({
        "resultCode": "success",
        "userQuestBattleResultList": [userQuestBattleResult],
        'userArenaBattleResult': [userArenaBattleResult]
    })

    dt.saveJson('data/user/userQuestBattleResult.json', userQuestBattleResult)
    dt.saveJson('data/user/userArenaBattleResult.json', userArenaBattleResult)
Ejemplo n.º 27
0
def buy():
    body = flask.request.json
    shopList = dt.readJson('data/shopList.json')

    currShop = {}
    for shop in shopList:
        if shop['shopId'] == body['shopId']:
            currShop = shop
            break
    if currShop == {}:
        flask.abort(
            400,
            description=
            '{"errorTxt": "Trying to buy from a nonexistent shop","resultCode": "error","title": "Error"}'
        )

    item = {}
    for shopItem in shop['shopItemList']:
        if shopItem['id'] == body['shopItemId']:
            item = shopItem
            break
    if item == {}:
        flask.abort(
            400,
            description=
            '{"errorTxt": "Trying to buy something not in this shop","resultCode": "error","title": "Error"}'
        )

    # get the thing
    args = {}
    if item['shopItemType'] == 'SET':
        obtainSet(item, body, args)
    else:
        obtain(item, body, args)

    # spend items
    if item['consumeType'] == 'ITEM':
        spendArgs = getItem(item['needItemId'],
                            -1 * item['needNumber'] * body['num'])
        if 'userItemList' in args:
            args['userItemList'] += spendArgs['userItemList']
        else:
            args = dt.updateJson(args, spendArgs)
    elif item['consumeType'] == 'MONEY':
        itemList = gacha.spend('MONEY', item['needNumber'] * body['num'])
        if 'userItemList' in args:
            args['userItemList'] += itemList
        else:
            args['userItemList'] = itemList

    userShopItem = {
        "createdAt": nowstr(),
        "num": body['num'],
        "shopItemId": body['shopItemId'],
        "userId": dt.userId
    }
    args['userShopItemList'] = [userShopItem]
    path = 'data/user/userShopItemList.json'
    dt.saveJson(path, dt.readJson(path) + [userShopItem])

    return flask.jsonify(args)
Ejemplo n.º 28
0
def send():
    body = flask.request.json
    battle = dt.readJson('data/user/userQuestBattleResult.json')

    if (battle['battleType'] == "ARENA"):
        return sendArena(
            body, {
                'userQuestBattleResultList': [battle],
                'gameUser': dt.readJson('data/user/gameUser.json')
            })

    if not battle['id'] == body['userQuestBattleResultId']:
        flask.abort(
            400,
            description=
            '{"errorTxt": "You didn\'t really start this quest, or something...","resultCode": "error","title": "Error"}'
        )

    # really gross, but cbf'd rn to refactor
    storyResponse = None
    dropResponse = None
    rewardResponse = None
    resultUserCardList = None
    resultUserCharaList = None
    resultUserSectionList = None
    gameUser = dt.readJson('data/user/gameUser.json')
    newStatus = []

    # change userQuestBattleResult status
    if body['result'] == 'FAILED':
        battle['questBattleStatus'] = 'FAILED'
        resultUserQuestBattle = dt.getUserObject('userQuestBattleList',
                                                 battle['questBattleId'])
        if resultUserQuestBattle is None:  # not sure why this would happen, but?? make it just in case
            resultUserQuestBattle = newtil.createUserQuestBattle(
                battle['questBattleId'])
            dt.setUserObject('userQuestBattleList', battle['questBattleId'],
                             resultUserQuestBattle)
    else:
        battle['questBattleStatus'] = 'SUCCESSFUL'
        resultUserQuestBattle = dt.getUserObject('userQuestBattleList',
                                                 battle['questBattleId'])
        # add exp to user and level up, maybe
        gameUser, newStatus = giveUserExp(battle)
        # level up/episode up megucas
        resultUserCardList, resultUserCharaList, resultUserSectionList = giveMegucaExp(
            battle)
        cleared = 'cleared' in resultUserQuestBattle and resultUserQuestBattle[
            'cleared']
        # add drops -- required before clearing
        dropResponse = giveDrops(battle)
        # clear
        if not cleared:
            resultUserQuestBattle = storyUtil.clearBattle(battle)
            storyResponse = storyUtil.progressStory(battle)
        else:
            resultUserQuestBattle['lastClearedAt'] = homu.nowstr()
            resultUserQuestBattle['clearCount'] = resultUserQuestBattle.get(
                'clearCount', 0) + 1
        # missions
        battle, resultUserQuestBattle, rewardResponse = clearMissions(
            body, battle)

    # make response
    response = {
        "resultCode": "success",
        'gameUser': gameUser,
        'userCardList': resultUserCardList,
        'userCharaList': resultUserCharaList,
        'userQuestBattleResultList': [battle],
        'userQuestBattleList': [resultUserQuestBattle]
    }

    # a bunch of stuff that may or may not be necessary depending on which story and who's participating
    for partResponse in [storyResponse, dropResponse, rewardResponse]:
        if partResponse is not None:
            response = dt.updateJson(response, partResponse)

    userCards, userCharas = getBattleCards(battle)
    if resultUserCardList is not None:
        response['userCardList'] = resultUserCardList
    else:
        response['userCardList'] = userCards
    if resultUserCharaList is not None:
        response['userCharaList'] = resultUserCharaList
    else:
        response['userCharaList'] = userCharas
    if resultUserSectionList is not None and len(resultUserSectionList) != 0:
        response['userSectionList'] = resultUserSectionList

    if newStatus != []:
        response['userStatusList'] = newStatus

    return flask.jsonify(response)
Ejemplo n.º 29
0
def draw():
    # handle different types of gachas
    body = flask.request.json

    chosenGacha = None
    for gacha in dt.readJson('data/gachaScheduleList.json'):
        if gacha['id'] == body['gachaScheduleId']:
            chosenGacha = gacha
            break
    if chosenGacha is None:
        flask.abort(404, description="Tried to pull on a gacha that doesn't exist...")

    if 'gachaGroupId' in chosenGacha.keys():
        _, pity = setUpPity(chosenGacha['gachaGroupId'])
    else:
        pity = 0

    # draw
    draw10 = body['gachaBeanKind'].endswith('10') or body['gachaBeanKind'] == 'SELECTABLE_TUTORIAL'
    isFreePull = False
    results = []
    itemTypes = []
    if body['gachaBeanKind'].startswith('NORMAL'):
        if draw10:
            results, itemTypes = drawTenNormal()
            isFreePull = beforeToday(dt.getGameUserValue('freeGachaAt'))
        else:
            results, itemTypes = drawOneNormal()
    else:
        if draw10:
            results, itemTypes, pity = drawTenPremium(pity)
        else:
            results, itemTypes, pity = drawOnePremium(pity)

    if 'gachaGroupId' in chosenGacha.keys():
        pityGroup, _ = setUpPity(chosenGacha['gachaGroupId'], pity)
    else:
        pityGroup = None
    
    # sort into lists
    userCardList = []
    userCharaList = []
    userPieceList = []
    userLive2dList = []
    userItemList = []
    userSectionList = []
    userQuestBattleList = []

    responseList = []

    for result, itemType in zip(results, itemTypes):
        if itemType.startswith('g'):
            userItemList.append(addGem(result))
            responseList.append({
                "direction": 5,
                "displayName": result['name'],
                "isNew": False,
                "itemId": result['itemCode'],
                "rarity": 'RANK_'+str(result['name'].count('+')+1),
                "type": "ITEM"
            })
        if itemType.startswith('p'):
            card, chara, live2ds, foundExisting = addMeguca(result['charaId'])
            if not foundExisting:
                userCardList.append(card)
                userLive2dList += live2ds
                newSectionList, newQuestBattleList = addStory(result['charaId'])
                userSectionList += newSectionList
                userQuestBattleList += newQuestBattleList
            userCharaList.append(chara)
            directionType = 3
            if result['cardList'][0]['card']['rank'][-1] == "4":
                # give it the rainbow swirlies
                directionType = 4
            responseList.append({
                "type": "CARD",
                "rarity": result['cardList'][0]['card']['rank'],
                "maxRarity": result['cardList'][-1]['card']['rank'],
                "cardId": result['cardList'][0]['cardId'],
                "attributeId": result['chara']['attributeId'],
                "charaId": result['charaId'],
                "direction": directionType,
                "displayName": result['chara']['name'],
                "isNew": not foundExisting
            })
            if foundExisting:
                responseList[-1]["itemId"] = "LIMIT_BREAK_CHARA"
        if itemType.startswith('m'):
            userPiece, foundExisting = addPiece(result['pieceId'])
            userPieceList.append(userPiece)
            directionType = 1
            if result['rank'][-1] == "4":
                # give it the memoria equivalent of the rainbow swirlies
                directionType = 2
            responseList.append({
                "type": "PIECE",
                "rarity": result['rank'],
                "pieceId": result['pieceId'],
                "direction": directionType,
                "displayName": result['pieceName'],
                "isNew": not foundExisting
            })

    # spend items
    gachaKind = None
    for kind in chosenGacha['gachaKindList']:
        if kind['beanKind'] == body['gachaBeanKind']:
            gachaKind = kind

    if not isFreePull:
        userItemList += \
            spend(gachaKind['needPointKind'], 
                gachaKind['needQuantity'], 
                gachaKind['substituteItemId'] if 'substituteItemId' in gachaKind else None)

    # create response
    gachaAnimation = {
            "live2dDetail": gachaKind['live2dDetail'],
            "messageId": gachaKind['messageId'],
            "message": gachaKind['message'],
            # Determines which picture to show in the intro animation
            #
            # first picture
            # 1 = flower thingy (default, no real meaning)
            # 2 = inverted flower thingy (should mean at least 1 3+ star CARD (not necessarily meguca, could be memoria))
            "direction1": 1,
            #
            # second picture
            # 1 = mokyuu (default, no real meaning)
            # 2 = attribute (specified with "direction2AttributeId")
            "direction2": 1,
            #
            # third picture
            # 1 = spear thingy (default, no real meaning)
            # 2 = iroha (should mean at least 1 3+ star)
            # 3 = mikazuki villa (at least 1 4 star)
            "direction3": 1,
            "gachaResultList": responseList
        }

    high_rarity_pulled = [thingy for thingy in responseList if thingy["rarity"] == "RANK_3" or thingy["rarity"] == "RANK_4"]
    cards_pulled = [thingy for thingy in responseList if thingy["type"] == "CARD"]
    any_3stars_pulled = [card for card in cards_pulled if card["rarity"] == "RANK_3"]
    any_4stars_pulled = [card for card in cards_pulled if card["rarity"] == "RANK_4"]

    # if any high rarity thingies pulled, set direction1
    if len(high_rarity_pulled) >= 1:
        gachaAnimation["direction1"] = 2

    # 50-50 chance of displaying a random card's attribute symbol instead of mokyuu
    # but only if cards were pulled (i.e. not for FP gacha)
    if len(cards_pulled) >= 1 and random.randint(1, 2) == 2:
        random_card = random.choice(cards_pulled)
        gachaAnimation["direction2"] = 2
        gachaAnimation["direction2AttributeId"] = random_card["attributeId"]

    if len(any_4stars_pulled) >= 1:
        # show mikazuki villa if any 4 stars were pulled
        gachaAnimation["direction3"] = 3
    elif len(any_3stars_pulled) >= 1:
        # show iroha if any 3 stars were pulled
        gachaAnimation["direction3"] = 2

    if pityGroup is not None:
        gachaAnimation["userGachaGroup"] = pityGroup
    response = {
        "resultCode": "success",
        "gachaAnimation": gachaAnimation,
        "userCardList": userCardList,
        "userCharaList": userCharaList,
        "userLive2dList": userLive2dList,
        "userItemList": userItemList,
        "userPieceList": userPieceList
    }

    if isFreePull:
        response['gameUser'] = dt.setGameUserValue('freeGachaAt', nowstr())

    if len(userSectionList) > 0: response['userSectionList'] = userSectionList
    if len(userQuestBattleList) > 0: response['userQuestBattleList'] = userQuestBattleList

    # add to user history
    pullId = str(uuid1())
    if not os.path.exists('data/user/gachaHistory'):
        os.mkdir('data/user/gachaHistory')
    dt.saveJson('data/user/gachaHistory/'+pullId+'.json', {'gachaAnimation': gachaAnimation})
    newHistory = {
        "id": pullId,
        "userId": dt.userId,
        "gachaScheduleId": body['gachaScheduleId'],
        "gachaSchedule": chosenGacha,
        "gachaBeanKind": body['gachaBeanKind'],
        "bonusTimeFlg": False,
        "createdAt": nowstr()
    }
    dt.setUserObject('gachaHistoryList', pullId, newHistory)
    return flask.jsonify(response)