def select(self, playdata=None, rand=None): rand = rand or AppRandom() idx = 0 indexlist = [] weightlist = [] opened = [] while True: prizeid = self.getPrizeId(idx) if prizeid is None: break weight = self.getWeight(idx) if prizeid and weight: if playdata and playdata.getFlag(idx): opened.append(idx) else: indexlist.append(idx) weightlist.append(weight) idx += 1 if not weightlist: if opened: playdata.clearFlags() return self.select(playdata, rand) else: return None v = rand.getIntN(sum(weightlist)) for idx, weight in enumerate(weightlist): if v < weight: return indexlist[idx] v -= weight return None
def battle(self, player, o_player): BattleEventOppList.create(player.id, [o_player.id]).save() model_mgr = ModelRequestMgr() v_deck = BackendApi.get_deck(player.id, model_mgr) o_deck = BackendApi.get_deck(o_player.id, model_mgr) v_deck_cardlist = BackendApi.get_cards(v_deck.to_array(), model_mgr) o_deck_cardlist = BackendApi.get_cards(o_deck.to_array(), model_mgr) data = BackendApi.battle(player, v_deck_cardlist, o_player, o_deck_cardlist, AppRandom(), self.__eventmaster) BackendApi.tr_battleevent_battle(model_mgr, self.__eventmaster, self.__eventrankmaster, self.__eventrankmaster, player, o_player, v_deck.to_array(), o_deck.to_array(), data, 1, None, False, player.req_confirmkey, now=OSAUtil.get_now()) model_mgr.write_all() model_mgr.write_end() self.__player0.setModel( BackendApi.get_model(model_mgr, PlayerRequest, self.__player0.id))
def __choice_item(self, items): rate_total = sum([item.get('rate', 0) for item in items]) v = AppRandom().getIntN(rate_total) for item in items: rate = item.get('rate', 0) v -= rate if rate > 0 and v <= 0: return item['id']
def select_obj(self, rand=None): """グループの中から選別. """ rand = rand or AppRandom() v = rand.getIntN(self.rate_total) for carddata in self.__carddata_list: v -= carddata.rate if v < 0: break return carddata
def select(self, rand=None, rate_max=10000): """選別. """ if self.__rate_total < 1: return None elif rand is None or type(rand) == int: rand = AppRandom() v = rand.getIntN(self.__rate_total) for data in self.__data_list: v -= data.rate if v < 1: return data return None
def __init__(self, player, progressdata, seed, master, nextlevelexp, cardnum=0, do_happening=True, happnings=None, title=None): self.ap = player.get_ap() self.apmax = player.get_ap_max() self.exp = player.exp self.result = [] self.eventlist = [] self.rand = AppRandom(seed=seed) self.happeningselector = None self.treasureselector = None self.progress = progressdata.progress self.master = master self.nextlevelexp = nextlevelexp self.__exec_cnt = 0 self.__progressdata = progressdata self.__eventrate_drop = 1 self.__eventrate_happening = 0 self.__eventrate_treasure = 0 if isinstance(master, ScoutMaster): self.__eventrate_drop = master.eventrate_drop if do_happening: self.__eventrate_happening = master.eventrate_happening self.happeningselector = ScoutHappeningSelector( player, master, happnings) self.treasureselector = ScoutTreasureSelector(master) if self.treasureselector.can_select(): self.__eventrate_treasure = master.eventrate_treasure self.itemselector = ScoutDropItemSelector(player, master, cardnum) # 称号効果. if title: self.__title_effect_gold = title.gold_up self.__title_effect_exp = title.exp_up else: self.__title_effect_gold = 0 self.__title_effect_exp = 0 self.__player = player
def select(self, rand=None): if not self.can_select(): return None elif rand is None: rand = AppRandom() table = ( (Defines.TreasureType.GOLD, self.__scoutmaster.treasuregold), (Defines.TreasureType.SILVER, self.__scoutmaster.treasuresilver), (Defines.TreasureType.BRONZE, self.__scoutmaster.treasurebronze), ) v = rand.getIntN(self.__rate_total) for treasure_type, rate in table: if 0 < rate and v < rate: return treasure_type v -= rate return None
def select(self, rand=None, cnt=None): """グループを選別. """ if self.is_empty: raise CabaretError(u'BOXが空っぽです.リセットしましょう') is_special = False rand = rand or AppRandom() if self.__special_box.get(cnt): # 特別なOdds.なんか無理やり. groupdata_list, _, rate_total, _, _ = self.__aggregateBoxData( self.__special_box[cnt]) is_special = True else: groupdata_list, rate_total = (self.__groupdata_list, self.__rate_total) if self.num_total == -1: v = rand.getIntN(rate_total) getRate = lambda x: x.rate else: v = rand.getIntN(self.rest) getRate = lambda x: (x.num - self.__playdata.getGroupCount(x.group) ) groupdata = None for index, groupdata in enumerate(groupdata_list): groupdata = groupdata_list[index] v -= getRate(groupdata) if v < 0: break if groupdata and 0 < groupdata.num: self.__playdata.addGroupCount(groupdata.group) if groupdata.num <= self.__playdata.getGroupCount(groupdata.group): # このグループはもう選べない. self.__groupdata_list.pop(index) self.rate_total -= groupdata.rate if self.__rest != -1: self.__rest -= 1 return groupdata.group, is_special
def setUp(self): # DMMID. self.__player = self.makePlayer(10) self.__o_player = self.makePlayer(1000) self.__o_player.getModel(PlayerGold).save() # 報酬. prize = self.create_dummy(DummyType.PRIZE_MASTER, gold=100) # ランク. prizes = [{'prizes': [prize.id], 'rate': 10}] self.__rankmaster = self.create_dummy(DummyType.BATTLE_RANK_MASTER, win=10, times=10, loseprizes=prizes) # 最大ランクを作っておく. self.create_dummy(DummyType.BATTLE_RANK_MASTER, win=10, times=10, loseprizes=prizes) # 対戦相手設定. self.__battleplayer = self.create_dummy(DummyType.BATTLE_PLAYER, self.__player.id, self.__rankmaster.id, oid=self.__o_player.id, win=0, times=self.__rankmaster.times - 1) model_mgr = ModelRequestMgr() v_deck = BackendApi.get_deck(self.__player.id, model_mgr) o_deck = BackendApi.get_deck(self.__o_player.id, model_mgr) v_deck_cardlist = BackendApi.get_cards(v_deck.to_array(), model_mgr) o_deck_cardlist = BackendApi.get_cards(o_deck.to_array(), model_mgr) data = BackendApi.battle(self.__player, v_deck_cardlist, self.__o_player, o_deck_cardlist, AppRandom()) BackendApi.tr_battle(model_mgr, self.__player, self.__o_player, v_deck.to_array(), o_deck.to_array(), data, self.__battleplayer.result) model_mgr.write_all() model_mgr.write_end()
def handle(self, *args, **options): print '=======================================' print 'Generate cabaret club user ranking data' print '=======================================' players = Player.fetchValues(using=settings.DB_READONLY) rand = AppRandom() redisdb = RedisModel.getDB() pipe = redisdb.pipeline() for player in players: sales = rand.getIntN(10000) CabaClubRanking.create("currentweek", player.id, sales).save(pipe) CabaClubRanking.create("lastweek", player.id, max(100, sales - 1500)).save(pipe) pipe.execute() print '================================' print 'all done...'
def choice_bonus(self, rand=None): """おまけを選定. """ if not self.bonus or not isinstance(self.bonus, list): return [] elif not isinstance(self.bonus[0], dict): return self.bonus rand = rand or AppRandom() rate_total = sum([data.get('rate', 0) for data in self.bonus]) if rate_total < 1 or AppRandom.RAND_MAX <= rate_total: raise CabaretError(u'おまけの確率が壊れています', CabaretError.Code.INVALID_MASTERDATA) v = rand.getIntN(rate_total) for data in self.bonus: rate = data.get('rate', 0) v -= rate if 0 < rate and v <= 0: return data['prize'] raise CabaretError(u'想定外のバグです')
def setUp2(self): model_mgr = ModelRequestMgr() # Player. self.__player0 = self.makePlayer(1000) # イベントマスター. eventmaster = self.setUpEvent(model_mgr=model_mgr) self.__eventmaster = eventmaster # ランクのマスター. prize = self.create_dummy(DummyType.PRIZE_MASTER, gold=1000) params = { 'winprizes': [{ 'prizes': [prize.id], 'rate': 100, }], 'battlepoint_w': 100, 'battlepoint_lv': 10, } eventrankmaster = self.createRankMaster(params=params) self.__eventrankmaster = eventrankmaster # オープニングを閲覧済みに. self.setOpeningViewTime(self.__player0.id) # 参加させておく. self.joinRank(self.__player0.id) # 参加させておく. self.setLoginBonusReceived(self.__player0.id) # 対戦相手を設定. player = self.makePlayer(10) self.joinRank(player.id) BattleEventOppList.create(self.__player0.id, [player.id]).save() self.__player1 = player # 対戦書き込み. model_mgr = ModelRequestMgr() v_deck = BackendApi.get_deck(self.__player0.id, model_mgr) o_deck = BackendApi.get_deck(self.__player1.id, model_mgr) v_deck_cardlist = BackendApi.get_cards(v_deck.to_array(), model_mgr) o_deck_cardlist = BackendApi.get_cards(o_deck.to_array(), model_mgr) data = BackendApi.battle(self.__player0, v_deck_cardlist, self.__player1, o_deck_cardlist, AppRandom(), self.__eventmaster) BackendApi.tr_battleevent_battle(model_mgr, eventmaster, eventrankmaster, eventrankmaster, self.__player0, self.__player1, v_deck.to_array(), o_deck.to_array(), data, 1, None, False, self.__player0.req_confirmkey, now=OSAUtil.get_now()) model_mgr.write_all() model_mgr.write_end()
def __testGacha(self, gachamaster, cnt): """ガチャをテスト実行. """ model_mgr = self.getModelMgr() test_playdata = GachaPlayData.makeInstance( GachaPlayData.makeID(0, gachamaster.boxid)) # BOX. box = GachaBox(gachamaster, test_playdata) groupidlist = box.get_group_id_list() groupdict = dict([ (groupmaster.id, GachaBoxGroup(groupmaster)) for groupmaster in BackendApi.get_gachagroupmaster_list( model_mgr, groupidlist, using=backup_db) ]) # 設定値. group_rate_dict = {} cardrate_dict = {} cardgroup_dict = {} for groupid in groupidlist: rate = box.get_group_rate(groupid) group_rate_dict[groupid] = group_rate_dict.get(groupid, 0) + rate group_cardrate_dict = {} group = groupdict[groupid] for carddata in group.carddata_list: cardid = carddata.card group_cardrate_dict[cardid] = group_cardrate_dict.get( cardid, 0) + carddata.rate arr = cardgroup_dict[cardid] = cardgroup_dict.get(cardid) or [] arr.append(groupid) cardrate_dict[groupid] = group_cardrate_dict # ランダム. rand = AppRandom() # result_list = [] distribution_dict = dict.fromkeys(cardgroup_dict.keys(), 0) group_distribution_dict = dict.fromkeys(groupdict.keys(), 0) def addResult(cardid, point, groupid): # result_list.append((cardid, point, groupid)) distribution_dict[cardid] = (distribution_dict.get(cardid) or 0) + 1 group_distribution_dict[groupid] = ( group_distribution_dict.get(groupid) or 0) + 1 # ランキングガチャ用ポイント獲得関数. point_getter = lambda x: 0 if gachamaster.consumetype == Defines.GachaConsumeType.RANKING: rankinggachamaster = BackendApi.get_rankinggacha_master( model_mgr, gachamaster.boxid, using=backup_db) if rankinggachamaster: randmax = rankinggachamaster.randmax randmin = rankinggachamaster.randmin point_getter = lambda x: x.point * (100 + rand.getIntN( randmin + randmax) - randmin) / 100 # BOXからグループを選択. groupidlist = [] for _ in xrange(cnt): if box.is_empty: # 空になったのでリセット. test_playdata.resetGroupCounts() box = GachaBox(gachamaster, test_playdata) groupid, _ = box.select(rand) group = groupdict[groupid] carddata = group.select_obj(rand) addResult(carddata.card, point_getter(carddata), groupid) # self.html_param['result_list'] = result_list self.html_param['distribution_dict'] = distribution_dict self.html_param['group_dict'] = groupdict self.html_param['group_distribution_dict'] = group_distribution_dict self.html_param['group_rate_dict'] = group_rate_dict self.html_param['group_rate_total'] = sum(group_rate_dict.values()) self.html_param['cardrate_dict'] = cardrate_dict self.html_param['cardgroup_dict'] = cardgroup_dict cardmaster_idlist = distribution_dict.keys() cardmaster_dict = BackendApi.get_cardmasters(cardmaster_idlist, model_mgr, using=backup_db) self.html_param['cardmaster_dict'] = cardmaster_dict
def process(self): try: args = self.getUrlArgs('/battledo/') battleid = int(args.get(0, 0)) except: if settings_sub.IS_LOCAL: raise CabaretError(u'引数が正しくありません', CabaretError.Code.ILLEGAL_ARGS) url = UrlMaker.battle() self.appRedirect(self.makeAppLinkUrlRedirect(url)) return # バトル情報. battleplayer = self.getBattlePlayer(using=settings.DB_DEFAULT) if battleplayer is None: if settings_sub.IS_LOCAL: raise CabaretError(u'対戦相手が見つかりませんでした', CabaretError.Code.NOT_DATA) self.redirectToOppSelect() return elif battleplayer.result and battleid != battleplayer.result: url = self.makeAppLinkUrlRedirect(UrlMaker.battleanim()) self.appRedirect(url) return model_mgr = self.getModelMgr() v_player = self.getViewerPlayer() # 対戦相手. oid = battleplayer.opponent o_player = None if oid and v_player.id != oid: arr = BackendApi.get_players(self, [oid], [PlayerExp], using=settings.DB_READONLY) if arr: o_player = arr[0] if o_player is None: if settings_sub.IS_LOCAL: raise CabaretError(u'対戦相手が見つかりませんでした', CabaretError.Code.NOT_DATA) self.redirectToOppSelect() return if battleid == battleplayer.result: # お互いのカード. v_deck = BackendApi.get_deck(v_player.id, model_mgr, using=settings.DB_READONLY) o_deck = BackendApi.get_deck(o_player.id, model_mgr, using=settings.DB_READONLY) v_deck_cardlist = BackendApi.get_cards(v_deck.to_array(), model_mgr, using=settings.DB_READONLY) o_deck_cardlist = BackendApi.get_cards(o_deck.to_array(), model_mgr, using=settings.DB_READONLY) # 計算. rand = AppRandom() data = BackendApi.battle(v_player, v_deck_cardlist, o_player, o_deck_cardlist, rand) v_deck_cardidlist = v_deck.to_array() o_deck_cardidlist = o_deck.to_array() try: model_mgr, _ = db_util.run_in_transaction( self.tr_write, v_player.id, oid, v_deck_cardidlist, o_deck_cardidlist, data, battleid) model_mgr.write_end() except CabaretError, err: if err.code == CabaretError.Code.ALREADY_RECEIVED: pass elif settings_sub.IS_LOCAL: raise err else: url = self.makeAppLinkUrlRedirect(UrlMaker.battlepre()) self.appRedirect(url) return
def process(self): eventmaster = self.getCurrentBattleEvent() if not self.checkBattleEventUser(): return args = self.getUrlArgs('/battleeventbattledo/') confirmkey = urllib.unquote(args.get(0) or '') oid = args.getInt(1) rival_index = BackendApi._check_is_rival_strings(oid, eventmaster.id, args) rival_key = BackendApi.get_rival_key(oid, eventmaster.id, args) if rival_key and rival_index == 3: revengeid = args.getInt(2) elif not rival_key: revengeid = args.getInt(2) else: revengeid = None rival_key = BackendApi.get_rival_key(oid, eventmaster.id, args) now = OSAUtil.get_now() v_player = self.getViewerPlayer() uid = v_player.id o_player = None if oid: o_player = BackendApi.get_player(self, oid, [PlayerFriend, PlayerExp], using=settings.DB_READONLY) if not o_player: url = UrlMaker.battleevent_opplist() self.appRedirect(self.makeAppLinkUrlRedirect(url)) return elif not self.checkOpponentId(oid, revengeid, args=args): # 対戦できない相手. return model_mgr = self.getModelMgr() #piecedata = None if v_player.req_confirmkey == confirmkey: self.addloginfo(u'req_confirmkey==confirmkey') # 正しいリクエスト. # お互いのカード. v_deck = BackendApi.get_deck(v_player.id, model_mgr, using=settings.DB_READONLY) o_deck = BackendApi.get_deck(o_player.id, model_mgr, using=settings.DB_READONLY) v_deck_cardlist = BackendApi.get_cards(v_deck.to_array(), model_mgr, using=settings.DB_READONLY) o_deck_cardlist = BackendApi.get_cards(o_deck.to_array(), model_mgr, using=settings.DB_READONLY) self.addloginfo(u'get deck') # 現在の称号. titlemaster = BackendApi.get_current_title_master(model_mgr, v_player.id, now, using=settings.DB_READONLY) battleevent_power_up = titlemaster.battleevent_power_up if titlemaster else 0 # 計算. rand = AppRandom() data = BackendApi.battle(v_player, v_deck_cardlist, o_player, o_deck_cardlist, rand, eventmaster=eventmaster, title_effect=battleevent_power_up) self.addloginfo(u'battle') v_deck_cardidlist = v_deck.to_array() o_deck_cardidlist = o_deck.to_array() eventrankmaster = self.getCurrentBattleRankMaster() v_rankrecord = self.getCurrentBattleRankRecord() o_rankrecord = BackendApi.get_battleevent_rankrecord(model_mgr, eventmaster.id, oid, using=settings.DB_READONLY) o_eventrankmaster = None if o_rankrecord: config = BackendApi.get_current_battleeventconfig(model_mgr, using=settings.DB_READONLY) o_eventrankmaster = BackendApi.get_battleevent_rankmaster(model_mgr, eventmaster.id, o_rankrecord.getRank(config), using=settings.DB_READONLY) self.addloginfo(u'get rankrecord') # グループ内順位. group = self.getCurrentBattleGroup() grouprankdata = BackendApi.make_battleevent_grouprankingdata(self, group, v_rankrecord.uid, now, using=settings.DB_READONLY, do_get_name=False) grouprank = grouprankdata['rank'] if grouprankdata else -1 is_worst = grouprankdata['worst'] if grouprankdata else False self.addloginfo(u'make rankdata') # piecedata = self.present_piece(model_mgr, uid, eventmaster.id, data[0]['is_win'], rival_key) try: model_mgr = db_util.run_in_transaction(self.tr_write, eventmaster, eventrankmaster, o_eventrankmaster, uid, oid, v_deck_cardidlist, o_deck_cardidlist, data, grouprank, is_worst, revengeid, confirmkey, now, rival_key) self.addloginfo(u'write') model_mgr.write_end() self.addloginfo(u'write end') except CabaretError, err: if err.code == CabaretError.Code.ALREADY_RECEIVED: pass elif settings_sub.IS_LOCAL: raise err else: url = self.makeAppLinkUrlRedirect(UrlMaker.battleevent_opplist()) self.appRedirect(url) return
def __init__(self, player, progressdata, seed, master, nextlevelexp, cardnum=0, do_happening=True, happnings=None, is_lovetime=False, title=None, is_full=None): self.ap = player.get_ap() self.apmax = player.get_ap_max() self.exp = player.exp self.result = [] self.eventlist = [] self.rand = AppRandom(seed=seed) self.happeningselector = None self.treasureselector = None self.is_cleared = master.stage == progressdata.cleared if self.is_cleared and master.stage != progressdata.stage: resultlist = progressdata.result.get('result', []) if resultlist: self.progress = resultlist[-1]['progress'] else: self.progress = master.execution else: self.progress = progressdata.progress self.master = master self.nextlevelexp = nextlevelexp self.__exec_cnt = 0 self.__progressdata = progressdata self.__eventrate_drop = 1 self.__eventrate_happening = 0 self.__eventrate_treasure = 0 self.__eventrate_gachapt = 0 self.__eventrate_drop = master.eventrate_drop self.__eventrate_gachapt = getattr(master, 'eventrate_gachapt', 0) if do_happening: if is_full: self.__eventrate_happening = master.eventrate_happening_full else: self.__eventrate_happening = master.eventrate_happening self.happeningselector = ScoutHappeningSelector( player, master, happnings) self.treasureselector = ScoutTreasureSelector(master) if self.treasureselector.can_select(): if is_full: self.__eventrate_treasure = master.eventrate_treasure_full else: self.__eventrate_treasure = master.eventrate_treasure self.itemselector = ScoutDropItemSelector(player, master, cardnum) self.__eventpointmin = getattr(master, 'eventpointmin', 0) self.__eventpointmax = getattr(master, 'eventpointmax', 0) self.__eventrate_lt_star = getattr(master, 'eventrate_lt_star', 0) if not is_lovetime else 0 eventrate_total = self.__eventrate_drop eventrate_total += self.__eventrate_happening eventrate_total += self.__eventrate_treasure eventrate_total += self.__eventrate_gachapt eventrate_total += self.__eventrate_lt_star self.__eventrate_total = eventrate_total # 称号効果. if title: self.__title_effect_gold = title.gold_up self.__title_effect_exp = title.exp_up else: self.__title_effect_gold = 0 self.__title_effect_exp = 0 self.__player = player
def battle(self): """対戦する. """ continuity = 0 if self.__continuity and self.__continuity.isdigit(): continuity = int(self.__continuity) continuity = min(1000, max(1, continuity)) v_carddict = dict([(cardset.id, cardset) for cardset in self.__v_deck]) o_carddict = dict([(cardset.id, cardset) for cardset in self.__o_deck]) def skillinfoToText(skillinfo): if skillinfo.playerFlag: cardset = v_carddict[skillinfo.skillUseCardId] else: cardset = o_carddict[skillinfo.skillUseCardId] return u'{skillname} Lv{skilllevel}'.format( skillname=skillinfo.skillName, skilllevel=cardset.card.skilllevel) # カードごとにどれだけスキルを発動していて発動した時のどれだけ勝っているか. v_cardSkillCounts = {} o_cardSkillCounts = {} def addSkillCount(skillinfo, is_win): if skillinfo.playerFlag: cardSkillCounts = v_cardSkillCounts else: cardSkillCounts = o_cardSkillCounts is_win = not is_win cardid = skillinfo.skillUseCardId data = cardSkillCounts[cardid] = cardSkillCounts.get( cardid, { 'win': 0, 'count': 0 }) data['count'] += 1 if is_win: data['win'] += 1 win = 0 feverWin = 0 feverCnt = 0 results = [] for i in xrange(continuity): resultdata, animdata = BackendApi.battle(None, self.__v_deck, None, self.__o_deck, AppRandom()) is_win = resultdata['is_win'] pSkill = [] eSkill = [] for skillinfolist, skilltextlist in ((animdata.pSkill, pSkill), (animdata.eSkill, eSkill)): for skillinfo in skillinfolist: skilltextlist.append(skillinfoToText(skillinfo)) addSkillCount(skillinfo, is_win) if i < 100: resultdata.update({ 'fever': animdata.feverFlag, 'pSale': animdata.pSale, 'eSale': animdata.eSale, 'pSkill': pSkill, 'eSkill': eSkill, }) results.append(resultdata) if is_win: win += 1 if animdata.feverFlag: if is_win: feverWin += 1 feverCnt += 1 self.html_param['battleresult'] = { 'win': win, 'feverCnt': feverCnt, 'feverWin': feverWin, 'continuity': continuity, 'resultlist': results, 'v_cardSkillCounts': v_cardSkillCounts, 'o_cardSkillCounts': o_cardSkillCounts, }