chore(release): 0.2.5
[risinglegends.git] / src / events / items / server.ts
1 import { getItemFromPlayer, getPlayersItems, updateItemCount } from "../../server/items";
2 import {API, SocketEvent} from "../../server/socket-event.server";
3 import { maxHp } from "../../shared/player";
4 import { updatePlayer } from "../../server/player";
5 import { HealthPotionSmall } from "../../shared/items/health_potion";
6 import { getInventory } from "../../server/inventory";
7
8 export const smallHeal: SocketEvent = {
9   eventName: 'item:use:heal_small',
10   handler: async (api: API, data: {args: string}): Promise<any> => {
11     const itemId = parseInt(data.args);
12     const item = await getItemFromPlayer(api.player.id, itemId);
13
14     if(!item) {
15       console.log(`Can't find item [${data.args}]`);
16       return;
17     }
18
19     if(item.amount < 1) {
20       api.socket.emit('alert', {
21         type: 'error',
22         text: `You don't have enough ${item.name}`
23       });
24       return;
25     }
26
27     item.amount -= 1;
28
29     const hpGain = HealthPotionSmall.effect(api.player);
30
31     api.player.hp += hpGain;
32
33     if(api.player.hp > maxHp(api.player.constitution, api.player.level)) {
34       api.player.hp = maxHp(api.player.constitution, api.player.level);
35     }
36
37     await updateItemCount(api.player.id, item.item_id, -1);
38     await updatePlayer(api.player);
39     const inventory = await getInventory(api.player.id);
40     const items = await getPlayersItems(api.player.id);
41
42     api.socket.emit('updatePlayer', api.player);
43     api.socket.emit('inventory', {
44       inventory,
45       items
46     });
47     api.socket.emit('alert', {
48       type: 'success',
49       text: `You used the Small Health Potion`
50     });
51
52     return;
53   }
54 }