Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Lottery SE #2514

Merged
merged 6 commits into from
Jun 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions Core/resources/smallEvents/lottery.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,22 @@
{
"properties": {
"rewardType": [
"xp",
"money",
"guildXp",
"points"
],
"successRate": {
"easy": 0.8,
"medium": 0.5,
"hard": 0.2
},
"coefficients": {
"easy": 1,
"medium": 3,
"hard": 10
},
"lostTime": 10
},
"rarity": 3
}
10 changes: 10 additions & 0 deletions Core/src/core/database/game/models/Guild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,16 @@ export class Guilds {
offset: minRank - 1
});
}

static async ofPlayer(player: Player): Promise<Guild> {
try {
return await Guilds.getById(player.guildId);
}
catch {
return null;
}
}

}

export function initModel(sequelize: Sequelize): void {
Expand Down
193 changes: 193 additions & 0 deletions Core/src/core/smallEvents/lottery.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
import {SmallEventDataController, SmallEventFuncs} from "../../data/SmallEvent";
import Player from "../database/game/models/Player";
import {Maps} from "../maps/Maps";
import {EndCallback, ReactionCollectorInstance} from "../utils/ReactionsCollector";
import {BlockingUtils} from "../utils/BlockingUtils";
import {BlockingConstants} from "../../../../Lib/src/constants/BlockingConstants";
import {
ReactionCollectorLottery,
ReactionCollectorLotteryHardReaction,
ReactionCollectorLotteryMediumReaction
} from "../../../../Lib/src/packets/interaction/ReactionCollectorLottery";
import {DraftBotPacket, makePacket} from "../../../../Lib/src/packets/DraftBotPacket";
import {
SmallEventLotteryLosePacket,
SmallEventLotteryNoAnswerPacket,
SmallEventLotteryPoorPacket,
SmallEventLotteryWinPacket
} from "../../../../Lib/src/packets/smallEvents/SmallEventLotteryPacket";
import {SmallEventConstants} from "../../../../Lib/src/constants/SmallEventConstants";
import {Guild, Guilds} from "../database/game/models/Guild";
import {TravelTime} from "../maps/TravelTime";
import {Effect} from "../../../../Lib/src/enums/Effect";
import {NumberChangeReason} from "../../../../Lib/src/constants/LogsConstants";
import {RandomUtils} from "../utils/RandomUtils";

type LotteryProperties = {
successRate: {
[lotteryLevel in LotteryLevelKey]: number
},
coefficients: {
[lotteryLevel in LotteryLevelKey]: number
},
lostTime: number,
}

type LotteryLevelKey = "hard" | "medium" | "easy";

async function effectIfGoodRisk(levelKey: LotteryLevelKey, player: Player, dataLottery: LotteryProperties): Promise<number> {
if (levelKey !== "easy") {
await TravelTime.applyEffect(
player,
Effect.OCCUPIED,
dataLottery.lostTime,
new Date(),
NumberChangeReason.SMALL_EVENT
);

return dataLottery.lostTime;
}

return 0;
}

// eslint-disable-next-line max-params
async function giveRewardToPlayer(
rewardType: string,
player: Player,
coefficient: number,
response: DraftBotPacket[],
lostTime: number,
levelKey: LotteryLevelKey,
guild: Guild
): Promise<void> {
switch (rewardType) {
case SmallEventConstants.LOTTERY.REWARD_TYPES.XP:
await player.addExperience({
amount: SmallEventConstants.LOTTERY.REWARDS.EXPERIENCE * coefficient,
response,
reason: NumberChangeReason.SMALL_EVENT
});
response.push(makePacket(SmallEventLotteryWinPacket, {
xp: SmallEventConstants.LOTTERY.REWARDS.EXPERIENCE * coefficient,
lostTime,
level: levelKey
}));
break;
case SmallEventConstants.LOTTERY.REWARD_TYPES.MONEY:
await player.addMoney({
amount: SmallEventConstants.LOTTERY.REWARDS.MONEY * coefficient,
response,
reason: NumberChangeReason.SMALL_EVENT
});
response.push(makePacket(SmallEventLotteryWinPacket, {
money: SmallEventConstants.LOTTERY.REWARDS.MONEY * coefficient,
lostTime,
level: levelKey
}));
break;
case SmallEventConstants.LOTTERY.REWARD_TYPES.GUILD_XP:
await guild.addExperience(SmallEventConstants.LOTTERY.REWARDS.GUILD_EXPERIENCE * coefficient, response, NumberChangeReason.SMALL_EVENT);
await guild.save();
response.push(makePacket(SmallEventLotteryWinPacket, {
guildXp: SmallEventConstants.LOTTERY.REWARDS.GUILD_EXPERIENCE * coefficient,
lostTime,
level: levelKey
}));
break;
case SmallEventConstants.LOTTERY.REWARD_TYPES.POINTS:
await player.addScore({
amount: SmallEventConstants.LOTTERY.REWARDS.POINTS * coefficient,
response,
reason: NumberChangeReason.SMALL_EVENT
});
response.push(makePacket(SmallEventLotteryWinPacket, {
points: SmallEventConstants.LOTTERY.REWARDS.POINTS * coefficient,
lostTime,
level: levelKey
}));
break;
default:
throw new Error("lottery reward type not found");
}
}

export const smallEventFuncs: SmallEventFuncs = {
canBeExecuted: Maps.isOnContinent,

executeSmallEvent(context, response, player): void {
const dataLottery = SmallEventDataController.instance.getById("lottery").getProperties<LotteryProperties>();

const collector = new ReactionCollectorLottery();

const endCallback: EndCallback = async (collector, response) => {
BlockingUtils.unblockPlayer(player.id, BlockingConstants.REASONS.LOTTERY);

const reaction = collector.getFirstReaction();

if (reaction === null) {
response.push(makePacket(SmallEventLotteryNoAnswerPacket, {}));
}
else {
let levelKey: LotteryLevelKey;

if (reaction.reaction.type === ReactionCollectorLotteryHardReaction.name) {
levelKey = "hard";
}
else if (reaction.reaction.type === ReactionCollectorLotteryMediumReaction.name) {
levelKey = "medium";
}
else {
levelKey = "easy";
}

if (player.money < SmallEventConstants.LOTTERY.MONEY_MALUS && levelKey === "hard") {
response.push(makePacket(SmallEventLotteryPoorPacket, {}));
return;
}

let rewardTypes = Object.values(SmallEventConstants.LOTTERY.REWARD_TYPES);
const guild = await Guilds.ofPlayer(player);
if (guild === null || guild.isAtMaxLevel()) {
rewardTypes = rewardTypes.filter(r => r !== SmallEventConstants.LOTTERY.REWARD_TYPES.GUILD_XP);
}

const lostTime = await effectIfGoodRisk(levelKey, player, dataLottery);

const rewardType = RandomUtils.draftbotRandom.pick(rewardTypes);

if (RandomUtils.draftbotRandom.bool(dataLottery.successRate[levelKey]) && (guild || rewardType !== SmallEventConstants.LOTTERY.REWARD_TYPES.GUILD_XP)) {
const coefficient = dataLottery.coefficients[levelKey];
Feiryn marked this conversation as resolved.
Show resolved Hide resolved
await giveRewardToPlayer(rewardType, player, coefficient, response, lostTime, levelKey, guild);

await player.save();
}
else if (levelKey === "hard" && RandomUtils.draftbotRandom.bool(dataLottery.successRate[levelKey])) {
await player.addMoney({
amount: -SmallEventConstants.LOTTERY.MONEY_MALUS,
response,
reason: NumberChangeReason.SMALL_EVENT
});
await player.save();
response.push(makePacket(SmallEventLotteryLosePacket, { moneyLost: Math.abs(SmallEventConstants.LOTTERY.MONEY_MALUS), lostTime, level: levelKey }));
}
else {
response.push(makePacket(SmallEventLotteryLosePacket, { moneyLost: 0, lostTime, level: levelKey }));
}
}
};

const packet = new ReactionCollectorInstance(
collector,
context,
{
allowedPlayerKeycloakIds: [player.keycloakId]
},
endCallback
)
.block(player.id, BlockingConstants.REASONS.LOTTERY)
.build();

response.push(packet);
}
};
1 change: 0 additions & 1 deletion Core/src/data/SmallEvent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import {DataControllerString} from "./DataController";
import {Data} from "./Data";
import {readdirSync} from "fs";
import Player from "../core/database/game/models/Player";
import {WebsocketClient} from "../../../Lib/src/instances/WebsocketClient";
import {DraftBotPacket, PacketContext} from "../../../Lib/src/packets/DraftBotPacket";

export class SmallEvent extends Data<string> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import {chooseDestinationCollector, createBigEventCollector} from "../../command
import {ReactionCollectorChooseDestinationData} from "../../../../Lib/src/packets/interaction/ReactionCollectorChooseDestination";
import {ReactionCollectorGoToPVEIslandData} from "../../../../Lib/src/packets/interaction/ReactionCollectorGoToPVEIsland";
import {goToPVEIslandCollector} from "../../smallEvents/goToPVEIsland";
import {ReactionCollectorLotteryData} from "../../../../Lib/src/packets/interaction/ReactionCollectorLottery";
import {lotteryCollector} from "../../smallEvents/lottery";

export default class ReactionCollectorHandler {
@packetHandler(ReactionCollectorCreationPacket)
Expand All @@ -21,6 +23,9 @@ export default class ReactionCollectorHandler {
case ReactionCollectorGoToPVEIslandData.name:
await goToPVEIslandCollector(packet, context);
break;
case ReactionCollectorLotteryData.name:
await lotteryCollector(packet, context);
break;
default:
throw `Unknown collector with data: ${packet.data.type}`; // Todo error embed
}
Expand Down
77 changes: 77 additions & 0 deletions Discord/src/packetHandlers/handlers/SmallEventsHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ import {
} from "../../../../Lib/src/packets/smallEvents/SmallEventGoToPVEIslandPacket";
import {KeycloakUtils} from "../../../../Lib/src/keycloak/KeycloakUtils";
import {keycloakConfig} from "../../bot/DraftBotShard";
import {
SmallEventLotteryLosePacket,
SmallEventLotteryNoAnswerPacket,
SmallEventLotteryPoorPacket, SmallEventLotteryWinPacket
} from "../../../../Lib/src/packets/smallEvents/SmallEventLotteryPacket";

export function getRandomSmallEventIntro(language: Language): string {
return StringUtils.getRandomTranslation("smallEvents:intro", language);
Expand Down Expand Up @@ -119,4 +124,76 @@ export default class SmallEventsHandler {
)]});
}
}

@packetHandler(SmallEventLotteryNoAnswerPacket)
async smallEventLotteryNoAnswer(socket: WebSocket, packet: SmallEventLotteryNoAnswerPacket, context: PacketContext): Promise<void> {
const interaction = DiscordCache.getInteraction(context.discord!.interaction);
if (interaction) {
await interaction.editReply({
embeds: [
new DraftbotSmallEventEmbed("lottery", i18n.t("smallEvents:lottery.end", { lng: interaction.userLanguage }), interaction.user, interaction.userLanguage)
]
});
}
}

@packetHandler(SmallEventLotteryPoorPacket)
async smallEventLotteryPoor(socket: WebSocket, packet: SmallEventLotteryPoorPacket, context: PacketContext): Promise<void> {
const user = (await KeycloakUtils.getUserByKeycloakId(keycloakConfig, context.keycloakId!))!;
const interaction = DiscordCache.getButtonInteraction(context.discord!.buttonInteraction!);
if (interaction) {
await interaction.editReply({ embeds: [
new DraftbotSmallEventEmbed(
"lottery",
i18n.t("smallEvents:lottery.poor", { lng: user.attributes.language[0] }),
interaction.user,
user.attributes.language[0]
)]});
}
}

@packetHandler(SmallEventLotteryLosePacket)
async smallEventLotteryLose(socket: WebSocket, packet: SmallEventLotteryLosePacket, context: PacketContext): Promise<void> {
const user = (await KeycloakUtils.getUserByKeycloakId(keycloakConfig, context.keycloakId!))!;
const interaction = DiscordCache.getButtonInteraction(context.discord!.buttonInteraction!);
if (interaction) {
const failKey = packet.moneyLost && packet.moneyLost > 0 ? "failWithMalus" : "fail";
await interaction.editReply({ embeds: [
new DraftbotSmallEventEmbed(
"lottery",
i18n.t(`smallEvents:lottery.${packet.level}.${failKey}`, { lng: user.attributes.language[0], lostTime: packet.lostTime, money: packet.moneyLost }),
interaction.user,
user.attributes.language[0]
)]});
}
}

@packetHandler(SmallEventLotteryWinPacket)
romain22222 marked this conversation as resolved.
Show resolved Hide resolved
async smallEventLotteryWin(socket: WebSocket, packet: SmallEventLotteryWinPacket, context: PacketContext): Promise<void> {
const user = (await KeycloakUtils.getUserByKeycloakId(keycloakConfig, context.keycloakId!))!;
const interaction = DiscordCache.getButtonInteraction(context.discord!.buttonInteraction!);
if (interaction) {
let rewardDesc: string;
if (packet.xp) {
rewardDesc = i18n.t("smallEvents:lottery.rewardTypeText.xp", { lng: user.attributes.language[0], xpWon: packet.xp });
}
else if (packet.money) {
rewardDesc = i18n.t("smallEvents:lottery.rewardTypeText.money", { lng: user.attributes.language[0], moneyWon: packet.money });
}
else if (packet.guildXp) {
rewardDesc = i18n.t("smallEvents:lottery.rewardTypeText.guildXp", { lng: user.attributes.language[0], guildXpWon: packet.guildXp });
}
else {
rewardDesc = i18n.t("smallEvents:lottery.rewardTypeText.points", { lng: user.attributes.language[0], pointsWon: packet.points });
}

await interaction.editReply({ embeds: [
new DraftbotSmallEventEmbed(
"lottery",
i18n.t(`smallEvents:lottery.${packet.level}.success`, { lng: user.attributes.language[0], lostTime: packet.lostTime }) + rewardDesc,
interaction.user,
user.attributes.language[0]
)]});
}
}
}
Loading
Loading