Ejemplo n.º 1
0
def obtainReward(clearReward, args):
    presentType = clearReward['presentType']
    quantity = clearReward['quantity']
    if presentType == 'DOPPEL':
        userDoppel, exists = newtil.createUserDoppel(clearReward['genericId'])
        if not exists:
            dt.setUserObject('userDoppelList', clearReward['genericId'],
                             userDoppel)
        args['userDoppelList'] = args.get('userDoppelList', []) + [userDoppel]
    elif presentType == 'GEM':  # only Iroha's gems are rewards, so no need to check missing chara
        userChara = dt.getUserObject('userCharaList', clearReward['genericId'])
        userChara['lbItemNum'] += quantity
        dt.setUserObject('userCharaList', clearReward['genericId'], userChara)
        args['userCharaList'] = args.get('userCharaList', []) + [userChara]
    elif presentType == 'ITEM':
        userItem = dt.getUserObject('userItemList', clearReward['itemId'])
        userItem['quantity'] += quantity
        dt.setUserObject('userItemList', clearReward['itemId'], userItem)
        args['userItemList'] = args.get('userItemList', []) + [userItem]
    elif presentType == 'LIVE2D':
        newLive2d, exists = newtil.createUserLive2d(clearReward['genericId'],
                                                    clearReward['genericCode'],
                                                    clearReward['displayName'])
        if not exists:
            userLive2dList = dt.readJson('data/user/userLive2dList.json')
            dt.saveJson('data/user/userLive2dList.json',
                        userLive2dList + [newLive2d])
        args['userLive2dList'] = args.get('userLive2dList', []) + [newLive2d]
    elif presentType == 'PIECE':
        args['userPieceList'] = args.get('userPieceList', [])
        for _ in range(quantity):
            newPiece = newtil.createUserMemoria(clearReward['genericId'])
            args['userPieceList'].append(newPiece)
            dt.setUserObject('userPieceList', newPiece['id'], newPiece)
    return args
Ejemplo 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
Ejemplo n.º 3
0
def use():
    body = flask.request.json
    itemId = body['itemId']

    # spend items
    userItem = dt.getUserObject('userItemList', itemId)
    userItem['quantity'] -= body['num']
    if userItem['quantity'] < 0:
        flask.abort(400, '{"errorTxt": "You don\'t have enough.","resultCode": "error","title": "Error"}')
    
    # add AP/BP
    capPoint = float('inf')
    if itemId == 'CURE_BP':
        apType = 'BTP'
        recoverPoint = dt.getUserObject('userStatusList', 'MAX_BTP')['point']
        capPoint = dt.getUserObject('userStatusList', 'MAX_BTP')['point']
    elif itemId == 'CURE_AP_50':
        apType = 'ACP'
        recoverPoint = 50
    else:
        apType = 'ACP'
        recoverPoint = dt.getUserObject('userStatusList', 'MAX_ACP')['point']

    apStatus = homu.getStatus(apType)
    apStatus['point'] = min(capPoint, apStatus['point']+recoverPoint)

    dt.setUserObject('userItemList', itemId, userItem)
    dt.setUserObject('userStatusList', apType, apStatus)

    response = {
        "resultCode": "success",
        'userItemList': [userItem],
        'userStatusList': [apStatus]
    }
    return flask.jsonify(response)
Ejemplo n.º 4
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
Ejemplo n.º 5
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.º 6
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.º 7
0
def process():
    # get gems
    gems = dt.getUserObject('userItemList', 'PRESENTED_MONEY')
    gems['item']['itemType'] = 'MONEY'
    response = {
        "resultCode": "success",
        "userItemList": [gems]
    }

    money = dt.getUserObject('userItemList', 'MONEY')
    if money is not None:
        money['item']['itemType'] = 'MONEY'
        response['userItemList'].append(money)
    return flask.jsonify(response)
Ejemplo n.º 8
0
def calculateArenaRating():
    arenaDeck = dt.getUserObject('userDeckList', 21)
    cards = [dt.getUserObject('userCardList', v) for k, v in arenaDeck.items() if k.startswith('userCardId')]
    pieces = [dt.getUserObject('userPieceList', v) for k, v in arenaDeck.items() if k.startswith('userPieceId')]
    
    rating = 0
    for userCard in cards:
        rating += userCard['hp']
        rating += userCard['defense']
        rating += userCard['attack']
    for userPiece in pieces:
        rating += userPiece['hp']
        rating += userPiece['defense']
        rating += userPiece['attack']
    return rating
Ejemplo n.º 9
0
def sale():
    body = flask.request.json
    charaId = body['charaId']
    amount = body['num']

    rarity = 0
    responseCharaList = []
    userChara = dt.getUserObject('userCharaList', charaId)
    chara = userChara['chara']
    userChara['lbItemNum'] -= amount
    rarity = int(chara['defaultCard']['rank'][-1])
    responseCharaList.append(userChara)
    if userChara['lbItemNum'] < 0:
        flask.abort(
            400,
            description=
            '{"errorTxt": "You don\'t have that many gems to sell >:(","resultCode": "error","title": "Error"}'
        )
        return

    dt.setUserObject('userCharaList', charaId, userChara)
    responseItemList = []

    if chara['saleItemId'] == 'PRISM':
        gemsReceived = [1, 1, 3, 10]
        userItem = dt.getUserObject('userItemList', 'PRISM')
        userItem['quantity'] += amount * gemsReceived[rarity - 1]
        responseItemList.append(userItem)

        dt.setUserObject('userItemList', 'PRISM', userItem)

    if 'maxSaleItemId' in chara and chara['maxSaleItemId'] == 'DESTINY_CRYSTAL':
        logger.info('selling for crystal')
        userCrystal = dt.getUserObject('userItemList', 'DESTINY_CRYSTAL')
        if userCrystal is None:
            userCrystal = newtil.createUserItem(
                dt.masterItems['DESTINY_CRYSTAL'])
        userCrystal['quantity'] += amount
        responseItemList.append(userCrystal)

        dt.setUserObject('userItemList', 'DESTINY_CRYSTAL', userCrystal)

    response = {
        "resultCode": "success",
        'userCharaList': responseCharaList,
        'userItemList': responseItemList
    }
    return flask.jsonify(response)
Ejemplo n.º 10
0
def customize():
    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...')

    targetMatPos = body['target']

    # set info about chara
    targetUserCard['customized'+str(targetMatPos)] = True
    dt.setUserObject('userCardList', targetUserCardId, targetUserCard)

    # spend mats
    matId = targetUserCard['card']['cardCustomize']['giftId'+str(targetMatPos)]
    amount = targetUserCard['card']['cardCustomize']['giftNum'+str(targetMatPos)]
    
    try:
        revisedItemList = spendGift({matId: amount})
    except ValueError as e:
        flask.abort(400, description='{"errorTxt": "'+repr(e)+'","resultCode": "error","title": "Error"}')
    
    # make response
    response = {
        'resultCode': 'success',
        'userCardList': [targetUserCard],
        'userGiftList': revisedItemList
    }
    return flask.jsonify(response)
Ejemplo n.º 11
0
def check():
    userQuestBattleResult = dt.readJson('data/user/userQuestBattleResult.json')
    userSection = dt.getUserObject('userSectionList', userQuestBattleResult['questBattle']['sectionId'])
    response = {
        'resultCode': 'success',
        'gameUser': dt.readJson('data/user/gameUser.json'), 
        'user': dt.readJson('data/user/user.json'),
        'userQuestBattleResultList': [userQuestBattleResult],
        'userQuestBattleList': [dt.getUserObject('userQuestBattleList', userQuestBattleResult['questBattleId'])],
        'userSectionList': [userSection],
        'userChapterList': []
    }
    chapter = dt.getUserObject('userChapterList', userSection['section']['genericId'])
    if chapter is not None:
        response['userChapterList'] = [chapter]
    return flask.jsonify(response)
Ejemplo n.º 12
0
def setProtect(isProtected):
    body = flask.request.json
    userPiece = dt.getUserObject('userPieceList', body['userPieceId'])
    userPiece['protect'] = isProtected
    dt.setUserObject('userPieceList', body['userPieceId'], userPiece)
    response = {'resultCode': 'success', 'userPieceList': [userPiece]}
    return flask.jsonify(response)
Ejemplo n.º 13
0
def spendAP(battle):
    apType, apDisplay = 'ACP', 'AP'
    if battle['battleType'] == 'ARENA':
        apType, apDisplay = 'BTP', 'BP'
        apAmount = 1
    elif battle['questBattle']['consumeType'] == 'FREE_AT_NOT_CLEAR':
        userQuestBattle = dt.getUserObject('userQuestBattleList',
                                           battle['questBattleId'])
        apAmount = battle['scenario']['cost'] if (
            'cleared' in userQuestBattle and userQuestBattle['cleared']) else 0
    else:  # TODO: this won't work for event stuff
        apAmount = battle['scenario']['cost']
        if 'consumeType' not in battle['questBattle'] or battle['questBattle'][
                'consumeType'] != 'NORMAL':
            # TODO: this is just an error log to help debug
            logger.error('Unexpected consumeType; entire battle is ' +
                         json.dumps(battle['questBattle']))
            apAmount = 0

    apStatus = homu.getStatus(apType)
    apStatus['point'] -= apAmount
    if apStatus['point'] < 0:
        flask.abort(
            400, '{"errorTxt": "Not enough ' + apDisplay +
            '.","resultCode": "error","title": "Error"}')
    dt.setUserObject('userStatusList', apType, apStatus)
    return apStatus
Ejemplo n.º 14
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.º 15
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.º 16
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.º 17
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.º 18
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.º 19
0
def getEpisodeUpCards(deckType):
    # in order to do this we have to actually use the userDeck, there's no other record of which
    # meguca has which memes on it
    episodeUpCards = []

    userDeck = dt.getUserObject('userDeckList', deckType)
    for card in range(1, 5):
        for piece in range(1, 5):
            pieceKey = f'userPieceId0{card}{piece}'
            if pieceKey in userDeck:
                userPiece = dt.getUserObject('userPieceList',
                                             userDeck[pieceKey])
                if '700216301' in json.dumps(
                        userPiece
                ):  # this is so hacky I hate this but I'm too lazy to do more
                    episodeUpCards.append(userDeck[f'userCardId{card}'])

    return episodeUpCards
Ejemplo n.º 20
0
def receive():
    body = flask.request.json
    userChallenge = dt.getUserObject('userDailyChallengeList',
                                     body['challengeId'])

    response = receiveReward(userChallenge)
    response['resultCode'] = 'success'
    response['userDailyChallengeList'] = [userChallenge]
    return flask.jsonify(response)
Ejemplo n.º 21
0
def getLive2d(charaId, live2dId, live2dItem):
    idx = int(str(charaId) + str(live2dId))
    userLive2d = dt.getUserObject('userLive2dList', idx)
    if userLive2d is None:
        userLive2d, _ = newtil.createUserLive2d(charaId, live2dId,
                                                live2dItem['description'])
        dt.setUserObject('userLive2dList', idx, userLive2d)
        return {'userLive2dList': [userLive2d]}
    return {}
Ejemplo n.º 22
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)
Ejemplo n.º 23
0
def setLive2d():
    body = flask.request.json

    response = {"resultCode": "success"}
    userChara = dt.getUserObject('userCharaList', body['charaId'])
    userChara['live2dId'] = body['live2dId']
    response['userCharaList'] = [userChara]
    dt.setUserObject('userCharaList', body['charaId'], userChara)

    return flask.jsonify(response)
Ejemplo n.º 24
0
def getBattleCards(battle):
    cardIds = [
        battle[key] for key in battle.keys() if key.startswith('userCardId')
    ]
    cards = []
    charaIds = []
    for cardId in cardIds:
        userCard = dt.getUserObject('userCardList', cardId)
        if userCard is not None:
            cards.append(userCard)
            charaIds.append(userCard['card']['charaNo'])

    charas = []
    for charaId in charaIds:
        userChara = dt.getUserObject('userCharaList', charaId)
        if userChara is not None:
            charas.append(userChara)

    return cards, charas
Ejemplo n.º 25
0
def addUserToBattle(battleData, position, deck):
    currCardIdx = 0
    for i in range(5):
        if 'questPositionId' + str(i + 1) in deck:
            if deck['questPositionId' + str(i + 1)] == position:
                currCardIdx = i + 1

    userCardId = deck['userCardId' + str(currCardIdx)]
    userCard = dt.getUserObject('userCardList', userCardId)
    if userCard is None:
        flask.abort(
            400,
            description=
            '{"errorTxt": "Tried to start quest with a meguca you don\'t have: '
            + userCardId + '","resultCode": "error","title": "Error"}')

    pieceIds = [
        deck[key] for key in deck.keys()
        if key.startswith('userPieceId0' + str(currCardIdx))
    ]
    pieces = [
        dt.getUserObject('userPieceList', pieceId) for pieceId in pieceIds
    ]
    currMemoriae = battleTranslate(battleData, userCard, pieces)

    userCharaId = userCard['card']['charaNo']
    userChara = dt.getUserObject('userCharaList', userCharaId)
    if userChara is None:
        flask.abort(
            400,
            description=
            '{"errorTxt": "Tried to start quest with a meguca you don\'t have: '
            + userCharaId + '","resultCode": "error","title": "Error"}')

    battleInfo = {
        'helper': False,
        'friend': False,
        'pos': position,
        'leader': deck['questEpisodeUserCardId'] == userCharaId,
        'memoriaList': currMemoriae
    }
    battleData['playerList'].append(
        cardToPlayer(userCard, userChara, battleInfo))
Ejemplo n.º 26
0
def getItem(itemCode, amount, item=None):
    userItem = dt.getUserObject('userItemList', itemCode)
    if userItem is None:  # assumes only backgrounds and stuff
        if item is None:
            flask.abort(500,
                        description=
                        'Item is None, but userItem doesn\'t already exist...')
        userItem, _ = newtil.createUserItem(item)
    userItem['quantity'] += amount
    dt.setUserObject('userItemList', itemCode, userItem)
    return {'userItemList': [userItem]}
Ejemplo n.º 27
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.º 28
0
def clearLabyrinths():
    clearedSection = {
        "cleared": True,
        "clearedAt": "2020/01/01 00:00:00"
    }

    clearedBattle = {
        "cleared": True,
        "missionStatus1": "CLEARED",
        "missionStatus2": "CLEARED",
        "missionStatus3": "CLEARED",
        "rewardDone": True,
        "firstClearedAt": "2020/01/01 00:00:00",
        "lastClearedAt": "2020/01/01 00:00:00",
        "clearCount": 1,
        "maxDamage": 1,
    }

    for labType in range(1, 3):
        for day in range(1, 7):
            sectionId = int(f'4000{day}{labType}')
            section = dt.getUserObject('userSectionList', sectionId)

            if section is None: 
                section, _ = newtil.createUserSection(sectionId)

            if not section['cleared']:
                section.update(clearedSection)
                dt.setUserObject('userSectionList', sectionId, section)

            for level in range(1, 5):
                battleId = int(f'4000{day}{labType}{level}')
                battle = dt.getUserObject('userQuestBattleList', battleId)

                if battle is None:
                    battle, _ = newtil.createUserQuestBattle(battleId)

                if not battle['cleared']: 
                    battle.update(clearedBattle)
                    dt.setUserObject('userQuestBattleList', battleId, battle)
Ejemplo n.º 29
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)
Ejemplo n.º 30
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)