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

Poc von einem Kampfsystem mit items #479

Open
wants to merge 29 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
5315a09
poc for fighting
Feluin Oct 19, 2024
f92dfaa
poc for fighting
Feluin Oct 19, 2024
7351905
Merge remote-tracking branch 'origin/fightsystem' into fightsystem
Feluin Oct 19, 2024
e5d5095
added rudamentary visualisation
Feluin Oct 19, 2024
9781695
added rudamentary visualisation
Feluin Oct 19, 2024
cc81c09
added rudamentary visualisation
Feluin Oct 19, 2024
134e4a0
added rudamentary visualisation
Feluin Oct 19, 2024
c1433ff
added some item
Feluin Oct 22, 2024
7f011fa
add command ausrüsten
Feluin Oct 23, 2024
7b197ed
add command ausrüsten
Feluin Nov 28, 2024
3d24dd0
added kampfinventar
Feluin Dec 13, 2024
ff39e52
added fight with current inventory
Feluin Dec 15, 2024
7423034
added fight with current inventory
Feluin Dec 15, 2024
e62142d
fixed multiselection
Feluin Dec 23, 2024
18e55c0
fixed multiselection
Feluin Dec 23, 2024
0bf4354
added history and stuff
Feluin Jan 2, 2025
dbab44a
added history and stuff
Feluin Jan 2, 2025
679b41b
fixed lint and reverted multiple drops
Feluin Jan 3, 2025
3e8a0d0
fixed copy paste error
Feluin Jan 3, 2025
78e6277
Merge branch 'master' into fightsystem
holzmaster Jan 23, 2025
8eafebe
Fix casing of fightHistory + fightInventory
holzmaster Jan 23, 2025
a89dbc3
Move to service
holzmaster Jan 23, 2025
6882cd7
Make random API more clear
holzmaster Jan 23, 2025
4fcc8ef
Merge branch 'master' into fightsystem
holzmaster Jan 23, 2025
853ce6a
Fix var casing
holzmaster Jan 23, 2025
d076d2a
Copy function
holzmaster Jan 23, 2025
404c2bd
Merge branch 'master' into fightsystem
holzmaster Jan 23, 2025
7178c35
Fix var casing
holzmaster Jan 23, 2025
b9cc22d
British english -> american english
holzmaster Jan 23, 2025
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
228 changes: 228 additions & 0 deletions src/commands/fight.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
import type { ApplicationCommand } from "@/commands/command.js";
import {
type APIEmbed,
APIEmbedField,
type BooleanCache,
type CacheType,
type CommandInteraction,
type InteractionResponse,
SlashCommandBuilder,
type User,
} from "discord.js";
import type { BotContext } from "@/context.js";
import type { JSONEncodable } from "@discordjs/util";
import {
type BaseEntity,
baseStats,
bossMap,
Entity,
type EquipableArmor,
type EquipableItem,
type EquipableWeapon,
type FightScene,
} from "@/service/fightData.js";
import { setTimeout } from "node:timers/promises";
import { getFightInventoryEnriched, removeItemsAfterFight } from "@/storage/fightInventory.js";
import { getLastFight, insertResult } from "@/storage/fightHistory.js";

async function getFighter(user: User): Promise<BaseEntity> {
const userInventory = await getFightInventoryEnriched(user.id);

return {
...baseStats,
name: user.displayName,
weapon: {
name: userInventory.weapon?.itemInfo?.displayName ?? "Nichts",
...(userInventory.weapon?.gameTemplate as EquipableWeapon),
},
armor: {
name: userInventory.armor?.itemInfo?.displayName ?? "Nichts",
...(userInventory.armor?.gameTemplate as EquipableArmor),
},
items: userInventory.items.map(value => {
return {
name: value.itemInfo?.displayName ?? "Error",
...(value.gameTemplate as EquipableItem),
};
}),
};
}

export default class FightCommand implements ApplicationCommand {
readonly description = "TBD";
readonly name = "fight";
readonly applicationCommand = new SlashCommandBuilder()
.setName(this.name)
.setDescription(this.description)
.addStringOption(builder =>
builder
.setRequired(true)
.setName("boss")
.setDescription("Boss")
//switch to autocomplete when we reach 25
.addChoices(
Object.entries(bossMap)
.filter(boss => boss[1].enabled)
.map(boss => {
return {
name: boss[1].name,
value: boss[0],
};
}),
),
);

async handleInteraction(command: CommandInteraction, context: BotContext) {
const boss = command.options.get("boss", true).value as string;

const lastFight = await getLastFight(command.user.id);

// if (lastFight !== undefined && (new Date(lastFight?.createdAt).getTime() > new Date().getTime() - 1000 * 60 * 60 * 24 * 5)) {
// await command.reply({
// embeds:
// [{
// title: "Du bist noch nicht bereit",
// color: 0xe74c3c,
// description: `Dein Letzter Kampf gegen ${bossMap[lastFight.bossName]?.name} ist noch keine 5 Tage her. Gegen ${bossMap[boss].name} hast du sowieso Chance, aber noch weniger, wenn nicht die vorgeschriebenen Pausenzeiten einhältst `
// }
// ]
// ,
// ephemeral: true
// }
// );

// return;
// }

const interactionResponse = await command.deferReply();

const playerstats = await getFighter(command.user);

await fight(command.user, playerstats, boss, { ...bossMap[boss] }, interactionResponse);
}
}

type result = "PLAYER" | "ENEMY" | undefined;

function checkWin(fightscene: FightScene): result {
if (fightscene.player.stats.health < 0) {
return "ENEMY";
}
if (fightscene.enemy.stats.health < 0) {
return "PLAYER";
}
}

function renderEndScreen(fightscene: FightScene): APIEmbed | JSONEncodable<APIEmbed> {
const result = checkWin(fightscene);
const fields = [
renderStats(fightscene.player),
renderStats(fightscene.enemy),
{
name: "Verlauf",
value: " ",
},
{
name: " Die Items sind dir leider beim Kampf kaputt gegangen: ",
value: fightscene.player.stats.items.map(value => value.name).join(" \n"),
},
];
if (result === "PLAYER") {
return {
title: `Mit viel Glück konnte ${fightscene.player.stats.name} ${fightscene.enemy.stats.name} besiegen `,
color: 0x57f287,
description: fightscene.enemy.stats.description,
fields: fields,
};
}
if (result === "ENEMY") {
return {
title: `${fightscene.enemy.stats.name} hat ${fightscene.player.stats.name} gnadenlos vernichtet`,
color: 0xed4245,
description: fightscene.enemy.stats.description,
fields: fields,
};
}
return {
title: `Kampf zwischen ${fightscene.player.stats.name} und ${fightscene.enemy.stats.name}`,
description: fightscene.enemy.stats.description,
fields: fields,
};
}

export async function fight(
user: User,
playerstats: BaseEntity,
boss: string,
enemystats: BaseEntity,
interactionResponse: InteractionResponse<BooleanCache<CacheType>>,
) {
const enemy = new Entity(enemystats);
const player = new Entity(playerstats);

const scene: FightScene = {
player: player,
enemy: enemy,
};
while (checkWin(scene) === undefined) {
player.itemText = [];
enemy.itemText = [];
//playerhit first
player.attack(enemy);
// then enemny hit
enemy.attack(player);
//special effects from items
for (const value of player.stats.items) {
if (!value.afterFight) {
continue;
}
value.afterFight(scene);
}
for (const value of enemy.stats.items) {
if (!value.afterFight) {
continue;
}
value.afterFight({ player: enemy, enemy: player });
}
await interactionResponse.edit({ embeds: [renderFightEmbedded(scene)] });
await setTimeout(200);
}

await interactionResponse.edit({ embeds: [renderEndScreen(scene)] });
//delete items
await removeItemsAfterFight(user.id);
//
await insertResult(user.id, boss, checkWin(scene) === "PLAYER");
}

function renderStats(player: Entity) {
while (player.itemText.length < 5) {
player.itemText.push("-");
}
return {
name: player.stats.name,
value: `❤️ HP${player.stats.health}/${player.maxHealth}
❤️ ${"=".repeat(Math.max(0, (player.stats.health / player.maxHealth) * 10))}
⚔️ Waffe: ${player.stats.weapon?.name ?? "Schwengel"} ${player.lastAttack}
🛡️ Rüstung: ${player.stats.armor?.name ?? "Nackt"} ${player.lastDefense}
📚 Items:
${player.itemText.join("\n")}
`,
inline: true,
};
}

function renderFightEmbedded(fightscene: FightScene): JSONEncodable<APIEmbed> | APIEmbed {
return {
title: `Kampf zwischen ${fightscene.player.stats.name} und ${fightscene.enemy.stats.name}`,
description: fightscene.enemy.stats.description,
fields: [
renderStats(fightscene.player),
renderStats(fightscene.enemy),
{
name: "Verlauf",
value: " ",
},
],
};
}
58 changes: 57 additions & 1 deletion src/commands/gegenstand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import * as lootDataService from "@/service/lootData.js";
import { LootAttributeClassId, LootAttributeKindId, LootKindId } from "@/service/lootData.js";

import log from "@log";
import { equipItembyLoot, getFightInventoryUnsorted } from "@/storage/fightInventory.js";

export default class GegenstandCommand implements ApplicationCommand {
name = "gegenstand";
Expand Down Expand Up @@ -60,6 +61,18 @@ export default class GegenstandCommand implements ApplicationCommand {
.setDescription("Die Sau, die du benutzen möchtest")
.setAutocomplete(true),
),
)
.addSubcommand(
new SlashCommandSubcommandBuilder()
.setName("ausrüsten")
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Vielleicht passt hier "anlegen" oder "tragen" besser. Zumindest glaube ich, dass sich /gegenstand anlegen oder so verständlicher ist als /gegenstand ausrüsten

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oder kollidiert das mit "benutzen"?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

anlegen finde ich tatsächlich passender.

Meinst du das benutzen und anlegen eigenlich das selbe tut? noch könnte man beides in ein command machen, aber potentiell gibt es items die man im chat und im kampf nutzen kann, daher würd ich das getrennt lassen

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Benutzen ist etwas, was in dem moment eine Aktion ausführt. Also z.b. ein Geschenk in den Chat droppt

.setDescription("Rüste einen gegenstand aus")
.addStringOption(
new SlashCommandStringOption()
.setRequired(true)
.setName("item")
.setDescription("Rüste dich für deinen nächsten Kampf")
.setAutocomplete(true),
),
);

async handleInteraction(interaction: CommandInteraction, context: BotContext) {
Expand All @@ -75,6 +88,9 @@ export default class GegenstandCommand implements ApplicationCommand {
case "benutzen":
await this.#useItem(interaction, context);
break;
case "ausrüsten":
await this.#equipItem(interaction, context);
break;
default:
throw new Error(`Unknown subcommand: "${subCommand}"`);
}
Expand Down Expand Up @@ -309,7 +325,7 @@ export default class GegenstandCommand implements ApplicationCommand {

async autocomplete(interaction: AutocompleteInteraction) {
const subCommand = interaction.options.getSubcommand(true);
if (subCommand !== "info" && subCommand !== "benutzen") {
if (subCommand !== "info" && subCommand !== "benutzen" && subCommand !== "ausrüsten") {
return;
}

Expand Down Expand Up @@ -337,6 +353,9 @@ export default class GegenstandCommand implements ApplicationCommand {
if (subCommand === "benutzen" && template.onUse === undefined) {
continue;
}
if (subCommand === "ausrüsten" && template.gameEquip === undefined) {
continue;
}

const emote = lootDataService.getEmote(interaction.guild, item);
completions.push({
Expand All @@ -351,4 +370,41 @@ export default class GegenstandCommand implements ApplicationCommand {

await interaction.respond(completions);
}

async #equipItem(interaction: CommandInteraction, context: BotContext) {
if (!interaction.isChatInputCommand()) {
throw new Error("Interaction is not a chat input command");
}
if (!interaction.guild || !interaction.channel) {
return;
}

const info = await this.#fetchItem(interaction);
if (!info) {
return;
}
const { item, template } = info;
log.info(item);
if (template.gameEquip === undefined) {
await interaction.reply({
content: ` ${item.displayName} kann nicht ausgerüstet werden.`,
ephemeral: true,
});
return;
}
const items = await getFightInventoryUnsorted(interaction.user.id);
if (items.filter(i => i.id === item.id).length !== 0) {
await interaction.reply({
content: `Du hast ${item.displayName} schon ausgerüstet`,
ephemeral: true,
});
return;
}
const result = await equipItembyLoot(interaction.user.id, item, template.gameEquip.type);
const message =
result.unequipped.length === 0
? `Du hast ${result.equipped?.displayName} ausgerüstet`
: `Du hast ${result.unequipped.join(", ")} abgelegt und dafür ${result.equipped?.displayName} ausgerüstet`;
await interaction.reply(message);
}
}
Loading
Loading