1 import * as otel from './tracing';
2 import { version } from "../../package.json";
3 import { config as dotenv } from 'dotenv';
4 import { join } from 'path';
5 import express, {Request, Response} from 'express';
6 import bodyParser from 'body-parser';
8 import http from 'http';
9 import { Server, Socket } from 'socket.io';
10 import { logger } from './lib/logger';
11 import { loadPlayer, createPlayer, updatePlayer, movePlayer } from './player';
12 import { random, sample } from 'lodash';
13 import {broadcastMessage, Message} from '../shared/message';
14 import {expToLevel, maxHp, Player} from '../shared/player';
15 import {clearFight, createFight, getMonsterList, getRandomMonster, loadMonster, loadMonsterFromFight, loadMonsterWithFaction, saveFightState} from './monster';
16 import {FightRound} from '../shared/fight';
17 import {addInventoryItem, deleteInventoryItem, getEquippedItems, getInventory, getInventoryItem, updateAp} from './inventory';
18 import { getItemFromPlayer, getItemFromShop, getPlayersItems, getShopItems, givePlayerItem, updateItemCount } from './items';
19 import {FightTrigger, Monster, MonsterForFight, MonsterWithFaction} from '../shared/monsters';
20 import {getShopEquipment, listShopItems } from './shopEquipment';
21 import {EquippedItemDetails} from '../shared/equipped';
22 import {ArmourEquipmentSlot, EquipmentSlot} from '../shared/inventory';
23 import { clearTravelPlan, completeTravel, getAllPaths, getAllServices, getCityDetails, getService, getTravelPlan, stepForward, travel } from './map';
24 import { signup, login, authEndpoint, AuthRequest } from './auth';
25 import {db} from './lib/db';
26 import { getPlayerSkills, getPlayerSkillsAsObject, updatePlayerSkills } from './skills';
27 import {SkillID, Skills} from '../shared/skills';
29 import { router as healerRouter } from './locations/healer';
31 import * as Alert from './views/alert';
32 import { renderPlayerBar } from './views/player-bar'
33 import { renderEquipmentDetails, renderStore } from './views/stores';
34 import { renderMap } from './views/map';
35 import { renderProfilePage } from './views/profile';
36 import { renderSkills } from './views/skills';
37 import { renderInventoryPage } from './views/inventory';
38 import { renderMonsterSelector } from './views/monster-selector';
39 import { renderFight, renderRoundDetails } from './views/fight';
40 import { renderTravel, travelButton } from './views/travel';
41 import { renderChatMessage } from './views/chat';
44 import { createMonsters } from '../../seeds/monsters';
45 import { createAllCitiesAndLocations } from '../../seeds/cities';
46 import { createShopItems, createShopEquipment } from '../../seeds/shop_items';
47 import { Item, PlayerItem, ShopItem } from 'shared/items';
48 import { equip, unequip } from './equipment';
49 import { HealthPotionSmall } from '../shared/items/health_potion';
55 const app = express();
56 const server = http.createServer(app);
58 app.use(express.static(join(__dirname, '..', '..', 'public')));
59 app.use(bodyParser.urlencoded({ extended: true }));
60 app.use(express.json());
62 const io = new Server(server);
64 const cache = new Map<string, any>();
65 const chatHistory: Message[] = [];
67 app.use((req, res, next) => {
68 console.log(req.method, req.url);
72 async function bootstrapSocket(socket: Socket, player: Player) {
73 // ref to get the socket id for a particular player
74 cache.set(`socket:${player.id}`, socket.id);
75 // ref to get the player object
76 cache.set(`token:${player.id}`, player);
78 socket.emit('authToken', player.id);
80 socket.emit('chat', renderChatMessage(broadcastMessage('server', `${player.username} just logged in`)));
83 io.on('connection', async socket => {
84 logger.log(`socket ${socket.id} connected, authToken: ${socket.handshake.headers['x-authtoken']}`);
86 let authToken = socket.handshake.headers['x-authtoken'].toString() === 'null' ? null : socket.handshake.headers['x-authtoken'].toString();
90 logger.log(`Attempting to load player with id ${authToken}`);
91 player = await loadPlayer(authToken);
94 logger.log(`Creating player`);
95 player = await createPlayer();
96 authToken = player.id;
97 socket.handshake.headers['x-authtoken'] = authToken;
100 logger.log(`Socket [${socket.id}] auth token: ${player.id}`);
102 bootstrapSocket(socket, player);
104 socket.on('disconnect', () => {
105 console.log(`Player ${player.username} left`);
106 io.emit('status', `${io.sockets.sockets.size} Online (v${version})`);
110 io.emit('status', `${io.sockets.sockets.size} Online (v${version})`);
111 // this is a special event to let the client know it can start
113 socket.emit('ready');
116 async function fightRound(player: Player, monster: MonsterWithFaction, data: {action: 'attack' | 'cast' | 'flee', target: 'head' | 'body' | 'arms' | 'legs'}) {
117 const playerSkills = await getPlayerSkillsAsObject(player.id);
118 const roundData: FightRound = {
121 winner: 'in-progress',
122 fightTrigger: monster.fight_trigger,
130 const equippedItems = await getEquippedItems(player.id);
132 // we only use this if the player successfully defeated the monster
133 // they were fighting, then we load the other monsters in this area
134 // so they can "fight again"
135 let potentialMonsters: MonsterForFight[] = [];
138 * cumulative chance of head/arms/body/legs
142 * we use the factor to decide how many decimal places
146 const monsterTarget = [0.2, 0.4, 0.9, 1];
147 const targets: ArmourEquipmentSlot[] = ['HEAD', 'CHEST', 'ARMS', 'LEGS'];
149 const rand = Math.ceil(Math.random() * factor);
150 let target: ArmourEquipmentSlot = 'CHEST';
151 monsterTarget.forEach((i, idx) => {
152 if (rand > (i * factor)) {
153 target = targets[idx] as ArmourEquipmentSlot;
166 const equipment: Map<EquipmentSlot, EquippedItemDetails> = new Map<EquipmentSlot, EquippedItemDetails>();
167 const weapons: EquippedItemDetails[] = [];
168 let anyDamageSpells: boolean = false;
169 equippedItems.forEach(item => {
170 if(item.type === 'ARMOUR') {
171 equipment.set(item.equipment_slot, item);
173 else if(item.type === 'WEAPON') {
176 else if(item.type === 'SPELL') {
177 if(item.affectedSkills.includes('destruction_magic')) {
178 anyDamageSpells = true;
183 boost.strength += item.boosts.strength;
184 boost.constitution += item.boosts.constitution;
185 boost.dexterity += item.boosts.dexterity;
186 boost.intelligence += item.boosts.intelligence;
188 if(item.type === 'SPELL' && item.affectedSkills.includes('restoration_magic')) {
189 boost.hp += item.boosts.damage;
192 boost.damage += item.boosts.damage;
196 // if you flee'd, then we want to check your dex vs. the monsters
197 // but we want to give you the item/weapon boosts you need
198 // if not then you're going to get hit.
199 if(data.action === 'flee') {
200 roundData.roundDetails.push(`You managed to escape from the ${monster.name}!`)
201 roundData.winner = 'monster';
202 await clearFight(player.id);
204 return { roundData, monsters: [], player };
207 const attackType = data.action === 'attack' ? 'physical' : 'magical';
208 const primaryStat = data.action === 'attack' ? player.strength : player.intelligence;
209 const boostStat = data.action === 'attack' ? boost.strength : boost.intelligence;
211 const playerDamage = Math.floor(((primaryStat + boostStat) * 1.3) + boost.damage);
212 const skillsUsed: Record<SkillID | any, number> = {};
213 let hpHealAfterMasteries: number = -1;
214 let playerDamageAfterMasteries: number = 0;
216 weapons.forEach(item => {
217 item.affectedSkills.forEach(id => {
218 if(id === 'restoration_magic') {
219 if(hpHealAfterMasteries < 0) {
220 hpHealAfterMasteries = 0;
222 hpHealAfterMasteries += Skills.get(id).effect(playerSkills.get(id));
225 playerDamageAfterMasteries += playerDamage * Skills.get(id).effect(playerSkills.get(id));
228 if(!skillsUsed[id]) {
235 await updatePlayerSkills(player.id, skillsUsed);
237 const playerFinalDamage = (data.action === 'cast' && !anyDamageSpells) ? 0 : Math.floor(playerDamage + playerDamageAfterMasteries);
238 const playerFinalHeal = Math.floor(boost.hp + hpHealAfterMasteries);
240 roundData.roundDetails.push(`You targeted the monsters ${data.target.toUpperCase()} with ${attackType} damage!`);
241 let armourKey: string;
242 switch(data.target) {
244 armourKey = 'armsAp';
247 armourKey = 'helmAp';
250 armourKey = 'legsAp';
253 armourKey = 'chestAp';
257 if(monster[armourKey] && monster[armourKey] > 0) {
258 monster[armourKey] -= playerFinalDamage;
260 roundData.roundDetails.push(`You dealt ${playerFinalDamage} damage to their armour`);
261 if(monster[armourKey] < 0) {
262 roundData.roundDetails.push(`You destroyed the ${monster.name}'s armour!'`);
263 roundData.roundDetails.push(`You dealt ${monster[armourKey] * -1} damage to their HP`);
264 monster.hp += monster[armourKey];
265 monster[armourKey] = 0;
269 roundData.roundDetails.push(`You hit the ${monster.name} for ${playerFinalDamage} damage.`);
270 monster.hp -= playerFinalDamage;
273 if(monster.hp <= 0) {
274 roundData.monster.hp = 0;
275 roundData.winner = 'player';
277 roundData.rewards.exp = monster.exp;
278 roundData.rewards.gold = monster.gold;
280 player.gold += monster.gold;
281 player.exp += monster.exp;
283 if(player.exp >= expToLevel(player.level + 1)) {
284 player.exp -= expToLevel(player.level + 1)
286 roundData.rewards.levelIncrease = true;
287 let statPointsGained = 1;
289 if(player.profession !== 'Wanderer') {
290 statPointsGained = 2;
293 player.stat_points += statPointsGained;
295 roundData.roundDetails.push(`You gained ${statPointsGained} stat points!`);
297 player.hp = maxHp(player.constitution, player.level);
299 // get the monster location if it was an EXPLORED fight
300 if(roundData.fightTrigger === 'explore') {
301 const rawMonster = await loadMonster(monster.ref_id);
302 const monsterList = await getMonsterList(rawMonster.location_id);
303 potentialMonsters = monsterList.map(monster => {
307 level: monster.level,
309 maxHp: monster.maxHp,
310 fight_trigger: 'explore'
315 await clearFight(player.id);
316 await updatePlayer(player);
317 return { roundData, monsters: potentialMonsters, player };
320 roundData.roundDetails.push(`The ${monster.name} targeted your ${target}!`);
321 if(equipment.has(target)) {
322 const item = equipment.get(target);
324 const mitigationPercentage = item.boosts.damage_mitigation || 0;
325 const damageAfterMitigation = Math.floor(monster.strength * ((100-mitigationPercentage)/100));
327 item.currentAp -= damageAfterMitigation;
329 if(item.currentAp < 0) {
330 roundData.roundDetails.push(`Your ${item.name} amour was destroyed`);
331 roundData.roundDetails.push(`The ${monster.name} hit your HP for ${item.currentAp * -1} damage!`);
332 player.hp += item.currentAp;
334 await deleteInventoryItem(player.id, item.item_id);
337 roundData.roundDetails.push(`Your ${target} took ${damageAfterMitigation} damage!`);
338 await updateAp(player.id, item.item_id, item.currentAp, item.maxAp);
343 roundData.roundDetails.push(`The ${monster.name} hit you for ${monster.strength} damage`);
344 player.hp -= monster.strength;
347 if(playerFinalHeal > 0) {
348 player.hp += playerFinalHeal;
349 if(player.hp > maxHp(player.constitution, player.level)) {
350 player.hp = maxHp(player.constitution, player.level);
352 roundData.roundDetails.push(`You healed for ${playerFinalHeal} HP`);
355 // update the players inventory for this item!
359 roundData.winner = 'monster';
361 roundData.roundDetails.push(`You were killed by the ${monster.name}`);
363 await clearFight(player.id);
364 await updatePlayer(player);
365 await clearTravelPlan(player.id);
367 return { roundData, monsters: [], player};
370 await updatePlayer(player);
371 await saveFightState(player.id, monster);
373 return { roundData, monsters: [], player};
376 app.use(healerRouter);
379 app.get('/chat/history', authEndpoint, async (req: AuthRequest, res: Response) => {
380 let html = chatHistory.map(renderChatMessage);
382 res.send(html.join("\n"));
385 app.post('/chat', authEndpoint, async (req: AuthRequest, res: Response) => {
386 const msg = req.body.message.trim();
388 if(!msg || !msg.length) {
393 let message: Message;
394 if(msg.startsWith('/server lmnop')) {
395 if(msg === '/server lmnop refresh-monsters') {
396 await createMonsters();
397 message = broadcastMessage('server', 'Monster refresh!');
399 else if(msg === '/server lmnop refresh-cities') {
400 await createAllCitiesAndLocations();
401 message = broadcastMessage('server', 'Cities, Locations, and Paths refreshed!');
403 else if(msg === '/server lmnop refresh-shops') {
404 await createShopItems();
405 await createShopEquipment();
406 message = broadcastMessage('server', 'Refresh shop items');
409 const str = msg.split('/server lmnop ')[1];
411 message = broadcastMessage('server', str);
416 message = broadcastMessage(req.player.username, msg);
417 chatHistory.push(message);
418 chatHistory.slice(-10);
422 io.emit('chat', renderChatMessage(message));
427 app.get('/player', authEndpoint, async (req: AuthRequest, res: Response) => {
428 const inventory = await getEquippedItems(req.player.id);
430 res.send(renderPlayerBar(req.player, inventory) + renderProfilePage(req.player));
433 app.post('/player/stat/:stat', authEndpoint, async (req: AuthRequest, res: Response) => {
434 const stat = req.params.stat;
435 if(!['strength', 'constitution', 'dexterity', 'intelligence'].includes(stat)) {
436 res.send(Alert.ErrorAlert(`Sorry, that's not a valid stat to increase`));
440 if(req.player.stat_points <= 0) {
441 res.send(Alert.ErrorAlert(`Sorry, you don't have enough stat points`));
445 req.player.stat_points -= 1;
448 updatePlayer(req.player);
450 const equippedItems = await getEquippedItems(req.player.id);
451 res.send(renderPlayerBar(req.player, equippedItems) + renderProfilePage(req.player));
454 app.get('/player/skills', authEndpoint, async (req: AuthRequest, res: Response) => {
455 const skills = await getPlayerSkills(req.player.id);
457 res.send(renderSkills(skills));
460 app.get('/player/inventory', authEndpoint, async (req: AuthRequest, res: Response) => {
461 const [inventory, items] = await Promise.all([
462 getInventory(req.player.id),
463 getPlayersItems(req.player.id)
466 res.send(renderInventoryPage(inventory, items));
469 app.post('/player/equip/:item_id/:slot', authEndpoint, async (req: AuthRequest, res: Response) => {
470 const inventoryItem = await getInventoryItem(req.player.id, req.params.item_id);
471 const equippedItems = await getEquippedItems(req.player.id);
472 const requestedSlot = req.params.slot;
473 let desiredSlot: EquipmentSlot = inventoryItem.equipment_slot;
476 // handes the situation where you're trying to equip an item
477 // that can be equipped to any hand
478 if(inventoryItem.equipment_slot === 'ANY_HAND') {
479 if(requestedSlot === 'LEFT_HAND' || requestedSlot === 'RIGHT_HAND') {
480 // get the players current equipment in that slot!
481 if(equippedItems.some(v => {
482 return v.equipment_slot === requestedSlot || v.equipment_slot === 'TWO_HANDED';
487 desiredSlot = requestedSlot;
492 if(requestedSlot === 'TWO_HANDED') {
493 if(equippedItems.some(v => {
494 return v.equipment_slot === 'LEFT_HAND' || v.equipment_slot === 'RIGHT_HAND';
501 await equip(req.player.id, inventoryItem, desiredSlot);
502 const socketId = cache.get(`socket:${req.player.id}`).toString();
503 io.to(socketId).emit('updatePlayer', req.player);
504 io.to(socketId).emit('alert', {
506 text: `You equipped your ${inventoryItem.name}`
513 const [inventory, items] = await Promise.all([
514 getInventory(req.player.id),
515 getPlayersItems(req.player.id)
518 res.send(renderInventoryPage(inventory, items, inventoryItem.type) + renderPlayerBar(req.player, inventory));
521 app.post('/player/unequip/:item_id', authEndpoint, async (req: AuthRequest, res: Response) => {
522 const [item, ] = await Promise.all([
523 getInventoryItem(req.player.id, req.params.item_id),
524 unequip(req.player.id, req.params.item_id)
527 const [inventory, items] = await Promise.all([
528 getInventory(req.player.id),
529 getPlayersItems(req.player.id)
532 res.send(renderInventoryPage(inventory, items, item.type) + renderPlayerBar(req.player, inventory));
535 app.get('/player/explore', authEndpoint, async (req: AuthRequest, res: Response) => {
536 const fight = await loadMonsterFromFight(req.player.id);
537 let closestTown = req.player.city_id;
540 // ok lets display the fight screen!
541 const data: MonsterForFight = {
547 fight_trigger: fight.fight_trigger
550 res.send(renderFight(data));
553 const travelPlan = await getTravelPlan(req.player.id);
556 const travelPlan = await getTravelPlan(req.player.id);
558 const closest: number = (travelPlan.current_position / travelPlan.total_distance) > 0.5 ? travelPlan.destination_id : travelPlan.source_id;
560 const chanceToSeeMonster = random(0, 100);
561 const things: any[] = [];
562 if(chanceToSeeMonster <= 30) {
563 const monster = await getRandomMonster([closest]);
564 things.push(monster);
568 const nextAction = cache[`step:${req.player.id}`] || 0;
570 res.send(renderTravel({
573 closestTown: closest,
578 // display the city info!
579 const [city, locations, paths] = await Promise.all([
580 getCityDetails(req.player.city_id),
581 getAllServices(req.player.city_id),
582 getAllPaths(req.player.city_id)
585 res.send(await renderMap({city, locations, paths}, closestTown));
591 // used to purchase equipment from a particular shop
592 app.put('/location/:location_id/equipment/:item_id', authEndpoint, async (req: AuthRequest, res: Response) => {
593 const item = await getShopEquipment(parseInt(req.params.item_id), parseInt(req.params.location_id));
596 logger.log(`Invalid item [${req.params.item_id}]`);
597 return res.sendStatus(400);
600 if(req.player.gold < item.cost) {
601 res.send(Alert.ErrorAlert(`Sorry, you need at least ${item.cost.toLocaleString()}G to purchase this.`));
605 req.player.gold -= item.cost;
607 await updatePlayer(req.player);
608 await addInventoryItem(req.player.id, item);
610 const equippedItems = await getEquippedItems(req.player.id);
612 res.send(renderPlayerBar(req.player, equippedItems) + Alert.SuccessAlert(`You purchased ${item.name}`));
615 // used to purchase items from a particular shop
616 app.put('/location/:location_id/items/:item_id', authEndpoint, async (req: AuthRequest, res: Response) => {
617 const item: (ShopItem & Item) = await getItemFromShop(parseInt(req.params.item_id), parseInt(req.params.location_id));
620 logger.log(`Invalid item [${req.params.item_id}]`);
621 return res.sendStatus(400);
624 if(req.player.gold < item.price_per_unit) {
625 res.send(Alert.ErrorAlert(`Sorry, you need at least ${item.price_per_unit.toLocaleString()}G to purchase this.`));
629 req.player.gold -= item.price_per_unit;
631 await updatePlayer(req.player);
632 await givePlayerItem(req.player.id, item.id, 1);
634 const equippedItems = await getEquippedItems(req.player.id);
636 res.send(renderPlayerBar(req.player, equippedItems) + Alert.SuccessAlert(`You purchased a ${item.name}`));
639 // used to display equipment modals in a store, validates that
640 // the equipment is actually in this store before displaying
642 app.get('/location/:location_id/equipment/:item_id/overview', authEndpoint, async (req: AuthRequest, res: Response) => {
643 const equipment = await getShopEquipment(parseInt(req.params.item_id), parseInt(req.params.location_id));
646 logger.log(`Invalid equipment [${req.params.item_id}]`);
647 return res.sendStatus(400);
652 <div class="item-modal-overview">
654 <img src="${equipment.icon ? `/assets/img/icons/equipment/${equipment.icon}` : 'https://via.placeholder.com/64x64'}" title="${equipment.name}" alt="${equipment.name}">
657 ${renderEquipmentDetails(equipment, req.player)}
660 <div class="actions">
661 <button hx-put="/location/${equipment.location_id}/equipment/${equipment.id}" formmethod="dialog" value="cancel">Buy</button>
662 <button class="close-modal" formmethod="dialog" value="cancel">Cancel</button>
670 // used to display item modals in a store, validates that
671 // the item is actually in this store before displaying
673 app.get('/location/:location_id/items/:item_id/overview', authEndpoint, async (req: AuthRequest, res: Response) => {
674 const item: (ShopItem & Item) = await getItemFromShop(parseInt(req.params.item_id), parseInt(req.params.location_id));
677 logger.log(`Invalid item [${req.params.item_id}]`);
678 return res.sendStatus(400);
683 <div class="item-modal-overview">
685 <img src="/assets/img/icons/items/${item.icon_name}" title="${item.name}" alt="${item.name}">
688 <h4>${item.name}</h4>
689 <p>${item.description}</p>
692 <div class="actions">
693 <button hx-put="/location/${item.location_id}/items/${item.id}" formmethod="dialog" value="cancel">Buy</button>
694 <button class="close-modal" formmethod="dialog" value="cancel">Cancel</button>
702 app.put('/item/:item_id', authEndpoint, async (req: AuthRequest, res: Response) => {
703 const item: PlayerItem = await getItemFromPlayer(req.player.id, parseInt(req.params.item_id));
706 console.log(`Can't find item [${req.params.item_id}]`);
710 if(item.amount < 1) {
711 res.send(Alert.ErrorAlert(`You dont have enough ${item.name}`));
717 switch(item.effect_name) {
719 const hpGain = HealthPotionSmall.effect(req.player);
721 req.player.hp += hpGain;
723 if(req.player.hp > maxHp(req.player.constitution, req.player.level)) {
724 req.player.hp = maxHp(req.player.constitution, req.player.level);
729 await updateItemCount(req.player.id, item.item_id, -1);
730 await updatePlayer(req.player);
732 const inventory = await getInventory(req.player.id);
733 const equippedItems = inventory.filter(i => i.is_equipped);
734 const items = await getPlayersItems(req.player.id);
738 renderPlayerBar(req.player, equippedItems),
739 renderInventoryPage(inventory, items, 'ITEMS'),
740 Alert.SuccessAlert(`You used the ${item.name}`)
746 app.get('/modal/items/:item_id', authEndpoint, async (req: AuthRequest, res: Response) => {
747 const item: PlayerItem = await getItemFromPlayer(req.player.id, parseInt(req.params.item_id));
750 logger.log(`Invalid item [${req.params.item_id}]`);
751 return res.sendStatus(400);
756 <div class="item-modal-overview">
758 <img src="/assets/img/icons/items/${item.icon_name}" title="${item.name}" alt="${item.name}">
761 <h4>${item.name}</h4>
762 <p>${item.description}</p>
765 <div class="actions">
766 <button hx-put="/item/${item.item_id}" formmethod="dialog" value="cancel" hx-target="#inventory">Use</button>
767 <button class="close-modal" formmethod="dialog" value="cancel">Cancel</button>
775 app.get('/city/stores/city:stores/:location_id', authEndpoint, async (req: AuthRequest, res: Response) => {
776 const location = await getService(parseInt(req.params.location_id));
778 if(!location || location.city_id !== req.player.city_id) {
779 logger.log(`Invalid location: [${req.params.location_id}]`);
782 const [shopEquipment, shopItems] = await Promise.all([
783 listShopItems({location_id: location.id}),
784 getShopItems(location.id)
787 const html = await renderStore(shopEquipment, shopItems, req.player);
792 app.get('/city/explore/city:explore/:location_id', authEndpoint, async (req: AuthRequest, res: Response) => {
793 const location = await getService(parseInt(req.params.location_id));
794 if(!location || location.city_id !== req.player.city_id) {
796 logger.log(`Invalid location: [${req.params.location_id}]`);
800 const monsters: Monster[] = await getMonsterList(location.id);
801 res.send(renderMonsterSelector(monsters));
804 app.post('/travel', authEndpoint, async (req: AuthRequest, res: Response) => {
805 const destination_id = parseInt(req.body.destination_id);
807 if(!destination_id || isNaN(destination_id)) {
808 logger.log(`Invalid destination_id [${req.body.destination_id}]`);
809 return res.sendStatus(400);
812 const travelPlan = travel(req.player, req.body.destination_id);
814 res.json(travelPlan);
817 app.post('/fight/turn', authEndpoint, async (req: AuthRequest, res: Response) => {
818 const monster = await loadMonsterWithFaction(req.player.id);
821 res.send(Alert.ErrorAlert('Not in a fight'));
825 const fightData = await fightRound(req.player, monster, {
826 action: req.body.action,
827 target: req.body.fightTarget
830 let html = renderFight(
832 renderRoundDetails(fightData.roundData),
833 fightData.roundData.winner === 'in-progress'
836 if(fightData.monsters.length && monster.fight_trigger === 'explore') {
837 html += renderMonsterSelector(fightData.monsters, monster.ref_id);
840 let travelSection = '';
841 if(monster.fight_trigger === 'travel' && fightData.roundData.winner === 'player') {
842 // you're travellinga dn you won.. display the keep walking!
843 const travelPlan = await getTravelPlan(req.player.id);
844 const closest: number = (travelPlan.current_position / travelPlan.total_distance) > 0.5 ? travelPlan.destination_id : travelPlan.source_id;
845 travelSection = travelButton(0);
848 const equippedItems = await getEquippedItems(req.player.id);
849 const playerBar = renderPlayerBar(fightData.player, equippedItems);
851 res.send(html + travelSection + playerBar);
854 app.post('/fight', authEndpoint, async (req: AuthRequest, res: Response) => {
855 if(req.player.hp <= 0) {
856 logger.log(`Player didn\'t have enough hp`);
857 return res.sendStatus(400);
860 const monsterId: number = req.body.monsterId;
861 const fightTrigger: FightTrigger = req.body.fightTrigger ?? 'travel';
864 logger.log(`Missing monster Id ${monsterId}`);
865 return res.sendStatus(400);
868 if(!fightTrigger || !['travel', 'explore'].includes(fightTrigger)) {
869 logger.log(`Invalid fight trigger [${fightTrigger}]`);
870 return res.sendStatus(400);
873 const monster = await loadMonster(monsterId);
876 logger.log(`Couldnt find monster for ${monsterId}`);
877 return res.sendStatus(400);
880 const fight = await createFight(req.player.id, monster, fightTrigger);
883 const data: MonsterForFight = {
889 fight_trigger: fight.fight_trigger
892 res.send(renderFight(data));
895 app.post('/travel/step', authEndpoint, async (req: AuthRequest, res: Response) => {
896 const stepTimerKey = `step:${req.player.id}`;
898 const travelPlan = await getTravelPlan(req.player.id);
900 res.send(Alert.ErrorAlert('You don\'t have a travel plan'));
904 if(cache[stepTimerKey]) {
905 if(cache[stepTimerKey] > Date.now()) {
906 res.send(Alert.ErrorAlert('Hmm.. travelling too quickly'));
911 travelPlan.current_position++;
913 if(travelPlan.current_position >= travelPlan.total_distance) {
914 const travel = await completeTravel(req.player.id);
916 req.player.city_id = travel.destination_id;
917 await movePlayer(travel.destination_id, req.player.id);
919 const [city, locations, paths] = await Promise.all([
920 getCityDetails(travel.destination_id),
921 getAllServices(travel.destination_id),
922 getAllPaths(travel.destination_id)
925 delete cache[stepTimerKey];
926 res.send(await renderMap({city, locations, paths}, req.player.city_id));
929 const walkingText: string[] = [
930 'You take a step forward',
933 // update existing plan..
934 // decide if they will run into anything
935 const travelPlan = await stepForward(req.player.id);
937 const closest: number = (travelPlan.current_position / travelPlan.total_distance) > 0.5 ? travelPlan.destination_id : travelPlan.source_id;
939 const chanceToSeeMonster = random(0, 100);
940 const things: any[] = [];
941 if(chanceToSeeMonster <= 30) {
942 const monster = await getRandomMonster([closest]);
943 things.push(monster);
947 const nextAction = Date.now() + 3000;
949 cache[stepTimerKey] = nextAction;
951 res.send(renderTravel({
954 closestTown: closest,
955 walkingText: sample(walkingText)
961 app.post('/travel/:destination_id', authEndpoint, async (req: AuthRequest, res: Response) => {
962 if(req.player.hp <= 0) {
963 logger.log(`Player didn\'t have enough hp`);
964 res.send(Alert.ErrorAlert('Sorry, you need some HP to start travelling.'));
968 const destination = await getCityDetails(parseInt(req.params.destination_id));
971 res.send(Alert.ErrorAlert(`Thats not a valid desination`));
975 await travel(req.player, destination.id);
977 res.send(renderTravel({
981 closestTown: req.player.city_id
985 app.get('/settings', authEndpoint, async (req: AuthRequest, res: Response) => {
988 if(req.player.account_type === 'session') {
989 warning += `<div class="alert error">If you log out without signing up first, this account is lost forever.</div>`;
992 html += '<a href="#" hx-post="/logout">Logout</a>';
993 res.send(warning + html);
996 app.post('/logout', authEndpoint, async (req: AuthRequest, res: Response) => {
997 // ref to get the socket id for a particular player
998 cache.delete(`socket:${req.player.id}`);
999 // ref to get the player object
1000 cache.delete(`token:${req.player.id}`);
1002 logger.log(`${req.player.username} logged out`);
1008 app.post('/auth', async (req: Request, res: Response) => {
1009 if(req.body.authType === 'login') {
1010 loginHandler(req, res);
1012 else if(req.body.authType === 'signup') {
1013 signupHandler(req, res);
1016 logger.log(`Invalid auth type [${req.body.authType}]`);
1017 res.sendStatus(400);
1022 async function signupHandler(req: Request, res: Response) {
1023 const {username, password} = req.body;
1024 const authToken = req.headers['x-authtoken'];
1026 if(!username || !password || !authToken) {
1027 res.send(Alert.ErrorAlert('Invalid username/password'));
1032 const player = await loadPlayer(authToken.toString());
1033 logger.log(`Attempted claim for ${player.username}`);
1035 await signup(authToken.toString(), username, password);
1037 await db('players').where({id: player.id}).update({
1038 account_type: 'auth',
1042 logger.log(`${username} claimed ${player.username}`);
1044 io.emit('chat', broadcastMessage('server', `${player.username} is now ${username}`));
1046 res.setHeader('hx-refresh', 'true');
1047 res.sendStatus(200);
1051 if(e?.constraint === 'players_username_unique') {
1052 res.send(Alert.ErrorAlert('That username is already taken'));
1055 res.send(Alert.ErrorAlert('Please try again'));
1060 async function loginHandler (req: Request, res: Response) {
1061 const {username, password} = req.body;
1062 if(!username || !username.length) {
1063 res.send(Alert.ErrorAlert('Invalid username'));
1066 if(!password || !password.length) {
1067 res.send(Alert.ErrorAlert('Invalid password'));
1072 const player = await login(username, password);
1073 io.sockets.sockets.forEach(socket => {
1074 if(socket.handshake.headers['x-authtoken'] === req.headers['x-authtoken']) {
1075 bootstrapSocket(socket, player);
1078 res.sendStatus(204);
1082 res.send(Alert.ErrorAlert('That user doesn\'t exist'));
1086 server.listen(process.env.API_PORT, () => {
1087 logger.log(`Listening on port ${process.env.API_PORT}`);