Exemplo n.º 1
0
def setBackground():
    body = flask.request.json
    bgItem = dt.getUserObject('userItemList', body['itemId'])

    gameUser = dt.setGameUserValue('bgItemId', body['itemId'])
    if bgItem is not None:
        gameUser = dt.setGameUserValue('bgItem', bgItem['item'])

    response = {"resultCode": "success", 'gameUser': gameUser}
    return flask.jsonify(response)
Exemplo n.º 2
0
def obtainItem(itemCode, amount=1):
    resultDict = {}
    if itemCode.startswith('GIFT'):
        giftId = int(itemCode.split('_')[1])
        dropNum = amount * int(
            itemCode.split('_')[-1])  # seems to be always 1, but whatever
        userGift = dt.getUserObject('userGiftList', giftId)
        userGift['quantity'] += dropNum
        resultDict['userGiftList'] = resultDict.get('userGiftList',
                                                    []) + [userGift]
        dt.setUserObject('userGiftList', giftId, userGift)
    elif itemCode.startswith('ITEM'):
        itemId = '_'.join(itemCode.split('_')[1:-1])
        dropNum = amount * int(
            itemCode.split('_')[-1])  # seems to be always 1, but whatever
        userItem = dt.getUserObject('userItemList', itemId)
        userItem['quantity'] += dropNum
        resultDict['userItemList'] = resultDict.get('userItemList',
                                                    []) + [userItem]
        dt.setUserObject('userItemList', itemId, userItem)
    elif itemCode.startswith('RICHE'):
        cc = amount * int(itemCode.split('_')[-1])
        resultDict['gameUser'] = dt.setGameUserValue(
            'riche',
            dt.getGameUserValue('riche') + cc)
    return resultDict
Exemplo n.º 3
0
def giveDrops(battle):
    resultDict = {}
    # default drop seems to always be CC...
    if 'defaultDropItem' in battle['questBattle']:
        cc = int(battle['questBattle']['defaultDropItem']['rewardCode1'].split(
            '_')[-1])
        if len(getEpisodeUpCards(battle['deckType'])) > 0:
            cc *= 1.05  # CC up memes
        resultDict['gameUser'] = dt.setGameUserValue(
            'riche',
            dt.getGameUserValue('riche') + cc)
        battle['riche'] = cc

    dropRewardCodes = []
    dropCodes = dt.readJson('data/user/promisedDrops.json')
    if dropCodes['questBattleId'] != battle[
            'questBattleId']:  # weird error that should never happen...
        logger.error('questBattleId mismatch when sending drops')
        return resultDict
    for dropCode, amount in dropCodes.items():
        if dropCode == 'questBattleId': continue
        resultDict = dt.updateJson(resultDict, obtainItem(dropCode, amount))
        dropRewardCodes += [dropCode] * amount

    battle['dropRewardCodes'] = ','.join(dropRewardCodes)
    return resultDict
Exemplo n.º 4
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
    })
Exemplo n.º 5
0
def editComment():
    body = flask.request.json
    gameUser = dt.setGameUserValue('comment', body['comment'])
    response = {
        "resultCode": "success",
        'gameUser': gameUser,
        'user': dt.readJson('data/user/user.json')
    }
    return flask.jsonify(response)
Exemplo n.º 6
0
def changeLeader():
    body = flask.request.json
    gameUser = dt.setGameUserValue('leaderId', body['userCardId'])
    response = {
        "resultCode": "success",
        'gameUser': gameUser,
        'user': dt.readJson('data/user/user.json')
    }
    return flask.jsonify(response)
Exemplo n.º 7
0
def giveUserExp(battle):
    userExp = battle['questBattle']['exp']
    battle['exp'] = battle['questBattle']['exp']
    gameUser = dt.setGameUserValue('exp', dt.getGameUserValue('exp') + userExp)
    newStatus = []
    if gameUser['exp'] >= gameUser['totalExpForNextLevel']:
        newLevel = gameUser['level'] + 1
        dt.setGameUserValue('level', newLevel)
        dt.setGameUserValue('totalExpForCurrentLevel',
                            gameUser['totalExpForNextLevel'])

        expAdd = 0
        for i in range(0, newLevel + 1):
            expAdd += expForNextLevel[i] if i < len(expForNextLevel) else 30704

        gameUser = dt.setGameUserValue(
            'totalExpForNextLevel', gameUser['totalExpForNextLevel'] + expAdd)

        maxAP = dt.getUserObject('userStatusList', 'MAX_ACP')
        currAP = dt.getUserObject('userStatusList', 'ACP')
        maxAP['point'] += 1
        currAP['point'] += maxAP['point']

        currBP = dt.getUserObject('userStatusList', 'BTP')
        currBP['point'] = 5

        newStatus.append(maxAP)
        newStatus.append(currAP)

        dt.setUserObject('userStatusList', 'MAX_ACP', maxAP)
        dt.setUserObject('userStatusList', 'ACP', currAP)
        dt.setUserObject('userStatusList', 'BTP', currBP)
    return gameUser, newStatus
Exemplo n.º 8
0
def sale():
    body = flask.request.json
    totalCC = 0
    for userPieceId in body['saleUserPieceIdList']:
        soldMemoria = dt.getUserObject('userPieceList', userPieceId)
        totalCC += priceCalc(soldMemoria['piece']['rank'],
                             soldMemoria['lbCount'])
        dt.deleteUserObject('userPieceList', soldMemoria['id'])

    gameUser = dt.setGameUserValue('riche',
                                   dt.getGameUserValue('riche') + totalCC)
    response = {'resultCode': 'success', 'gameUser': gameUser}
    return flask.jsonify(response)
Exemplo n.º 9
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
Exemplo n.º 10
0
def compose():
    body = flask.request.json
    targetUserCardId = body['userCardId']
    
    targetUserCard = dt.getUserObject('userCardList', targetUserCardId)
    if targetUserCard is None:
        flask.abort(400, description='Tried to level up a card you don\'t have...')
    
    # figure out success type
    # (totally BS rates but whatevs)
    success = np.random.choice([1, 1.5, 2], p=[0.9, 0.08, 0.02])

    # modify meguca's level and stats
    rank = targetUserCard['card']['rank']
    origLevel = targetUserCard['level']
    
    exp = getComposeExp(targetUserCard['card']['attributeId'], body['useItem']) * success
    targetUserCard = levelUp(targetUserCard, rank, exp)
    
    dt.setUserObject('userCardList', targetUserCardId, targetUserCard)

    # spend items
    try:
        revisedItemList = spend(body['useItem'])
    except ValueError as e:
        flask.abort(400, description='{"errorTxt": "'+repr(e)+'","resultCode": "error","title": "Error"}')
    
    # modify CC
    cc = getCCAmount(rank, origLevel, body['useItem'])
    currCC = dt.getGameUserValue('riche')
    if currCC < cc:
        flask.abort(400, description='{"errorTxt": "Tried to use more cc than you have...","resultCode": "error","title": "Error"}')
    gameUser = dt.setGameUserValue('riche', currCC-cc)
    
    # make response
    response = {
        'composeEffect': success,
        'resultCode': 'success',
        'gameUser': gameUser,
        'userCardList': [targetUserCard],
        'userItemList': revisedItemList
    }
    return flask.jsonify(response)
Exemplo n.º 11
0
def composeMagia():
    body = flask.request.json
    targetUserCardId = body['userCardId']

    # change userCard magia level
    targetUserCard = dt.getUserObject('userCardList', targetUserCardId)
    targetUserCard['magiaLevel'] += 1
    if targetUserCard is None:
        flask.abort(400, description='{"errorTxt": "Tried to level magia of a card you don\'t have...' + targetUserCardId  + '","resultCode": "error","title": "Error"}')
    dt.setUserObject('userCardList', targetUserCardId, targetUserCard)

    # spend items
    charaId = targetUserCard['card']['charaNo']
    giftsToSpend = {}
    magiaLevel = {2: 'first', 3: 'second', 4: 'third', 5: 'fourth'}
    magiaPrefix = magiaLevel[targetUserCard['magiaLevel']]
    targetChara = dt.getUserObject('userCharaList', charaId)['chara']
    for i in range(6):
        if magiaPrefix+'MagiaGiftId'+str(i+1) in targetChara \
        and magiaPrefix+'MagiaGiftNum'+str(i+1) in targetChara:
            giftsToSpend[targetChara[magiaPrefix+'MagiaGiftId'+str(i+1)]] = targetChara[magiaPrefix+'MagiaGiftNum'+str(i+1)]

    revisedGiftList = spendGift(giftsToSpend)

    # spend CC
    ccByLevel = {2: 10000, 3: 100000, 4: 300000, 5: 1000000} # not sure about how much CC this actually takes
    currCC = dt.getGameUserValue('riche')
    if currCC - ccByLevel[targetUserCard['magiaLevel']] < 0:
        flask.abort(400, description='{"errorTxt": "Tried to use more cc than you have...","resultCode": "error","title": "Error"}')
    gameUser = dt.setGameUserValue('riche', currCC - ccByLevel[targetUserCard['magiaLevel']])

    # make response
    response = {
        'resultCode': 'success',
        'gameUser': gameUser,
        'userCardList': [targetUserCard],
        'userGiftList': revisedGiftList
    }
    return flask.jsonify(response)
Exemplo n.º 12
0
def limitBreak():
    body = flask.request.json
    targetUserCardId = body['userCardId']
    
    # edit userCard
    targetUserCard = dt.getUserObject('userCardList', targetUserCardId)
    if targetUserCard is None:
        flask.abort(400, description='{"errorTxt": "Tried to limit break a card you don\'t have...' + targetUserCardId + '","resultCode": "error","title": "Error"}')
    targetUserCard['revision'] += 1
    dt.setUserObject('userCardList', targetUserCardId, targetUserCard)
    
    # edit userChara
    neededGems = {'RANK_1': 10, 'RANK_2': 10, 'RANK_3': 3, 'RANK_4': 1}
    charaNo = targetUserCard['card']['charaNo']

    targetUserChara = dt.getUserObject('userCharaList', targetUserCard['card']['charaNo'])
    if targetUserChara is None:
        flask.abort(400, description='{"errorTxt": "Tried to limit break a card you don\'t have...' + 
                                targetUserCard['card']['charaNo'] + '","resultCode": "error","title": "Error"}')
    targetUserChara['lbItemNum'] -= neededGems[targetUserChara['chara']['defaultCard']['rank']]
    dt.setUserObject('userCharaList', charaNo, targetUserChara)

    # spend cc
    ccBySlotNum = [0, 0, 0, 0] # no idea how much it actually takes lol
    currCC = dt.getGameUserValue('riche')
    if currCC - ccBySlotNum[targetUserCard['revision']-1] < 0:
        flask.abort(400, description='{"errorTxt": "Tried to use more cc than you have...","resultCode": "error","title": "Error"}')
    gameUser = dt.setGameUserValue('riche', currCC - ccBySlotNum[targetUserCard['revision']-1])

    # make response
    response = {
        "resultCode": "success",
        'gameUser': gameUser,
        'userCardList': [targetUserCard],
        'userCharaList': [targetUserChara]
    }
    return flask.jsonify(response)
Exemplo n.º 13
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')
Exemplo n.º 14
0
def getCC(amount):
    gameUser = dt.setGameUserValue('riche',
                                   dt.getGameUserValue('riche') + amount)
    return {'gameUser': gameUser}
Exemplo n.º 15
0
def get():
    body = flask.request.json
    battle = dt.readJson('data/user/userQuestBattleResult.json')
    isMirrors = battle['battleType'] == "ARENA"

    if isMirrors:
        arenaBattle = dt.readJson('data/user/userArenaBattleResult.json')
        if not arenaBattle['userQuestBattleResultId'] == battle['id']:
            flask.abort(
                500,
                description=
                '{"errorTxt": "Something weird happened with order of battles","resultCode": "error","title": "Error"}'
            )

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

    # grab team info
    deck = dt.getUserObject('userDeckList', battle['deckType'])
    battleData = {
        'playerList': [],
        'artList': [],
        'magiaList': [],
        'connectList': [],
        'doppelList': [],
        'memoria': []
    }
    for key in battle.keys():
        if key.startswith('userCardId'):
            addUserToBattle(battleData, int(key[-1]), deck)

    # do the same, but now for the helper
    # TODO: use actual support
    if not isMirrors:
        npcs = dt.readJson('data/npc.json')
        helper = None
        for npc in npcs:
            if npc['npcHelpId'] == battle['npcHelpId']:
                helper = npc
        helperCard = helper['userCardList'][0]
        helperChara = helper['userCharaList'][0]
        helperPieces = helper['userPieceList']

        helperMemoriae = battleTranslate(battleData, helperCard, helperPieces)

        battleInfo = {
            'helper': True,
            'friend': True,  # TODO: actually change this
            'pos': deck['questPositionHelper'],
            'leader': False,
            'memoriaList': helperMemoriae
        }
        battleData['playerList'].append(
            cardToPlayer(helperCard, helperChara, battleInfo))

        # add support points
        supportPoints = dt.getUserObject('userItemList', 'YELL')
        supportPoints['quantity'] += 60
        dt.setUserObject('userItemList', 'YELL', supportPoints)

    # spend AP/BP
    apStatus = spendAP(battle)

    # change quest status
    battle['questBattleStatus'] = 'LOTTERY'
    dt.saveJson('data/user/userQuestBattleResult.json', battle)

    # TODO: use follower
    userFollowList = []

    # set last used team
    gameUser = dt.setGameUserValue('deckType', battle['deckType'])

    # compile web data
    webData = {
        "gameUser": gameUser,
        "userStatusList": [apStatus],
        "userQuestBattleResultList": [battle],
        "resultCode": "success",
        "userFollowList": userFollowList,
    }
    if not isMirrors:
        webData["userItemList"] = [supportPoints]

    # add opponent stuff
    if not isMirrors:
        if battle['questBattleId'] in dt.masterWaves:
            waves = getQuestData(battle['questBattleId'], battleData)
        else:
            waves = [dt.readJson('data/hardCodedWave.json')]
    else:
        opponent = dt.readJson('data/arenaEnemies/' +
                               arenaBattle['opponentUserId'] + '.json')
        waves = [{
            "field": 21181,
            "boss": False,
            "sheetType": 9,
            "enemyList": opponent['enemyList']
        }]
        # this is a mess lol, only the arts from the memoria are in artList
        battleData['memoria'] += opponent['memoriaList']
        battleData['artList'] += opponent['artList']

        # the rest have to be extracted from the cards
        for enemyCard in opponent['opponentUserArenaBattleInfo'][
                'userCardList']:
            battleTranslate(battleData, enemyCard, [])

    response = {
        'battleType': 'QUEST' if not isMirrors else
        'ARENA',  # TODO: change for tutorials, challenge quests
        'scenario': mirrorScenario if isMirrors else battle['scenario'],
        'waveList': waves,
        'playerList': battleData['playerList'],
        'doppelList': dedupeDictList(battleData['doppelList'], 'doppelId'),
        'artList': dedupeDictList(battleData['artList'], 'artId'),
        'memoriaList': dedupeDictList(battleData['memoria'], 'memoriaId'),
        'connectList': dedupeDictList(battleData['connectList'], 'connectId'),
        'magiaList': dedupeDictList(battleData['magiaList'], 'magiaId'),
        'continuable': True,
        'isHalfSkill': False,
        'webData': webData
    }
    return flask.jsonify(response)
Exemplo n.º 16
0
def evolve():
    body = flask.request.json
    targetUserCardId = body['userCardId']
    
    targetUserCard = dt.getUserObject('userCardList', targetUserCardId)
    if targetUserCard is None:
        flask.abort(400, description='{"errorTxt": "Tried to awaken a card you don\'t have: ' + targetUserCardId  + '","resultCode": "error","title": "Error"}')
    charaId = targetUserCard['card']['charaNo']

    # get next card
    masterCard = dt.masterCards[charaId]
    if masterCard is None:
        flask.abort(400, description='{"errorTxt": "Tried to awaken a character that doesn\'t exist...","resultCode": "error","title": "Error"}')
    cardList = masterCard['cardList']

    newCard = None
    foundCurrentCard = False
    for card in cardList:
        if foundCurrentCard:
            newCard = card['card']
            break
        if targetUserCard['card']['cardId'] == card['cardId']:
            foundCurrentCard = True
    if newCard is None and foundCurrentCard:
        newCard = cardList[-1]['card']
    if newCard is None:
        flask.abort(400, description='{"errorTxt": "This character can\'t be awakened anymore...","resultCode": "error","title": "Error"}')
    
    # make new userCard and userChara
    newUserCard, _, _ = newtil.createUserMeguca(charaId, newCard)
    newUserCard['revision'] = targetUserCard['revision']
    newUserCard['magiaLevel'] = targetUserCard['magiaLevel']

    revisedUserChara = dt.getUserObject('userCharaList', charaId)
    if revisedUserChara is None:
        flask.abort(400, description='Tried to awaken a character you don\'t have...')
    revisedUserChara['userCardId'] = newUserCard['id']

    # save user info
    targetUserCard['enabled'] = False
    dt.setUserObject('userCardList', targetUserCardId, targetUserCard)
    dt.setUserObject('userCardList', newUserCard['id'], newUserCard)
    dt.setUserObject('userCharaList', charaId, revisedUserChara)
    
    with open('data/user/userDeckList.json', encoding='utf-8') as f:
        decks = f.read()
    decks = decks.replace(targetUserCardId, newUserCard['id'])
    with open('data/user/userDeckList.json', 'w+', encoding='utf-8') as f:
        f.write(decks)
    
    if dt.getGameUserValue('leaderId') == targetUserCardId:
        dt.setGameUserValue('leaderId', newUserCard['id'])

    # spend CC
    ccByLevel = {'RANK_2': 10000, 'RANK_3': 100000, 'RANK_4': 300000, 'RANK_5': 1000000} # not sure about how much CC it takes to go from 2* to 3*
    currCC = dt.getGameUserValue('riche')
    if currCC - ccByLevel[newCard['rank']] < 0:
        flask.abort(400, description='{"errorTxt": "Tried to use more cc than you have...","resultCode": "error","title": "Error"}')
    gameUser = dt.setGameUserValue('riche', currCC - ccByLevel[newCard['rank']])

    # make response
    response = {
        'evolution': {
            'current': {
                'attr': targetUserCard['card']['attributeId'],
                'cardId': targetUserCard['card']['cardId'],
                'rarity': int(targetUserCard['card']['rank'][-1])
            },
            'giftIdList': [targetUserCard['card']['cardCustomize'][giftKey] for giftKey in targetUserCard['card']['cardCustomize'].keys() if giftKey.startswith('giftId')],
            'result': {
                'attr': newCard['attributeId'],
                'cardId': newCard['cardId'],
                'rarity': int(newCard['rank'][-1])
            }
        },
        "resultCode": "success",
        'gameUser': gameUser,
        'userCardList': [targetUserCard, newUserCard],
        'userCharaList': [revisedUserChara]
    }
    return flask.jsonify(response)
Exemplo n.º 17
0
def compose():
    body = flask.request.json
    targetUserPieceId = body['baseUserPieceId']
    targetUserPiece = dt.getUserObject('userPieceList', targetUserPieceId)
    memoriaToSpend = []

    for materialPieceId in body['materialUserPieceIdList']:
        memoriaToSpend.append(
            dt.getUserObject('userPieceList', materialPieceId))

    if targetUserPiece == {}:
        flask.abort(
            400, description='Tried to level up a memoria you don\'t have...')

    # limit break
    isLimitBreak = False
    for memoria in memoriaToSpend:
        if memoria['pieceId'] == targetUserPiece['pieceId'] or \
        ('pieceKind' in memoria['piece'] and memoria['piece']['pieceKind']=='LIMIT_BREAK'):
            isLimitBreak = True
    if isLimitBreak:
        targetUserPiece['lbCount'] += len(memoriaToSpend)

    originalUserPiece = {k: v for k, v in targetUserPiece.items()}
    targetUserPiece, success = levelUp(targetUserPiece, memoriaToSpend)

    dt.setUserObject('userPieceList', targetUserPieceId, targetUserPiece)

    # modify CC
    totalCC = 0
    for memoria in memoriaToSpend:
        totalCC += priceCalc(memoria['piece']['rank'], memoria['lbCount'])
        dt.deleteUserObject('userPieceList', memoria['id'])

    currCC = dt.getGameUserValue('riche')
    if currCC < totalCC:
        raise ValueError("Tried to use more cc than you have...")
    gameUser = dt.setGameUserValue('riche', currCC - totalCC)

    # It looks like the archive ignores this information and shows everything max leveld and mlb'd...
    # with open('data/user/userPieceCollectionList.json', encoding='utf-8') as f:
    #     pieceCollection = json.load(f)
    # for i, piece in enumerate(pieceCollection):
    #     if piece['pieceId'] == targetUserPiece['pieceId']:
    #         if targetUserPiece['level'] > piece['maxLevel']:
    #             pieceCollection[i]['maxLevel'] = targetUserPiece['level']
    #         if targetUserPiece['lbCount'] > piece['maxLbCount']:
    #             pieceCollection[i]['maxLbCount'] = targetUserPiece['lbCount']
    # with open('data/user/userPieceCollectionList.json', 'w+', encoding='utf-8') as f:
    #     json.dump(pieceCollection, f, ensure_ascii=False)

    response = {
        'resultCode': 'success',
        'gameUser': gameUser,
        'userPieceList': [targetUserPiece],
        "memoria": {
            "materialList": [memoria['pieceId'] for memoria in memoriaToSpend],
            "memoriaId": targetUserPiece['pieceId'],
            "status": {
                "current": {
                    "atk":
                    originalUserPiece['attack'],
                    "def":
                    originalUserPiece['defense'],
                    "gainedExp":
                    originalUserPiece['experience'],
                    "hp":
                    originalUserPiece['hp'],
                    "lbCount":
                    originalUserPiece['lbCount'],
                    "level":
                    originalUserPiece['level'],
                    "limitExp":
                    dExpdLevel[originalUserPiece['level'] - 1],
                    "limitLevel":
                    getMaxLevel(originalUserPiece['piece']['rank'],
                                originalUserPiece['lbCount']),
                    "rarity":
                    int(originalUserPiece['piece']['rank'][-1])
                },
                "result": {
                    "atk":
                    targetUserPiece['attack'],
                    "def":
                    targetUserPiece['defense'],
                    "gainedExp":
                    targetUserPiece['experience'],
                    "hp":
                    targetUserPiece['hp'],
                    "lbCount":
                    targetUserPiece['lbCount'],
                    "level":
                    targetUserPiece['level'],
                    "limitExp":
                    dExpdLevel[targetUserPiece['level'] - 1],
                    "limitLevel":
                    getMaxLevel(targetUserPiece['piece']['rank'],
                                targetUserPiece['lbCount']),
                    "rarity":
                    int(targetUserPiece['piece']['rank'][-1])
                }
            },
            "successType": success
        }
    }
    return flask.jsonify(response)
Exemplo n.º 18
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)
Exemplo n.º 19
0
def skipAdventure():
    body = flask.request.json
    gameUser = dt.setGameUserValue('skipAdventure', body['skipAdventure'])
    response = {"resultCode": "success", 'gameUser': gameUser}
    return flask.jsonify(response)
Exemplo n.º 20
0
def sendArena(request, response):
    """
        The response has 7 values:
        gameUser (should be in response),
        resultCode="success"
        userArenaBattle,
        userArenaBattleResultList,
        userDailyChallengeList,
        userItemList,
        userQuestBattleResultList (should be in response),

    """
    userArenaBattle = dt.readJson('data/user/userArenaBattle.json')
    userArenaBattleResult = dt.readJson('data/user/userArenaBattleResult.json')

    coins = dt.getUserObject('userItemList', 'ARENA_COIN')

    if (request['result'] == 'SUCCESSFUL'):
        coins['quantity'] += 3

        numTurnsCapped = min(max(request['totalTurn'], 2), 7)  # cap to 2 and 7
        turnBonus = 1.0 + 0.1 * (7 - numTurnsCapped)
        opponentBonus = {
            'SAME': 1.0,
            'HIGHER': 1.2,
            'LOWER': 0.8
        }[userArenaBattleResult['arenaBattleOpponentType']]
        consecBonus = [0, 1, 2, 3, 5, 7, 10
                       ][userArenaBattleResult['numberOfConsecutiveWins'] - 1]
        getPoints = 10 * turnBonus * opponentBonus + consecBonus
        userArenaBattle['freeRankArenaPoint'] += getPoints

        userArenaBattleResult['arenaBattleStatus'] = 'WIN'
        userArenaBattleResult[
            'numberOfConsecutiveWins'] = userArenaBattleResult[
                'numberOfConsecutiveWins'] % 7 + 1
        userArenaBattleResult['point'] = getPoints

        dt.setGameUserValue(
            'numberOfFreeRankTotalWins',
            dt.getGameUserValue('numberOfFreeRankTotalWins') + 1)
    else:
        userArenaBattleResult['arenaBattleStatus'] = 'LOSE'
        coins['quantity'] += 1
        userArenaBattleResult['numberOfConsecutiveWins'] = 0

        userArenaBattle['freeRankArenaPoint'] += 3
        userArenaBattleResult['point'] = userArenaBattle['freeRankArenaPoint']

    dt.setGameUserValue('freeRankArenaPoint',
                        userArenaBattle['freeRankArenaPoint'])
    gameUser = dt.setGameUserValue(
        'numberOfFreeRankConsecutiveWins',
        userArenaBattleResult['numberOfConsecutiveWins'])

    dt.saveJson('data/user/userArenaBattle.json', userArenaBattle)
    dt.saveJson('data/user/userArenaBattleResult.json', userArenaBattleResult)

    # updating coins
    dt.setUserObject('userItemList', 'ARENA_COIN', coins)
    userItemList = [coins]

    resultCode = "success"
    response.update({
        'gameUser': gameUser,
        'userArenaBattle': userArenaBattle,
        'userItemList': userItemList,
        'userArenaBattleResultList': [userArenaBattleResult],
        'resultCode': resultCode
    })
    response = storyUtil.progressMirrors(response)
    return flask.jsonify(response)