package com.ljsd.jieling.logic.activity; import com.ljsd.GameApplication; import com.ljsd.jieling.config.clazzStaticCfg.CommonStaticConfig; import com.ljsd.jieling.core.VipPrivilegeType; import com.ljsd.jieling.db.mongo.MongoUtil; import com.ljsd.jieling.db.redis.RedisKey; import com.ljsd.jieling.db.redis.RedisUtil; import com.ljsd.jieling.exception.ErrorCode; import com.ljsd.jieling.exception.ErrorCodeException; import com.ljsd.jieling.globals.BIReason; import com.ljsd.jieling.globals.Global; import com.ljsd.jieling.handler.activity.BlessInfoConfig; import com.ljsd.jieling.jbean.*; import com.ljsd.jieling.logic.OnlineUserManager; import com.ljsd.jieling.logic.activity.event.*; import com.ljsd.jieling.logic.dao.*; import com.ljsd.jieling.logic.dao.root.GlobalSystemControl; import com.ljsd.jieling.logic.dao.root.User; import com.ljsd.jieling.logic.mail.MailLogic; import com.ljsd.jieling.logic.mission.GameEvent; import com.ljsd.jieling.logic.mission.event.MissionEventDistributor; import com.ljsd.jieling.logic.player.PlayerLogic; import com.ljsd.jieling.logic.store.StoreLogic; import com.ljsd.jieling.logic.store.bean.AbstractWelfareBag; import com.ljsd.jieling.network.server.ProtocolsManager; import com.ljsd.jieling.network.session.ISession; import com.ljsd.jieling.protocols.*; import com.ljsd.jieling.util.*; import config.*; import manager.STableManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Sort; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.redis.core.ZSetOperations; import util.MathUtils; import util.TimeUtils; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; /** * */ public class ActivityLogic implements IEventHandler { private static final Logger LOGGER = LoggerFactory.getLogger(ActivityLogic.class); private ActivityLogic() { LOGGER.info("------ddd ActivityLogic进入001------"); Poster.getPoster().listenEvent(this, MinuteTaskEvent.class); } private Set openActivityIds = new HashSet<>(); private Map seasonActivityIds = new HashMap<>(); private int secretBoxSeasonTimes = 0; //秘盒赛季 @Override public void onEvent(IEvent event) throws Exception { if (event instanceof MinuteTaskEvent) { checkActiviyStatus(); } } public void flushEveryDay(User user, PlayerInfoProto.FivePlayerUpdateIndication.Builder fBuilder) throws Exception { //跟新签到天数 if (user.getPlayerInfoManager().getSignTotay() == 1) { user.getPlayerInfoManager().setSign(user.getPlayerInfoManager().getSign() + 1); user.getPlayerInfoManager().setSignTotay(0); if (user.getPlayerInfoManager().getOffLineTime() != 0) { if (user.getPlayerInfoManager().getSign() >= SSignInConfig.getsSignInConfigMap().size()) { user.getPlayerInfoManager().setSign(0); user.getPlayerInfoManager().setSignTotay(0); } } } //更新每日充值 ActivityLogic.getInstance().resumeActivity(user, ActivityType.DAILY_RECHARGE); ActivityLogic.getInstance().resumeActivity(user, ActivityType.DAILY_RECHARGE_2); //更新每日累计充值 ActivityLogic.getInstance().resumeActivity(user, ActivityType.RECHARGE_NUM); ActivityLogic.getInstance().resumeActivity(user, ActivityType.RECHARGE_SUM_DAY); //更新首日充值st user.getPlayerInfoManager().getRechargeInfo().setDailyFirst(0); //更新累计充值天数 user.getPlayerInfoManager().setRechargedaily(0); user.getPlayerInfoManager().setLuckWheelLimitTime(0); user.getPlayerInfoManager().setLuckAdvanceWheelLimitTime(0); updateActivityMissionProgress(user, ActivityType.SevenLogin, 1); updateActivityMissionProgress(user, ActivityType.NEW_DAY_LOGIN, 1); Poster.getPoster().dispatchEvent(new NewWelfareEvent(user, NewWelfareTypeEnum.LOGIN_TIMES.getType(), 1)); //幸运转盘活动刷新 ActivityLogic.getInstance().resumeActivity(user, ActivityType.LUCK_WHEEL); ActivityLogic.getInstance().resumeActivity(user, ActivityType.LUCK_WHEEL_ADVANCE); ActivityLogic.getInstance().resumeActivity(user, ActivityType.TREASURE); ActivityLogic.getInstance().resumeActivity(user, ActivityType.FOREVER_MEMBER); ActivityLogic.getInstance().resumeActivity(user, ActivityType.FOREVER_MEMBER_PLUS); //神秘指令 ActivityLogic.getInstance().resumeActivity(user, ActivityType.CARD_SUBJECT_MYSTICAL_INSTRUCT); Set upFiveActivityTypes = new HashSet<>(); upFiveActivityTypes.add(ActivityType.SevenLogin); upFiveActivityTypes.add(ActivityType.NEW_DAY_LOGIN); upFiveActivityTypes.add(ActivityType.RECHARGE_SUM_DAY); upFiveActivityTypes.add(ActivityType.DAILY_RECHARGE); upFiveActivityTypes.add(ActivityType.DAILY_RECHARGE_2); upFiveActivityTypes.add(ActivityType.LUCK_WHEEL); upFiveActivityTypes.add(ActivityType.LUCK_WHEEL_ADVANCE); upFiveActivityTypes.add(ActivityType.RECHARGE_NUM); upFivePlayerActivity(user, upFiveActivityTypes, fBuilder); ActivityLogic.getInstance().resumeActivity(user,ActivityType.ADJUTANTFIGHT); ActivityLogic.getInstance().resumeActivity(user,ActivityType.JADE_DYNASTY_MISSION); } public void flushForLogin(User user, ISession iSession) throws Exception { checkActivityIsFinish(user); checkActivityOfUser(user, null); sendLuckWheelPool(user, iSession); } public static class Instance { public final static ActivityLogic instance = new ActivityLogic(); } //检查活动状态 public void checkActiviyStatus() throws Exception { long now = System.currentTimeMillis(); Map sGlobalActivityMap = SGlobalActivity.getsGlobalActivityMap(); checkRoleActiviyStatus(); //检查角色活动状态 (活动开启类型:5循环) //检查开启的活动 非相对创角时间 (活动开启类型:1绝对时间,3开服时间) for (SGlobalActivity sGlobalActivity : sGlobalActivityMap.values()) { int time = sGlobalActivity.getTime(); ActivityTypeEnum.getActicityType(sGlobalActivity.getId()); //2创角时间,4解锁时间,5循环 if (time == ActivityType.OPEN_TYPE_ROLE || time == ActivityType.OPEN_TYPE_ROLE_SERVER || time == ActivityType.OPEN_TYPE_SEASON) { continue; } long startTime = ToolsUtil.getTimeLong(sGlobalActivity.getStartTimeLong(), sGlobalActivity.getEndTimeLong(), sGlobalActivity.getTime(), 0, 1); long endTime = ToolsUtil.getTimeLong(sGlobalActivity.getStartTimeLong(), sGlobalActivity.getEndTimeLong(), sGlobalActivity.getTime(), 0, 2); long gapEndTime = endTime + sGlobalActivity.getGapTime() * TimeUtils.DAY; LOGGER.debug("checkActiviyStatus:" + sGlobalActivity.getId() + " 开始时间:" + startTime + " 结束时间:" + endTime + " gapEndTime:" + gapEndTime); if (now < startTime || sGlobalActivity.getIsOpen() == 0) { //如果没到活动开启时间,但是openActivityIds里有了这个活动,证明是热更延迟开启的活动,需要清除掉 if (openActivityIds.contains(sGlobalActivity.getId())) { openActivityIds.remove(sGlobalActivity.getId()); } LOGGER.debug("活动未开始:" + sGlobalActivity.getId()); continue; } //如果没有开放 if (!isOpen(sGlobalActivity)) { LOGGER.debug("活动未开放:" + sGlobalActivity.getId()); continue; } if (endTime != 0 && now > endTime) { if (!openActivityIds.contains(sGlobalActivity.getId())) { if (now < gapEndTime) { openActivityIds.add(sGlobalActivity.getId()); LOGGER.debug("活动已开启:" + sGlobalActivity.getId()); } continue; } if (now > gapEndTime) { LOGGER.debug("活动已结束:" + sGlobalActivity.getId()); openActivityIds.remove(sGlobalActivity.getId()); } AbstractActivity abstractActivity = ActivityTypeEnum.getActicityType(sGlobalActivity.getId()); if (null == abstractActivity) { LOGGER.debug("活动不存在:" + sGlobalActivity.getId()); continue; } abstractActivity.onActivityEnd(); LOGGER.debug("活动已结束:" + sGlobalActivity.getId()); continue; } // if (endTime != 0 && now > endTime) { // if (openActivityIds.contains(sGlobalActivity.getId())) { // openActivityIds.remove(sGlobalActivity.getId()); // AbstractActivity abstractActivity = ActivityTypeEnum.getActicityType(sGlobalActivity.getId()); // if (null == abstractActivity) { // continue; // } // abstractActivity.onActivityEnd(); // } // continue; // } AbstractActivity abstractActivity = ActivityTypeEnum.getActicityType(sGlobalActivity.getId()); if (null == abstractActivity) { LOGGER.error("活动不存在:" + sGlobalActivity.getId()); continue; } abstractActivity.onActivityStart(); openActivityIds.add(sGlobalActivity.getId()); } //活动数据处理分发到角色线程 InnerMessageUtil.broadcastWithRandom(user1 -> { if (user1 == null) { return; } ISession session = OnlineUserManager.getSessionByUid(user1.getId()); if (null == session) { return; } PlayerInfoProto.ActivityUpateIndication.Builder builder = PlayerInfoProto.ActivityUpateIndication.newBuilder(); MissionEventDistributor.requestStart(); /** * czq * @see SecretExpectRankActivity 关联这个活动 * 如果训练精英活动结束了 两个写死的VIP特权需要去掉 */ Set openNews = checkActivityOfUser(user1, builder); for (int i = 0; i < builder.getCloseActivityIdList().size(); i++) { SGlobalActivity sGlobalActivity = SGlobalActivity.getsGlobalActivityMap().get(builder.getCloseActivityIdList().get(i)); int[] shopId = sGlobalActivity.getShopId(); //如果活动关联了商店 if (shopId != null && shopId.length > 0) { for (int j = 0; j < shopId.length; i++) { int realShopId = shopId[i]; if (realShopId > 0) { user1.getStoreManager().removeStoreInfo(realShopId); } } } if(sGlobalActivity.getType() == ActivityTypeEnum.SECURT_EXPERT.getType()) { user1.getPlayerInfoManager().removeVipPriviliageId(153); user1.getPlayerInfoManager().removeVipPriviliageId(154); break; } } //send new/close activity indication if (!openNews.isEmpty()) { Map activityMissionMap = user1.getActivityManager().getActivityMissionMap(); Map activityUpdateMap = new HashMap<>(); boolean sendLuckWheelPool = false; for (Integer activityId : openNews) { int type = SGlobalActivity.getsGlobalActivityMap().get(activityId).getType(); if (type == ActivityType.LUCK_WHEEL || type == ActivityType.LUCK_WHEEL_ADVANCE) sendLuckWheelPool = true; activityUpdateMap.put(activityId, activityMissionMap.get(activityId)); } List activityInfos = getActivityInfos(activityUpdateMap, user1.getPlayerInfoManager().getCreateTime()); builder.addAllActivityInfo(activityInfos); if (sendLuckWheelPool) { sendLuckWheelPool(user1, session); } } if (builder.getActivityInfoCount() > 0 || builder.getCloseActivityIdCount() > 0) { MessageUtil.sendIndicationMessage(session, 1, MessageTypeProto.MessageType.ACTIVITY_UPDATE_INDICATION_VALUE, builder.build(), true); } MissionEventDistributor.requestEnd(session, true); }, new LinkedList<>(OnlineUserManager.sessionMap.keySet()), 5); } private static boolean isOpen(SGlobalActivity sGlobalActivity) { boolean isOpen = true; if (sGlobalActivity.getIsOpen() == 0) { isOpen = false; return isOpen; } int[][] ifOpen = sGlobalActivity.getIfOpen(); if (ifOpen != null && ifOpen.length > 0) { for (int i = 0; i < ifOpen.length ; i++) { if (ifOpen[i][0] == 2) { //开服 if (GameApplication.serverConfig.getCacheOpenTime() + ifOpen[i][1] * TimeUtils.ONE_DAY > TimeUtils.now()) { isOpen = false; break; } } } } return isOpen; } //检查角色活动状态 (活动开启类型:5循环) 轮询活动判断 public void checkRoleActiviyStatus() throws Exception { long now = System.currentTimeMillis(); Map sGlobalActivityMap = SGlobalActivity.getsGlobalActivityMap(); List openList = new ArrayList<>(); List closeList = new ArrayList<>(); for (SGlobalActivity sGlobalActivity : sGlobalActivityMap.values()) { int time = sGlobalActivity.getTime(); ActivityTypeEnum.getActicityType(sGlobalActivity.getId()); if (time != ActivityType.OPEN_TYPE_SEASON) { //5 = 活动开启类型:循环 continue; } if(!isOpen(sGlobalActivity)) { continue; } long systemOpenLong = sGlobalActivity.getStartTimeLong(); long systemEndLong = sGlobalActivity.getEndTimeLong(); int id = sGlobalActivity.getId(); if (seasonActivityIds.containsKey(id)) { // //强制关闭 systemOpenLong = seasonActivityIds.get(id).getStartTime(); systemEndLong = seasonActivityIds.get(id).getEndTime(); if (now < systemOpenLong || (now > systemEndLong)) { closeList.add(id); continue; } long endTime = seasonActivityIds.get(id).getEndTime(); if (now > endTime) { closeList.add(id); } } else { long seasonOpenLong = sGlobalActivity.getStartTimeLong(); //活动开启时间 long seasonEndLong = sGlobalActivity.getEndTimeLong(); //活动结束时间(秒) 注:孙龙的宝藏时间是任务时间,奖励时间在此基础上多一天 东海寻仙包括了活动结束后的预告时间 long diffTime = seasonEndLong - seasonOpenLong; //活动时间 long seasonInterval = sGlobalActivity.getSleepTime() * 60 * 1000L; //循环活动间隔时间(分钟),最小2 long passTims = now - seasonOpenLong; //活动开始已过时间 if (passTims > 0) { //if (diffTime + seasonInterval == 0) { if (seasonInterval == 0 || diffTime > seasonInterval) { LOGGER.info("the sGlobalSystemConfig info{},{}", sGlobalActivity.getId(), sGlobalActivity.getSleepTime()); } long mod = passTims % (diffTime + seasonInterval); //long mod = passTims % seasonInterval; if (mod < diffTime) { //新的周期开启 openList.add(id); //计算开启时间、关闭时间 long turns = passTims / (diffTime + seasonInterval); long addTim = turns * (diffTime + seasonInterval); // long turns = passTims / seasonInterval; // long addTim = turns * seasonInterval; long timeOpenOfThis = seasonOpenLong + addTim; //开启时间 long timeCloseOfThis = seasonEndLong + addTim; //结束时间 TimeControllerOfFunction function = new TimeControllerOfFunction(id, 1, timeOpenOfThis, timeCloseOfThis,(int)turns); // GlobalSystemControl globalSystemControl = MongoUtil.getInstence().getMyMongoTemplate().findById(GameApplication.serverId, GlobalSystemControl.class); // if (globalSystemControl == null) { // globalSystemControl = new GlobalSystemControl(GameApplication.serverId); // } // Map timeControllerOfFunctionMap = globalSystemControl.getTimeControllerOfActivityMap(); // TimeControllerOfFunction function = new TimeControllerOfFunction(id, 1, timeOpenOfThis, timeCloseOfThis); // if (timeControllerOfFunctionMap.containsKey(id)) { // function.setTimes(timeControllerOfFunctionMap.get(id).getTimes()); // } seasonActivityIds.put(id, function); } } } } if (openList.isEmpty() && closeList.isEmpty()) { return; } GlobalSystemControl globalSystemControl = MongoUtil.getInstence().getMyMongoTemplate().findById(GameApplication.serverId, GlobalSystemControl.class); if (globalSystemControl == null) { globalSystemControl = new GlobalSystemControl(GameApplication.serverId); } Map timeControllerOfFunctionMap = globalSystemControl.getTimeControllerOfActivityMap(); List reallyOpenList = new ArrayList<>(); // List reallyCloseList = new ArrayList<>(); boolean needUpdate = false; for (Integer id : openList) { TimeControllerOfFunction timeControllerOfFunction = timeControllerOfFunctionMap.get(id); if (timeControllerOfFunction == null || timeControllerOfFunction.getStartTime() != seasonActivityIds.get(id).getStartTime()) { needUpdate = true; TimeControllerOfFunction timeControllerOfFunctionCacheItem = seasonActivityIds.get(id); if (timeControllerOfFunction != null) { timeControllerOfFunctionCacheItem.setTimes(timeControllerOfFunction.getTimes() + 1); } else { timeControllerOfFunctionCacheItem.setTimes(1); } globalSystemControl.updateTimeControllerOfActivityMap(seasonActivityIds.get(id)); reallyOpenList.add(id); } } LOGGER.info(" ----轮询关闭活动 seasonActivityIds---- closeList={}", closeList.toString()); for (Integer id : closeList) { LOGGER.info(" ----轮询关闭活动 seasonActivityIds---- id={}", id.toString()); seasonActivityIds.remove(id); AbstractActivity abstractActivity = ActivityTypeEnum.getActicityType(id); if (null != abstractActivity) { abstractActivity.onActivityEnd(); } } if (needUpdate) { MongoTemplate otherMonogTemplate = MongoUtil.getInstence().getMonogTemplate(GameApplication.serverId); otherMonogTemplate.save(globalSystemControl); // openAction(reallyOpenList); } // closeAction(closeList); // updateGetFunctionOfTimeResponse(); } public void newPlayerOpenActivityMission(User user) throws Exception { checkActivityOfUser(user, null); ISession session = OnlineUserManager.getSessionByUid(user.getId()); if (null != session) sendLuckWheelPool(user, session); } public void checkNeedOpenStore(User user, int storeId, long startTime, long endTime) throws Exception { if (storeId == 0) { return; } StoreLogic.initOnsStoereWithTime(user, storeId, startTime, endTime); } public boolean initAllActivityMission(Map map, int activityId) { if (map.containsKey(activityId)) { return false; } ActivityMission activityMission = new ActivityMission(); //自动初始化 map.put(activityId, activityMission); initMissionInfo(activityMission, activityId); // activityMission.init(getRootId(), getMongoKey() + ".activityMissionMap." + activityId); return true; } public boolean initAllActivityMission(Map map, int activityId, int version) { // if (map.containsKey(activityId)) { // return false; // } ActivityMission activityMission = new ActivityMission(); //自动初始化 map.put(activityId, activityMission); initMissionInfo(activityMission, activityId, version); activityMission.setSeason(version); // activityMission.init(getRootId(), getMongoKey() + ".activityMissionMap." + activityId); return true; } public void initMissionInfo(ActivityMission activityMission, int activityId) { List sActivityRewardConfigs = SActivityRewardConfig.getsActivityRewardConfigByActivityId(activityId); if (sActivityRewardConfigs == null) { return; } for (SActivityRewardConfig sActivityRewardConfig : sActivityRewardConfigs) { ActivityProgressInfo activityProgressInfo = new ActivityProgressInfo(); activityProgressInfo.setProgrss(ActivityLogic.getInstance().getInitActivityMissionProgress(activityId)); activityProgressInfo.setState(0); activityMission.getActivityMissionMap().put(sActivityRewardConfig.getId(), activityProgressInfo); } activityMission.setOpenType(1); activityMission.setActivityState(ActivityType.OPEN_STATE); activityMission.setV(0); activityMission.setCreatTime(TimeUtils.now()); } public void initMissionInfo(ActivityMission activityMission, int activityId, int version) { List sActivityRewardConfigs = SActivityRewardConfig.getsActivityRewardConfigByActivityId(activityId); if (sActivityRewardConfigs == null) { return; } for (SActivityRewardConfig sActivityRewardConfig : sActivityRewardConfigs) { ActivityProgressInfo activityProgressInfo = new ActivityProgressInfo(); activityProgressInfo.setProgrss(ActivityLogic.getInstance().getInitActivityMissionProgress(activityId)); activityProgressInfo.setState(0); activityMission.getActivityMissionMap().put(sActivityRewardConfig.getId(), activityProgressInfo); } activityMission.setOpenType(1); activityMission.setActivityState(ActivityType.OPEN_STATE); activityMission.setV(0); activityMission.setSeason(version); activityMission.setCreatTime(TimeUtils.now()); } public void initOtherMission(ActivityMission activityMission, List missionIds) { for (Integer missionId : missionIds) { ActivityProgressInfo activityProgressInfo = new ActivityProgressInfo(); activityProgressInfo.setProgrss(0); activityProgressInfo.setState(0); activityMission.getActivityMissionMap().put(missionId, activityProgressInfo); } activityMission.setOpenType(1); activityMission.setV(0); activityMission.setActivityState(ActivityType.OPEN_STATE); } public LuckWheelMission getLuckWheel(ActivityManager activityManager, int type) { LuckWheelMission luckWheelMission = type == ActivityType.LUCK_WHEEL ? activityManager.getLuckWheel() : activityManager.getLuckWheelAdvance(); if (null == luckWheelMission) { String key = type == ActivityType.LUCK_WHEEL ? "luckWheel" : "luckWheelAdvance"; if (type == ActivityType.LUCK_WHEEL) { luckWheelMission = new LuckWheelMission(); activityManager.setLuckWheel(luckWheelMission); } else { luckWheelMission = new LuckWheelMission(); activityManager.setLuckWheelAdvance(luckWheelMission); } } return luckWheelMission; } public void initLuckWheel(ActivityManager activityManager, int type) { LuckWheelMission luckWheelMission = type == ActivityType.LUCK_WHEEL ? activityManager.getLuckWheel() : activityManager.getLuckWheelAdvance(); if (null != luckWheelMission) { String key = type == ActivityType.LUCK_WHEEL ? "luckWheel" : "luckWheelAdvance"; if (type == ActivityType.LUCK_WHEEL) { activityManager.setLuckWheel(luckWheelMission); } else { luckWheelMission = new LuckWheelMission(); activityManager.setLuckWheelAdvance(luckWheelMission); } } } public Set checkActivityOfUser(User user, PlayerInfoProto.ActivityUpateIndication.Builder builder) throws Exception { long now = TimeUtils.now(); if (user == null) { return new HashSet<>(1); } ActivityManager activityManager = user.getActivityManager(); Map sGlobalActivityMap = SGlobalActivity.getsGlobalActivityMap(); Set openNewActivityIds = new HashSet<>(); long userCreateTime = user.getPlayerInfoManager().getCreateTime(); // LOGGER.info("----openActivityIds ={}",openActivityIds); //初始化活动 绝对时间和相对开服时间 for (Integer openActivityId : openActivityIds) { SGlobalActivity sGlobalActivity = sGlobalActivityMap.get(openActivityId); if(!isOpen(sGlobalActivity)) { continue; } ActivityMission activityMission = activityManager.getActivityMissionMap().get(openActivityId); List sActivityRewardConfigs = SActivityRewardConfig.getsActivityRewardConfigByActivityId(openActivityId); if (activityMission != null) { if(sActivityRewardConfigs == null){ // LOGGER.info("sActivityRewardConfigs is null,openActivityId ={}",openActivityId); continue; } if(activityMission.getActivityMissionMap() != null && activityMission.getActivityMissionMap().size() == sActivityRewardConfigs.size()) { continue; }else { List idList = SActivityRewardConfig.getsActivityIdByActivityId(openActivityId); Iterator iterator = idList.iterator(); while (iterator.hasNext()){ Integer id = iterator.next(); if(!activityMission.getActivityMissionMap().keySet().contains(id)){ ActivityProgressInfo activityProgressInfo = new ActivityProgressInfo(); activityProgressInfo.setProgrss(ActivityLogic.getInstance().getInitActivityMissionProgress(openActivityId)); activityProgressInfo.setState(0); activityMission.getActivityMissionMap().put(id, activityProgressInfo); } } if(activityMission.getActivityMissionMap().size() == sActivityRewardConfigs.size()) { continue; } } } // if(!initOtherActivity(user, sGlobalActivity)){ initAllActivityMission(activityManager.getActivityMissionMap(), openActivityId); // } AbstractActivity abstractActivity = ActivityTypeEnum.getActicityType(openActivityId); if (null == abstractActivity) { continue; } abstractActivity.initActivity(user); // //ReportUtil.onReportEvent(user, ReportEventEnum.JOIN_ACTIVITY.getType(),String.valueOf(openActivityId)); int activityOpenState = getActivityOpenState(user, openActivityId); abstractActivity.setOpenState(user, activityOpenState); if (activityOpenState == ActivityType.UNOPEN_STATE) { continue; } //非角色活动开启通知 openNewActivityIds.add(openActivityId); } // LOGGER.info("----seasonActivityIds ={}",seasonActivityIds.values()); for (TimeControllerOfFunction timeIDinfo : seasonActivityIds.values()) { int openActivityId = timeIDinfo.getId(); SGlobalActivity sGlobalActivity = sGlobalActivityMap.get(openActivityId); if(!isUserCreateTimeOpen(sGlobalActivity, userCreateTime, now)) { continue; } ActivityMission activityMission = activityManager.getActivityMissionMap().get(openActivityId); if (activityMission != null) { if (activityMission.getSeason() == 0) { //更新season activityMission.setSeason(timeIDinfo.getTimes()); } if (activityMission.getSeason() == seasonActivityIds.getOrDefault(openActivityId, new TimeControllerOfFunction()).getTimes()) { continue; } //如果任务创建的时间大于本轮开始的时间 则不需要初始化 long startTime = seasonActivityIds.getOrDefault(sGlobalActivity.getId(), new TimeControllerOfFunction()).getStartTime(); if(activityMission.getCreatTime() >= startTime) { continue; } if(sGlobalActivity.getType() == ActivityType.COW_FLY_SKY && activityMission.getSeason() != timeIDinfo.getTimes() && now <= timeIDinfo.getEndTime() + sGlobalActivity.getGapTime() * TimeUtils.ONE_DAY) { //特殊处理下,因循环周期时间判断有问题,开启不了任务,重启开启任务 activityMission.setSeason(timeIDinfo.getTimes()); AbstractActivity abstractActivity = ActivityTypeEnum.getActicityType(openActivityId); if (null == abstractActivity) continue; abstractActivity.initActivity(user); continue; } LOGGER.info("[活动新周期2] [uid:{}] [activityId:{}] [activityType:{}] [activityStartTime:{}] [activitySeason:{}] [confactivitySeason:{}]", user.getId(), openActivityId, sGlobalActivity.getType(), sGlobalActivity.getStartTimeLong(), activityMission.getSeason(), timeIDinfo.getTimes()); goRewardActivity(user, openActivityId, builder, now > timeIDinfo.getEndTime() + sGlobalActivity.getGapTime() * TimeUtils.ONE_DAY); continue; } // if(!initOtherActivity(user, sGlobalActivity)){ initAllActivityMission(activityManager.getActivityMissionMap(), openActivityId, timeIDinfo.getTimes()); // } AbstractActivity abstractActivity = ActivityTypeEnum.getActicityType(openActivityId); if (null == abstractActivity) { continue; } abstractActivity.initActivity(user); // //ReportUtil.onReportEvent(user, ReportEventEnum.JOIN_ACTIVITY.getType(),String.valueOf(openActivityId)); int activityOpenState = getActivityOpenState(user, openActivityId); abstractActivity.setOpenState(user, activityOpenState); if (activityOpenState == ActivityType.UNOPEN_STATE) { continue; } //非角色活动开启通知 openNewActivityIds.add(openActivityId); } Map activityMissionMap = activityManager.getActivityMissionMap(); for (SGlobalActivity sGlobalActivity : sGlobalActivityMap.values()) { int activityId = sGlobalActivity.getId(); if (openActivityIds.contains(activityId)) { if (!isConfigIfOpen(sGlobalActivity, userCreateTime, now)) { continue; } } else if (activityMissionMap.containsKey(activityId)) { //如果活动没有开启,但是玩家有这个活动的数据,则清除,并通知客户端活动关闭 long startTime = ToolsUtil.getTimeLong(sGlobalActivity.getStartTimeLong(), sGlobalActivity.getEndTimeLong(), sGlobalActivity.getTime(), userCreateTime, 1); if (SGlobalActivity.getsGlobalActivityMap().get(activityId).getTime() == 5) { if (seasonActivityIds.containsKey(activityId)) { startTime = seasonActivityIds.getOrDefault(activityId, new TimeControllerOfFunction()).getStartTime(); // LOGGER.info("[5类型活动] [uid:{}] [activityId:{}] [activityType:{}] [activityStartTime:{}]", user.getId(), activityId, sGlobalActivity.getType(), startTime); } } if (TimeUtils.now() < startTime) { LOGGER.info("[活动延期,清除遗留玩家数据] [uid:{}] [activityId:{}] [activityType:{}] [activityStartTime:{}]", user.getId(), activityId, sGlobalActivity.getType(), sGlobalActivity.getStartTimeLong()); activityMissionMap.remove(activityId); if (builder != null) { builder.addCloseActivityId(activityId); } } } int time = sGlobalActivity.getTime(); if (sGlobalActivity.getOpenRules().length == 3 && sGlobalActivity.getOpenRules()[0] != 4) { //等级关闭 int level = sGlobalActivity.getOpenRules()[2]; if (user.getPlayerInfoManager().getLevel() >= level && level != 0) { goRewardActivity(user, activityId, builder, now > now + sGlobalActivity.getGapTime() * TimeUtils.ONE_DAY); } if (user.getPlayerInfoManager().getLevel() < sGlobalActivity.getOpenRules()[1]) { //等級未開啓 user.getActivityManager().getActivityMissionMap().remove(activityId); } } if (time == ActivityType.OPEN_TYPE_ROLE) { // 活动开启类型:创角时间 long startTime = ToolsUtil.getTimeLong(sGlobalActivity.getStartTimeLong(), sGlobalActivity.getEndTimeLong(), sGlobalActivity.getTime(), userCreateTime, 1); long endTime = ToolsUtil.getTimeLong(sGlobalActivity.getStartTimeLong(), sGlobalActivity.getEndTimeLong(), sGlobalActivity.getTime(), userCreateTime, 2); if (now < startTime) { continue; } if (endTime != 0 && now > endTime) { goRewardActivity(user, activityId, builder, now > endTime + sGlobalActivity.getGapTime() * TimeUtils.ONE_DAY); continue; } ActivityMission activityMission = activityMissionMap.get(activityId); if (activityMission != null) { continue; } int activityOpenState = getActivityOpenState(user, activityId); if (activityOpenState != ActivityType.OPEN_STATE) { continue; } AbstractActivity abstractActivity = ActivityTypeEnum.getActicityType(activityId); if (null == abstractActivity) { continue; } // //ReportUtil.onReportEvent(user, ReportEventEnum.JOIN_ACTIVITY.getType(),String.valueOf(activityId)); abstractActivity.initActivity(user); // if(!initOtherActivity(user, sGlobalActivity)){ initAllActivityMission(activityManager.getActivityMissionMap(), activityId); abstractActivity.setOpenState(user, activityOpenState); if (activityOpenState == ActivityType.UNOPEN_STATE) { continue; } openNewActivityIds.add(activityId); } else if (time == ActivityType.OPEN_TYPE_ROLE_SERVER) { // 活动开启类型:解锁时间 long startTime = ToolsUtil.getTimeLong(sGlobalActivity.getStartTimeLong(), sGlobalActivity.getEndTimeLong(), ActivityType.OPEN_TYPE_SERVER, userCreateTime, 1); long endTime = 0; if (now < startTime) { continue; } if (endTime != 0 && now > endTime) { goRewardActivity(user, activityId, builder, now > endTime + sGlobalActivity.getGapTime() * TimeUtils.ONE_DAY); continue; } ActivityMission activityMission = activityMissionMap.get(activityId); if (activityMission != null) { continue; } int activityOpenState = getActivityOpenState(user, activityId); if (activityOpenState != ActivityType.OPEN_STATE) { continue; } AbstractActivity abstractActivity = ActivityTypeEnum.getActicityType(activityId); if (null == abstractActivity) { continue; } // //ReportUtil.onReportEvent(user, ReportEventEnum.JOIN_ACTIVITY.getType(),String.valueOf(activityId)); abstractActivity.initActivity(user); // if(!initOtherActivity(user, sGlobalActivity)){ initAllActivityMission(activityManager.getActivityMissionMap(), activityId); // abstractActivity.setOpenState(user, activityOpenState); if (activityOpenState == ActivityType.UNOPEN_STATE) { continue; } openNewActivityIds.add(activityId); } else if (time == ActivityType.OPEN_TYPE_SEASON) { //活动开启类型:循环 if (!seasonActivityIds.containsKey(activityId)) { //LOGGER.info("[循环活动结束周期1] [uid:{}] [activityId:{}] [activityType:{}] [activityStartTime:{}] [activitySeason:{}] [confactivitySeason:{}]", user.getId(), activityId, sGlobalActivity.getType(), sGlobalActivity.getStartTimeLong()); long endTime = ToolsUtil.getTimeLong(sGlobalActivity.getStartTimeLong(), sGlobalActivity.getEndTimeLong(), sGlobalActivity.getTime(), user.getPlayerInfoManager().getCreateTime(), 2); goRewardActivity(user, activityId, builder, now > endTime + sGlobalActivity.getGapTime() * TimeUtils.ONE_DAY); continue; } long startTime = seasonActivityIds.get(activityId).getStartTime(); long endTime = seasonActivityIds.get(activityId).getEndTime(); if (now < startTime) { continue; } if (endTime != 0 && now > endTime) { LOGGER.info("[循环活动结束周期2] [uid:{}] [activityId:{}] [activityType:{}] [activityStartTime:{}] [activitySeason:{}] [confactivitySeason:{}]", user.getId(), activityId, sGlobalActivity.getType(), sGlobalActivity.getStartTimeLong()); goRewardActivity(user, activityId, builder, now > endTime + sGlobalActivity.getGapTime() * TimeUtils.ONE_DAY); continue; } ActivityMission activityMission = activityMissionMap.get(activityId); if (activityMission != null) { //如果season为0 修改为当前活动season if(activityMission.getSeason() == 0) { activityMission.setSeason(seasonActivityIds.getOrDefault(activityId, new TimeControllerOfFunction()).getTimes()); } if (activityMission.getSeason() == seasonActivityIds.getOrDefault(activityId, new TimeControllerOfFunction()).getTimes()) { continue; } startTime = seasonActivityIds.getOrDefault(activityId, new TimeControllerOfFunction()).getStartTime(); if(activityMission.getCreatTime() >= startTime) { continue; } LOGGER.info("[活动新周期] [uid:{}] [activityId:{}] [activityType:{}] [activityStartTime:{}] [activitySeason:{}] [confactivitySeason:{}]", user.getId(), activityId, sGlobalActivity.getType(), sGlobalActivity.getStartTimeLong(), activityMission.getSeason(), seasonActivityIds.get(activityId).getTimes()); goRewardActivity(user, activityId, builder, now > endTime + sGlobalActivity.getGapTime() * TimeUtils.ONE_DAY); } int activityOpenState = getActivityOpenState(user, activityId); if (activityOpenState != ActivityType.OPEN_STATE) { continue; } AbstractActivity abstractActivity = ActivityTypeEnum.getActicityType(activityId); if (null == abstractActivity) { continue; } // //ReportUtil.onReportEvent(user, ReportEventEnum.JOIN_ACTIVITY.getType(),String.valueOf(activityId)); //abstractActivity.initActivity(user); // if(!initOtherActivity(user, sGlobalActivity)){ //initAllActivityMission(activityManager.getActivityMissionMap(), activityId); initAllActivityMission(activityManager.getActivityMissionMap(), activityId, seasonActivityIds.get(activityId).getTimes()); abstractActivity.setOpenState(user, activityOpenState); if (activityOpenState == ActivityType.UNOPEN_STATE) { continue; } openNewActivityIds.add(activityId); checkRoleActiviyStatus(); //检查角色活动状态 (活动开启类型:5循环) } else { long endTime = ToolsUtil.getTimeLong(sGlobalActivity.getStartTimeLong(), sGlobalActivity.getEndTimeLong(), sGlobalActivity.getTime(), userCreateTime, 2); goRewardActivity(user, activityId, builder, now > endTime + sGlobalActivity.getGapTime() * TimeUtils.ONE_DAY); } } return openNewActivityIds; } /** * 配置了ifOpen 并且活动开放才返回true * @param sGlobalActivity * @param userCreateTime 用户创角时间 * @param now //系统当前时间 * @return */ private boolean isConfigIfOpen(SGlobalActivity sGlobalActivity, long userCreateTime, long now) { boolean isConfig = false; int[][] ifOpen = sGlobalActivity.getIfOpen(); if (ifOpen != null && ifOpen.length > 0) { for (int i = 0; i < ifOpen.length ; i++) { if (ifOpen[i][0] == 1) { //创角 if (userCreateTime + ifOpen[i][1] * TimeUtils.ONE_DAY <= now) { isConfig = true; break; } } } } return isConfig; } /** * 判断活动开放 是否符合创角配置 * @param sGlobalActivity * @param userCreateTime * @param now * @return */ private boolean isUserCreateTimeOpen(SGlobalActivity sGlobalActivity, long userCreateTime, long now) { boolean isConfig = true; int[][] ifOpen = sGlobalActivity.getIfOpen(); if (ifOpen != null && ifOpen.length > 0) { for (int i = 0; i < ifOpen.length ; i++) { if (ifOpen[i][0] == 1) { //创角 if (userCreateTime + ifOpen[i][1] * TimeUtils.ONE_DAY > now) { isConfig = false; break; } } } } return isConfig; } private static void goRewardActivity(User user, int activityId, PlayerInfoProto.ActivityUpateIndication.Builder builder, boolean isRemoveInfo) throws Exception { ActivityMission activityMission = user.getActivityManager().getActivityMissionMap().get(activityId); if (activityMission != null) { AbstractActivity abstractActivity = ActivityTypeEnum.getActicityType(activityId); if (null == abstractActivity) { return; } SGlobalActivity _sGlobalActivity = SGlobalActivity.getsGlobalActivityInfo(activityId); if(_sGlobalActivity != null && (_sGlobalActivity.getType() == ActivityType.EXCHANGEANDDROP || _sGlobalActivity.getType() == ActivityType.HERO_TRIAL_STAR)) { if(!isRemoveInfo) //这个类型特殊判断一下,暂时不修改通用的checkActivityOfUser方法 return; } if (activityMission.getOpenType() != ActivityType.CLOSE_STATE) { abstractActivity.onActivityEndSelfWithDealReward(user); abstractActivity.setOpenState(user, ActivityType.CLOSE_STATE); Poster.getPoster().dispatchEvent(new ActivityStateChangeEvent(user.getId(), activityId, ActivityType.CLOSE_STATE)); } if (isRemoveInfo) { user.getActivityManager().getActivityMissionMap().remove(activityId); LOGGER.info("the uid={},remove the activity id ={}", user.getId(), activityId); if (builder != null) { builder.addCloseActivityId(activityId); } } } } public static ActivityLogic getInstance() { return ActivityLogic.Instance.instance; } //获取所有活动 public void getAllActivityInfo(ISession session) throws Exception { int uid = session.getUid(); User user = UserManager.getUser(uid); long createTime = user.getPlayerInfoManager().getCreateTime(); int rewardResponseValue = MessageTypeProto.MessageType.GET_ALL_ACTIVITY_RESPONSE_VALUE; checkActivityOfUser(user, null); List activityInfoList = getActivityInfos(user.getActivityManager().getActivityMissionMap(), createTime); PlayerInfoProto.GetAllActivityResponse.Builder builder = PlayerInfoProto.GetAllActivityResponse.newBuilder(); if(user.getPlayerInfoManager().getLevel() >= 10) { //10级以上才有活动 List activityIdList = new ArrayList<>(); //没有结束的活动ID for (CommonProto.ActivityInfo activityInfo : activityInfoList) { activityIdList.add(activityInfo.getActivityId()); } ActivityEndDelItem(user,activityIdList); //活动结束 删除对应的背包道具 } for (CommonProto.ActivityInfo activityInfo : activityInfoList) { LOGGER.info("the uid={},getAllActivityInfo={}", uid, activityInfo.getActivityId()); } builder.addAllActivityInfo(activityInfoList); sendLuckWheelPool(user, session); MessageUtil.sendMessage(session, 1, rewardResponseValue, builder.build(), true); } /** * 活动结束 删除对应的背包道具 */ public void ActivityEndDelItem(User user,List activityIdList) { ItemManager itemManager = user.getItemManager(); List itemIdList = new ArrayList<>(); //没有结束的活动ID,活动结束要删除的道具Id for (int activityId : activityIdList){ SGlobalActivity sGlobalActivity = SGlobalActivity.getsGlobalActivityMap().get(activityId); int[] activityItem = sGlobalActivity.getActivityItem(); if(activityItem != null && activityItem.length > 0) { for (int i = 0; i < activityItem.length; i++) { itemIdList.add(activityItem[i]); } } } //默认不存在训练精英活动 boolean hasSE = false; //开启的商店 Map openShopInfos = new HashMap<>(); List closeShopIds = new ArrayList<>(); for (SGlobalActivity sGlobalActivity : SGlobalActivity.getsGlobalActivityMap().values()) { //如果存在训练精英活动 if (activityIdList.contains(sGlobalActivity.getId()) && sGlobalActivity.getType() == ActivityTypeEnum.SECURT_EXPERT.getType()) { hasSE = true; } //如果活动结束了 删除活动关联的商店 if (!activityIdList.contains(sGlobalActivity.getId()) && sGlobalActivity.getShopId() != null && sGlobalActivity.getShopId().length > 0 ) { for (int i = 0; i < sGlobalActivity.getShopId().length; i++) { int shopId = sGlobalActivity.getShopId()[i]; if ( shopId > 0 ) { closeShopIds.add(shopId); } } } if (activityIdList.contains(sGlobalActivity.getId()) && sGlobalActivity.getShopId() != null && sGlobalActivity.getShopId().length > 0 ) { for (int i = 0; i < sGlobalActivity.getShopId().length; i++) { int shopId = sGlobalActivity.getShopId()[i]; if ( shopId > 0 ) { OpenActData shop = new OpenActData(); long startTime = ToolsUtil.getTimeLong(sGlobalActivity.getStartTimeLong(),sGlobalActivity.getEndTimeLong(),sGlobalActivity.getTime(),user.getPlayerInfoManager().getCreateTime(), 1); long endTime = ToolsUtil.getTimeLong(sGlobalActivity.getStartTimeLong(),sGlobalActivity.getEndTimeLong(),sGlobalActivity.getTime(),user.getPlayerInfoManager().getCreateTime(), 2); shop.shopId = shopId; shop.startTime = startTime; shop.endTime = endTime; openShopInfos.put(shopId, shop); } } } if (sGlobalActivity.getActivityItem() != null && sGlobalActivity.getActivityItem().length > 0) { if (!activityIdList.contains(sGlobalActivity.getId())) { int[] activityItem = sGlobalActivity.getActivityItem(); for (int itemId : activityItem) { if(itemManager.getItemMap().containsKey(itemId)) { if (!itemIdList.contains(itemId)) { itemManager.removeItem(itemId); LOGGER.info("----活动结束 删除道具----UserId={},ItemId", user.getId(), itemId); continue; } LOGGER.info("----活动结束 有不同期活动开始,不删除道具----UserId={},ItemId={}", user.getId(), itemId); } } } } } if(!closeShopIds.isEmpty()) { closeShopIds.forEach(e-> { //如果活动被关闭 并且活动关联的商店在开启的活动中没有关联 则删除 if(!openShopInfos.containsKey(e)) { user.getStoreManager().removeStoreInfo(e); } }); } if(!openShopInfos.isEmpty()) { openShopInfos.forEach((shopId, shopInfo)-> { //如果商店不包括应该开启的商店 则重新初始化 if(!user.getStoreManager().getStoreInfoMap().containsKey(shopId)) { try { StoreLogic.initOnsStoereWithTime(user, shopId, shopInfo.startTime, shopInfo.endTime); } catch (Exception e) { LOGGER.error("initOnsStoreWithTime failed !!!"); } } }); } /** * @see SecretExpectRankActivity * 如果是训练精英活动结束了 */ if(! hasSE) { user.getPlayerInfoManager().removeVipPriviliageId(153); user.getPlayerInfoManager().removeVipPriviliageId(154); } else { //不存在则加回去 if(user.getPlayerInfoManager().getVipInfo().get(153) == null) { user.getPlayerInfoManager().addVipInfo(153); } if(user.getPlayerInfoManager().getVipInfo().get(154) == null) { user.getPlayerInfoManager().addVipInfo(154); } } } private static class OpenActData { OpenActData() { } public long startTime; public long endTime; public int shopId; } private void sendLuckWheelPool(User user, ISession session) { PlayerInfoProto.LuckWheelIndication.Builder builder = PlayerInfoProto.LuckWheelIndication.newBuilder(); builder.addAllPosInfos(LuckWheelActivity.getLuckWheelReward(user, ActivityType.LUCK_WHEEL)); builder.addAllPosInfosAdvance(LuckWheelActivity.getLuckWheelReward(user, ActivityType.LUCK_WHEEL_ADVANCE)); if (builder.getPosInfosAdvanceCount() == 0 || builder.getPosInfosCount() == 0) { return; } MessageUtil.sendIndicationMessage(session, 1, MessageTypeProto.MessageType.LUCKWHEEL_POOL_INDICATION_VALUE, builder.build(), true); } public List getActivityInfos(Map activityMissionMap, long createTime) { Map sGlobalActivityMap = SGlobalActivity.getsGlobalActivityMap(); List activityInfoList = new ArrayList<>(activityMissionMap.size()); LOGGER.info("--openActivityIds={}",openActivityIds); LOGGER.info("--seasonActivityIds={}",seasonActivityIds.keySet()); int dayOfWeek = TimeUtils.getDayOfWeek(); //获取周几, 周日 7; 其他正常 List dayList = new ArrayList<>(); dayList.add(6); dayList.add(7); dayList.add(1); for (Map.Entry activityState : activityMissionMap.entrySet()) { Integer activityId = activityState.getKey(); ActivityMission activityMission = activityState.getValue(); //todo 活动未初始化成功 // if (activityMission == null) { // continue; // } if (activityMission.getActivityMissionMap().size() == 0) { Iterator iterator = sGlobalActivityMap.values().iterator(); while (iterator.hasNext()) { SGlobalActivity next = iterator.next(); if (next.getType() == activityId) { ActivityProgressInfo aInfo = new ActivityProgressInfo(); aInfo.setRootId(next.getId()); aInfo.setProgrss(0); aInfo.setState(0); activityMission.getActivityMissionMap().put(activityId, aInfo); } } } int activityStatus = activityMission.getActivityState(); if (activityStatus == -1) { continue; } SGlobalActivity sGlobalActivity = sGlobalActivityMap.get(activityId); if (activityStatus == ActivityType.CLOSE_STATE) { long prepareTime = ToolsUtil.getEndTimeLong(sGlobalActivity.getStartTimeLong(), sGlobalActivity.getEndTimeLong(), sGlobalActivity.getTime(), 0, sGlobalActivity.getGapTime()); activityInfoList.add(CommonProto.ActivityInfo.newBuilder().setActivityId(activityId).setEndTime((int) (prepareTime / 1000)).build()); continue; } if (sGlobalActivity == null) { sGlobalActivity = new SGlobalActivity(); } if (sGlobalActivity.getIsSaving() == 0 && activityStatus != ActivityType.OPEN_STATE) { continue; } int startTime = (int) (ToolsUtil.getTimeLong(sGlobalActivity.getStartTimeLong(), sGlobalActivity.getEndTimeLong(), sGlobalActivity.getTime(), createTime, 1) / 1000); int endTime; if (sGlobalActivity.getGapTime() != 0) { endTime = (int) (ToolsUtil.getEndTimeLong(sGlobalActivity.getStartTimeLong(), sGlobalActivity.getEndTimeLong(), sGlobalActivity.getTime(), createTime, sGlobalActivity.getGapTime()) / 1000); } else { endTime = (int) (ToolsUtil.getTimeLong(sGlobalActivity.getStartTimeLong(), sGlobalActivity.getEndTimeLong(), sGlobalActivity.getTime(), createTime, 2) / 1000); } if (sGlobalActivity.getTime() == 5) { if (seasonActivityIds.containsKey(sGlobalActivity.getId())) { startTime = (int)( seasonActivityIds.get(sGlobalActivity.getId()).getStartTime() / 1000); endTime = (int) (seasonActivityIds.get(sGlobalActivity.getId()).getEndTime() / 1000); } } AbstractActivity abstractActivity = ActivityTypeEnum.getActicityType(sGlobalActivity.getId()); if (abstractActivity == null) { LOGGER.error(sGlobalActivity.getId() + ":活动类型不存在"); continue; } List missionInfos = abstractActivity.getAllMissInfo(activityMission); int time = sGlobalActivity.getTime(); // ActivityTypeEnum.getActicityType(sGlobalActivity.getId()); //2创角时间,4解锁时间,5循环 // if (time == ActivityType.OPEN_TYPE_ROLE || time == ActivityType.OPEN_TYPE_ROLE_SERVER || time == ActivityType.OPEN_TYPE_SEASON) { // // } if(openActivityIds.contains(activityId)){ activityInfoList.add(CommonProto.ActivityInfo.newBuilder().setActivityId(activityId).addAllMission(missionInfos).setStartTime(startTime).setEndTime(endTime).setValue(activityMission.getV()).setReallyOpen(activityMission.getOpenType()).build()); }else if(seasonActivityIds.containsKey(activityId)){ if(activityId == ActivityType.WEEK_END_REWARD && !dayList.contains(dayOfWeek)){ //周末福利 非周末时间 continue; } activityInfoList.add(CommonProto.ActivityInfo.newBuilder().setActivityId(activityId).addAllMission(missionInfos).setStartTime(startTime).setEndTime(endTime).setValue(activityMission.getV()).setReallyOpen(activityMission.getOpenType()).build()); } if(time == ActivityType.OPEN_TYPE_ROLE || time == ActivityType.OPEN_TYPE_ROLE_SERVER){ activityInfoList.add(CommonProto.ActivityInfo.newBuilder().setActivityId(activityId).addAllMission(missionInfos).setStartTime(startTime).setEndTime(endTime).setValue(activityMission.getV()).setReallyOpen(activityMission.getOpenType()).build()); } } return activityInfoList; } public void sendActivityInfo(User user, int activityId) { ISession session = OnlineUserManager.getSessionByUid(user.getId()); if (session != null) { PlayerInfoProto.ActivityUpateIndication.Builder builder = PlayerInfoProto.ActivityUpateIndication.newBuilder(); Map activityMissionMap = user.getActivityManager().getActivityMissionMap(); Map activityUpdateMap = new HashMap<>(); boolean sendLuckWheelPool = false; int type = SGlobalActivity.getsGlobalActivityMap().get(activityId).getType(); if (type == ActivityType.LUCK_WHEEL || type == ActivityType.LUCK_WHEEL_ADVANCE) sendLuckWheelPool = true; activityUpdateMap.put(activityId, activityMissionMap.get(activityId)); List activityInfos = getActivityInfos(activityUpdateMap, user.getPlayerInfoManager().getCreateTime()); builder.addAllActivityInfo(activityInfos); if (sendLuckWheelPool) { sendLuckWheelPool(user, session); } MessageUtil.sendIndicationMessage(session, 1, MessageTypeProto.MessageType.ACTIVITY_UPDATE_INDICATION_VALUE, builder.build(), true); } } public void openActivityReallyOpen(User user, int activityType) { ActivityManager activityManager = user.getActivityManager(); Map activityMissionMap = activityManager.getActivityMissionMap(); for (Map.Entry item : activityMissionMap.entrySet()) { SGlobalActivity sGlobalActivity = SGlobalActivity.getsGlobalActivityMap().get(item.getKey()); int targetActivityType = sGlobalActivity.getType(); if (targetActivityType == activityType) { ActivityMission value = item.getValue(); if (value.getOpenType() == 0) { value.setOpenType(1); } } } } public int getActivityOpenState(User user, int activityId) { SGlobalActivity sGlobalActivity = SGlobalActivity.getsGlobalActivityInfo(activityId); if (sGlobalActivity == null) { return ActivityType.CLOSE_STATE; } int[] openRules = sGlobalActivity.getOpenRules(); int state = ActivityType.OPEN_STATE; if (openRules != null && openRules.length > 0) { int openRuleType = openRules[0]; int openRulleValue = openRules[1]; if (openRuleType == 1) { int virtureId = SMainLevelConfig.config.get(openRulleValue).getVirtureId(); int fightId = user.getMainLevelManager().getFightId(); SMainLevelConfig mineMainLevelConfig = SMainLevelConfig.fightPreMap.get(fightId); if (user.getMainLevelManager().getState() == 2) { mineMainLevelConfig = SMainLevelConfig.config.get(user.getMainLevelManager().getFightId()); } int myVirtureId = 0; if (mineMainLevelConfig != null) { myVirtureId = mineMainLevelConfig.getVirtureId(); } if (virtureId > myVirtureId) { state = ActivityType.UNOPEN_STATE; } } else if (openRuleType == 2) { int maxLevel = Integer.MAX_VALUE - 1; if (openRules.length >= 3) { maxLevel = openRules[2]; } if (user.getPlayerInfoManager().getLevel() < openRulleValue || user.getPlayerInfoManager().getLevel() > maxLevel) { state = ActivityType.UNOPEN_STATE; } } else if (openRuleType == 3) { state = ActivityType.UNOPEN_STATE; } else if (openRuleType == 4) { int openLevel = 0; if(openRules.length >= 3){ openLevel = openRules[2]; } if(openRulleValue > 0 && openRulleValue > user.getPlayerInfoManager().getVipLevel()){ state = ActivityType.UNOPEN_STATE; } if(openLevel > 0 && openLevel > user.getPlayerInfoManager().getLevel()){ state = ActivityType.UNOPEN_STATE; } } } return state; } public void updateActivityMissionProgress(User user, int activityType, int count) { for (Integer id : getOpenActivityIdsByType(user, activityType, true)) { AbstractActivity abstractActivity = ActivityTypeEnum.getActicityType(id); if (abstractActivity == null) { continue; } abstractActivity.update(user, count); } } //活动PVE任务:通过活动Id更新任务 public void updateActivityMissionProgressByActivityId(User user, int activityId, int count) { AbstractActivity abstractActivity = ActivityTypeEnum.getActicityType(activityId); if (abstractActivity != null) { abstractActivity.update(user, count); } } public void resumeActivity(User user, int activityType) throws Exception { for (Integer id : getOpenActivityIdsByType(user, activityType, false)) { AbstractActivity abstractActivity = ActivityTypeEnum.getActicityType(id); if (abstractActivity == null) { continue; } abstractActivity.onResume(user); } } public Set getOpenActivityIdsByType(User user, int activityType, boolean withState) { Set ids = new HashSet<>(); ActivityManager activityManager = user.getActivityManager(); Map activityMissionMap = activityManager.getActivityMissionMap(); for (Map.Entry item : activityMissionMap.entrySet()) { ActivityMission activityMission = item.getValue(); if (withState && activityMission.getActivityState() != ActivityType.OPEN_STATE) { continue; } Integer activityId = item.getKey(); SGlobalActivity sGlobalActivity = SGlobalActivity.getsGlobalActivityMap().get(activityId); if (sGlobalActivity != null) { int targetActivityType = sGlobalActivity.getType(); if (targetActivityType != activityType) { continue; } } ids.add(activityId); } return ids; } public void upFivePlayerActivity(User user, Set activityType, PlayerInfoProto.FivePlayerUpdateIndication.Builder fBuilder) { if (fBuilder == null) { return; } ActivityManager activityManager = user.getActivityManager(); Map activityMissionMap = activityManager.getActivityMissionMap(); for (Map.Entry item : activityMissionMap.entrySet()) { ActivityMission activityMission = item.getValue(); if (activityMission.getActivityState() != ActivityType.OPEN_STATE) { continue; } Integer activityId = item.getKey(); SGlobalActivity sGlobalActivity = SGlobalActivity.getsGlobalActivityMap().get(activityId); int targetActivityType = sGlobalActivity.getType(); if (!activityType.contains(targetActivityType)) { continue; } AbstractActivity abstractActivity = ActivityTypeEnum.getActicityType(activityId); if (null == abstractActivity) { continue; } if (abstractActivity instanceof LuckWheelActivity) { if (targetActivityType == ActivityType.LUCK_WHEEL) fBuilder.addAllPosInfos(LuckWheelActivity.getLuckWheelReward(user, targetActivityType)); if (targetActivityType == ActivityType.LUCK_WHEEL_ADVANCE) fBuilder.addAllPosInfosAdvance(LuckWheelActivity.getLuckWheelReward(user, targetActivityType)); continue; } long createTime = user.getPlayerInfoManager().getCreateTime(); int startTime = (int) (ToolsUtil.getTimeLong(sGlobalActivity.getStartTimeLong(), sGlobalActivity.getEndTimeLong(), sGlobalActivity.getTime(), createTime, 1) / 1000); int endTime = (int) (ToolsUtil.getTimeLong(sGlobalActivity.getStartTimeLong(), sGlobalActivity.getEndTimeLong(), sGlobalActivity.getTime(), createTime, 2) / 1000); List missionInfos = abstractActivity.getAllMissInfo(activityMission); fBuilder.addActivityInfo(CommonProto.ActivityInfo.newBuilder().setValue(activityMission.getV()).setActivityId(activityId).addAllMission(missionInfos).setStartTime(startTime).setEndTime(endTime).setReallyOpen(activityMission.getOpenType()).build()); fBuilder.setHadLuckTime(user.getPlayerInfoManager().getLuckWheelLimitTime()); fBuilder.setHadAdvanceLuckTime(user.getPlayerInfoManager().getLuckAdvanceWheelLimitTime()); } } public void checkActivityIsFinish(User user) { ActivityManager activityManager = user.getActivityManager(); Map activityMissionMap = activityManager.getActivityMissionMap(); // for (Map.Entry item : activityMissionMap.entrySet()) { // ActivityMission activityMission = item.getValue(); // if (activityMission.getActivityState() != ActivityType.OPEN_STATE) { // continue; // } // if(SGlobalActivity.getsGlobalActivityInfo(item.getKey() )==null){ // activityMissionMap.remove(item.getKey()); // continue; // } // checkActivityMissionFinishAndTaked(user.getId(), item.getKey(), activityMission); // } for (Iterator> it = activityMissionMap.entrySet().iterator(); it.hasNext(); ) { Map.Entry item = it.next(); ActivityMission activityMission = item.getValue(); if (activityMission.getActivityState() != ActivityType.OPEN_STATE) { continue; } if (SGlobalActivity.getsGlobalActivityInfo(item.getKey()) == null) { it.remove(); continue; } checkActivityMissionFinishAndTaked(user.getId(), item.getKey(), activityMission); } } public boolean checkActivityMissionFinishAndTaked(int uid, int activityId, ActivityMission activityMission) { Map activityProgressInfoMap = activityMission.getActivityMissionMap(); for (Map.Entry item : activityProgressInfoMap.entrySet()) { ActivityProgressInfo activityProgressInfo = item.getValue(); int missionStatus = activityProgressInfo.getState(); if (missionStatus == ActivityType.WILL_TAKE) { return false; } // if (SGlobalActivity.getsGlobalActivityMap().get(activityId).getType() == ActivityType.TREASURE) { if (SGlobalActivity.getsGlobalActivityTypeInfo(activityId, ActivityType.TREASURE)) { if (missionStatus == ActivityType.HAD_TAKED) { return false; } } } if (activityProgressInfoMap.isEmpty()) { return false; } // SGlobalActivity sGlobalActivity = SGlobalActivity.getsGlobalActivityMap().get(activityId); SGlobalActivity sGlobalActivity = SGlobalActivity.getsGlobalActivityInfo(activityId); if (sGlobalActivity == null) { return true; } if (sGlobalActivity.getResetGrade() == 0) { activityMission.setActivityState(ActivityType.FINISH_STATE); Poster.getPoster().dispatchEvent(new ActivityStateChangeEvent(uid, activityId, ActivityType.FINISH_STATE)); } return true; } public int getInitActivityMissionProgress(int activityId) { int defalutProgress = 0; SGlobalActivity sGlobalActivity = SGlobalActivity.getsGlobalActivityInfo(activityId); int activityType = sGlobalActivity.getType(); switch (activityType) { case ActivityType.SevenLogin: case ActivityType.NEW_DAY_LOGIN: defalutProgress = 1; break; default: break; } return defalutProgress; } //秘盒 public void getSecretBox(ISession session) throws Exception { int uid = session.getUid(); User user = UserManager.getUser(uid); SecretBoxManager secretBoxManager = user.getSecretBoxManager(); if (secretBoxSeasonTimes == 0) { throw new ErrorCodeException(ErrorCode.ACTIVITY_NOT_OPEN); } if (secretBoxManager.getCurSeason() != secretBoxSeasonTimes) { flushSecretBoxOfSeasonChange(secretBoxManager); } PlayerInfoProto.GetSecretBoxInfoResponse build = PlayerInfoProto.GetSecretBoxInfoResponse.newBuilder() .setSeason(secretBoxManager.getCurSeason()) .setCount(secretBoxManager.getCount()) .build(); MessageUtil.sendMessage(session, 1, MessageTypeProto.MessageType.GET_SECRETBOX_RESPONSE_VALUE, build, true); } public void flushSecretBoxOfSeasonChange(SecretBoxManager secretBoxManager) { secretBoxManager.setCount(0); secretBoxManager.setCurSeason(secretBoxSeasonTimes); } public void randomSecretBox(ISession session, int id) throws Exception { int uid = session.getUid(); User user = UserManager.getUser(uid); SecretBoxManager secretBoxManager = user.getSecretBoxManager(); SDifferDemonsBoxSetting sDifferDemonsBoxSetting = SDifferDemonsBoxSetting.getConfig().get(id); if (sDifferDemonsBoxSetting == null || sDifferDemonsBoxSetting.getSeasonTimes() != secretBoxSeasonTimes) { throw new ErrorCodeException(ErrorCode.ACTIVITY_NOT_OPEN); } if (secretBoxManager.getCurSeason() != secretBoxSeasonTimes) { flushSecretBoxOfSeasonChange(secretBoxManager); } int randCount = sDifferDemonsBoxSetting.getSecondaryCost(); boolean allowedFree = false; if (randCount == 1) { allowedFree = PlayerLogic.getInstance().checkAndUpdate(user, VipPrivilegeType.FREE_SECRET_RANDOM, 1); } if (!allowedFree) { int[][] mainCost = sDifferDemonsBoxSetting.getMainCost(); boolean enough = ItemUtil.itemCost(user, mainCost, BIReason.SECRETBOX_CONSUME, id); if (!enough) { throw new ErrorCodeException(ErrorCode.ITEM_NOT_ENOUGH); } } int count = secretBoxManager.getCount(); int[][] randDrop = new int[randCount][]; for (int i = 1; i <= randCount; i++) { int secretBoxRandomPool = getSecretBoxRandomPool(sDifferDemonsBoxSetting, count + i); int[] dropInfos = getSecretBoxRewardByPool(secretBoxRandomPool); randDrop[i - 1] = dropInfos; } secretBoxManager.setCount(secretBoxManager.getCount() + randCount); CommonProto.Drop.Builder drop = ItemUtil.dropPer(user, randDrop, BIReason.TAKE_SECRET_REWARD); int[] extraItem = sDifferDemonsBoxSetting.getExtraItem(); CommonProto.Drop.Builder extraDrop = ItemUtil.drop(user, new int[][]{extraItem}, BIReason.TAKE_SECRET_EXTRA_REWARD); PlayerInfoProto.SecretBoxRandomResponse build = PlayerInfoProto.SecretBoxRandomResponse.newBuilder().setDrop(drop).setExtrarReward(extraDrop).build(); MessageUtil.sendMessage(session, 1, MessageTypeProto.MessageType.SECRETBOX_RANDOM_RESPONSE_VALUE, build, true); user.getUserMissionManager().onGameEvent(user, GameEvent.SECRETBOX, id, randCount); Poster.getPoster().dispatchEvent(new SecretBoxEvent(uid, randCount)); } private int[] getSecretBoxRewardByPool(int secretBoxRandomPool) { List sDifferDemonsBoxPoolsList = SDifferDemonsBoxPools.getsDifferDemonsBoxPoolByPoolId(secretBoxRandomPool); int totalWeight = 0; for (SDifferDemonsBoxPools sDifferDemonsBoxPool : sDifferDemonsBoxPoolsList) { totalWeight += sDifferDemonsBoxPool.getWeight(); } int randomWeight = MathUtils.randomInt(totalWeight) + 1; for (SDifferDemonsBoxPools sDifferDemonsBoxPool : sDifferDemonsBoxPoolsList) { randomWeight -= sDifferDemonsBoxPool.getWeight(); if (randomWeight <= 0) { return sDifferDemonsBoxPool.getReward(); } } return null; } private int getSecretBoxRandomPool(SDifferDemonsBoxSetting sDifferDemonsBoxSetting, int count) { int seasonTimes = sDifferDemonsBoxSetting.getSeasonTimes(); int poolId = 0; List sDifferDemonsBoxSeaonList = SDifferDemonsBoxSeaons.getsDifferDemonsBoxSeaonsBySeason(seasonTimes); for (SDifferDemonsBoxSeaons sDifferDemonsBoxSeaons : sDifferDemonsBoxSeaonList) { int surelyTimes = sDifferDemonsBoxSeaons.getSurelyTimes(); if (count % surelyTimes != 0) { continue; } if (count / surelyTimes > 0) { poolId = sDifferDemonsBoxSeaons.getSurelyPools(); } } if (poolId == 0) { poolId = sDifferDemonsBoxSetting.getRandomPool(); } return poolId; } public void checkSecretBoxSeason() { try { long now = TimeUtils.now(); int newSecretBoxSeasonTimes = 0; for (SDifferDemonsBoxSetting sDifferDemonsBoxSetting : SDifferDemonsBoxSetting.getConfig().values()) { long seasonStartLong = sDifferDemonsBoxSetting.getSeasonStartLong(); long seasonEndLong = sDifferDemonsBoxSetting.getSeasonEndLong(); if (now >= seasonStartLong && now <= seasonEndLong) { newSecretBoxSeasonTimes = sDifferDemonsBoxSetting.getSeasonTimes(); break; } } if (newSecretBoxSeasonTimes != secretBoxSeasonTimes) { secretBoxSeasonTimes = newSecretBoxSeasonTimes; PlayerInfoProto.UpdateSecretBoxSeasonIndication build = PlayerInfoProto.UpdateSecretBoxSeasonIndication.newBuilder().setNewSeasonId(newSecretBoxSeasonTimes).build(); MessageUtil.sendAllOnlineUserMsg(MessageTypeProto.MessageType.UPDATE_SECRET_BOX_SEASON_INDICATION_VALUE, build); } } catch (Exception e) { LOGGER.error("Exception::=>{}", e.toString()); } } private int getBlessActivityId(User user) { Map activityMissionMap = user.getActivityManager().getActivityMissionMap(); for (Integer activityId : activityMissionMap.keySet()) { if (SGlobalActivity.getsGlobalActivityMap().get(activityId).getType() == ActivityType.BLESSACTIVITY) { return activityId; } } return 0; } /** * 云梦抽取 * * @param session * @param locationId * @param messageType * @throws Exception */ public void blessChoose(ISession session, int locationId, MessageTypeProto.MessageType messageType) throws Exception { User user = UserManager.getUser(session.getUid()); int blessActivityId = getBlessActivityId(user); if (blessActivityId == 0) { throw new ErrorCodeException(ErrorCode.ACTIVITY_NOT_OPEN); } ActivityMission activityMission = user.getActivityManager().getActivityMissionMap().get(blessActivityId); if (activityMission == null) { throw new ErrorCodeException(ErrorCode.ACTIVITY_NOT_OPEN); } Map activityProgressInfoMap = activityMission.getActivityMissionMap(); if (activityProgressInfoMap.get(locationId + BlessInfoConfig.START_CAPACITY).getProgrss() != 0) { throw new ErrorCodeException(ErrorCode.REWARD_DRAWN); } int resultRewardId = 0; if (activityProgressInfoMap.get(BlessInfoConfig.BLESS_STATUS).getProgrss() == -1) { Map poolMap = STableManager.getConfig(SBlessingRewardPool.class); int[][] result = new int[BlessInfoConfig.START_CAPACITY][]; int index = 0; for (Map.Entry entry : activityProgressInfoMap.entrySet()) { if (entry.getKey() > BlessInfoConfig.START_CAPACITY) { continue; } int[] temp = new int[2]; temp[0] = entry.getValue().getProgrss(); temp[1] = poolMap.get(entry.getValue().getProgrss()).getExtractWeight(); result[index] = temp; index++; } int[] order = MathUtils.randomFromWeightWithTaking(result, BlessInfoConfig.START_CAPACITY); for (int i = 0; i < order.length; i++) { LOGGER.info("获取顺序{}", order[i]); } index = 0; for (Map.Entry entry : activityProgressInfoMap.entrySet()) { if (entry.getKey() > BlessInfoConfig.START_CAPACITY) { continue; } ActivityProgressInfo progress = new ActivityProgressInfo(); progress.setProgrss(order[index]); activityMission.getActivityMissionMap().put(entry.getKey(), progress); index++; } // ActivityProgressInfo activityProgressInfo1 = activityProgressInfoMap.getOrDefault(BlessInfoConfig.BLESS_PROGRESS_STATUS,new ActivityProgressInfo()); // activityProgressInfo1.setProgrss(activityProgressInfo1.getProgrss()+1); // activityProgressInfo1.setState(0); // activityMission.getActivityMissionMap().put(BlessInfoConfig.BLESS_PROGRESS_STATUS,activityProgressInfo1); activityMission.getActivityMissionMap().put(BlessInfoConfig.BLESS_STATUS, new ActivityProgressInfo()); // activityMission.updateProgressInfo(BlessInfoConfig.BLESS_PROGRESS_STATUS, new ActivityProgressInfo(1, 0)); } ActivityProgressInfo activityProgressInfo1 = new ActivityProgressInfo(); activityProgressInfo1.setProgrss(activityProgressInfoMap.get(BlessInfoConfig.BLESS_PROGRESS_STATUS).getProgrss() + 1); activityProgressInfo1.setState(0); activityMission.getActivityMissionMap().put(BlessInfoConfig.BLESS_PROGRESS_STATUS, activityProgressInfo1); //检验消耗道具 int[][] costConfig = SBlessingConfig.blessingConfigMap.get(blessActivityId).getCost(); int[][] cost = new int[1][]; int[] temp = new int[2]; temp[0] = costConfig[0][0]; temp[1] = (int) MathUtils.calABX(activityProgressInfoMap.get(BlessInfoConfig.BLESS_PROGRESS_STATUS).getProgrss(), costConfig[1]); cost[0] = temp; LOGGER.info("本次为第{}次抽取,消耗{}个数为{}", activityProgressInfoMap.get(BlessInfoConfig.BLESS_PROGRESS_STATUS).getProgrss(), temp[0], temp[1]); boolean costResult = ItemUtil.itemCost(user, cost, BIReason.BLESS_CHOOSE_CONSUME, 1); if (!costResult) { throw new ErrorCodeException(ErrorCode.ITEM_NOT_ENOUGH); } if (activityProgressInfoMap.get(BlessInfoConfig.BLESS_PROGRESS_STATUS).getProgrss() > 0) { for (Map.Entry entry : activityProgressInfoMap.entrySet()) { if (entry.getKey() > BlessInfoConfig.START_CAPACITY) { continue; } if (entry.getValue().getProgrss() == 0) { continue; } resultRewardId = entry.getValue().getProgrss(); ActivityProgressInfo progress = new ActivityProgressInfo(); progress.setProgrss(entry.getValue().getProgrss()); activityMission.getActivityMissionMap().put(locationId + BlessInfoConfig.START_CAPACITY, progress); activityMission.getActivityMissionMap().put(entry.getKey(), new ActivityProgressInfo()); break; } } LOGGER.info("本次抽取的Id为{}", resultRewardId); Map poolMap = STableManager.getConfig(SBlessingRewardPool.class); int[][] dropItem = new int[1][]; for (Integer count : SBlessingConfig.blessingConfigMap.get(blessActivityId).getCounts()) { if (count != activityProgressInfoMap.get(BlessInfoConfig.BLESS_PROGRESS_STATUS).getProgrss()) { continue; } dropItem = new int[2][]; dropItem[1] = poolMap.get(activityProgressInfoMap.get(BlessInfoConfig.COUNT_REWARD_START_ID + count).getProgrss()).getReward(); break; } int[] reward = poolMap.get(resultRewardId).getReward(); dropItem[0] = reward; CommonProto.Drop.Builder drop = ItemUtil.dropPer(user, dropItem, BIReason.BLESS_REWARD); // if (activityProgressInfoMap.get(BlessInfoConfig.BLESS_PROGRESS_STATUS).getProgrss() == BlessInfoConfig.START_CAPACITY + 1) { // if (SBlessingConfig.sBlessingConfig.getIsRefresh() != 0) { // blessRefresh(user); // } // } PlayerInfoProto.blessChooseResponse response = PlayerInfoProto.blessChooseResponse.newBuilder().setReward(drop).setChooseRewardId(resultRewardId).build(); MessageUtil.sendMessage(session, 1, messageType.getNumber(), response, true); } //云梦请求数据 public void blessInfo(ISession session, MessageTypeProto.MessageType messageType) throws Exception { User user = UserManager.getUser(session.getUid()); int blessActivityId = getBlessActivityId(user); if (blessActivityId == 0) { throw new ErrorCodeException(ErrorCode.ACTIVITY_NOT_OPEN); } ActivityMission activityMission = user.getActivityManager().getActivityMissionMap().get(blessActivityId); if (activityMission == null) { throw new ErrorCodeException(ErrorCode.ACTIVITY_NOT_OPEN); } PlayerInfoProto.blessResponse.Builder response = getBlessInfoResponse(activityMission); // LOGGER.info("{},{},{}",response.getFixRewardList().toString(),response.getLegendRewardList().toString(),response.getSupremeRewardList().toString()); MessageUtil.sendMessage(session, 1, messageType.getNumber(), response.build(), true); } public PlayerInfoProto.blessResponse.Builder getBlessInfoResponse(ActivityMission activityMission) { PlayerInfoProto.blessResponse.Builder response = PlayerInfoProto.blessResponse.newBuilder(); Map blessInfoMap = activityMission.getActivityMissionMap(); //保存之前 if (blessInfoMap.get(BlessInfoConfig.BLESS_STATUS).getProgrss() == -1) { for (Map.Entry entry : blessInfoMap.entrySet()) { if (entry.getKey() / BlessInfoConfig.COUNT_REWARD_START_ID > 0) { CommonProto.blessReward blessReward = CommonProto.blessReward.newBuilder() .setLocationId(entry.getKey() % BlessInfoConfig.COUNT_REWARD_START_ID) .setState(0) .setRewardId(entry.getValue().getProgrss()) .build(); response.addCountReward(blessReward); continue; } else if (entry.getKey() / BlessInfoConfig.SUPREME_REWARD_START_ID > 0) { CommonProto.blessReward blessReward = CommonProto.blessReward.newBuilder() .setLocationId(entry.getKey() % BlessInfoConfig.SUPREME_REWARD_START_ID + 1) .setState(0) .setRewardId(entry.getValue().getProgrss()) .build(); response.addSupremeReward(blessReward); continue; } else if (entry.getKey() / BlessInfoConfig.LEGEND_REWARD_START_ID > 0) { CommonProto.blessReward blessReward = CommonProto.blessReward.newBuilder() .setLocationId(entry.getKey() % BlessInfoConfig.LEGEND_REWARD_START_ID + 1) .setState(0) .setRewardId(entry.getValue().getProgrss()) .build(); response.addLegendReward(blessReward); continue; } else if (entry.getKey() <= BlessInfoConfig.START_CAPACITY) { CommonProto.blessReward blessReward = CommonProto.blessReward.newBuilder() .setLocationId(entry.getKey()) .setState(0) .setRewardId(entry.getValue().getProgrss()) .build(); response.addFixReward(blessReward); } } } else {//保存之后 for (Map.Entry entry : blessInfoMap.entrySet()) { if (entry.getKey() / BlessInfoConfig.COUNT_REWARD_START_ID > 0) { CommonProto.blessReward blessReward = CommonProto.blessReward.newBuilder() .setLocationId(entry.getKey() % BlessInfoConfig.COUNT_REWARD_START_ID) .setState(1) .setRewardId(entry.getValue().getProgrss()) .build(); response.addCountReward(blessReward); continue; } else if (entry.getKey() / BlessInfoConfig.SUPREME_REWARD_START_ID > 0) { CommonProto.blessReward blessReward = CommonProto.blessReward.newBuilder() .setLocationId(entry.getKey() % BlessInfoConfig.SUPREME_REWARD_START_ID + 1) .setState(1) .setRewardId(entry.getValue().getProgrss()) .build(); response.addSupremeReward(blessReward); continue; } else if (entry.getKey() / BlessInfoConfig.LEGEND_REWARD_START_ID > 0) { CommonProto.blessReward blessReward = CommonProto.blessReward.newBuilder() .setLocationId(entry.getKey() % BlessInfoConfig.LEGEND_REWARD_START_ID + 1) .setState(1) .setRewardId(entry.getValue().getProgrss()) .build(); response.addLegendReward(blessReward); continue; } } for (int i = BlessInfoConfig.CHOOSE_START_ID; i <= BlessInfoConfig.REWARD_VIEW_END_ID; i++) { for (Map.Entry entry : blessInfoMap.entrySet()) { if (entry.getKey() != i) { continue; } if (i < BlessInfoConfig.REWARD_VIEW_START_ID) { // LOGGER.info("显示顺序是{}", entry.getKey()); CommonProto.blessReward blessReward = CommonProto.blessReward.newBuilder() .setLocationId(i - BlessInfoConfig.START_CAPACITY) .setState(1) .setRewardId(entry.getValue().getProgrss()) .build(); response.addFixReward(blessReward); } else { CommonProto.blessReward blessReward = CommonProto.blessReward.newBuilder() .setLocationId(i - BlessInfoConfig.CHOOSE_END_ID) .setState(1) .setRewardId(entry.getValue().getProgrss()) .build(); response.addRewardView(blessReward); } } } } response.setCount(blessInfoMap.get(BlessInfoConfig.BLESS_PROGRESS_STATUS).getProgrss()); response.setLastRefreshTime(blessInfoMap.get(BlessInfoConfig.LAST_REFRESH_TIME).getProgrss()); return response; } public void blessSaveOptionalReward(ISession session, int[] rewardIds, MessageTypeProto.MessageType messageType) throws Exception { User user = UserManager.getUser(session.getUid()); // for(Map.Entry entry:SBlessingConfig.blessingConfigMap.entrySet()){ // // int activityOpenState = getActivityOpenState(user, entry.getKey()); // if(activityOpenState==ActivityType.OPEN_STATE){ // blessingConfig = entry.getValue(); // continue; // } // } int blessActivityId = getBlessActivityId(user); if (blessActivityId == 0) { throw new ErrorCodeException(ErrorCode.ACTIVITY_NOT_OPEN); } SBlessingConfig blessingConfig = SBlessingConfig.blessingConfigMap.get(blessActivityId); ActivityMission activityMission = user.getActivityManager().getActivityMissionMap().get(blessActivityId); if (activityMission.getActivityMissionMap().get(BlessInfoConfig.BLESS_STATUS).getProgrss() != -1) { throw new ErrorCodeException(ErrorCode.CANNOT_SAVE); } if (blessingConfig.getRandomNum() != BlessInfoConfig.START_CAPACITY - rewardIds.length) { throw new ErrorCodeException(ErrorCode.NUM_ERR); } for (int i = 0; i < rewardIds.length; i++) { ActivityProgressInfo info = new ActivityProgressInfo(); info.setProgrss(rewardIds[i]); activityMission.getActivityMissionMap().put(i + 1, info); } //奖励预览赋值 for (int i = 0; i < BlessInfoConfig.START_CAPACITY; i++) { activityMission.getActivityMissionMap().put(i + BlessInfoConfig.REWARD_VIEW_START_ID, activityMission.getActivityMissionMap().get(i + 1)); } ActivityProgressInfo activityProgressInfo1 = new ActivityProgressInfo(); activityProgressInfo1.setProgrss(0); activityProgressInfo1.setState(0); activityMission.getActivityMissionMap().put(BlessInfoConfig.BLESS_STATUS, activityProgressInfo1); MessageUtil.sendMessage(session, 1, messageType.getNumber(), null, true); } /** * 云梦手动刷新 * * @param session * @param messageType * @throws Exception */ public void blessRefreshReward(ISession session, MessageTypeProto.MessageType messageType) throws Exception { User user = UserManager.getUser(session.getUid()); // ActivityMission activityMission = blessRefresh(user); // // Poster.getPoster().dispatchEvent(new BlessInfoRefreshEvent(session.getUid())); // ActivityProgressInfo newInfo = new ActivityProgressInfo(); //// newInfo.setState(); //// activityMission.getActivityMissionMap().put(BlessInfoConfig.LAST_REFRESH_TIME, new ActivityProgressInfo((int) (TimeUtils.now() / 1000), 0)); // PlayerInfoProto.blessRefresh res = PlayerInfoProto.blessRefresh.newBuilder().setReward(getBlessInfoResponse(activityMission).build()).build(); // MessageUtil.sendMessage(session, 1, messageType.getNumber(), res, true); Poster.getPoster().dispatchEvent(new BlessInfoRefreshEvent(session.getUid())); } // /** // * 获取战力排行榜 // */ // public void getForceRank(ISession session, int page, int acitvityId) throws Exception { // // if (page == 0) { // page = 1; // } // int start = (page - 1) * 20, end = page * 20 - 1; // List useForceInfoList = new ArrayList<>(20); // Set> rankInfo = RedisUtil.getInstence().getZsetreverseRangeWithScores(RedisKey.FORCE_RANK,"", start, end); // for (ZSetOperations.TypedTuple item : rankInfo) { // String value = item.getValue(); // int score = item.getScore().intValue(); // int uid = Integer.parseInt(value); // User user = UserManager.getUser(uid, true); // if (null == user) { // continue; // } // PlayerManager playerInfoManager = user.getPlayerInfoManager(); // CommonProto.UseForceInfo personInfoBuild = CommonProto.UseForceInfo.newBuilder() // .setLeve(playerInfoManager.getLevel()) // .setName(playerInfoManager.getNickName()) // .setForce(score) // .setRank(++start) // .setHeadFrame(playerInfoManager.getHeadFrame()) // .setHead(playerInfoManager.getHead()) // .setUid(uid) // .build(); // useForceInfoList.add(personInfoBuild); // } // // int uid = session.getUid(); //// int score = RedisUtil.getInstence().getZSetScore(RedisKey.FORCE_RANK, "", Integer.toString(uid)).intValue(); // int score = Double.valueOf(RankContext.getRankEnum(RankEnum.FORCE_RANK.getType()).getScoreById(uid)).intValue(); // int myRank = RedisUtil.getInstence().getZSetreverseRank(RedisKey.FORCE_RANK, "", Integer.toString(uid)).intValue(); // // PlayerInfoProto.GetForceRankInfoResponse buildResponse = PlayerInfoProto.GetForceRankInfoResponse.newBuilder() // .setMyRank(myRank) // .setMyForce(score) // .addAllUseForceInfo(useForceInfoList) // .build(); // MessageUtil.sendMessage(session, 1, MessageTypeProto.MessageType.GETF_FORCE_RANK_INFO_RESPONSE_VALUE, buildResponse, true); // // } /** * 获取达人排行榜 */ public void getExpertRank(ISession session, int acitvityId) throws Exception { int start = 0; int maxSize = STableManager.getFigureConfig(CommonStaticConfig.class).getGameSetting().getShowRank(); List expertInfos = new LinkedList<>(); Set> rankInfo = RedisUtil.getInstence().getZsetreverseRangeWithScores(RedisKey.EXPERT_RANK, Integer.toString(acitvityId), 0, maxSize - 1); for (ZSetOperations.TypedTuple item : rankInfo) { String value = item.getValue(); int score = item.getScore().intValue(); int uid = Integer.parseInt(value); User user = UserManager.getUser(uid, true); if (null == user) { continue; } PlayerManager playerInfoManager = user.getPlayerInfoManager(); CommonProto.ExpertInfo personInfoBuild = CommonProto.ExpertInfo.newBuilder() .setName(playerInfoManager.getNickName()) .setScore(score) .setLevel(playerInfoManager.getLevel()) .setHeadFrame(playerInfoManager.getHeadFrame()) .setHead(playerInfoManager.getHead()) .setRank(++start) .build(); expertInfos.add(personInfoBuild); } //策划要全部数据 // if (rankInfo.size() > 2 * maxSize) { // //删除多余数据 预留一些 长度maxSize // String key = RedisKey.getKey(RedisKey.EXPERT_RANK, String.valueOf(acitvityId), false); // int size = RedisUtil.getInstence().getZsetSize(key); // RedisUtil.getInstence().removeZSetRangeByRank(key, maxSize, size); // } int uid = session.getUid(); int score = RedisUtil.getInstence().getZSetScore(RedisKey.EXPERT_RANK, Integer.toString(acitvityId), Integer.toString(uid)).intValue(); int myRank = RedisUtil.getInstence().getZSetreverseRank(RedisKey.EXPERT_RANK, Integer.toString(acitvityId), Integer.toString(uid)).intValue(); PlayerInfoProto.GetExpertInfoResponse buildResponse = PlayerInfoProto.GetExpertInfoResponse.newBuilder() .setMyRank(myRank) .addAllExpert(expertInfos) .setMyScore(score) .build(); MessageUtil.sendMessage(session, 1, MessageTypeProto.MessageType.GETF_EXPERT_RANK_INFO_RESPONSE_VALUE, buildResponse, true); } /** * 我要变强 * * @param session * @param messageType */ public void toBeStronger(ISession session, MessageTypeProto.MessageType messageType) throws Exception { User user = UserManager.getUser(session.getUid()); user.getUserMissionManager().onGameEvent(user, GameEvent.TO_BE_STRONGER); // PlayerInfoProto.GetToBeStrongerResponse.Builder response = PlayerInfoProto.GetToBeStrongerResponse.newBuilder(); // for(int i = 0 ; i <6;i++){ // CommonProto.StrongerInfo.Builder info = CommonProto.StrongerInfo.newBuilder().setCurScore(1000).setMaxScore(6000); // response.addInfos(info.build()); // } MessageUtil.sendMessage(session, 1, messageType.getNumber(), null, true); } /** * 戒灵秘宝直接购买等级 * * @param session * @param messageType * @throws Exception */ public void treasureBuyLevel(ISession session, int level, MessageTypeProto.MessageType messageType) throws Exception { User user = UserManager.getUser(session.getUid()); int treasureLevel = user.getPlayerInfoManager().getTreasureLevel(); if (level <= treasureLevel) { throw new ErrorCodeException(ErrorCode.LEVEL_ERR); } int num = 0; int[][] cost = SSpecialConfig.getTwiceArrayValue(SSpecialConfig.SUNLONG_COST); //这段代码并没有实现每一级相同的购买价格??? /*for(int i = level;i>treasureLevel;i--){ num+=MathUtils.calABX(i,cost[1]); }*/ num = (int) MathUtils.calABX(level - treasureLevel, cost[1]); int[][] costItems = new int[1][]; int[] costTemp = {cost[0][0], num}; costItems[0] = costTemp; boolean result = ItemUtil.itemCost(user, costItems, BIReason.TREASURE_BUY_LEVEL_CONSUME, 1); if (result) { user.getPlayerInfoManager().setTreasureLevel(level); } else { throw new ErrorCodeException(ErrorCode.ITEM_NOT_ENOUGH); } PlayerInfoProto.TreasureLevelUpIndication indication = PlayerInfoProto.TreasureLevelUpIndication.newBuilder().setLevel(user.getPlayerInfoManager().getTreasureLevel()).build(); MessageUtil.sendIndicationMessage(session, 1, MessageTypeProto.MessageType.TREASURE_LEVELUP_INDICATION_VALUE, indication, true); MessageUtil.sendMessage(session, 1, messageType.getNumber(), null, true); } public Set getActivityStatusByType(User user, int type) { List activities = SGlobalActivity.sGlobalActivityMapByType.get(type); if (activities.isEmpty()) { return new HashSet<>(); } else { Set objects = activities.stream().filter(n -> user.getActivityManager().getActivityMissionMap().keySet().contains(n.getId())).map(sGlobalActivity -> sGlobalActivity.getId()).collect(Collectors.toSet()); return objects; } } public void getNextActivityId(ISession session, int activityId, MessageTypeProto.MessageType messageType) throws Exception { User user = UserManager.getUser(session.getUid()); List sGlobalActivities = SGlobalActivity.sGlobalActivityMapByType.get(activityId); if (sGlobalActivities.isEmpty()) { throw new ErrorCodeException(ErrorCode.ACTIVITY_NOT_OPEN); } Function function = v -> (int) ToolsUtil.getTimeLong(v.getStartTimeLong(), v.getEndTimeLong(), v.getTime(), user.getPlayerInfoManager().getCreateTime(), 1); Stream stream = sGlobalActivities.stream().sorted(Comparator.comparing(function)) .filter(v -> ToolsUtil.getTimeLong(v.getStartTimeLong(), v.getEndTimeLong(), v.getTime(), user.getPlayerInfoManager().getCreateTime(), 1) > TimeUtils.now()); List collect = stream.collect(Collectors.toList()); if (collect.isEmpty()) { throw new ErrorCodeException(ErrorCode.ACTIVITY_NOT_OPEN); } int id = collect.get(0).getId(); SGlobalActivity sGlobalActivity = SGlobalActivity.getsGlobalActivityMap().get(id); if (sGlobalActivity == null) { throw new ErrorCodeException(ErrorCode.ACTIVITY_NOT_ON); } long startTime = ToolsUtil.getTimeLong(sGlobalActivity.getStartTimeLong(), sGlobalActivity.getEndTimeLong(), sGlobalActivity.getTime(), user.getPlayerInfoManager().getCreateTime(), 1); PlayerInfoProto.NextActivityResponse response = PlayerInfoProto.NextActivityResponse.newBuilder().setId(id).setTime((int) (startTime / 1000)).build(); MessageUtil.sendMessage(session, 1, messageType.getNumber(), response, true); } public void getTreasureNextRefreshTime(ISession session, MessageTypeProto.MessageType messageType) throws Exception { int dayRefreshTime = (int) (TimeUtils.getLastOrUnderHour(TimeUtils.now(), 0, 0, false) / 1000); //int weekRefreshTime = (int) (TimeUtils.getNextWeekendStartTime(1, 0) / 1000); User user = UserManager.getUser(session.getUid()); long _time = getTreasureNextWeekRefreshTime(user); int weekRefreshTime = (int)(_time/1000); long checkTime = TimeUtils.getTimeBeforeOrAfterMinute(_time,-7 * 24 * TimeUtils.MIN_HOUR); long weekRefresh = user.getUserMissionManager().getTreasureMissionIdsType().getWeekRefresh(); if(checkTime != weekRefresh) {//修复线上玩家的时间不对问题 LOGGER.info("check uid:{},checkTime:{},weekRefresh:{}",user.getId(),checkTime,weekRefresh); user.getUserMissionManager().getTreasureMissionIdsType().setWeekRefresh(checkTime); } PlayerInfoProto.TreasureRefreshTimeResponse response = PlayerInfoProto.TreasureRefreshTimeResponse.newBuilder().setDayTime(dayRefreshTime).setWeekTime(weekRefreshTime).build(); MessageUtil.sendMessage(session, 1, messageType.getNumber(), response, true); } public long getTreasureNextWeekRefreshTime(User user){ Set activityIds = getActivityStatusByType(user,ActivityType.TREASURE); long result = 0; if(!activityIds.isEmpty()){ int activityId = activityIds.stream().findFirst().get(); long startTime = getSeasonActivityStartAndEndTime(user,activityId)[0]; long now = System.currentTimeMillis(); if(startTime > 0) { long _time; for(int i = 1; i < 999999; i++) { _time = TimeUtils.getTimeBeforeOrAfterMinute(startTime,i * 7 * 24 * TimeUtils.MIN_HOUR); if(_time > now) { result = _time; break; } } } } return result; } // public void getTreasureNextRefreshTime(ISession session,MessageTypeProto.MessageType messageType) throws Exception { // int dayRefreshTime=(int) (TimeUtils.getLastOrUnderHour(TimeUtils.now(), 5,0, false)/1000); // int uid = session.getUid(); // User user = UserManager.getUser(uid); // PlayerInfoProto.TreasureRefreshTimeResponse response; // if(user.getActivityManager().getActivityMissionMap().containsKey(801)){ // int weekRefreshTime = (int)(TimeUtils.getNextWeekendStartTime(1,5)/1000); // response = PlayerInfoProto.TreasureRefreshTimeResponse.newBuilder().setDayTime(dayRefreshTime).setWeekTime(weekRefreshTime).build(); // }else{ // long weekRefresh = user.getUserMissionManager().getTreasureMissionIdsType().getWeekRefresh(); // response = PlayerInfoProto.TreasureRefreshTimeResponse.newBuilder().setDayTime(dayRefreshTime).setWeekTime((int)(weekRefresh/1000)).build(); // } // MessageUtil.sendMessage(session,1,messageType.getNumber(),response,true); // } public void getJadeDynastyNextRefreshTime(ISession session, MessageTypeProto.MessageType messageType) throws Exception { int dayRefreshTime = (int) (TimeUtils.getLastOrUnderHour(TimeUtils.now(), 0, 0, false) / 1000); int weekRefreshTime = (int) (TimeUtils.getNextWeekendStartTime(1, 0) / 1000); PlayerInfoProto.JadeDynastyRefreshTimeResponse response = PlayerInfoProto.JadeDynastyRefreshTimeResponse.newBuilder().setDayTime(dayRefreshTime).setWeekTime(weekRefreshTime).build(); MessageUtil.sendMessage(session, 1, messageType.getNumber(), response, true); } public void getShengDanNextRefreshTime(ISession session, MessageTypeProto.MessageType messageType) throws Exception { int dayRefreshTime = (int) (TimeUtils.getLastOrUnderHour(TimeUtils.now(), 0, 0, false) / 1000); int weekRefreshTime = (int) (TimeUtils.getNextWeekendStartTime(1, 0) / 1000); PlayerInfoProto.ShengDanRefreshTimeResponse response = PlayerInfoProto.ShengDanRefreshTimeResponse.newBuilder().setDayTime(dayRefreshTime).setWeekTime(weekRefreshTime).build(); MessageUtil.sendMessage(session, 1, messageType.getNumber(), response, true); } public void getMysticalInstructNextRefreshTime(ISession session, MessageTypeProto.MessageType messageType) throws Exception { int dayRefreshTime = (int) (TimeUtils.getLastOrUnderHour(TimeUtils.now(), 0, 0, false) / 1000); int weekRefreshTime = (int) (TimeUtils.getNextWeekendStartTime(1, 0) / 1000); PlayerInfoProto.MysticalInstructRefreshTimeResponse response = PlayerInfoProto.MysticalInstructRefreshTimeResponse.newBuilder().setDayTime(dayRefreshTime).setWeekTime(weekRefreshTime).build(); MessageUtil.sendMessage(session, 1, messageType.getNumber(), response, true); } public void getHeroCollectNextRefreshTime(ISession session, MessageTypeProto.MessageType messageType) throws Exception { int dayRefreshTime = (int) (TimeUtils.getLastOrUnderHour(TimeUtils.now(), 0, 0, false) / 1000); int weekRefreshTime = (int) (TimeUtils.getNextWeekendStartTime(1, 0) / 1000); PlayerInfoProto.HeroCollectRefreshTimeResponse response = PlayerInfoProto.HeroCollectRefreshTimeResponse.newBuilder().setDayTime(dayRefreshTime).setWeekTime(weekRefreshTime).build(); MessageUtil.sendMessage(session, 1, messageType.getNumber(), response, true); } //检查活动是否开启 public static boolean checkActivityOpen(User user, int activityType) { ActivityManager activityManager = user.getActivityManager(); Map activityMissionMap = activityManager.getActivityMissionMap(); for (Map.Entry item : activityMissionMap.entrySet()) { // LOGGER.info("user id {} activityType {} key{}", user.getId(), activityType, item.getKey()); SGlobalActivity sGlobalActivity = SGlobalActivity.getsGlobalActivityMap().get(item.getKey()); if (sGlobalActivity == null) { // LOGGER.info("user id {} activityType {} key{}",user.getId(),activityType,item.getKey()); // return false; continue; } int targetActivityType = sGlobalActivity.getId(); if (targetActivityType == activityType) { return true; } } return false; } //检查活动是否开启 public static boolean checkActivityIsOpen(User user, int activityType) { ActivityManager activityManager = user.getActivityManager(); Map activityMissionMap = activityManager.getActivityMissionMap(); for (Map.Entry item : activityMissionMap.entrySet()) { SGlobalActivity sGlobalActivity = SGlobalActivity.getsGlobalActivityMap().get(item.getKey()); if (sGlobalActivity == null) { continue; // return false; } int targetActivityType = sGlobalActivity.getId(); if (targetActivityType == activityType) { if (item.getValue().getActivityState() == ActivityType.UNOPEN_STATE || item.getValue().getActivityState() == ActivityType.CLOSE_STATE) { return false; } return true; } } return false; } /** * 检查绝对时间 和相对开服时间活动是否开启 */ public boolean checkGlobleActivityOpen(int activityId) { return openActivityIds.contains(activityId); } //扭转乾坤 public void goodLuckRandom(ISession session, int activityId, MessageTypeProto.MessageType messageType) throws Exception { SGoodLuck sGoodLuck = SGoodLuck.goodLuckMap.get(activityId); if (sGoodLuck == null) { throw new ErrorCodeException(ErrorCode.ACTIVITY_NOT_ON); } User user = UserManager.getUser(session.getUid()); if (!user.getActivityManager().getActivityMissionMap().containsKey(activityId)) { throw new ErrorCodeException(ErrorCode.ACTIVITY_NOT_OPEN); } int[][] cost = sGoodLuck.getCost(); boolean itemCost = ItemUtil.itemCost(user, cost, BIReason.GOOD_LUCK_CONSUME, 1); if (!itemCost) { throw new ErrorCodeException(ErrorCode.ITEM_NOT_ENOUGH); } int[][] reward = sGoodLuck.getReward(); int random = MathUtils.random(1, reward.length); CommonProto.Drop.Builder drop = ItemUtil.drop(user, new int[][]{reward[random - 1]}, BIReason.GOOD_LUCK_DROP); ActivityProto.GoodLuckResponse.Builder response = ActivityProto.GoodLuckResponse.newBuilder().setIndex(random).setDrop(drop); MessageUtil.sendMessage(session, 1, messageType.getNumber(), response.build(), true); } /** * 灵兽活动选择灵兽 * * @param session * @param activityId * @param chooseId */ public void chooseSpecialMonster(ISession session, int activityId, int chooseId) throws Exception { SGlobalActivity activity = SGlobalActivity.getsGlobalActivityMap().get(activityId); if (activity == null || activity.getType() != ActivityType.SPECIAL_MONSTER_RANDOM_ACTIVITY) { throw new ErrorCodeException(ErrorCode.ACTIVITY_NOT_ON); } User user = UserManager.getUser(session.getUid()); Map activityMissionMap = user.getActivityManager().getActivityMissionMap(); ActivityMission activityMission = activityMissionMap.get(activityId); if (activityMission == null || !activityMission.getActivityMissionMap().containsKey(0)) { throw new ErrorCodeException(ErrorCode.ACTIVITY_NOT_ON); } Map sSpiritAnimalSummon = STableManager.getConfig(SSpiritAnimalSummon.class); if (!sSpiritAnimalSummon.containsKey(chooseId) || sSpiritAnimalSummon.get(chooseId).getActivityID() != activityId) { throw new ErrorCodeException(ErrorCode.ACTIVITY_NOT_ON); } activityMission.getActivityMissionMap().get(0).setProgrss(chooseId); MessageUtil.sendMessage(session, 1, MessageTypeProto.MessageType.SPECICAL_MONSTER_CHOOSE_RESPONSE_VALUE, null, true); } public static long[] getStartAndEndTime(User user, int activityId) { long[] result = new long[2]; long startTime = 0; long endTime = 0; SGlobalActivity sGlobalActivity = SGlobalActivity.getsGlobalActivityMap().get(activityId); if (sGlobalActivity.getTime() == ActivityType.OPEN_TYPE_ROLE) { startTime = ToolsUtil.getTimeLong(sGlobalActivity.getStartTimeLong(), sGlobalActivity.getEndTimeLong(), sGlobalActivity.getTime(), user.getPlayerInfoManager().getCreateTime(), 1); endTime = ToolsUtil.getTimeLong(sGlobalActivity.getStartTimeLong(), sGlobalActivity.getEndTimeLong(), sGlobalActivity.getTime(), user.getPlayerInfoManager().getCreateTime(), 2); } else { startTime = ToolsUtil.getTimeLong(sGlobalActivity.getStartTimeLong(), sGlobalActivity.getEndTimeLong(), sGlobalActivity.getTime(), 0, 1); endTime = ToolsUtil.getTimeLong(sGlobalActivity.getStartTimeLong(), sGlobalActivity.getEndTimeLong(), sGlobalActivity.getTime(), 0, 2); } result[0] = startTime; result[1] = endTime; return result; } /** * 轮询活动的时间 * @param user * @param activityId * @return */ public long[] getSeasonActivityStartAndEndTime(User user, int activityId){ long[] result = new long[2]; long startTime = 0; long endTime = 0; SGlobalActivity sGlobalActivity = SGlobalActivity.getsGlobalActivityMap().get(activityId); if (sGlobalActivity.getTime() == ActivityType.OPEN_TYPE_ROLE) { startTime = ToolsUtil.getTimeLong(sGlobalActivity.getStartTimeLong(), sGlobalActivity.getEndTimeLong(), sGlobalActivity.getTime(), user.getPlayerInfoManager().getCreateTime(), 1); endTime = ToolsUtil.getTimeLong(sGlobalActivity.getStartTimeLong(), sGlobalActivity.getEndTimeLong(), sGlobalActivity.getTime(), user.getPlayerInfoManager().getCreateTime(), 2); } if(sGlobalActivity.getTime() == ActivityType.OPEN_TYPE_SEASON && seasonActivityIds.containsKey(activityId)) { startTime = seasonActivityIds.get(activityId).getStartTime(); endTime = seasonActivityIds.get(activityId).getEndTime(); } else { startTime = ToolsUtil.getTimeLong(sGlobalActivity.getStartTimeLong(), sGlobalActivity.getEndTimeLong(), sGlobalActivity.getTime(), 0, 1); endTime = ToolsUtil.getTimeLong(sGlobalActivity.getStartTimeLong(), sGlobalActivity.getEndTimeLong(), sGlobalActivity.getTime(), 0, 2); } result[0] = startTime; result[1] = endTime; return result; } /** * 集字活动 -- 炮击 * * @param iSession * @param id * @param messageType * @throws Exception */ public void wordExchangeBombardActivity(ISession iSession, int id, MessageTypeProto.MessageType messageType) throws Exception { User user = UserManager.getUser(iSession.getUid()); SLotterySetting sLotterySetting = STableManager.getConfig(SLotterySetting.class).get(id); int lotteryType = sLotterySetting.getLotteryType(); //招募类型 int[][] costItem = sLotterySetting.getCostItem(); //招募消耗的道具 int[][] diamondBoxContain = sLotterySetting.getDiamondBoxContain(); //高级招募包含库(库#概率) int perCount = sLotterySetting.getPerCount(); //抽卡次数 int mergePool = sLotterySetting.getMergePool(); //将单抽和十连合并起来 数字相同为同一卡池 int activityId = sLotterySetting.getActivityId(); //活动id if (lotteryType != 22 && activityId != 104004) { throw new ErrorCodeException(ErrorCode.PARAM_ERR); } int costItemKey = costItem[0][0]; int costItemNum = costItem[0][1]; long itemNum = user.getItemManager().getItemNum(costItemKey); //背包物品数量 if (itemNum < costItemNum) { throw new ErrorCodeException(ErrorCode.ITEM_NULL); } //消耗物品 boolean enoughCost = ItemUtil.itemCost(user, costItem, BIReason.WORDEXCHANGEBOMBARD_CONSUME, 1); if (!enoughCost) { throw new ErrorCodeException(ErrorCode.ITEM_NOT_ENOUGH); } int pool_id = diamondBoxContain[0][0]; ActivityManager activityManager = user.getActivityManager(); Map idCountMap = activityManager.getIdCountMap(); List poolIdList = new ArrayList<>(); int minCount = 0; int minPoolId = pool_id; if(mergePool != 0) { List specialConfigs = SLotterySpecialConfig.getLotterySpecialConfigListByType(mergePool); if (specialConfigs != null && !specialConfigs.isEmpty()) { for (SLotterySpecialConfig everyConfig : specialConfigs) { if (everyConfig.getIsNeedShow() == 0) { minCount = everyConfig.getCount(); minPoolId = everyConfig.getpool_id(); break; } } } } int count = 0; if (idCountMap.get(costItemKey) != null) { count = idCountMap.get(costItemKey); } for (int i = 0; i < perCount; i++) { //本次是否触发保底 if (count + 1 < minCount) { //count + 1 表示 最小是1,从1开始 count++; poolIdList.add(pool_id); continue; } poolIdList.add(minPoolId); count = 0; } idCountMap.put(costItemKey, count); //增加的商品 int[][] rewardSum = new int[perCount][2]; //单次奖励 for (int i = 0; i < poolIdList.size(); i++) { //SLotteryRewardConfig sLotteryRewardConfig = randomMotherShipPlanByPoolId(pool_id, 1, user.getPlayerInfoManager().getLevel()); SLotteryRewardConfig sLotteryRewardConfig = randomMotherShipPlanByPoolId(poolIdList.get(i), 1, user.getPlayerInfoManager().getLevel()); if(sLotteryRewardConfig == null){ throw new ErrorCodeException(ErrorCode.PARAM_ERR); } //增加的商品 int[] reward = sLotteryRewardConfig.getReward(); //单次奖励 rewardSum[i] = reward; } //增加商品 CommonProto.Drop.Builder drop = ItemUtil.drop(user, rewardSum, BIReason.WORDEXCHANGEBOMBARD_REWARD); PlayerInfoProto.WordExchangeBombardActivityResponse.Builder response = PlayerInfoProto.WordExchangeBombardActivityResponse.newBuilder(); response.setDrop(drop); MessageUtil.sendMessage(iSession, 1, messageType.getNumber(), response.build(), true); } /** * 卡牌主题:初始化信息 请求 * @param iSession * @param activityId * @param messageType * @throws Exception */ public void CardSubjectInit(ISession iSession, int activityId, MessageTypeProto.MessageType messageType) throws Exception { User user = UserManager.getUser(iSession.getUid()); int relationActivityId = activityId; Map map = SWishActivityRelationConfig.getWishActivityRelationMapByActivityId(); if (map != null && map.containsKey(activityId)) { relationActivityId = map.get(activityId); } ActivityManager activityManager = user.getActivityManager(); Map wishRewardTimesMap = activityManager.getWishRewardTimesMap(); //卡牌主题:英雄驾到 心愿奖励次数 key=activityId, value=心愿奖励次数 int rewardTimes = 0; //心愿奖励次数 if(wishRewardTimesMap != null && wishRewardTimesMap.containsKey(relationActivityId)){ rewardTimes = wishRewardTimesMap.get(relationActivityId); //心愿奖励次数 } Map wishTimesMap = activityManager.getWishTimesMap(); //获取 招募次数 int wishTimes = 0; //招募次数 if(wishTimesMap != null && wishTimesMap.containsKey(relationActivityId)){ wishTimes = wishTimesMap.get(relationActivityId); } Map wishIdMap = activityManager.getWishIdMap();//心愿奖励Id key=activityId, value=心愿奖励Id int wishId = 0; //心愿奖励Id if(wishIdMap != null && wishIdMap.containsKey(relationActivityId)){ wishId = wishIdMap.get(relationActivityId); } SWishPoolConfig sWishPoolConfig = SWishPoolConfig.getsWishPoolConfigMapByActivityId().get(relationActivityId); int times = sWishPoolConfig.getWishTimes(); //心愿奖励所需要的保底次数 40 PlayerInfoProto.CardSubjectInitResponse.Builder response = PlayerInfoProto.CardSubjectInitResponse.newBuilder(); response.setWishTimes(rewardTimes); response.setTimes(times - wishTimes); response.setWishId(wishId == 0 ? 1 : wishId); //心愿奖励Id 默认=1 MessageUtil.sendMessage(iSession, 1, messageType.getNumber(), response.build(), true); } /** * 卡牌主题:英雄豪礼-免费领取 * @param iSession * @param activityId * @param taskId * @param messageType * @throws Exception */ public void cardSubjectHeroLuxuryGetFreeActivity(ISession iSession, int activityId,int taskId, MessageTypeProto.MessageType messageType) throws Exception { User user = UserManager.getUser(iSession.getUid()); int relationActivityId = activityId; Map map = SWishActivityRelationConfig.getWishActivityRelationMapByActivityId(); if (map != null && map.containsKey(activityId)) { relationActivityId = map.get(activityId); } ActivityManager activityManager = user.getActivityManager(); Map wishRewardTimesMap = activityManager.getWishRewardTimesMap(); //卡牌主题:英雄驾到 心愿奖励次数 key=activityId, value=心愿奖励次数 //int rewardTimes = wishRewardTimesMap.get(relationActivityId); //心愿奖励次数 int rewardTimes = 0; //心愿奖励次数 if(wishRewardTimesMap != null && wishRewardTimesMap.containsKey(relationActivityId)){ rewardTimes = wishRewardTimesMap.get(relationActivityId); //心愿奖励次数 } Map wishFreeRewardMap = activityManager.getWishFreeRewardMap(); //int wishTimes = wishFreeRewardMap.get(activityId); //已领取心愿奖励条件 次数 int wishTimes = 0; //已领取心愿奖励条件 次数 if(wishFreeRewardMap != null && wishFreeRewardMap.containsKey(activityId)){ wishTimes = wishFreeRewardMap.get(activityId); //已领取心愿奖励条件 次数 } SWishTaskRewardConfig sWishTaskRewardConfig = STableManager.getConfig(SWishTaskRewardConfig.class).get(taskId); int condition = sWishTaskRewardConfig.getCondition(); //达成心愿条件 if(condition > rewardTimes){ throw new ErrorCodeException(ErrorCode.COUNT_NOT_ENOUGH); //次数不足 }else { if(wishTimes > condition){ throw new ErrorCodeException(ErrorCode.HAD_TAKE_REWARD); //2已领取 } } int[] freeReward = sWishTaskRewardConfig.getFreeReward(); //免费奖励 //更新 已领取心愿奖励条件 次数 wishFreeRewardMap.put(activityId,condition); activityManager.setWishFreeRewardMap(wishFreeRewardMap); //增加商品 CommonProto.Drop.Builder drop = ItemUtil.drop(user, new int[][]{freeReward}, BIReason.CARD_SUBJECT_HERO_LUXURY_GET_FREE_REWARD); PlayerInfoProto.CardSubjectHeroGetFreeResponse.Builder response = PlayerInfoProto.CardSubjectHeroGetFreeResponse.newBuilder(); response.setDrop(drop); MessageUtil.sendMessage(iSession, 1, messageType.getNumber(), response.build(), true); } /** * 牌主题:英雄豪礼 * @param iSession * @param activityId 活动ID * @param messageType * @throws Exception */ public void cardSubjectHeroLuxuryActivity(ISession iSession, int activityId, MessageTypeProto.MessageType messageType) throws Exception { User user = UserManager.getUser(iSession.getUid()); int relationActivityId = activityId; Map map = SWishActivityRelationConfig.getWishActivityRelationMapByActivityId(); if (map != null && map.containsKey(activityId)) { relationActivityId = map.get(activityId); } ActivityManager activityManager = user.getActivityManager(); Map wishRewardTimesMap = activityManager.getWishRewardTimesMap(); //卡牌主题:英雄驾到 心愿奖励次数 key=activityId, value=心愿奖励次数 int rewardTimes = 0; //心愿奖励次数 if(wishRewardTimesMap != null && wishRewardTimesMap.containsKey(relationActivityId)){ rewardTimes = wishRewardTimesMap.get(relationActivityId); //心愿奖励次数 } // int freeStatus = 0; //免费礼包状态; 0不能领取,1可领取,2已领取 Map wishFreeRewardMap = activityManager.getWishFreeRewardMap(); //int wishTimes = activityManager.getWishFreeRewardMap().get(activityId); //已领取心愿奖励条件 次数 value=达成心愿条件最后次数 对应WishTaskRewardConfig表 int wishTimes = 0; if(wishFreeRewardMap != null && wishFreeRewardMap.containsKey(activityId)){ wishTimes = wishFreeRewardMap.get(activityId); } List heroLuxuries = new ArrayList<>(); List sWishTaskRewardConfigs = SWishTaskRewardConfig.getWishTaskRewardConfigByActivityIdMap().get(activityId); for (SWishTaskRewardConfig config : sWishTaskRewardConfigs) { CommonProto.HeroLuxury heroLuxury = buildHeroLuxury(config, rewardTimes, wishTimes); heroLuxuries.add(heroLuxury); } PlayerInfoProto.CardSubjectHeroLuxuryGetResponse.Builder response = PlayerInfoProto.CardSubjectHeroLuxuryGetResponse.newBuilder(); response.setTimes(rewardTimes); response.addAllHeroLuxury(heroLuxuries); MessageUtil.sendMessage(iSession, 1, messageType.getNumber(), response.build(), true); } public static CommonProto.HeroLuxury buildHeroLuxury(SWishTaskRewardConfig config,int rewardTimes,int wishTimes) { CommonProto.HeroLuxury.Builder heroLuxury = CommonProto.HeroLuxury.newBuilder(); heroLuxury.setId(config.getId()); int freeStatus = 0; //免费礼包状态; 0不能领取,1可领取,2已领取 if(config.getCondition() <= rewardTimes){ //可领取 if(wishTimes < config.getCondition()){ freeStatus = 1; //可领取 }else { freeStatus = 2; //2已领取 } } heroLuxury.setFreeStatus(freeStatus); return heroLuxury.build(); } /** * 卡牌主题:英雄驾到 切换心愿池 */ public void cardSubjeckWishPoolChange(ISession iSession,int activityId, int id, MessageTypeProto.MessageType messageType) throws Exception { User user = UserManager.getUser(iSession.getUid()); //英雄驾到 ActivityType=50000的活动ID List activityIdList = new ArrayList<>(); List sGlobalActivities = SGlobalActivity.sGlobalActivityMapByType.get(ActivityType.CARD_SUBJECT_HERO_GET); for (SGlobalActivity globalActivity : sGlobalActivities){ activityIdList.add(globalActivity.getId()); } //int activityId = activityIdList.get(0); SWishPoolConfig sWishPoolConfig = SWishPoolConfig.getsWishPoolConfigMapByActivityId().get(activityId); //int wishTimes = sWishPoolConfig.getWishTimes(); //心愿奖励保底次数,本期活动每个心愿奖励所需要的保底次数 int[] changeWishCost = sWishPoolConfig.getChangeWishCost(); //切换心愿奖励消耗,填写值为:道具id#数量 int[] wishReward = sWishPoolConfig.getWishReward1(); //切换的心愿奖池 if(id == 1){ wishReward = sWishPoolConfig.getWishReward1(); }else if(id == 2){ wishReward = sWishPoolConfig.getWishReward2(); }else if(id == 3){ wishReward = sWishPoolConfig.getWishReward3(); }else if(id == 4){ wishReward = sWishPoolConfig.getWishReward4(); }else if(id == 5){ wishReward = sWishPoolConfig.getWishReward5(); } Item item = new Item(); item.setItemId(wishReward[0]); item.setItemNum(wishReward[1]); int costItemKey = changeWishCost[0]; int costItemNum = changeWishCost[1]; long itemNum = user.getItemManager().getItemNum(costItemKey); //背包物品数量 if (itemNum < costItemNum) { throw new ErrorCodeException(ErrorCode.ITEM_NULL); } //消耗物品 boolean enoughCost = ItemUtil.itemCost(user, new int[][]{{costItemKey,costItemNum}}, BIReason.CARD_SUBJECT_WISH_POOL_CHANGE_COST, 1); if (!enoughCost) { throw new ErrorCodeException(ErrorCode.ITEM_NOT_ENOUGH); } ActivityManager activityManager = user.getActivityManager(); //更新 心愿奖励 Map wishRewardMap = activityManager.getWishRewardMap(); wishRewardMap.put(activityId,item); activityManager.setWishRewardMap(wishRewardMap); //更新心愿Id Map wishIdMap = activityManager.getWishIdMap(); wishIdMap.put(activityId,id); activityManager.setWishIdMap(wishIdMap); PlayerInfoProto.CardSubjeckWishPoolChangeResponse.Builder response = PlayerInfoProto.CardSubjeckWishPoolChangeResponse.newBuilder(); MessageUtil.sendMessage(iSession, 1, messageType.getNumber(), response.build(), true); } /** * 卡牌主题:英雄驾到 招募 * @param iSession * @param id * @param messageType * @throws Exception */ public void cardSubjectHeroGetActivity(ISession iSession, int id, MessageTypeProto.MessageType messageType) throws Exception { User user = UserManager.getUser(iSession.getUid()); SLotterySetting sLotterySetting = STableManager.getConfig(SLotterySetting.class).get(id); int lotteryType = sLotterySetting.getLotteryType(); //招募类型 int[][] costItem = sLotterySetting.getCostItem(); //招募消耗的道具 int[][] diamondBoxContain = sLotterySetting.getDiamondBoxContain(); //高级招募包含库(库#概率) int perCount = sLotterySetting.getPerCount(); //抽卡次数 int mergePool = sLotterySetting.getMergePool(); //将单抽和十连合并起来 数字相同为同一卡池 int activityId = sLotterySetting.getActivityId(); //活动id //英雄驾到 ActivityType=50000的活动ID List activityIdList = new ArrayList<>(); List sGlobalActivities = SGlobalActivity.sGlobalActivityMapByType.get(ActivityType.CARD_SUBJECT_HERO_GET); for (SGlobalActivity globalActivity : sGlobalActivities) { activityIdList.add(globalActivity.getId()); } if (lotteryType != 52 && !activityIdList.contains(activityId)) { //52 = LotterySetting表ActivityId=70001的 LotteryType throw new ErrorCodeException(ErrorCode.PARAM_ERR); } int costItemKey = costItem[0][0]; int costItemNum = costItem[0][1]; long itemNum = user.getItemManager().getItemNum(costItemKey); //背包物品数量 if (itemNum < costItemNum) { throw new ErrorCodeException(ErrorCode.ITEM_NULL); } //消耗物品 boolean enoughCost = ItemUtil.itemCost(user, costItem, BIReason.CARD_SUBJECT_HERO_GET_COST, 1); if (!enoughCost) { throw new ErrorCodeException(ErrorCode.ITEM_NOT_ENOUGH); } ActivityManager activityManager = user.getActivityManager(); //------------心愿保底 WishPoolConfig Start ----------- Map wishTimesMap = activityManager.getWishTimesMap(); //获取 招募次数 Map wishRewardMap = activityManager.getWishRewardMap(); //获取 心愿奖励 Map wishRewardTimesMap = activityManager.getWishRewardTimesMap(); //获取 心愿奖励次数 Map wishIdMap = activityManager.getWishIdMap(); //心愿奖励Id key=activityId, value=心愿奖励Id SWishPoolConfig sWishPoolConfig = SWishPoolConfig.getsWishPoolConfigMapByActivityId().get(activityId); int wishTimes = sWishPoolConfig.getWishTimes(); //心愿奖励所需要的保底次数 40 int relationActivityId = activityId; if(!SWishActivityRelationConfig.getWishActivityRelationMapByActivityId().values().contains(activityId)){ relationActivityId = SWishActivityRelationConfig.getWishActivityRelationMapByActivityId().get(activityId); } int wishId = 0; //心愿奖励Id if(wishIdMap != null && wishIdMap.containsKey(relationActivityId)){ wishId = wishIdMap.get(relationActivityId); } int[] wishReward = sWishPoolConfig.getWishReward1(); //切换的心愿奖池 if(wishId == 1){ wishReward = sWishPoolConfig.getWishReward1(); }else if(wishId == 2){ wishReward = sWishPoolConfig.getWishReward2(); }else if(wishId == 3){ wishReward = sWishPoolConfig.getWishReward3(); }else if(wishId == 4){ wishReward = sWishPoolConfig.getWishReward4(); }else if(wishId == 5){ wishReward = sWishPoolConfig.getWishReward5(); } int pool_id = diamondBoxContain[0][0]; //高级招募包含库(库#概率) // List poolIdList = new ArrayList<>(); int cardCount = 0; //获取 招募次数 if (wishTimesMap.get(activityId) != null) { cardCount = wishTimesMap.get(activityId); } //------------心愿保底 WishPoolConfig End ----------- //------------Lottery保底 Start-------------------- // int pool_id = diamondBoxContain[0][0]; //高级招募包含库(库#概率) Map idCountMap = activityManager.getIdCountMap(); List poolIdList = new ArrayList<>(); int minCount = 0; int minPoolId = pool_id; if (mergePool != 0) { List specialConfigs = SLotterySpecialConfig.getLotterySpecialConfigListByType(mergePool); if (specialConfigs != null && !specialConfigs.isEmpty()) { for (SLotterySpecialConfig everyConfig : specialConfigs) { if (everyConfig.getIsNeedShow() == 0) { minCount = everyConfig.getCount(); minPoolId = everyConfig.getpool_id(); break; } } } } else { minCount = wishTimes; } //增加的商品 int[][] rewardSum = new int[perCount][2]; //单次奖励 int curWishTimes = 0; //本次招募获取心愿次数 // int count = 0; // if (idCountMap.get(costItemKey) != null) { // count = idCountMap.get(costItemKey); // } for (int i = 0; i < perCount; i++) { //本次是否触发保底 if (cardCount + 1 < minCount) { //count + 1 表示 最小是1,从1开始 //count++; cardCount++; poolIdList.add(pool_id); continue; } //count = 0; cardCount = 0; curWishTimes+=1; //wishTimesMap.put(activityId,count); int wishRewardTimes = 0; if(wishRewardTimesMap.containsKey(activityId)){ wishRewardTimes = wishRewardTimesMap.get(activityId); } wishRewardTimesMap.put(activityId, wishRewardTimes + 1); //更新 心愿奖励次数 activityManager.setWishRewardTimesMap(wishRewardTimesMap); } //idCountMap.put(costItemKey, count); wishTimesMap.put(activityId, cardCount); //更新 招募次数 activityManager.setWishTimesMap(wishTimesMap); //------------Lottery保底 End-------------------- boolean haveWishReward = false; //此次招募是否有心愿奖励 for (int i = 0; i < poolIdList.size(); i++) { //SLotteryRewardConfig sLotteryRewardConfig = randomMotherShipPlanByPoolId(pool_id, 1, user.getPlayerInfoManager().getLevel()); SLotteryRewardConfig sLotteryRewardConfig = randomMotherShipPlanByPoolId(poolIdList.get(i), 1, user.getPlayerInfoManager().getLevel()); if (sLotteryRewardConfig == null) { throw new ErrorCodeException(ErrorCode.PARAM_ERR); } //增加的商品 int[] reward = sLotteryRewardConfig.getReward(); //单次奖励 if (wishReward[0] == reward[0] && wishReward[1] == reward[1]) { //玩家获得心愿奖励次数 user.getUserMissionManager().onGameEvent(user, GameEvent.WISH_REWARD_TIMES, 900); curWishTimes += 1; haveWishReward = true; int wishRewardTimes = 0; if(wishRewardTimesMap.containsKey(activityId)){ wishRewardTimes = wishRewardTimesMap.get(activityId); } wishRewardTimesMap.put(activityId, wishRewardTimes + 1); //更新 心愿奖励次数 activityManager.setWishRewardTimesMap(wishRewardTimesMap); } rewardSum[i] = reward; } if(haveWishReward){ cardCount = 0; wishTimesMap.put(activityId, cardCount); //更新 招募次数 activityManager.setWishTimesMap(wishTimesMap); } if(curWishTimes > 0){ for (int i = poolIdList.size(); i< perCount; i++) { rewardSum[i] = wishReward; //玩家获得心愿奖励次数 user.getUserMissionManager().onGameEvent(user, GameEvent.WISH_REWARD_TIMES, 900); } } //增加商品 CommonProto.Drop.Builder drop = ItemUtil.drop(user, rewardSum, BIReason.CARD_SUBJECT_HERO_GET_REWARD); int wishRewardTimes = 0; //心愿奖励次数 if(wishRewardTimesMap != null && wishRewardTimesMap.containsKey(relationActivityId)){ wishRewardTimes = wishRewardTimesMap.get(relationActivityId); } PlayerInfoProto.CardSubjectHeroGetActivityResponse.Builder response = PlayerInfoProto.CardSubjectHeroGetActivityResponse.newBuilder(); response.setDrop(drop); response.setTimes(wishTimes-cardCount); //X次之后必定获得心愿奖励 response.setWishRewardTimes(wishRewardTimes); //心愿奖励次数 MessageUtil.sendMessage(iSession, 1, messageType.getNumber(), response.build(), true); } public static SLotteryRewardConfig randomMotherShipPlanByPoolId(int poolId, int randomCount, int userLevel) { List sLotteryRewardConfigs = new ArrayList<>(); List sLotteryRewardConfigListByPoolId = SLotteryRewardConfig.getSLotteryRewardConfigListByPoolId(poolId); int totalCountByPoolId = 0; for (SLotteryRewardConfig sLotteryRewardConfig : sLotteryRewardConfigListByPoolId) { int[] openRules = sLotteryRewardConfig.getOpenRules(); boolean canAdd = true; if (openRules != null && openRules.length > 0) { int openType = openRules[0]; int openValue = openRules[1]; switch (openType) { case 1: canAdd = randomCount > openValue; break; case 2: canAdd = userLevel > openValue; break; } } if (canAdd) { sLotteryRewardConfigs.add(sLotteryRewardConfig); totalCountByPoolId += sLotteryRewardConfig.getWeight(); } } int randCount = MathUtils.randomInt(totalCountByPoolId) + 1; int weight = 0; for (SLotteryRewardConfig sLotteryRewardConfig : sLotteryRewardConfigs) { weight += sLotteryRewardConfig.getWeight(); if (weight >= randCount) { return sLotteryRewardConfig; } } return null; } // public static SLotteryRewardConfig randomMotherShipPlanByPoolId(int poolId, int randomCount, int userLevel) { // List sLotteryRewardConfigs = new ArrayList<>(); // List sLotteryRewardConfigListByPoolId = SLotteryRewardConfig.getSLotteryRewardConfigListByPoolId(poolId); // int totalCountByPoolId = 0; // for (SLotteryRewardConfig sLotteryRewardConfig : sLotteryRewardConfigListByPoolId) { // int[] openRules = sLotteryRewardConfig.getOpenRules(); // boolean canAdd = true; // if (openRules != null && openRules.length > 0) { // int openType = openRules[0]; // int openValue = openRules[1]; // switch (openType) { // case 1: // canAdd = randomCount > openValue; // break; // case 2: // canAdd = userLevel > openValue; // break; // } // } // if (canAdd) { // sLotteryRewardConfigs.add(sLotteryRewardConfig); // totalCountByPoolId += sLotteryRewardConfig.getWeight(); // } // } // // int randCount = MathUtils.randomInt(totalCountByPoolId) + 1; // int weight = 0; // for (SLotteryRewardConfig sLotteryRewardConfig : sLotteryRewardConfigs) { // weight += sLotteryRewardConfig.getWeight(); // if (weight >= randCount) { // return sLotteryRewardConfig; // } // } // return null; // } /** * 副官招募 * * @param iSession * @param layer 层级 * @param type 抽奖道具类型 * @param messageType * @throws Exception */ public void adjutantLayerActivity(ISession iSession, int layer, int type, MessageTypeProto.MessageType messageType) throws Exception { User user = UserManager.getUser(iSession.getUid()); Set openActivityId = ActivityLogic.getInstance().getOpenActivityIdsByType(user, ActivityTypeEnum.ADJUTANTLAYER.getType(), true); if (openActivityId.size() == 0) { throw new ErrorCodeException(ErrorCode.PARAM_ERR); } int openId = 0; for (Iterator iterator = openActivityId.iterator(); iterator.hasNext(); ) { openId = (int) iterator.next(); } LOGGER.info("now adjutantLayerActivity id is {}", openId); Map layerPoolConfigMap = SLayerPoolConfig.sByLayerMap.get(openId); if (layerPoolConfigMap.size() == 0) { throw new ErrorCodeException(ErrorCode.PARAM_ERR); } SLayerPoolConfig config = layerPoolConfigMap.get(layer); int setId = config.getLotteryId()[type]; SLotterySetting sLotterySetting = STableManager.getConfig(SLotterySetting.class).get(setId); int perCount = sLotterySetting.getPerCount(); int maxTimes = sLotterySetting.getMaxTimes(); if (maxTimes != 0 && !PlayerLogic.getInstance().checkAndUpdate(user, maxTimes, perCount)) { throw new ErrorCodeException(ErrorCode.ADJUTANT_ACT_BUYCOUNT_ENOUGH); } //所有获得物品 int[][] resultRandom = new int[perCount][]; //进行抽取 for (int i = 0; i < perCount; i++) { int rewardId = randomOne(user, setId); SLotteryRewardConfig sLotteryRewardConfig = STableManager.getConfig(SLotteryRewardConfig.class).get(rewardId); resultRandom[i] = sLotteryRewardConfig.getReward(); } //消耗商品 int[][] costItem = sLotterySetting.getCostItem();//消耗的道具 boolean enoughCost = ItemUtil.itemCost(user, costItem, BIReason.ADJUTANT_LAYER_COST, 1); if (!enoughCost) { throw new ErrorCodeException(ErrorCode.ITEM_NOT_ENOUGH); } //增加商品 CommonProto.Drop.Builder drop = ItemUtil.drop(user, resultRandom, BIReason.ADJUTANT_LAYER_REWARD); Map resultRandomMap = ItemUtil.arrayToMap(resultRandom); int[] unlockItem = config.getUnlockitem(); if (resultRandomMap.get(unlockItem[0]) != null) { user.getActivityManager().setAdjutantLayer(user.getActivityManager().getAdjutantLayer() + 1); if (layer == 4) { user.getActivityManager().setAdjutantLayer(1); } } if (type == 0) { user.getActivityManager().setAdjutantLayerBuyNum(user.getActivityManager().getAdjutantLayerBuyNum() + 1); } AdjutantProto.AdjutantLayerActivityResponse.Builder response = AdjutantProto.AdjutantLayerActivityResponse.newBuilder(); response.setLayer(user.getActivityManager().getAdjutantLayer()); response.setBuyNum(user.getActivityManager().getAdjutantLayerBuyNum()); response.setDrop(drop); MessageUtil.sendMessage(iSession, 1, messageType.getNumber(), response.build(), true); } /** * 每次抽取 * * @param user * @param setId * @return * @throws Exception */ public static int randomOne(User user, int setId) throws Exception { SLotterySetting sLotterySetting = STableManager.getConfig(SLotterySetting.class).get(setId); if (sLotterySetting == null) { throw new ErrorCodeException(ErrorCode.PARAM_ERR); } int mergePool = sLotterySetting.getMergePool(); List specialConfigs = SLotterySpecialConfig.getLotterySpecialConfigListByType(mergePool); HeroManager heroManager = user.getHeroManager(); Set mustSet = new HashSet<>(); Map> randomPoolByType = heroManager.getRandomPoolByType(); //设置用户必出计数器 if (specialConfigs != null && !specialConfigs.isEmpty()) { if (!randomPoolByType.containsKey(mergePool)) { randomPoolByType.put(mergePool, new HashMap<>()); for (SLotterySpecialConfig config : specialConfigs) { randomPoolByType.get(mergePool).put(config.getDifferentType(), 0); } } //保底次数计算 for (Map.Entry countEntry : randomPoolByType.get(mergePool).entrySet()) { SLotterySpecialConfig config = null; // if(specialConfigs.isEmpty()){ // continue; // } for (SLotterySpecialConfig everyConfig : specialConfigs) { if (everyConfig.getDifferentType() != countEntry.getKey()) { continue; } config = everyConfig; } if (config == null) { throw new ErrorCodeException(ErrorCode.CFG_NULL); } //本次是否触发保底 if (countEntry.getValue() + 1 < config.getCount()) { continue; } //保底触发次数统计 Map mustRandomCount = heroManager.getMustRandomCount(); if (mustRandomCount.containsKey(countEntry.getKey())) { //是否已经到了保底触发上限 if (config.getMin_num() != 0 && mustRandomCount.get(countEntry.getKey()) >= config.getMin_num()) { continue; } else { mustRandomCount.put(countEntry.getKey(), mustRandomCount.get(countEntry.getKey()) + 1); } } else { mustRandomCount.put(countEntry.getKey(), 1); } heroManager.setMustRandomCount(mustRandomCount); mustSet.add(countEntry.getKey()); } } SLotteryRewardConfig sLotteryRewardConfig; //是否有必出 if (mustSet.isEmpty()) { sLotteryRewardConfig = randomHeroByPoolId(getPooId(sLotterySetting), 1, user.getPlayerInfoManager().getLevel()); int star = sLotteryRewardConfig.getStar(); if (randomPoolByType.get(mergePool) != null) { for (int key : randomPoolByType.get(mergePool).keySet()) { if (star == key) { randomPoolByType.get(mergePool).put(key, 0); } else { int curValue = randomPoolByType.get(mergePool).getOrDefault(key, 0); randomPoolByType.get(mergePool).put(key, curValue + 1); } } } } else { //有必出时比较各个优先级,取优先级高的 int maxId = 0; for (int mustId : mustSet) { maxId = mustId > maxId ? mustId : maxId; } System.out.println("触发必出" + maxId); SLotterySpecialConfig onConfig = null; for (SLotterySpecialConfig everyConfig : specialConfigs) { if (everyConfig.getDifferentType() != maxId) { continue; } onConfig = everyConfig; } if (onConfig == null) { throw new ErrorCodeException(ErrorCode.CFG_NULL); } sLotteryRewardConfig = randomHeroByPoolId(onConfig.getpool_id(), 1, user.getPlayerInfoManager().getLevel()); randomPoolByType.get(mergePool).put(maxId, 0); } heroManager.updateRandomPoolByType(mergePool, randomPoolByType.get(mergePool)); int result = sLotteryRewardConfig.getId(); return result; } private static int getPooId(SLotterySetting sLotterySetting) throws Exception { int[][] diamondBoxContain = sLotterySetting.getDiamondBoxContain(); int totalWeight = 0; for (int i = 0; i < diamondBoxContain.length; i++) { int[] poolWeightInfo = diamondBoxContain[i]; totalWeight += poolWeightInfo[1]; } int randWeight = MathUtils.randomInt(totalWeight) + 1; int weight = 0; for (int i = 0; i < diamondBoxContain.length; i++) { int[] poolWeightInfo = diamondBoxContain[i]; weight += poolWeightInfo[1]; if (randWeight <= weight) { return poolWeightInfo[0]; } } return 0; } public static SLotteryRewardConfig randomHeroByPoolId(int poolId, int randomCount, int userLevel){ return randomHeroByPoolId(poolId,randomCount,userLevel,null); } public static SLotteryRewardConfig randomHeroByPoolId(int poolId, int randomCount, int userLevel, List excludeList) { List sLotteryRewardConfigs = new ArrayList<>(); List sLotteryRewardConfigListByPoolId = SLotteryRewardConfig.getSLotteryRewardConfigListByPoolId(poolId); int totalCountByPoolId = 0; for (SLotteryRewardConfig sLotteryRewardConfig : sLotteryRewardConfigListByPoolId) { if(excludeList != null && excludeList.contains(sLotteryRewardConfig.getId())) continue; int[] openRules = sLotteryRewardConfig.getOpenRules(); boolean canAdd = true; if (openRules != null && openRules.length > 0) { int openType = openRules[0]; int openValue = openRules[1]; switch (openType) { case 1: canAdd = randomCount > openValue; break; case 2: canAdd = userLevel > openValue; break; } } if (canAdd) { sLotteryRewardConfigs.add(sLotteryRewardConfig); totalCountByPoolId += sLotteryRewardConfig.getWeight(); } } int randCount = MathUtils.randomInt(totalCountByPoolId) + 1; int weight = 0; for (SLotteryRewardConfig sLotteryRewardConfig : sLotteryRewardConfigs) { if(excludeList != null && excludeList.contains(sLotteryRewardConfig.getId())) continue; weight += sLotteryRewardConfig.getWeight(); if (weight >= randCount) { return sLotteryRewardConfig; } } return null; } /** * BOX扭蛋 抽取 */ public void boxPoolRandom(ISession session, int id) throws Exception { SBoxPoolConfig sBoxPoolConfig = STableManager.getConfig(SBoxPoolConfig.class).get(id); if(sBoxPoolConfig == null){ throw new ErrorCodeException(ErrorCode.CFG_NULL); } int activityId = sBoxPoolConfig.getActivityId(); int uid = session.getUid(); User user = UserManager.getUser(uid); ActivityMission activityMission = user.getActivityManager().getActivityMissionMap().get(activityId); if(activityMission == null && activityMission.getActivityState() != ActivityType.OPEN_STATE){ throw new ErrorCodeException(ErrorCode.ACTIVITY_NOT_OPEN); } BoxPoolInfo boxPoolInfo = user.getActivityManager().getBoxPoolInfo(sBoxPoolConfig.getId()); if(boxPoolInfo == null){ boxPoolInfo = new BoxPoolInfo(sBoxPoolConfig.getId(),sBoxPoolConfig.getFirstLotteryId()); user.getActivityManager().addBoxPoolInfo(boxPoolInfo); } int lotteryId = boxPoolInfo.getLotteryId(); SLotterySetting sLotterySetting = STableManager.getConfig(SLotterySetting.class).get(lotteryId); if(sLotterySetting == null){ throw new ErrorCodeException(ErrorCode.CFG_NULL); } if(boxPoolRandomFinish(boxPoolInfo,sLotterySetting)){ LOGGER.error("box pool random finish uid:{},id:{},lotteryId:{}",uid,id,lotteryId); throw new ErrorCodeException(ErrorCode.PARAM_ERR); } //消耗商品 int[][] costItem = sLotterySetting.getCostItem();//消耗的道具 Map costItemMap = null; if(costItem != null && costItem.length > 0){ costItemMap = new HashMap<>(); for(int[] array : costItem){ costItemMap.put(array[0],array[1] + costItemMap.getOrDefault(array[0],0)); } } boolean enoughCost = ItemUtil.checkCost(user,costItemMap); if (!enoughCost) { throw new ErrorCodeException(ErrorCode.ITEM_NOT_ENOUGH); } ItemUtil.itemCost(user,costItemMap,BIReason.BOX_POOL_RANDOM_COST,1); int poolId = sLotterySetting.getDiamondBoxContain()[0][0]; SLotteryRewardConfig rewardConfig = randomHeroByPoolId(poolId,1,user.getPlayerInfoManager().getLevel(),boxPoolInfo.getRandomRewardList()); int[][] itemArray = new int[1][]; itemArray[0] = rewardConfig.getReward(); CommonProto.Drop.Builder drop = ItemUtil.drop(user,itemArray,BIReason.BOX_POOL_RANDOM_REWARD); List randomRewardList = boxPoolInfo.getRandomRewardList(); randomRewardList.add(rewardConfig.getId()); boxPoolInfo.setRandomRewardList(randomRewardList); int[] autoResetParam = sBoxPoolConfig.getAutoReset(); if(autoResetParam[0] == 1 && autoResetParam[1] != 0 && (boxPoolInfo.getAutoResetCount() < autoResetParam[1] || autoResetParam[1] < 0)){ //奖励抽完自动重置 boolean isFinish = boxPoolRandomFinish(boxPoolInfo,sLotterySetting); if(isFinish){ resetBoxPoolInfo(uid,boxPoolInfo,true); } } ActivityProto.BoxPoolInfo info = ActivityProto.BoxPoolInfo.newBuilder().setId(boxPoolInfo.getId()) .setLotteryId(boxPoolInfo.getLotteryId()).setAutoResetCount(boxPoolInfo.getAutoResetCount()) .setManualResetCount(boxPoolInfo.getManualResetCount()).addAllRewardList(boxPoolInfo.getRandomRewardList()).build(); ActivityProto.BoxPoolOperateResponse response = ActivityProto.BoxPoolOperateResponse.newBuilder() .setInfo(info) .setDrop(drop).build(); MessageUtil.sendMessage(session, 1, MessageTypeProto.MessageType.BoxPoolOperateResponse.getNumber(), response, true); } /** * BOX扭蛋 手动重置 * @param session * @param id */ public void boxPoolManualReset(ISession session, int id) throws Exception { int uid = session.getUid(); User user = UserManager.getUser(uid); SBoxPoolConfig sBoxPoolConfig = STableManager.getConfig(SBoxPoolConfig.class).get(id); if(sBoxPoolConfig == null){ throw new ErrorCodeException(ErrorCode.CFG_NULL); } ActivityMission activityMission = user.getActivityManager().getActivityMissionMap().get(sBoxPoolConfig.getActivityId()); if(activityMission == null && activityMission.getActivityState() != ActivityType.OPEN_STATE){ throw new ErrorCodeException(ErrorCode.ACTIVITY_NOT_OPEN); } int[] manualResetParam = sBoxPoolConfig.getManualReset(); if(manualResetParam[0] == 1 && manualResetParam[1] == 0) { LOGGER.error("uid:{},can not manual reset.",uid); throw new ErrorCodeException(ErrorCode.PARAM_ERR); } int lotteryId = sBoxPoolConfig.getFirstLotteryId(); SLotterySetting sLotterySetting = STableManager.getConfig(SLotterySetting.class).get(lotteryId); if(sLotterySetting == null){ throw new ErrorCodeException(ErrorCode.CFG_NULL); } BoxPoolInfo boxPoolInfo = user.getActivityManager().getBoxPoolInfo(sBoxPoolConfig.getId()); if(boxPoolInfo == null){ boxPoolInfo = new BoxPoolInfo(sBoxPoolConfig.getId(),sBoxPoolConfig.getFirstLotteryId()); user.getActivityManager().addBoxPoolInfo(boxPoolInfo); } if(manualResetParam[1] >0 && boxPoolInfo.getManualResetCount() >= manualResetParam[1]){ LOGGER.error("reset count not enough,uid:{},manualResetCount:{},maxTimes:{}",uid,boxPoolInfo.getManualResetCount(),manualResetParam[1]); throw new ErrorCodeException(ErrorCode.COUNT_NOT_ENOUGH); } //消耗商品 int[][] costItem = sBoxPoolConfig.getManualResetCost();//消耗的道具 Map costItemMap = null; if(costItem != null && costItem.length > 0){ costItemMap = new HashMap<>(); for(int[] array : costItem){ costItemMap.put(array[0],array[1] + costItemMap.getOrDefault(array[0],0)); } } boolean enoughCost = ItemUtil.checkCost(user,costItemMap); if (!enoughCost) { throw new ErrorCodeException(ErrorCode.ITEM_NOT_ENOUGH); } ItemUtil.itemCost(user,costItemMap,BIReason.BOX_POOL_MANUAL_RESET,1); resetBoxPoolInfo(uid,boxPoolInfo,false);//手动重置 ActivityProto.BoxPoolInfo info = ActivityProto.BoxPoolInfo.newBuilder().setId(boxPoolInfo.getId()) .setLotteryId(boxPoolInfo.getLotteryId()).setAutoResetCount(boxPoolInfo.getAutoResetCount()) .setManualResetCount(boxPoolInfo.getManualResetCount()).addAllRewardList(boxPoolInfo.getRandomRewardList()).build(); ActivityProto.BoxPoolOperateResponse response = ActivityProto.BoxPoolOperateResponse.newBuilder() .setInfo(info).build(); MessageUtil.sendMessage(session, 1, MessageTypeProto.MessageType.BoxPoolOperateResponse.getNumber(), response, true); } private boolean boxPoolRandomFinish(BoxPoolInfo boxPoolInfo, SLotterySetting sLotterySetting) { int poolId = sLotterySetting.getDiamondBoxContain()[0][0]; List sLotteryRewardConfigList = SLotteryRewardConfig.getSLotteryRewardConfigListByPoolId(poolId); for(SLotteryRewardConfig sLotteryRewardConfig : sLotteryRewardConfigList){ if(!boxPoolInfo.getRandomRewardList().contains(sLotteryRewardConfig.getId())){ return false; } } return true; } private void resetBoxPoolInfo(int uid, BoxPoolInfo boxPoolInfo, boolean autoReset){ SBoxPoolConfig sBoxPoolConfig = STableManager.getConfig(SBoxPoolConfig.class).get(boxPoolInfo.getId()); int poolRandomType = sBoxPoolConfig.getPoolRandomType(); List lotteryIdArray = Arrays.stream(sBoxPoolConfig.getLotteryId()).boxed().collect(Collectors.toList()); int lotteryId = 0; if(poolRandomType == 1){//顺序模式 int index = lotteryIdArray.indexOf(lotteryId); if(index < 0){ lotteryId = lotteryIdArray.get(0); } else if(index >= (lotteryIdArray.size()-1)){ lotteryId = lotteryIdArray.get(lotteryIdArray.size() - 1); }else{ lotteryId = lotteryIdArray.get(index+1); } }else if(poolRandomType == 2){//随机模式 Collections.shuffle(lotteryIdArray); lotteryId = lotteryIdArray.get(0); }else{ LOGGER.error("poolRandomType not exits, uid:{},id:{},poolRandomType:{}",uid,boxPoolInfo.getId(),poolRandomType); return; } boxPoolInfo.setLotteryId(lotteryId); boxPoolInfo.setRandomRewardList(new ArrayList<>()); if(autoReset){ boxPoolInfo.setAutoResetCount(boxPoolInfo.getAutoResetCount() + 1); }else{ boxPoolInfo.setManualResetCount(boxPoolInfo.getManualResetCount() + 1); } } public void dailyRefreshBoxInfo(User user) { try{ Collection list = user.getActivityManager().getBoxPoolInfos(); for(BoxPoolInfo info : list){ SBoxPoolConfig sBoxPoolConfig = STableManager.getConfig(SBoxPoolConfig.class).get(info.getId()); if(sBoxPoolConfig != null){ int[] autoResetParam = sBoxPoolConfig.getAutoReset(); int[] manualResetParam = sBoxPoolConfig.getManualReset(); if(autoResetParam[0] == 2){ info.setLotteryId(0); info.setRandomRewardList(new ArrayList<>()); info.setAutoResetCount(0); } if(manualResetParam[0] == 2) { info.setManualResetCount(0); } } } }catch (Exception e){ LOGGER.error("error",e); } } public int[][] fillUpForeverMemberReward(User user, int goodsId, int reward[][]){ int [][] result = reward; try{ Integer activityId = SGlobalActivity.sRechargeId2ActivityId.get(goodsId); SGlobalActivity sGlobalActivity2 = SGlobalActivity.getsGlobalActivityMap().get(activityId); int activityType = sGlobalActivity2.getType(); List sGlobalActivityList = SGlobalActivity.getsGlobalActivityMapByType().get(activityType); //List sGlobalActivityList = SGlobalActivity.getsGlobalActivityMapByType().get(ActivityType.FOREVER_MEMBER); if(sGlobalActivityList == null || sGlobalActivityList.isEmpty()){ LOGGER.info("sGlobalActivityList is null, uid:{},goodsId:{}",user.getId(),goodsId); return result; } SGlobalActivity config = null; for(SGlobalActivity sGlobalActivity : sGlobalActivityList) { if(Arrays.stream(sGlobalActivity.getCanBuyRechargeId()).anyMatch(e-> e==goodsId)){ config = sGlobalActivity; break; } } int[][] _reward = {}; List sActivityRewardConfigList = SActivityRewardConfig.getsActivityRewardConfigByActivityId(config.getId()); if(sActivityRewardConfigList != null){ for(SActivityRewardConfig sActivityRewardConfig : sActivityRewardConfigList) { if(sActivityRewardConfig.getValues()[1][0] == 1){ _reward = sActivityRewardConfig.getReward(); break; } } } if(_reward.length > 0) { Map itemMap = new HashMap<>(); for(int[] items : reward){ itemMap.put(items[0],items[1]); } int num = TimeUtils.differentDays(user.getPlayerInfoManager().getCreateTime(),System.currentTimeMillis()); if(num > 0) { for(int[] items : _reward){ itemMap.put(items[0],items[1] * num); } } result = new int[itemMap.size()][]; int index = 0; for(Map.Entry entry : itemMap.entrySet()) { result[index++] = new int[]{entry.getKey(),entry.getValue()}; } } }catch (Exception e) { LOGGER.error("exception===> ",e); } return result; } public void activationForeverMember(User user, int goodsId,int activityType) { try{ //List sGlobalActivityList = SGlobalActivity.getsGlobalActivityMapByType().get(ActivityType.FOREVER_MEMBER); List sGlobalActivityList = SGlobalActivity.getsGlobalActivityMapByType().get(activityType); if(sGlobalActivityList == null || sGlobalActivityList.isEmpty()){ LOGGER.info("sGlobalActivityList is null, uid:{},goodsId:{}",user.getId(),goodsId); return; } SGlobalActivity config = null; for(SGlobalActivity sGlobalActivity : sGlobalActivityList) { if(Arrays.stream(sGlobalActivity.getCanBuyRechargeId()).anyMatch(e-> e==goodsId)){ config = sGlobalActivity; break; } } user.getActivityManager().setForeverMember(true); ActivityMission activityMission = user.getActivityManager().getActivityMissionMap().get(config.getId()); if(activityMission == null){//活动检查定时任务可能还没检查到,手动检查一下再取活动数据 ActivityLogic.getInstance().checkActivityOfUser(user,null); activityMission = user.getActivityManager().getActivityMissionMap().get(config.getId()); } activityMission.setV(1);//客户端通过这个值判断已激活 // updateActivityMissionProgress(user,ActivityType.FOREVER_MEMBER,0); updateActivityMissionProgress(user,activityType,0); }catch (Exception e){ LOGGER.error("activationForeverMember exception, uid:{},goodsId:{}",user.getId(),goodsId); LOGGER.error("activationForeverMember exception,",e); } } public void checkDailyForeverMemberReward(){ sendDailyForeverMemberReward(); } private void sendDailyForeverMemberReward() { try{ LOGGER.info("sendDailyForeverMemberReward begin..."); MongoTemplate mongoTemplate = MongoUtil.getLjsdMongoTemplate().getMongoTemplate(GameApplication.serverId); if(mongoTemplate == null){ LOGGER.error("sendDailyForeverMemberReward error, serverId:{}",GameApplication.serverId); return; } Query countQuery = new Query(); countQuery.addCriteria(Criteria.where("activityManager.foreverMember").is(true)); long count = mongoTemplate.count(countQuery,User.class); if(count <= 0) { LOGGER.info("sendDailyForeverMemberReward count is 0."); return; } int _limit = 500;//一次只返回这么多数据,分批次查询,分批次发 int page = (int)(count + _limit -1) / _limit; int _id = 0; for(int i = 0; i < page; i++){ Query query = new Query(); query.addCriteria(Criteria.where("activityManager.foreverMember").is(true)) .with(new Sort(Sort.Direction.ASC,"_id")) .addCriteria(Criteria.where("_id").gt(_id)).limit(_limit) .fields().include("activityManager.foreverMember"); List list = mongoTemplate.find(query,User.class); if(list != null && !list.isEmpty()){ _id = list.get(list.size()-1).getId(); for(User _user : list){ User user = UserManager.getUser(_user.getId()); AyyncWorker ayyncWorker = new AyyncWorker(user, false, new AyncWorkerRunnable() { @Override public void work(User user) throws Exception { resumeActivity(user,ActivityType.FOREVER_MEMBER); resumeActivity(user,ActivityType.FOREVER_MEMBER_PLUS); } }); ProtocolsManager.getInstance().updateAyncWorker(ayyncWorker); } } } LOGGER.info("sendDailyForeverMemberReward end..."); }catch (Exception e){ LOGGER.error("sendDailyForeverMemberReward error: ",e); } } //周末福利 隔天刷新 public void flushDay(ISession session) throws Exception{ //周末福利 活动结束会清空道具 List sGlobalActivities = SGlobalActivity.getsGlobalActivityMapByType().get(ActivityType.WEEK_END_REWARD); if(sGlobalActivities != null) { Iterator iterator1 = sGlobalActivities.iterator(); while (iterator1.hasNext()) { SGlobalActivity next1 = iterator1.next(); int activityId = next1.getId(); //活动id User user = UserManager.getUser(session.getUid()); ActivityManager activityManager = user.getActivityManager(); ActivityMission activityMission = activityManager.getActivityMissionMap().get(activityId); int dayOfWeek = TimeUtils.getDayOfWeek(); //获取周几, 周日 0; 其他正常 List sActivityRewardConfigs = SActivityRewardConfig.getsActivityRewardConfigByActivityId(activityId); Iterator iterator = sActivityRewardConfigs.iterator(); int missionId = 0; while (iterator.hasNext()) { SActivityRewardConfig next = iterator.next(); int[][] values = next.getValues(); if (values[0][0] == 0 && values[1][0] == dayOfWeek) { missionId = next.getId(); // ActivityProgressInfo activityProgressInfo = new ActivityProgressInfo(); // if(activityMission != null){ // activityProgressInfo = activityMission.getActivityMissionMap().get(missionId); // } if (activityMission == null) { continue; } ActivityProgressInfo activityProgressInfo = activityMission.getActivityMissionMap().get(missionId); if (activityProgressInfo == null) { continue; } //up miss activityProgressInfo.setProgrss(0); activityProgressInfo.setState(ActivityType.WILL_TAKE); if (activityMission != null) { sendActivityProgress(session, activityMission, Collections.singleton(missionId), activityId); } } } } } } public void sendActivityProgress(ISession session, ActivityMission activityMission, Set filterMissId,int activityId) { PlayerInfoProto.ActivityUpateProgressIndication.Builder builder = PlayerInfoProto.ActivityUpateProgressIndication.newBuilder(); builder.setActivityInfo(CommonProto.ActivityInfo.newBuilder().setValue(activityMission.getV()).addAllMission(getAllMissInfo(activityMission, filterMissId)).setActivityId(activityId)); if (session != null) { MessageUtil.sendIndicationMessage(session, 1, MessageTypeProto.MessageType.ACTIVITY_UPDATE_PROGRESS_INDICATION_VALUE, builder.build(), true); } } public List getAllMissInfo(ActivityMission activityMission, Set filter) { Map activityProgressInfoMap = activityMission.getActivityMissionMap(); List missionInfos = new ArrayList<>(activityProgressInfoMap.size()); for (Map.Entry missionProgress : activityProgressInfoMap.entrySet()) { if (filter != null && !filter.contains(missionProgress.getKey())) { continue; } Integer missionId = missionProgress.getKey(); ActivityProgressInfo activityProgressInfo = missionProgress.getValue(); missionInfos.add(CommonProto.ActivityInfo.MissionInfo.newBuilder().setMissionId(missionId).setProgress(activityProgressInfo.getProgrss()).setState(activityProgressInfo.getState()).build()); } return missionInfos; } public void flushWeek(ISession session) throws Exception { //周末福利 活动结束会清空道具 List sGlobalActivities = SGlobalActivity.getsGlobalActivityMapByType().get(ActivityType.WEEK_END_REWARD); Iterator iterator1 = sGlobalActivities.iterator(); while (iterator1.hasNext()) { SGlobalActivity next1 = iterator1.next(); int activityId = next1.getId(); //活动id User user = UserManager.getUser(session.getUid()); ActivityManager activityManager = user.getActivityManager(); ActivityMission activityMission = activityManager.getActivityMissionMap().get(activityId); int dayOfWeek = TimeUtils.getDayOfWeek(); //获取周几, 周日 0; 其他正常 List sActivityRewardConfigs = SActivityRewardConfig.getsActivityRewardConfigByActivityId(activityId); Iterator iterator = sActivityRewardConfigs.iterator(); Set missions = new HashSet<>(); while (iterator.hasNext()) { SActivityRewardConfig next = iterator.next(); // int[][] values = next.getValues(); // if (values[0][0] == 0 && values[1][0] != dayOfWeek) { int missionId = next.getId(); missions.add(missionId); if(activityMission == null){ continue; } ActivityProgressInfo activityProgressInfo = activityMission.getActivityMissionMap().get(missionId); if(activityProgressInfo == null){ continue; } //up miss activityProgressInfo.setProgrss(0); activityProgressInfo.setState(ActivityType.WILL_TAKE); // } } if(activityMission != null) { sendActivityProgress(session, activityMission, missions, activityId); } } } }