All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
+### [0.3.3](https://git.xangelo.ca/?p=risinglegends.git;a=commitdiff;h=v0.3.3;hp=v0.3.2;ds=sidebyside) (2023-09-06)
+
+
+### Features
+
+* add debug/error methods to logger 3238965
+* display equippable hand option only d7569d3
+* migrate to augmenting express.Request interface d820e11
+* monster variants b8bed23
+* remove body-part targeting c6a5f62
+* variable level monsters b5577b4
+
+
+### Bug Fixes
+
+* min/max level definitions for monsters bedec85
+
### [0.3.2](https://git.xangelo.ca/?p=risinglegends.git;a=commitdiff;h=v0.3.2;hp=v0.3.1;ds=sidebyside) (2023-09-01)
--- /dev/null
+import { Knex } from "knex";
+
+
+export async function up(knex: Knex): Promise<void> {
+ return knex.schema.alterTable('monsters', function(table) {
+ table.dropColumn('level');
+ table.integer('minLevel').notNullable().defaultTo(1);
+ table.integer('maxLevel').notNullable().defaultTo(1);
+ });
+}
+
+
+export async function down(knex: Knex): Promise<void> {
+ return knex.schema.alterTable('monsters', function(table) {
+ table.dropColumn('minLevel');
+ table.dropColumn('maxLevel');
+ table.integer('level').notNullable().defaultTo(1);
+ });
+}
+
{
"name": "rising-legends",
- "version": "0.3.2",
+ "version": "0.3.3",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "rising-legends",
- "version": "0.3.2",
+ "version": "0.3.3",
"dependencies": {
"@honeycombio/opentelemetry-node": "^0.4.0",
"@opentelemetry/auto-instrumentations-node": "^0.37.0",
{
"name": "rising-legends",
"private": true,
- "version": "0.3.2",
+ "version": "0.3.3",
"scripts": {
"up": "npx prisma migrate dev --name \"init\"",
"start": "pm2 start dist/server/api.js",
"src/client/**",
"**/client.ts",
"public/**",
- "**.test.ts"
+ "**.test.ts",
+ "migrations/**"
]
},
"volta": {
width: 70%;
margin: 0 auto 1rem;
}
-#defender-name {
+.monster-identifier {
text-align: left;
}
+#defender-name {
+ font-weight: bold;
+}
+.Elder #defender-name {
+ color: #2b2b2b;
+}
+.Skittish #defender-name {
+ color: #8700ff;
+}
+.Brute #defender-name {
+ color: #a91313;
+}
#fight-results {
margin-top: 1rem;
}
return {
id: r.fields.id,
name: r.fields.Name,
- strength: r.fields['STR_override'] || r.fields.STR,
- constitution: r.fields['CON_override'] || r.fields.CON,
- dexterity: r.fields['DEX_override'] || r.fields.DEX,
- intelligence: r.fields['INT_override'] || r.fields.INT,
+ strength: r.fields.STR,
+ constitution: r.fields.CON,
+ dexterity: r.fields.DEX,
+ intelligence: r.fields.INT,
exp: r.fields.EXP,
- level: r.fields.Level,
+ minLevel: r.fields.minLevel,
+ maxLevel: r.fields.maxLevel ?? r.fields.minLevel,
gold: r.fields.GOLD,
hp: r.fields.HP,
maxHp: r.fields.HP,
+++ /dev/null
-export * from './profession-changing/client';
-export * from './travel/client';
+++ /dev/null
-import {SocketEvent} from "../../server/socket-event.server";
-import { Socket } from 'socket.io';
-import {EquipmentSlot} from '../../shared/inventory';
-import {getEquippedItems, getInventory, getInventoryItem} from '../../server/inventory';
-import { equip, unequip } from '../../server/equipment';
-import { logger } from '../../server/lib/logger';
-import {EquippedItemDetails} from '../../shared/equipped';
-import { getPlayersItems } from "../../server/items";
-
-class EquipmentInSlotError extends Error {
- code: number;
- constructor() {
- super('You already have something in that slot');
- this.code = 23505;
- }
-}
-
-
-function calcAp(inventoryItem: EquippedItemDetails[], socket: Socket) {
- const ap: Record<any | EquipmentSlot, {currentAp: number, maxAp: number}> = {};
- inventoryItem.forEach(item => {
- if(item.is_equipped && item.type === 'ARMOUR') {
- ap[item.equipment_slot] = {
- currentAp: item.currentAp,
- maxAp: item.maxAp
- };
- }
- });
-
- socket.emit('calc:ap', {ap});
-}
-
-export const equipItem: SocketEvent = {
- eventName: 'equip',
- handler: async (api, data: {id: string, slot: EquipmentSlot}) => {
- const inventoryItem = await getInventoryItem(api.player.id, data.id);
- const equippedItems = await getEquippedItems(api.player.id);
- let desiredSlot: EquipmentSlot = inventoryItem.equipment_slot;
-
- try {
- // handes the situation where you're trying to equip an item
- // that can be equipped to any hand
- if(inventoryItem.equipment_slot === 'ANY_HAND') {
- if(data.slot === 'LEFT_HAND' || data.slot === 'RIGHT_HAND') {
- // get the players current equipment in that slot!
- if(equippedItems.some(v => {
- return v.equipment_slot === data.slot || v.equipment_slot === 'TWO_HANDED';
- })) {
- throw new EquipmentInSlotError();
- }
- else {
- desiredSlot = data.slot;
- }
- }
- }
-
- if(data.slot === 'TWO_HANDED') {
- if(equippedItems.some(v => {
- return v.equipment_slot === 'LEFT_HAND' || v.equipment_slot === 'RIGHT_HAND';
- })) {
- throw new EquipmentInSlotError();
- }
- }
-
-
- await equip(api.player.id, inventoryItem, desiredSlot);
- api.socket.emit('alert', {
- type: 'success',
- text: `You equipped your ${inventoryItem.name}`
- });
- }
- catch(e) {
- if(e.code.toString() === '23505') {
- api.socket.emit('alert', {
- type: 'error',
- text: 'You already have an item equipped in that slot'
- });
- }
- else {
- logger.log(e);
- }
- }
-
- const inventory = await getInventory(api.player.id);
- const items = await getPlayersItems(api.player.id);
- api.socket.emit('inventory', {
- inventory,
- items
- });
- calcAp(inventory, api.socket);
-
- }
-}
-
-export const unequipItem: SocketEvent = {
- eventName: 'unequip',
- handler: async (api, data: {id: string}) => {
- await unequip(api.player.id, data.id);
-
- const inventory = await getInventory(api.player.id);
- calcAp(inventory, api.socket);
- const items = await getPlayersItems(api.player.id);
- api.socket.emit('inventory', {
- inventory,
- items
- });
- }
-}
+++ /dev/null
-import {Monster, MonsterForList} from "../../shared/monsters";
-import {SocketEvent} from "../../server/socket-event.server";
-import {getMonsterList} from "../../server/monster";
-
-export const exploreInCity: SocketEvent = {
- eventName: 'city:explore',
- handler: async (api, data: { args: string }) => {
- // @TODO add check to make sure player is in this town and can actually explore this area
- const locationId = parseInt(data.args);
-
- if(!locationId || isNaN(locationId)) {
- return;
- }
-
- const monsters: Monster[] = await getMonsterList(locationId);
- let monsterList: MonsterForList[] = monsters.map(monster => {
- return {
- id: monster.id,
- name: monster.name,
- level: monster.level
- }
- });
-
- api.socket.emit('explore:fights', monsterList);
- }
-}
+++ /dev/null
-import { getItemFromPlayer, getPlayersItems, updateItemCount } from "../../server/items";
-import {API, SocketEvent} from "../../server/socket-event.server";
-import { maxHp } from "../../shared/player";
-import { updatePlayer } from "../../server/player";
-import { HealthPotionSmall } from "../../shared/items/health_potion";
-import { getInventory } from "../../server/inventory";
-
-export const smallHeal: SocketEvent = {
- eventName: 'item:use:heal_small',
- handler: async (api: API, data: {args: string}): Promise<any> => {
- const itemId = parseInt(data.args);
- const item = await getItemFromPlayer(api.player.id, itemId);
-
- if(!item) {
- console.log(`Can't find item [${data.args}]`);
- return;
- }
-
- if(item.amount < 1) {
- api.socket.emit('alert', {
- type: 'error',
- text: `You don't have enough ${item.name}`
- });
- return;
- }
-
- item.amount -= 1;
-
- const hpGain = HealthPotionSmall.effect(api.player);
-
- api.player.hp += hpGain;
-
- if(api.player.hp > maxHp(api.player.constitution, api.player.level)) {
- api.player.hp = maxHp(api.player.constitution, api.player.level);
- }
-
- await updateItemCount(api.player.id, item.item_id, -1);
- await updatePlayer(api.player);
- const inventory = await getInventory(api.player.id);
- const items = await getPlayersItems(api.player.id);
-
- api.socket.emit('updatePlayer', api.player);
- api.socket.emit('inventory', {
- inventory,
- items
- });
- api.socket.emit('alert', {
- type: 'success',
- text: `You used the Small Health Potion`
- });
-
- return;
- }
-}
+++ /dev/null
-import {SocketEvent} from "../../client/socket-event.client";
-import $ from 'jquery';
-import { EVENT_NAME } from "./shared";
-
-function generalTextReplacementHandler(api, data: { text: string }) {
- $('#map').html(data.text);
-}
-
-export const professionRecruiter: SocketEvent = new SocketEvent(EVENT_NAME, generalTextReplacementHandler);
-
-export const professionChangeWarrior: SocketEvent = new SocketEvent(
- `${EVENT_NAME}:warrior`,
- generalTextReplacementHandler
-);
-
-export const professionChangeMage: SocketEvent = new SocketEvent(
- `${EVENT_NAME}:mage`,
- generalTextReplacementHandler
-);
-
-export const professionChangeRogue: SocketEvent = new SocketEvent(
- `${EVENT_NAME}:rogue`,
- generalTextReplacementHandler
-);
+++ /dev/null
-import {API, SocketEvent} from "../../server/socket-event.server";
-import { EVENT_NAME } from './shared';
-import { changeProfession } from "../../server/player";
-import {Profession} from "shared/profession";
-import {broadcastMessage} from "../../shared/message";
-
-const MIN_LEVEL = 25;
-
-export const professionRecruiter: SocketEvent = {
- eventName: EVENT_NAME,
- handler: (api, data): Promise<any> => {
-
- let text: string = '';
-
- if(api.player.profession === 'Wanderer') {
- text = `
- <b>Welcome to the Professional Services at Windcross!</b>
- <p>Our duty is to help Wanderers such as yourself become more than they are. By helping you achieve new levels in service of the King, we can ensure that the Kingdom of Khatis continues to grow!</p>
- <p>You have 3 choices laid before you.</p>
- <p>You could become a great and mighty <b>Warrior</b>! Wielding powerful swords and maces.</p>
- <p>You could become a powerful <b>Mage</b>! Casting spells to rain fire upon our enemies.</p>
- <p>You could become a lithe <b>Rogue</b>! Attacking our enemies swiftly when they least expect!</p>
- `;
-
- if(api.player.level < MIN_LEVEL) {
- text += `<p>Unfortunately.. you have to be at least level ${MIN_LEVEL} to take part in our training...</p>`;
- }
- else {
- text += `
- <p><b>Be Careful!</b> Once you change your profession, you will never again be a Wanderer</p>
- <div>
- <button class="city-emit-event" data-event="${EVENT_NAME}:warrior">Become a Warrior</button>
- <button class="city-emit-event" data-event="${EVENT_NAME}:mage">Become a Mage</button>
- <button class="city-emit-event" data-event="${EVENT_NAME}:rogue">Become a Rogue</button>
- </div>
- `
- }
- }
- else {
-
- let town = 'UNSET';
- let place = 'UNSETPLACE';
- switch(api.player.profession) {
- case 'Warrior':
- town = 'Stether';
- place = 'Highbreaker Inn'
- break;
- case 'Mage':
- town = 'Davelfell';
- place = 'Mages Tower';
- break;
- case 'Rogue':
- town = 'Ferbalt Gap';
- place = 'Keepers Tavern';
- break;
- }
-
- text = `<p>Welcome <b>${api.player.profession}</b>!`;
- text += `<p>Unfortunately I won't be of much help to you now that you are no longer a wanderer...</p>`;
- text += `<p>However, you should visit the ${place} in ${town} that can probably provide some guidance!</p>`;
- }
-
-
- api.socket.emit('city:services:profession_recruitor_windcross', {
- text
- });
-
- return;
- }
-};
-
-async function generalFirstLevelProfessionChange(api: API, data: unknown, profession: Profession) {
- console.log(`${api.player.username} is becoming a ${profession}!`);
- const update = await changeProfession(api.player.id, profession);
-
- api.player.level = update.level;
- api.player.exp = update.exp;
- api.player.profession = profession;
-
- api.socket.emit('updatePlayer', api.player);
- api.socket.emit(`${EVENT_NAME}:${profession.toLowerCase()}`, {
- text: `Congratulations! You are now a ${profession}!`
- });
-
- api.io.emit('chat', broadcastMessage('server', `${api.player.username} is now a ${profession}`));
-}
-
-export const professionChangeWarrior: SocketEvent = {
- eventName: `${EVENT_NAME}:warrior`,
- handler: async (api, data) => {
- generalFirstLevelProfessionChange(api, data, 'Warrior');
- }
-}
-
-export const professionChangeMage: SocketEvent = {
- eventName: `${EVENT_NAME}:mage`,
- handler: async (api, data) => {
- generalFirstLevelProfessionChange(api, data, 'Mage');
- }
-}
-
-export const professionChangeRogue: SocketEvent = {
- eventName: `${EVENT_NAME}:rogue`,
- handler: async (api, data) => {
- generalFirstLevelProfessionChange(api, data, 'Rogue');
- }
-}
+++ /dev/null
-export const EVENT_NAME: string = 'city:services:profession_recruitor_windcross';
+++ /dev/null
-export * from './profession-changing/server';
-export * from './equipping-items/server';
-export * from './travel/server';
-export * from './explore/server';
-export * from './stores/server';
-export * from './stat-points/server';
-export * from './items/server';
+++ /dev/null
-import {SocketEvent} from "../../server/socket-event.server";
-import { professionList } from "../../shared/profession";
-import { updatePlayer } from "../../server/player";
-import { Stat } from "../../shared/stats";
-
-export const spendStatPoint: SocketEvent = {
- eventName: 'spend-stat-point',
- handler: async (api, data: { args: any }): Promise<void> => {
-
- if(!Stat[data.args]) {
- api.socket.emit('alert', {
- type: 'error',
- text: `Invalid stat type [${data.args}]`
- });
- return;
- }
-
- const statToIncrease: Stat = data.args as Stat;
- const costToIncrease: number = professionList[api.player.profession].classStats.includes(statToIncrease) ? 1 : 2;
-
- if(api.player.stat_points < costToIncrease) {
- api.socket.emit('alert', {
- type: 'error',
- text: 'You don\'t have enough stat points'
- });
- }
- else {
- api.player[statToIncrease] += costToIncrease;
- api.player.stat_points -= costToIncrease;
-
- await updatePlayer(api.player);
- api.socket.emit('updatePlayer', api.player);
- }
-
- }
-}
+++ /dev/null
-import {SocketEvent} from "../../server/socket-event.server";
-import {listShopItems} from '../../server/shopEquipment';
-import { getShopItems } from "../../server/items";
-import { logger } from '../../server/lib/logger';
-
-export const stores: SocketEvent = {
- eventName: 'city:stores',
- handler: async (api, data: {args: string}) => {
- const storeId = parseInt(data.args);
-
- if(!storeId || isNaN(storeId)) {
- logger.log(`Invalid store id: ${storeId}`);
- }
-
- const [shopEquipemnt, shopItems] = await Promise.all([
- listShopItems({location_id: storeId}),
- getShopItems(storeId)
- ]);
-
- if(shopEquipemnt && shopEquipemnt.length) {
- api.socket.emit('city:stores', {
- equipment: shopEquipemnt,
- items: shopItems
- });
- }
- else {
- logger.log(`Insufficient shop items: ${shopEquipemnt.length}`);
- }
- }
-}
+++ /dev/null
-import {SocketEvent} from "../../client/socket-event.client";
-import $ from 'jquery';
-import { TravelDTO } from './shared';
-
-export const travel: SocketEvent = new SocketEvent(
- 'city:travel',
- (api, data) => {
- api.events.emit('renderTravel',[data as TravelDTO]);
- }
-);
-
-export const renderCity: SocketEvent = new SocketEvent(
- 'city:display',
- async (api, data) => {
- api.cache.delete('currentMapHTML');
- api.events.emit('renderMap', [data]);
- }
-)
+++ /dev/null
-import {movePlayer} from "../../server/player";
-import {getCityDetails, getAllServices, getAllPaths, travel, getTravelPlan, stepForward, completeTravel} from "../../server/map";
-import {SocketEvent} from "../../server/socket-event.server";
-import { sample, random } from 'lodash';
-import { getRandomMonster } from "../../server/monster";
-import { STEP_DELAY } from "./shared";
-
-const MONSTER_ENCOUNTER_CHANCE = 30;
-
-export const explore: SocketEvent = {
- eventName: 'city:travel',
- handler: async (api, data: { args: string }) => {
- if(api.player.hp <= 0) {
- api.socket.emit('alert', {
- type: 'error',
- text: 'Sorry, you need some HP to start your travel'
- });
- return;
- }
-
- const destinationCity = parseInt(data.args);
-
-
- if(!destinationCity || isNaN(destinationCity)) {
- console.log(`Invalid destination city [${destinationCity}]`);
- return;
- }
-
- try {
- const city = await getCityDetails(destinationCity);
-
- if(!city) {
- console.log(`Invalid destination city [${destinationCity}]`);
- return;
- }
-
- console.log(`${api.player.username} attempting travel to ${city.name}`);
- const travelPlan = await travel(api.player, city.id);
-
- api.socket.emit('city:travel', {
- things: [],
- nextAction: 0,
- closestTown: api.player.city_id,
- walkingText: ''
- });
- }
- catch(e) {
- console.log(e);
- }
- }
-}
-
-const walkingText: string[] = [
- 'You take a step forward',
- 'You keep moving'
-];
-
-export const nextStep: SocketEvent = {
- eventName: 'travel:step',
- handler: async (api, data: { args: string }) => {
- const stepTimerKey = `step:${api.player.id}`;
- const travelPlan = await getTravelPlan(api.player.id);
-
- if(api.cache[stepTimerKey]) {
- if(api.cache[stepTimerKey] > Date.now()) {
- // clicked too fast
- return;
- }
- }
-
- if(!travelPlan) {
- return;
- }
-
- travelPlan.current_position++;
- if(travelPlan.current_position >= travelPlan.total_distance) {
- const travel = await completeTravel(api.player.id);
-
- api.player.city_id = travel.destination_id;
- await movePlayer(travel.destination_id, api.player.id);
-
- const [city, locations, paths] = await Promise.all([
- getCityDetails(travel.destination_id),
- getAllServices(travel.destination_id),
- getAllPaths(travel.destination_id)
- ]);
-
- api.socket.emit('city:display', {
- city,
- locations,
- paths
- });
-
- delete api.cache[stepTimerKey];
- }
- else {
- // update existing plan..
- // decide if they will run into anything
- const travelPlan = await stepForward(api.player.id);
-
- const closest: number = (travelPlan.current_position / travelPlan.total_distance) > 0.5 ? travelPlan.destination_id : travelPlan.source_id;
-
- const chanceToSeeMonster = random(0, 100);
- const things: any[] = [];
- if(chanceToSeeMonster < MONSTER_ENCOUNTER_CHANCE) {
- const monster = await getRandomMonster([closest]);
- things.push(monster);
- }
-
- const nextAction = Date.now() + STEP_DELAY;
-
- api.cache[stepTimerKey] = nextAction;
-
- api.socket.emit('city:travel', {
- things,
- nextAction,
- closestTown: closest,
- walkingText: sample(walkingText)
- });
-
- }
- }
-};
+++ /dev/null
-import {City, Location, Path} from "../../shared/map"
-
-export type DTO = {
- city: City,
- locations: Location[],
- paths: Path[]
-}
-
-export type TravelDTO = {
- things: any[],
- nextAction: number;
- walkingText: string,
- closestTown: number;
-}
-
-export const STEP_DELAY = 3000;
import {getShopEquipment, listShopItems } from './shopEquipment';
import {EquipmentSlot} from '../shared/inventory';
import { clearTravelPlan, completeTravel, getAllPaths, getAllServices, getCityDetails, getService, getTravelPlan, stepForward, travel } from './map';
-import { signup, login, authEndpoint, AuthRequest } from './auth';
+import { signup, login, authEndpoint } from './auth';
import {db} from './lib/db';
import { getPlayerSkills} from './skills';
app.use(repairRouter);
-app.get('/chat/history', authEndpoint, async (req: AuthRequest, res: Response) => {
+app.get('/chat/history', authEndpoint, async (req: Request, res: Response) => {
let html = chatHistory.map(renderChatMessage);
res.send(html.join("\n"));
});
-app.post('/chat', authEndpoint, async (req: AuthRequest, res: Response) => {
+app.post('/chat', authEndpoint, async (req: Request, res: Response) => {
const msg = req.body.message.trim();
if(!msg || !msg.length) {
let message: Message;
if(msg.startsWith('/server lmnop')) {
- if(msg === '/server lmnop refresh-monsters') {
- await createMonsters();
- message = broadcastMessage('server', 'Monster refresh!');
- }
- else if(msg === '/server lmnop refresh-cities') {
- await createAllCitiesAndLocations();
- message = broadcastMessage('server', 'Cities, Locations, and Paths refreshed!');
- }
- else if(msg === '/server lmnop refresh-shops') {
- await createShopItems();
- await createShopEquipment();
- message = broadcastMessage('server', 'Refresh shop items');
- }
- else {
- const str = msg.split('/server lmnop ')[1];
- if(str) {
- message = broadcastMessage('server', str);
+ try {
+ if(msg === '/server lmnop refresh-monsters') {
+ await createMonsters();
+ message = broadcastMessage('server', 'Monster refresh!');
+ }
+ else if(msg === '/server lmnop refresh-cities') {
+ await createAllCitiesAndLocations();
+ message = broadcastMessage('server', 'Cities, Locations, and Paths refreshed!');
+ }
+ else if(msg === '/server lmnop refresh-shops') {
+ await createShopItems();
+ await createShopEquipment();
+ message = broadcastMessage('server', 'Refresh shop items');
}
+ else {
+ const str = msg.split('/server lmnop ')[1];
+ if(str) {
+ message = broadcastMessage('server', str);
+ }
+ }
+ }
+ catch(e) {
+ io.to(cache.get(`socket:${req.player.id}`)).emit('chat', renderChatMessage(broadcastMessage('server', e.message)));
}
}
else if(msg === '/online') {
}
});
-app.get('/player', authEndpoint, async (req: AuthRequest, res: Response) => {
+app.get('/player', authEndpoint, async (req: Request, res: Response) => {
const equipment = await getEquippedItems(req.player.id);
res.send(renderPlayerBar(req.player) + renderProfilePage(req.player, equipment));
});
-app.post('/player/stat/:stat', authEndpoint, async (req: AuthRequest, res: Response) => {
+app.post('/player/stat/:stat', authEndpoint, async (req: Request, res: Response) => {
const equipment = await getEquippedItems(req.player.id);
const stat = req.params.stat;
if(!['strength', 'constitution', 'dexterity', 'intelligence'].includes(stat)) {
res.send(renderPlayerBar(req.player) + renderProfilePage(req.player, equipment));
});
-app.get('/player/skills', authEndpoint, async (req: AuthRequest, res: Response) => {
+app.get('/player/skills', authEndpoint, async (req: Request, res: Response) => {
const skills = await getPlayerSkills(req.player.id);
res.send(renderSkills(skills));
});
-app.get('/player/inventory', authEndpoint, async (req: AuthRequest, res: Response) => {
+app.get('/player/inventory', authEndpoint, async (req: Request, res: Response) => {
const [inventory, items] = await Promise.all([
getInventory(req.player.id),
getPlayersItems(req.player.id)
res.send(renderInventoryPage(inventory, items));
});
-app.post('/player/equip/:item_id/:slot', authEndpoint, blockPlayerInFight, async (req: AuthRequest, res: Response) => {
+app.post('/player/equip/:item_id/:slot', authEndpoint, blockPlayerInFight, async (req: Request, res: Response) => {
const inventoryItem = await getInventoryItem(req.player.id, req.params.item_id);
const equippedItems = await getEquippedItems(req.player.id);
const requestedSlot = req.params.slot;
res.send(renderInventoryPage(inventory, items, inventoryItem.type) + renderPlayerBar(req.player));
});
-app.post('/player/unequip/:item_id', authEndpoint, blockPlayerInFight, async (req: AuthRequest, res: Response) => {
+app.post('/player/unequip/:item_id', authEndpoint, blockPlayerInFight, async (req: Request, res: Response) => {
const [item, ] = await Promise.all([
getInventoryItem(req.player.id, req.params.item_id),
unequip(req.player.id, req.params.item_id)
res.send(renderInventoryPage(inventory, items, item.type) + renderPlayerBar(req.player));
});
-app.get('/player/explore', authEndpoint, async (req: AuthRequest, res: Response) => {
+app.get('/player/explore', authEndpoint, async (req: Request, res: Response) => {
const fight = await loadMonsterFromFight(req.player.id);
const travelPlan = await getTravelPlan(req.player.id);
let closestTown = req.player.city_id;
}
if(fight) {
- const data: MonsterForFight = {
- id: fight.id,
- hp: fight.hp,
- maxHp: fight.maxHp,
- name: fight.name,
- level: fight.level,
- fight_trigger: fight.fight_trigger
- };
const location = await getMonsterLocation(fight.ref_id);
-
- res.send(renderPlayerBar(req.player) + renderFightPreRound(data, true, location, closestTown));
+ res.send(renderPlayerBar(req.player) + renderFightPreRound(fight, true, location, closestTown));
}
else {
if(travelPlan) {
});
// used to purchase equipment from a particular shop
-app.put('/location/:location_id/equipment/:item_id', authEndpoint, async (req: AuthRequest, res: Response) => {
+app.put('/location/:location_id/equipment/:item_id', authEndpoint, async (req: Request, res: Response) => {
const item = await getShopEquipment(parseInt(req.params.item_id), parseInt(req.params.location_id));
if(!item) {
});
// used to purchase items from a particular shop
-app.put('/location/:location_id/items/:item_id', authEndpoint, async (req: AuthRequest, res: Response) => {
+app.put('/location/:location_id/items/:item_id', authEndpoint, async (req: Request, res: Response) => {
const item: (ShopItem & Item) = await getItemFromShop(parseInt(req.params.item_id), parseInt(req.params.location_id));
if(!item) {
// used to display equipment modals in a store, validates that
// the equipment is actually in this store before displaying
// the modal
-app.get('/location/:location_id/equipment/:item_id/overview', authEndpoint, async (req: AuthRequest, res: Response) => {
+app.get('/location/:location_id/equipment/:item_id/overview', authEndpoint, async (req: Request, res: Response) => {
const equipment = await getShopEquipment(parseInt(req.params.item_id), parseInt(req.params.location_id));
if(!equipment) {
// used to display item modals in a store, validates that
// the item is actually in this store before displaying
// the modal
-app.get('/location/:location_id/items/:item_id/overview', authEndpoint, async (req: AuthRequest, res: Response) => {
+app.get('/location/:location_id/items/:item_id/overview', authEndpoint, async (req: Request, res: Response) => {
const item: (ShopItem & Item) = await getItemFromShop(parseInt(req.params.item_id), parseInt(req.params.location_id));
if(!item) {
res.send(html);
});
-app.put('/item/:item_id', authEndpoint, async (req: AuthRequest, res: Response) => {
+app.put('/item/:item_id', authEndpoint, async (req: Request, res: Response) => {
const item: PlayerItem = await getItemFromPlayer(req.player.id, parseInt(req.params.item_id));
if(!item) {
});
-app.get('/modal/items/:item_id', authEndpoint, async (req: AuthRequest, res: Response) => {
+app.get('/modal/items/:item_id', authEndpoint, async (req: Request, res: Response) => {
const item: PlayerItem = await getItemFromPlayer(req.player.id, parseInt(req.params.item_id));
if(!item) {
res.send(html);
});
-app.get('/city/stores/city:stores/:location_id', authEndpoint, async (req: AuthRequest, res: Response) => {
+app.get('/city/stores/city:stores/:location_id', authEndpoint, async (req: Request, res: Response) => {
const location = await getService(parseInt(req.params.location_id));
if(!location || location.city_id !== req.player.city_id) {
res.send(html);
});
-app.get('/city/explore/city:explore/:location_id', authEndpoint, async (req: AuthRequest, res: Response) => {
+app.get('/city/explore/city:explore/:location_id', authEndpoint, async (req: Request, res: Response) => {
const location = await getService(parseInt(req.params.location_id));
if(!location || location.city_id !== req.player.city_id) {
res.send(renderOnlyMonsterSelector(monsters, 0, location));
});
-app.post('/travel', authEndpoint, async (req: AuthRequest, res: Response) => {
+app.post('/travel', authEndpoint, async (req: Request, res: Response) => {
const destination_id = parseInt(req.body.destination_id);
if(!destination_id || isNaN(destination_id)) {
res.json(travelPlan);
});
-app.post('/fight/turn', authEndpoint, async (req: AuthRequest, res: Response) => {
+app.post('/fight/turn', authEndpoint, async (req: Request, res: Response) => {
const fightBlockKey = `fightturn:${req.player.id}`;
if(cache[fightBlockKey] && cache[fightBlockKey] > Date.now()) {
}
cache[fightBlockKey] = Date.now() + CONSTANT.FIGHT_ATTACK_DELAY;
- const monster = await loadMonsterWithFaction(req.player.id);
+ const monster = await loadMonsterFromFight(req.player.id);
if(!monster) {
res.send(Alert.ErrorAlert('Not in a fight'));
}
const fightData = await fightRound(req.player, monster, {
- action: req.body.action,
- target: req.body.fightTarget
+ action: req.body.action
});
res.send(html + travelSection + playerBar);
});
-app.post('/fight', fightRateLimiter, authEndpoint, async (req: AuthRequest, res: Response) => {
+app.post('/fight', fightRateLimiter, authEndpoint, async (req: Request, res: Response) => {
if(req.player.hp <= 0) {
logger.log(`Player didn\'t have enough hp`);
return res.sendStatus(400);
const fight = await createFight(req.player.id, monster, fightTrigger);
const location = await getService(monster.location_id);
-
- const data: MonsterForFight = {
- id: fight.id,
- hp: fight.hp,
- maxHp: fight.maxHp,
- name: fight.name,
- level: fight.level,
- fight_trigger: fight.fight_trigger
- };
-
- res.send(renderFightPreRound(data, true, location, location.city_id));
+ res.send(renderFightPreRound(fight, true, location, location.city_id));
});
-app.post('/travel/step', authEndpoint, async (req: AuthRequest, res: Response) => {
+app.post('/travel/step', authEndpoint, async (req: Request, res: Response) => {
const stepTimerKey = `step:${req.player.id}`;
const travelPlan = await getTravelPlan(req.player.id);
}
});
-app.post('/travel/return-to-source', authEndpoint, async (req: AuthRequest, res: Response) => {
+app.post('/travel/return-to-source', authEndpoint, async (req: Request, res: Response) => {
// puts the player back in their starting town
// doesn't matter if they don't have one
// redirect them!
const fight = await loadMonsterFromFight(req.player.id);
if(fight) {
// go to the fight screen
- const data: MonsterForFight = {
- id: fight.id,
- hp: fight.hp,
- maxHp: fight.maxHp,
- name: fight.name,
- level: fight.level,
- fight_trigger: fight.fight_trigger
- };
const location = await getMonsterLocation(fight.ref_id);
- res.send(renderPlayerBar(req.player) + renderFightPreRound(data, true, location, req.player.city_id));
+ res.send(renderPlayerBar(req.player) + renderFightPreRound(fight, true, location, req.player.city_id));
}
else {
const [city, locations, paths] = await Promise.all([
});
-app.post('/travel/:destination_id', authEndpoint, async (req: AuthRequest, res: Response) => {
+app.post('/travel/:destination_id', authEndpoint, async (req: Request, res: Response) => {
if(req.player.hp <= 0) {
logger.log(`Player didn\'t have enough hp`);
res.send(Alert.ErrorAlert('Sorry, you need some HP to start travelling.'));
}));
});
-app.get('/settings', authEndpoint, async (req: AuthRequest, res: Response) => {
+app.get('/settings', authEndpoint, async (req: Request, res: Response) => {
let warning = '';
let html = '';
if(req.player.account_type === 'session') {
res.send(warning + html);
});
-app.post('/logout', authEndpoint, async (req: AuthRequest, res: Response) => {
+app.post('/logout', authEndpoint, async (req: Request, res: Response) => {
// ref to get the socket id for a particular player
cache.delete(`socket:${req.player.id}`);
// ref to get the player object
import { db } from './lib/db';
import { Request, Response } from 'express';
-export interface AuthRequest extends Request {
- player: Player
-}
-
export async function signup(playerId: string, username: string, password: string): Promise<void> {
const salt = await bcrypt.genSalt(10);
const hash = await bcrypt.hash(password, salt);
}
-export async function authEndpoint(req: AuthRequest, res: Response, next: any) {
+export async function authEndpoint(req: Request, res: Response, next: any) {
const authToken = req.headers['x-authtoken'];
if(!authToken) {
console.log(`Invalid auth token ${authToken}`);
import { getEquippedItems, updateAp } from './inventory';
import { EquippedItemDetails } from '../shared/equipped';
import { EquipmentSlot } from '../shared/inventory';
-import { MonsterWithFaction, MonsterForFight } from '../shared/monsters';
+import { MonsterWithFaction, MonsterForFight, Fight } from '../shared/monsters';
import { getPlayerSkillsAsObject, updatePlayerSkills } from './skills';
import { SkillID, Skills } from '../shared/skills';
-import { AuthRequest } from './auth';
-import { Response } from 'express';
+import { Request, Response } from 'express';
import * as Alert from './views/alert';
-export async function blockPlayerInFight(req: AuthRequest, res: Response, next: any) {
+export async function blockPlayerInFight(req: Request, res: Response, next: any) {
const fight = await loadMonsterFromFight(req.player.id);
if(!fight) {
next();
return Math.floor(finalExp);
}
-export async function fightRound(player: Player, monster: MonsterWithFaction, data: {action: 'attack' | 'cast' | 'flee', target: 'head' | 'body' | 'arms' | 'legs'}) {
+export async function fightRound(player: Player, monster: Fight, data: {action: 'attack' | 'cast' | 'flee'}) {
const playerSkills = await getPlayerSkillsAsObject(player.id);
const roundData: FightRound = {
monster,
return {
id: monster.id,
name: monster.name,
- level: monster.level,
+ minLevel: monster.minLevel,
+ maxLevel: monster.maxLevel,
hp: monster.hp,
maxHp: monster.maxHp,
fight_trigger: 'explore'
export const logger = {
+ debug: (...args: any | any[]) => {
+ console.debug(...args);
+ },
log: (...args: any | any[]) => {
console.log(...args);
- }
+ },
+ error: (...args: any | any[]) => {
+ console.error(...args);
+ },
}
--- /dev/null
+import { Request, Response, Router } from "express";
+import { maxHp, maxVigor } from "../../shared/player";
+import { authEndpoint } from '../auth';
+import { logger } from "../lib/logger";
+import { updatePlayer } from "../player";
+import { getCityDetails, getService } from '../map';
+import { sample } from 'lodash';
+import { City, Location } from "../../shared/map";
+import { renderPlayerBar } from "../views/player-bar";
+import { BackToTown } from "../views/components/button";
+
+export const router = Router();
+
+type TextSegment = 'intro' | 'insufficient_money' | 'heal_successful';
+
+type HealText = Record<TextSegment, string[]>;
+
+const healCost = 10;
+
+const defaultTexts: HealText = {
+ intro: [
+ `Welcome traveller, I am {{NAME}}, Healer of {{CITY_NAME}}`,
+ "Please come in traveller, I am {{NAME}}, Healer of {{CITY_NAME}}",
+ ],
+ insufficient_money: [
+ "Sorry friend, you don't have enough money..",
+ "Sorry, that won't be enough..",
+ "Healing is hard work.. I'm afraid that won't cover it.."
+ ],
+ heal_successful: [
+ "I hope you feel better now",
+ "Good luck on your travels!",
+ "Glad to be of service..."
+ ]
+};
+
+// overrides for specific areas
+const playerTexts: Record<number, HealText> = {
+ [8]: {
+ intro: [
+ 'Welcome to Midfield traveller, I am Casim - healer in these parts',
+ 'I am Casim the Healer here... how are you enjoying your stay at Midfield?'
+ ],
+ insufficient_money: [
+ 'Sorry friend, you don\'t have enough money',
+ 'Look.. I\'m sorry.. that won\'t be enough...'
+ ],
+ heal_successful: [
+ 'Glad to help!'
+ ]
+ },
+ [16]: {
+ intro: [
+ 'Ah, welcome to Wildegard, one of the few safehavens in the Akari Woods. I am Adovras, healer in these parts.',
+ 'Welcome traveller, I am Adovras - healer in these parts'
+ ],
+ insufficient_money: [
+ `Sorry friend, you don't have enough money...`
+ ],
+ heal_successful: [
+ "Hope this small healing will be helpful on your journeys"
+ ]
+
+ },
+ [11]: {
+ intro: [
+ 'Ah, welcome traveler - I am Uthar, healer of Davelfell',
+ 'Hello, I am Uthar, healer of Davelfell',
+ 'Sorry I\'m a bit busy today, I am Uthar, healer of Davelfell'
+ ],
+ insufficient_money: [
+ "Bah, don't bother me if you don't have the money",
+ "Look, I'm very busy - come back when you have the money"
+ ],
+ heal_successful: [
+ "*Fizz* *POOF* YOU'RE HEALED!"
+ ]
+ }
+}
+
+function getText(type: TextSegment, location: Location, city: City): string {
+ let selected = sample(defaultTexts[type]);
+
+ if(playerTexts[location.id]) {
+ if(playerTexts[location.id][type].length) {
+ selected = sample(playerTexts[location.id][type]);
+ }
+ }
+
+ return selected.replace("{{NAME}}", location.name).replace("{{CITY_NAME}}", city.name);
+
+}
+
+router.get('/city/services/healer/:location_id', authEndpoint, async (req: Request, res: Response) => {
+ const service = await getService(parseInt(req.params.location_id));
+ const city = await getCityDetails(service.city_id);
+
+ if(!service || service.city_id !== req.player.city_id) {
+ logger.log(`Invalid location: [${req.params.location_id}]`);
+ res.sendStatus(400);
+ }
+
+ const text: string[] = [];
+
+ text.push(`<p>"${getText('intro', service, city)}"</p>`);
+
+ if(req.player.hp === maxHp(req.player.constitution, req.player.level) && req.player.vigor === maxVigor(req.player.constitution, req.player.level)) {
+ text.push(`<p>You're already in peak condition!</p>`);
+ }
+ else {
+ if(req.player.gold <= (healCost * 2)) {
+ text.push(`<p>You don't seem to have too much money... I guess I can do it for free this time...</p>`);
+ text.push(`<p><button type="button" hx-post="/city/services/healer/heal/${service.id}" hx-target="#explore">Heal for Free!</button></p>`);
+ }
+ else {
+ text.push(`<p><button type="button" hx-post="/city/services/healer/heal/${service.id}" hx-target="#explore">Heal for ${healCost}g!</button></p>`);
+ }
+
+ }
+
+ res.send(`
+<div class="city-title-wrapper"><div class="city-title">${service.city_name}</div></div>
+<div class="city-details">
+<h3 class="location-name"><span>${service.name}</span></h3>
+<div class="service-in-town">
+${text.join("\n")}
+${BackToTown()}
+</div>
+</div>
+ `);
+
+ //res.send(`<div class="service-in-town">${text.join("\n")}</div>`);
+});
+
+
+
+router.post('/city/services/healer/heal/:location_id', authEndpoint, async (req: Request, res: Response) => {
+ const service = await getService(parseInt(req.params.location_id));
+ const city = await getCityDetails(service.city_id);
+
+ if(!service || service.city_id !== req.player.city_id) {
+ logger.log(`Invalid location: [${req.params.location_id}]`);
+ res.sendStatus(400);
+ }
+
+ const text: string[] = [];
+ const cost = req.player.gold <= (healCost * 2) ? 0 : healCost;
+
+ if(req.player.gold < cost) {
+ text.push(`<p>${getText('insufficient_money', service, city)}</p>`)
+ }
+ else {
+ req.player.hp = maxHp(req.player.constitution, req.player.level);
+ req.player.vigor = maxVigor(req.player.constitution, req.player.level);
+ req.player.gold -= cost;
+
+ await updatePlayer(req.player);
+
+ text.push(`<p>${getText('heal_successful', service, city)}</p>`);
+ }
+
+ res.send(`
+<div class="city-title-wrapper"><div class="city-title">${service.city_name}</div></div>
+<div class="city-details">
+<h3 class="location-name"><span>${service.name}</span></h3>
+<div class="service-in-town">
+${text.join("\n")}
+${BackToTown()}
+</div>
+</div>
+${renderPlayerBar(req.player)}
+`);
+});
+++ /dev/null
-import { Response, Router } from "express";
-import { maxHp, maxVigor } from "../../../shared/player";
-import { authEndpoint, AuthRequest } from '../../auth';
-import { logger } from "../../lib/logger";
-import { updatePlayer } from "../../player";
-import { getCityDetails, getService } from '../../map';
-import { sample } from 'lodash';
-import { City, Location } from "../../../shared/map";
-import { renderPlayerBar } from "../../views/player-bar";
-import { BackToTown } from "../../views/components/button";
-
-export const router = Router();
-
-type TextSegment = 'intro' | 'insufficient_money' | 'heal_successful';
-
-type HealText = Record<TextSegment, string[]>;
-
-const healCost = 10;
-
-const defaultTexts: HealText = {
- intro: [
- `Welcome traveller, I am {{NAME}}, Healer of {{CITY_NAME}}`,
- "Please come in traveller, I am {{NAME}}, Healer of {{CITY_NAME}}",
- ],
- insufficient_money: [
- "Sorry friend, you don't have enough money..",
- "Sorry, that won't be enough..",
- "Healing is hard work.. I'm afraid that won't cover it.."
- ],
- heal_successful: [
- "I hope you feel better now",
- "Good luck on your travels!",
- "Glad to be of service..."
- ]
-};
-
-// overrides for specific areas
-const playerTexts: Record<number, HealText> = {
- [8]: {
- intro: [
- 'Welcome to Midfield traveller, I am Casim - healer in these parts',
- 'I am Casim the Healer here... how are you enjoying your stay at Midfield?'
- ],
- insufficient_money: [
- 'Sorry friend, you don\'t have enough money',
- 'Look.. I\'m sorry.. that won\'t be enough...'
- ],
- heal_successful: [
- 'Glad to help!'
- ]
- },
- [16]: {
- intro: [
- 'Ah, welcome to Wildegard, one of the few safehavens in the Akari Woods. I am Adovras, healer in these parts.',
- 'Welcome traveller, I am Adovras - healer in these parts'
- ],
- insufficient_money: [
- `Sorry friend, you don't have enough money...`
- ],
- heal_successful: [
- "Hope this small healing will be helpful on your journeys"
- ]
-
- },
- [11]: {
- intro: [
- 'Ah, welcome traveler - I am Uthar, healer of Davelfell',
- 'Hello, I am Uthar, healer of Davelfell',
- 'Sorry I\'m a bit busy today, I am Uthar, healer of Davelfell'
- ],
- insufficient_money: [
- "Bah, don't bother me if you don't have the money",
- "Look, I'm very busy - come back when you have the money"
- ],
- heal_successful: [
- "*Fizz* *POOF* YOU'RE HEALED!"
- ]
- }
-}
-
-function getText(type: TextSegment, location: Location, city: City): string {
- let selected = sample(defaultTexts[type]);
-
- if(playerTexts[location.id]) {
- if(playerTexts[location.id][type].length) {
- selected = sample(playerTexts[location.id][type]);
- }
- }
-
- return selected.replace("{{NAME}}", location.name).replace("{{CITY_NAME}}", city.name);
-
-}
-
-router.get('/city/services/healer/:location_id', authEndpoint, async (req: AuthRequest, res: Response) => {
- const service = await getService(parseInt(req.params.location_id));
- const city = await getCityDetails(service.city_id);
-
- if(!service || service.city_id !== req.player.city_id) {
- logger.log(`Invalid location: [${req.params.location_id}]`);
- res.sendStatus(400);
- }
-
- const text: string[] = [];
-
- text.push(`<p>"${getText('intro', service, city)}"</p>`);
-
- if(req.player.hp === maxHp(req.player.constitution, req.player.level) && req.player.vigor === maxVigor(req.player.constitution, req.player.level)) {
- text.push(`<p>You're already in peak condition!</p>`);
- }
- else {
- if(req.player.gold <= (healCost * 2)) {
- text.push(`<p>You don't seem to have too much money... I guess I can do it for free this time...</p>`);
- text.push(`<p><button type="button" hx-post="/city/services/healer/heal/${service.id}" hx-target="#explore">Heal for Free!</button></p>`);
- }
- else {
- text.push(`<p><button type="button" hx-post="/city/services/healer/heal/${service.id}" hx-target="#explore">Heal for ${healCost}g!</button></p>`);
- }
-
- }
-
- res.send(`
-<div class="city-title-wrapper"><div class="city-title">${service.city_name}</div></div>
-<div class="city-details">
-<h3 class="location-name"><span>${service.name}</span></h3>
-<div class="service-in-town">
-${text.join("\n")}
-${BackToTown()}
-</div>
-</div>
- `);
-
- //res.send(`<div class="service-in-town">${text.join("\n")}</div>`);
-});
-
-
-
-router.post('/city/services/healer/heal/:location_id', authEndpoint, async (req: AuthRequest, res: Response) => {
- const service = await getService(parseInt(req.params.location_id));
- const city = await getCityDetails(service.city_id);
-
- if(!service || service.city_id !== req.player.city_id) {
- logger.log(`Invalid location: [${req.params.location_id}]`);
- res.sendStatus(400);
- }
-
- const text: string[] = [];
- const cost = req.player.gold <= (healCost * 2) ? 0 : healCost;
-
- if(req.player.gold < cost) {
- text.push(`<p>${getText('insufficient_money', service, city)}</p>`)
- }
- else {
- req.player.hp = maxHp(req.player.constitution, req.player.level);
- req.player.vigor = maxVigor(req.player.constitution, req.player.level);
- req.player.gold -= cost;
-
- await updatePlayer(req.player);
-
- text.push(`<p>${getText('heal_successful', service, city)}</p>`);
- }
-
- res.send(`
-<div class="city-title-wrapper"><div class="city-title">${service.city_name}</div></div>
-<div class="city-details">
-<h3 class="location-name"><span>${service.name}</span></h3>
-<div class="service-in-town">
-${text.join("\n")}
-${BackToTown()}
-</div>
-</div>
-${renderPlayerBar(req.player)}
-`);
-});
-import { Response, Router } from "express";
+import { Request, Response, Router } from "express";
import { getService } from "../map";
-import { authEndpoint, AuthRequest } from '../auth';
+import { authEndpoint } from '../auth';
import { logger } from "../lib/logger";
import * as Alert from "../views/alert";
import { changeProfession } from "../player";
const MIN_LEVEL = 25;
-router.get('/city/services/profession_recruitor/:location_id', authEndpoint, async(req: AuthRequest, res: Response) => {
+router.get('/city/services/profession_recruitor/:location_id', authEndpoint, async(req: Request, res: Response) => {
const service = await getService(parseInt(req.params.location_id));
if(!service || service.city_id !== req.player.city_id) {
`);
});
-router.post('/city/services/profession_change/:location_id', authEndpoint, async(req: AuthRequest, res: Response) => {
+router.post('/city/services/profession_change/:location_id', authEndpoint, async(req: Request, res: Response) => {
const service = await getService(parseInt(req.params.location_id));
if(!service || service.city_id !== req.player.city_id) {
-import { Response, Router } from "express";
-import { authEndpoint, AuthRequest } from '../auth';
+import { Request, Response, Router } from "express";
+import { authEndpoint } from '../auth';
import { logger } from "../lib/logger";
import { getService } from "../map";
import { getInventory, getInventoryItem, repair } from '../inventory';
export const router = Router();
-router.get('/city/services/repair/:location_id', authEndpoint, async(req: AuthRequest, res: Response) => {
+router.get('/city/services/repair/:location_id', authEndpoint, async(req: Request, res: Response) => {
const service = await getService(parseInt(req.params.location_id));
if(!service || service.city_id !== req.player.city_id) {
res.send(renderRepairService(damaged, req.player, service));
});
-router.post('/city/services/:location_id/repair/:item_id', authEndpoint, async (req: AuthRequest, res: Response) => {
+router.post('/city/services/:location_id/repair/:item_id', authEndpoint, async (req: Request, res: Response) => {
const service = await getService(parseInt(req.params.location_id));
if(!service || service.city_id !== req.player.city_id) {
import { db } from './lib/db';
-import { Fight, Monster, MonsterWithFaction, MonsterForList, FightTrigger } from '../shared/monsters';
+import { Fight, Monster, MonsterWithFaction, MonsterForList, FightTrigger, MonsterVariant, MonsterVariants } from '../shared/monsters';
import { TimePeriod, TimeManager } from '../shared/time';
-import { LocationWithCity } from 'shared/map';
+import { LocationWithCity } from '../shared/map';
+import { random, sample } from 'lodash';
+import { CHANCE_TO_FIGHT_SPECIAL } from '../shared/constants';
const time = new TimeManager();
.where({ location_id })
.whereIn('time_period', timePeriod)
.from<Monster>('monsters')
- .orderBy('level');
+ .orderBy('minLevel');
return res;
}
export async function loadMonsterWithFaction(player_id: string): Promise<MonsterWithFaction> {
const res = await db.raw(`
select
- f.*, fa.id as faction_id, fa.name as faction_name
+ f.*, fa.id as faction_id, fa.name as faction_name,
+ m.minLevel, m.maxLevel
from fight f
join monsters m on f.ref_id = m.id
left outer join factions fa on m.faction_id = fa.id
}
export async function createFight(playerId: string, monster: Monster, fightTrigger: FightTrigger): Promise<Fight> {
- const res = await db('fight').insert({
+ const chosenLevel = random(monster.minLevel, monster.maxLevel);
+ // 30% boost per level difference
+ const modifier = Math.pow(Math.E, (chosenLevel - monster.minLevel)/monster.maxLevel);
+ let variant: MonsterVariant = {
+ name: '',
+ display: '{{name}}',
+ strength: 1,
+ constitution: 1,
+ dexterity: 1,
+ intelligence: 1,
+ exp: 1,
+ gold: 1,
+ maxHp: 1,
+ defence: 1
+ };
+
+ if(monster.maxLevel >= 5 && random(0,100) <= CHANCE_TO_FIGHT_SPECIAL) {
+ variant = sample(MonsterVariants);
+ }
+
+ const monsterData: Omit<Fight, 'id'> = {
player_id: playerId,
- name: monster.name,
- strength: monster.strength,
- constitution: monster.constitution,
- dexterity: monster.dexterity,
- intelligence: monster.intelligence,
- exp: monster.exp,
- level: monster.level,
- gold: monster.gold,
- hp: monster.hp,
- defence: monster.defence,
- maxHp: monster.maxHp,
+ variant: variant.name,
+ name: variant.display.replace("{{name}}", monster.name),
+ strength: Math.floor(monster.strength * modifier * variant.strength),
+ constitution: Math.floor(monster.constitution * modifier * variant.constitution),
+ dexterity: Math.floor(monster.dexterity * modifier * variant.dexterity),
+ intelligence: Math.floor(monster.intelligence * modifier * variant.intelligence),
+ exp: Math.floor(monster.exp * modifier * variant.exp),
+ level: chosenLevel,
+ gold: Math.floor(monster.gold * modifier * variant.exp),
+ hp: Math.floor(monster.hp * modifier * variant.maxHp),
+ defence: Math.floor(monster.defence * modifier * variant.defence),
+ maxHp: Math.floor(monster.maxHp * modifier * variant.maxHp),
ref_id: monster.id,
fight_trigger: fightTrigger
- }).returning<Fight[]>('*');
+ }
+
+ const res = await db('fight').insert(monsterData)
+ .returning<Fight[]>('*');
return res.pop();
}
import { FightRound } from "shared/fight";
import { LocationWithCity } from "shared/map";
-import { MonsterForFight } from "../../shared/monsters";
+import { Fight, MonsterForFight } from "../../shared/monsters";
import { Button, ButtonWithBlock } from "./components/button";
export function renderRoundDetails(roundData: FightRound): string {
}
}
-export function renderFight(monster: MonsterForFight, results: string = '', displayFightActions: boolean = true, blockTime: number = 0) {
+export function renderFight(monster: Fight, results: string = '', displayFightActions: boolean = true, blockTime: number = 0) {
const hpPercent = Math.floor((monster.hp / monster.maxHp) * 100);
let html = `
<img id="avatar" src="https://via.placeholder.com/64x64">
</div>
<div id="defender-stat-bars">
- <div id="defender-name">${monster.name}</div>
+ <div class="monster-identifier ${monster.variant}"><span id="defender-name">${monster.name}</span>, level ${monster.level}</div>
<div class="progress-bar" id="defender-hp-bar" style="background: linear-gradient(to right, red, red ${hpPercent}%, transparent ${hpPercent}%, transparent)" title="${hpPercent}% - ${monster.hp}/${monster.maxHp}">${hpPercent}% - ${monster.hp} / ${monster.maxHp}</div>
</div>
</div>
<div id="fight-actions">
${displayFightActions ? `
<form hx-post="/fight/turn" hx-target="#fight-container">
- <select id="fight-target" name="fightTarget">
- <option value="head">Head</option>
- <option value="body">Body</option>
- <option value="arms">Arms</option>
- <option value="legs">Legs</option>
- </select>
${AttackButton(blockTime)}
${CastButton(blockTime)}
<button type="submit" class="fight-action" name="action" value="flee">Flee</button>
return html;
}
-export function renderFightPreRound(monster: MonsterForFight, displayFightActions: boolean = true, location: LocationWithCity, closestTown: number) {
- const hpPercent = Math.floor((monster.hp / monster.maxHp) * 100);
-
+export function renderFightPreRound(monster: Fight, displayFightActions: boolean = true, location: LocationWithCity, closestTown: number) {
let html = `
<section id="explore" class="tab active" style="background-image: url('/assets/img/map/${closestTown}.jpeg')" hx-swap-oob="true">
<div class="city-title-wrapper">
<div class="city-details">
<h3 class="location-name"><span>${location.name}</span></h3>
- <div id="fight-container">
- <div id="defender-info">
- <div class="avatar-container">
- <img id="avatar" src="https://via.placeholder.com/64x64">
- </div>
- <div id="defender-stat-bars">
- <div id="defender-name">${monster.name}</div>
- <div class="progress-bar" id="defender-hp-bar" style="background: linear-gradient(to right, red, red ${hpPercent}%, transparent ${hpPercent}%, transparent)" title="${hpPercent}% - ${monster.hp}/${monster.maxHp}">${hpPercent}% - ${monster.hp} / ${monster.maxHp}</div>
- </div>
- </div>
- <div id="fight-actions">
- ${displayFightActions ? `
- <form hx-post="/fight/turn" hx-target="#fight-container">
- <select id="fight-target" name="fightTarget">
- <option value="head">Head</option>
- <option value="body">Body</option>
- <option value="arms">Arms</option>
- <option value="legs">Legs</option>
- </select>
- ${AttackButton()}
- ${CastButton()}
- <button type="submit" class="fight-action" name="action" value="flee">Flee</button>
- </form>
- `: ''}
- </div>
- <div id="fight-results"></div>
+ ${renderFight(monster, '', displayFightActions)}
</div>
-</div>
</section>
`;
}
function renderInventorySection(inventory: EquippedItemDetails[]): string {
+ const used_slots = inventory.filter(i => i.is_equipped).map(i => i.equipment_slot);
+
return inventory.map(item => {
return renderInventoryItem(item, item => {
if(item.is_equipped) {
return `<button type="button" class="unequip-item red" hx-post="/player/unequip/${item.item_id}">Unequip</button>`;
}
else {
- if(item.equipment_slot === 'ANY_HAND') {
- return `<button type="button" class="equip-item" hx-post="/player/equip/${item.item_id}/LEFT_HAND">Equip L</button>
-<button type="button" class="equip-item" hx-post="/player/equip/${item.item_id}/RIGHT_HAND">Equip R</button>`;
- }
- else if(item.equipment_slot === 'LEFT_HAND') {
- return `<button type="button" class="equip-item" hx-post="/player/equip/${item.item_id}/${item.equipment_slot}">Equip Left</button>`;
- }
- else if(item.equipment_slot === 'RIGHT_HAND') {
- return `<button type="button" class="equip-item" hx-post="/player/equip/${item.item_id}/${item.equipment_slot}">Equip Right</button>`;
+ if(['ANY_HAND', 'LEFT_HAND', 'RIGHT_HAND'].includes(item.equipment_slot)) {
+ const str: string[] = [
+ `<button type="button" class="equip-item" hx-post="/player/equip/${item.item_id}/LEFT_HAND">Equip L</button>`,
+ `<button type="button" class="equip-item" hx-post="/player/equip/${item.item_id}/RIGHT_HAND">Equip R</button>`
+ ];
+
+ if(used_slots.includes('LEFT_HAND') && !used_slots.includes('RIGHT_HAND')) {
+ return str[1];
+ }
+ else if(used_slots.includes('RIGHT_HAND') && !used_slots.includes('LEFT_HAND')) {
+ return str[0];
+ }
+ else if(used_slots.includes('LEFT_HAND') && used_slots.includes('RIGHT_HAND')) {
+ return "";
+ }
+ return str.join("");
}
else {
return `<button type="button" class="equip-item" hx-post="/player/equip/${item.item_id}/${item.equipment_slot}">Equip</button>`;
<div class="service-in-town"><form id="fight-selector" hx-post="/fight" hx-target="#explore">
<input type="hidden" name="fightTrigger" value="explore">
<select id="monsterId" name="monsterId">
- ${monsters.map((monster: (Monster | MonsterForFight)) => {
- const range = [monster.level, monster.level + 3];
- return `<option value="${monster.id}" ${monster.id === activeMonsterId ? 'selected': ''}>${monster.name} (${range[0]} - ${range[1]})</option>`;
+ ${monsters.map((monster: (any)) => {
+ const range = [monster?.minLevel, monster?.maxLevel];
+ return `<option value="${monster.id}" ${monster.id === activeMonsterId ? 'selected': ''}>${monster.name} (LVL ${range[0]} - ${range[1]})</option>`;
}).join("\n")}
</select> <button type="submit" class="red">Fight</button></form>
<br><br>
export const FIGHT_ATTACK_DELAY = 1500;
export const STEP_DELAY = 2000;
export const ALERT_DISPLAY_LENGTH = 3000;
+// this is displayed as a percentage out of 100
+export const CHANCE_TO_FIGHT_SPECIAL = 100;
-import {FightTrigger, MonsterWithFaction} from "./monsters"
+import {Fight, FightTrigger, MonsterWithFaction} from "./monsters"
import {Player} from "./player"
export type FightReward = {
}
export type FightRound = {
- monster: MonsterWithFaction,
+ monster: Fight,
player: Player,
fightTrigger: FightTrigger,
winner: 'player' | 'monster' | 'in-progress',
dexterity: number;
intelligence: number;
constitution: number;
- level: number;
+ minLevel: number;
+ maxLevel: number;
gold: number;
exp: number;
hp: number;
export type FightTrigger = 'explore' | 'travel';
-export type Fight = Omit<Monster, 'id' | 'faction_id' | 'location_id'> & {
- id: string,
- player_id: string,
- ref_id: number
- fight_trigger: FightTrigger
+export type Fight = Omit<Monster, 'id' | 'faction_id' | 'location_id' | 'minLevel' | 'maxLevel' | 'time_period'> & {
+ id: string;
+ player_id: string;
+ variant: string;
+ level: number;
+ ref_id: number;
+ fight_trigger: FightTrigger;
};
export type MonsterWithFaction = Fight & {
hp: number;
maxHp: number;
name: string;
- level: number;
+ minLevel: number;
+ maxLevel: number;
fight_trigger: FightTrigger;
}
+
+export type MonsterVariant = {
+ name: string;
+ display: string;
+ strength: number;
+ constitution: number;
+ dexterity: number;
+ intelligence: number;
+ exp: number;
+ gold: number;
+ maxHp: number;
+ defence: number;
+};
+
+export const MonsterVariants: MonsterVariant[] = [
+ {
+ name: 'Brute',
+ display: '{{name}} Brute',
+ strength: 1,
+ constitution: 1,
+ dexterity: 0.6,
+ intelligence: 0.2,
+ exp: 4,
+ gold: 3,
+ maxHp: 2,
+ defence: 3
+ },
+ {
+ name: 'Elder',
+ display: 'Elder {{name}}',
+ strength: 0.8,
+ constitution: 1.2,
+ dexterity: 0.6,
+ intelligence: 1.6,
+ exp: 2,
+ gold: 1,
+ maxHp: 1,
+ defence: 1
+ },
+ {
+ name: 'Skittish',
+ display: 'Skittish {{name}}',
+ strength: 0.8,
+ constitution: 1.2,
+ dexterity: 0.6,
+ intelligence: 1.6,
+ exp: 1,
+ gold: 1.2,
+ maxHp: 1,
+ defence: 0.8
+ }
+];
--- /dev/null
+import { Player } from '../../shared/player';
+
+declare module 'express-serve-static-core' {
+ interface Request {
+ player: Player
+ }
+}
{
- "compilerOptions": {
- "module": "commonjs",
- "esModuleInterop": true,
- "target": "es6",
- "moduleResolution": "node",
- "removeComments": true,
- "preserveConstEnums": true,
- "sourceMap": true,
- "baseUrl": "src",
- "outDir": "dist",
- "emitDecoratorMetadata": true,
- "experimentalDecorators": true,
- "resolveJsonModule": true
- },
- "include": ["src/server/api.ts"]
+ "compilerOptions": {
+ "module": "commonjs",
+ "esModuleInterop": true,
+ "target": "es6",
+ "moduleResolution": "node",
+ "removeComments": true,
+ "preserveConstEnums": true,
+ "sourceMap": true,
+ "baseUrl": "src",
+ "outDir": "dist",
+ "emitDecoratorMetadata": true,
+ "experimentalDecorators": true,
+ "resolveJsonModule": true,
+ "typeRoots": ["./src/types"],
+ },
+ "include": ["src/server/api.ts"]
}