1 import { io } from 'socket.io-client';
2 import $ from 'jquery';
3 import {expToLevel, maxHp, Player, StatDef, StatDisplay} from '../shared/player';
4 import { authToken, http } from './http';
5 import { CustomEventManager } from './events';
6 import {Fight, FightTrigger, MonsterForFight, MonsterForList} from '../shared/monsters';
7 import {FightRound} from '../shared/fight';
8 import { City, Location, LocationType, Path } from '../shared/map'
9 import { v4 as uuid } from 'uuid';
10 import {EquipmentSlot, ShopItem} from '../shared/inventory';
11 import { each } from 'lodash';
12 import {EquippedItemDetails} from '../shared/equipped';
13 import { Skill, Skills } from '../shared/skills';
14 import { configureChat } from './chat';
15 import { SocketEvent } from './socket-event.client';
16 import * as EventList from '../events/client';
17 import { TimeManager } from '../shared/time';
18 import { TravelDTO } from '../events/travel/shared';
21 const time = new TimeManager();
22 const cache = new Map<string, any>();
23 const events = new CustomEventManager();
26 'x-authtoken': authToken()
30 configureChat(socket);
32 function setTimeGradient() {
33 const gradientName = time.gradientName();
34 const $body = $('body');
35 $body.removeClass(Array.from($body[0].classList)).addClass(gradientName);
37 $body.addClass('night');
42 setInterval(setTimeGradient, 60 * 1000);
44 function icon(name: string): string {
45 return `<img src="/assets/img/${name}.png" class="icon">`;
49 function generateProgressBar(current: number, max: number, color: string, displayPercent: boolean = true): string {
52 percent = Math.floor((current / max) * 100);
54 const display = `${displayPercent? `${percent}% - `: ''}`;
55 return `<div class="progress-bar" style="background: linear-gradient(to right, ${color}, ${color} ${percent}%, transparent ${percent}%, transparent)" title="${display}${current}/${max}">${display}${current}/${max}</div>`;
58 function progressBar(current: number, max: number, el: string, color: string) {
61 percent = Math.floor((current / max) * 100);
65 `linear-gradient(to right, ${color}, ${color} ${percent}%, transparent ${percent}%, transparent)`
66 ).attr('title', `${percent}% - ${current}/${max}`).html(`${current}/${max} - ${percent}%`);
69 function updatePlayer() {
70 const player: Player = cache.get('player');
72 $('#username').html(`${player.username}, level ${player.level} ${player.profession}`);
76 maxHp(player.constitution, player.level),
83 expToLevel(player.level + 1),
88 ['strength', 'constitution', 'dexterity', 'intelligence','hp','exp'].forEach(s => {
89 $(`.${s}`).html(player[s]);
92 $('.maxHp').html(maxHp(player.constitution, player.level).toString());
93 $('.expToLevel').html(expToLevel(player.level + 1).toString());
94 $('.gold').html(player.gold.toLocaleString());
96 if(player.account_type === 'session') {
97 $('#signup-prompt').html(`<p>Hey there! It looks like you're using a SESSION account. This allows you to play with away, but the account is tied to your current device, and will be lost if you ever clear your cookies.</p><p>
99 <div class="form-group">
100 <label>Username:</label>
101 <input type="text" name="username">
103 <div class="form-group">
104 <label>Password:</label>
105 <input type="password" name="password">
107 <button type="submit" class="success">Create your Account</button>
108 <button type="button" id="login">Login To Existing Account</button>
109 </form></p>`).removeClass('hidden');
112 $('#extra-inventory-info').html(renderStatDetails());
115 socket.on('connect', () => {
116 console.log(`Connected: ${socket.id}`);
119 socket.on('ready', bootstrap);
121 socket.on('server-stats', (data: {onlinePlayers: number}) => {
122 $('#server-stats').html(`${data.onlinePlayers} players online`);
125 each(EventList, event => {
126 console.log(`Binding Event ${event.eventName}`);
127 if(event instanceof SocketEvent) {
128 socket.on(event.eventName, event.handler.bind(null, {
135 console.log('Skipped binding', event);
139 socket.on('calc:ap', (data: {ap: Record<EquipmentSlot, { currentAp: number, maxAp: number}>}) => {
144 ${generateProgressBar(ap.HEAD?.currentAp || 0, ap.HEAD?.maxAp || 0, '#7be67b')}
148 ${generateProgressBar(ap.ARMS?.currentAp || 0, ap.ARMS?.maxAp || 0, '#7be67b')}
152 ${generateProgressBar(ap.CHEST?.currentAp || 0, ap.CHEST?.maxAp || 0, '#7be67b')}
156 ${generateProgressBar(ap.LEGS?.currentAp || 0, ap.LEGS?.maxAp || 0, '#7be67b')}
159 $('#ap-bar').html(html);
162 events.on('tab:skills', () => {
163 $('#skills').html('');
164 socket.emit('skills');
167 socket.on('skills', (data: {skills: Skill[]}) => {
168 let html = `<table id="skill-list">
169 ${data.skills.map((skill: Skill) => {
170 const definition = Skills.get(skill.id);
171 const percent = skill.exp / definition.expToLevel(skill.level + 1);
174 <td class="skill-level">${skill.level.toLocaleString()}</td>
175 <td class="skill-description" title="Total Exp: ${skill.exp.toLocaleString()}/${definition.expToLevel(skill.level + 1).toLocaleString()}">
176 <span class="skill-exp">${(percent * 100).toPrecision(2)}% to next level</span>
177 <b>${definition.display}</b>
178 <p>${definition.description}</p>
185 $('#skills').html(html);
188 function Alert(text: string, type: string = 'error') {
190 $('#alerts').append(`<div class="alert ${type}" id="alert-${id}">${text}</div>`);
193 $(`#alert-${id}`).remove();
197 events.on('alert', (data: {type: string, text: string}) => {
198 Alert(data.text, data.type);
201 socket.on('alert', data => {
202 events.emit('alert', [data]);
205 socket.on('init', (data: {version: string}) => {
206 $('#version').html(`v${data.version}`);
209 socket.on('authToken', (authToken: string) => {
210 console.log(`recv auth token ${authToken}`);
211 localStorage.setItem('authToken', authToken);
215 socket.on('player', (player: Player) => {
216 cache.set('player', player);
220 async function fetchState() {
221 const res = await http.get('/state');
222 cache.set('state', res);
225 $('nav a').on('click', async e => {
229 const tabsDisabledInFight = [
235 const state = cache.get('state');
237 const $tabContainer = $(`#${$(e.target).data('container')}`);
238 let tabSection = $(e.target).data('section');
240 if(tabsDisabledInFight.includes(tabSection) && state?.fight !== null) {
241 Alert('You are currently in a fight', 'error');
242 // we want to force users over to the explore tab
243 // if they are currently in a fight and trying to
244 // access a disabled section
245 tabSection = 'explore';
248 $tabContainer.find('.tab').removeClass('active');
250 $(`#${tabSection}`).addClass('active');
252 if(e.target.innerHTML !== 'Settings') {
253 $(e.target).closest('nav').find('a').removeClass('active');
254 $(`nav a[data-section=${tabSection}]`).addClass('active');
257 events.emit(`tab:${tabSection}`);
260 events.on('tab:inventory', () => {
261 socket.emit('inventory');
264 function renderEquipmentPlacementGrid(items: EquippedItemDetails[]) {
265 const placeholder = 'https://via.placeholder.com/64x64';
267 const map: Record<EquipmentSlot, EquippedItemDetails> = items.filter(item => item.is_equipped).reduce((acc, item) => {
268 acc[item.equipment_slot] = item;
273 <table id="character-equipment-placement">
277 <td style="background-image: url('${placeholder}');" title="${map.HEAD ? map.HEAD.name : 'Empty'}">
278 ${map.HEAD ? map.HEAD.name : 'HEAD'}
280 <td style="background-image: url('${placeholder}');" title="${map.ARMS ? map.ARMS.name : 'Empty'}">
281 ${map.ARMS ? map.ARMS.name : 'ARMS'}
285 <td style="background-image: url('${placeholder}');" title="${map.LEFT_HAND ? map.LEFT_HAND.name : (map.TWO_HANDED ? map.TWO_HANDED.name : '')}">
286 ${map.LEFT_HAND ? map.LEFT_HAND.name : (map.TWO_HANDED ? map.TWO_HANDED.name : 'L_HAND')}
288 <td style="background-image: url('${placeholder}');" title="${map.CHEST ? map.CHEST.name : ''}">
289 ${map.CHEST ? map.CHEST.name : 'CHEST'}
291 <td style="background-image: url('${placeholder}');" title="${map.RIGHT_HAND ? map.RIGHT_HAND.name : (map.TWO_HANDED ? map.TWO_HANDED.name : '')}">
292 ${map.RIGHT_HAND ? map.RIGHT_HAND.name : (map.TWO_HANDED ? map.TWO_HANDED.name : 'R_HAND')}
298 <td style="background-image: url('${placeholder}');" title="${map.LEGS ? map.LEGS.name : ''}">
299 ${map.LEGS ? map.LEGS.name : 'LEGS'}
309 function statPointIncreaser(stat: StatDisplay) {
310 return `<button class="increase-stat emit-event" data-event="spend-stat-point" data-args="${stat.id}">+</button>`;
312 function renderStatDetails() {
313 const player: Player = cache.get('player');
314 let html = '<table id="stat-breakdown">';
316 StatDef.forEach(stat => {
318 <th>${stat.display}</th>
319 <td class="${stat.id}">
321 ${player.stat_points ? statPointIncreaser(stat) : ''}
326 html += `<tr><th>Stat Points</th><td class="stat_points">${player.stat_points}</td></tr>`;
333 $('body').on('click', 'nav.filter', e => {
337 const $target = $(e.target);
338 const filter = $target.data('filter');
340 $('.filter-result').removeClass('active').addClass('hidden');
341 $(`#filter_${filter}`).addClass('active').removeClass('hidden');
343 $target.closest('nav').find('a').removeClass('active');
344 $target.addClass('active');
346 cache.set('active-inventory-section', filter);
349 function renderInventorySection(inventory: EquippedItemDetails[]): string {
350 return inventory.map(item => {
351 return renderInventoryItem(item, item => {
352 if(item.is_equipped) {
353 return `<button type="button" class="unequip-item error" data-id="${item.item_id}">Unequip</button>`;
356 if(item.equipment_slot === 'ANY_HAND') {
357 return `<button type="button" class="equip-item" data-id="${item.item_id}" data-slot="LEFT_HAND">Equip L</button>
358 <button type="button" class="equip-item" data-id="${item.item_id}" data-slot="RIGHT_HAND">Equip R</button>`;
360 else if(item.equipment_slot === 'LEFT_HAND') {
361 return `<button type="button" class="equip-item" data-id="${item.item_id}" data-slot="${item.equipment_slot}">Equip Left</button>`;
363 else if(item.equipment_slot === 'RIGHT_HAND') {
364 return `<button type="button" class="equip-item" data-id="${item.item_id}" data-slot="${item.equipment_slot}">Equip Right</button>`;
366 else if(item.equipment_slot === 'TWO_HANDED') {
367 return `<button type="button" class="equip-item" data-id="${item.item_id}" data-slot="${item.equipment_slot}">Equip</button>`;
370 return `<button type="button" class="equip-item" data-id="${item.item_id}" data-slot="${item.equipment_slot}">Equip</button>`;
377 socket.on('inventory', (data: {inventory: EquippedItemDetails[]}) => {
378 const player: Player = cache.get('player');
379 const activeSection = cache.get('active-inventory-section') || 'ARMOUR';
380 // split the inventory into sections!
381 const sectionedInventory: {ARMOUR: EquippedItemDetails[], WEAPON: EquippedItemDetails[], SPELL: EquippedItemDetails[]} = {
387 data.inventory.forEach(item => {
388 sectionedInventory[item.type].push(item);
392 <div id="inventory-page">
393 <div id="character-summary">
394 ${renderEquipmentPlacementGrid(data.inventory)}
395 <div id="extra-inventory-info">
396 ${renderStatDetails()}
399 <div id="inventory-section">
401 <a href="#" data-filter="ARMOUR" class="${activeSection === 'ARMOUR' ? 'active': ''}">Armour</a>
402 <a href="#" data-filter="WEAPON" class="${activeSection === 'WEAPON' ? 'active': ''}">Weapons</a>
403 <a href="#" data-filter="SPELL" class="${activeSection === 'SPELL' ? 'active': ''}">Spells</a>
405 <div class="inventory-listing">
406 <div class="filter-result ${activeSection === 'ARMOUR' ? 'active' : 'hidden'}" id="filter_ARMOUR">
407 ${renderInventorySection(sectionedInventory.ARMOUR)}
409 <div class="filter-result ${activeSection === 'WEAPON' ? 'active' : 'hidden'}" id="filter_WEAPON">
410 ${renderInventorySection(sectionedInventory.WEAPON)}
412 <div class="filter-result ${activeSection === 'SPELL' ? 'active' : 'hidden'}" id="filter_SPELL">
413 ${renderInventorySection(sectionedInventory.SPELL)}
419 $('#inventory').html(html);
422 $('body').on('click', '.equip-item', e => {
426 const $target = $(e.target);
427 const id = $target.data('id');
428 const slot = $target.data('slot');
430 socket.emit('equip', {id, slot});
433 $('body').on('click', '.unequip-item', e => {
437 socket.emit('unequip', { id: $(e.target).data('id') });
440 function setMapBackground(city_id: number) {
442 'background-image': `linear-gradient(to left top, rgba(255,255,255,0) 0%,rgb(255,255,255) 100%), linear-gradient(to left, rgba(255, 255, 255, 0) 0%, rgb(255, 255, 255) 100%), url("/assets/img/map/${city_id}.jpeg")`
446 events.on('renderMap', async function renderMap(data: { city: City, locations: Location[], paths: Path[]}) {
447 if(!data && cache.has('currentMapHTML')) {
448 $('#map').html(cache.get('currentMapHTML'));
453 console.error('oh no.. this got triggered without any city data');
456 setMapBackground(data.city.id);
458 const servicesParsed: Record<LocationType, string[]> = {
464 data.locations.forEach(l => {
465 servicesParsed[l.type].push(`<a href="#" class="city-emit-event" data-event="${l.event_name}" data-args="${l.id}">${l.name}</a>`);
468 let html = `<h1>${data.city.name}</h1>
469 <div class="city-details">`;
471 if(servicesParsed.SERVICES.length) {
472 html += `<div><h3>Services</h3>${servicesParsed.SERVICES.join("<br>")}</div>`
474 if(servicesParsed.STORES.length) {
475 html += `<div><h3>Stores</h3>${servicesParsed.STORES.join("<br>")}</div>`
477 if(servicesParsed.EXPLORE.length) {
478 html += `<div><h3>Explore</h3>${servicesParsed.EXPLORE.join("<br>")}</div>`
483 ${data.paths.map(path => {
484 return `<a href="#" class="city-emit-event" data-event="city:travel" data-args="${path.ending_city}">${path.ending_city_name}</a>`
490 cache.set('currentMapHTML', html);
492 $('#map').html(html);
495 function renderRequirement(name: string, val: number | string, currentVal?: number): string {
496 let colorIndicator = '';
498 colorIndicator = currentVal >= val ? 'success' : 'error';
500 return `<span class="requirement-title">${name}</span>: <span class="requirement-value ${colorIndicator}">${val.toLocaleString()}</span>`;
503 function renderStatBoost(name: string, val: number | string): string {
504 let valSign: string = '';
505 if(typeof val === 'number') {
506 valSign = val > 0 ? '+' : '-';
508 return `<span class="requirement-title">${name}</span>: <span class="requirement-value ${typeof val === 'number' ? (val > 0 ? "success": "error") : ""}">${valSign}${val}</span>`;
511 function renderInventoryItem(item: EquippedItemDetails , action: (item: EquippedItemDetails) => string): string {
512 return `<div class="store-list">
514 <img src="https://via.placeholder.com/64x64">
516 <div class="details">
517 <div class="name">${item.name}</div>
518 <div class="requirements">
519 ${item.requirements.level ? renderRequirement('LVL', item.requirements.level): ''}
520 ${item.requirements.strength ? renderRequirement('STR', item.requirements.strength): ''}
521 ${item.requirements.constitution ? renderRequirement('CON', item.requirements.constitution): ''}
522 ${item.requirements.dexterity ? renderRequirement('DEX', item.requirements.dexterity): ''}
523 ${item.requirements.intelligence ? renderRequirement('INT', item.requirements.intelligence): ''}
524 ${renderRequirement('PRF', item.profession)}
526 <div class="stat-mods">
527 ${item.boosts.strength ? renderStatBoost('STR', item.boosts.strength) : ''}
528 ${item.boosts.constitution ? renderStatBoost('CON', item.boosts.constitution) : ''}
529 ${item.boosts.dexterity ? renderStatBoost('DEX', item.boosts.dexterity) : ''}
530 ${item.boosts.intelligence ? renderStatBoost('INT', item.boosts.intelligence) : ''}
531 ${item.boosts.damage ? renderStatBoost('DMG', item.boosts.damage) : ''}
532 ${item.boosts.damage_mitigation ? renderStatBoost('MIT', item.boosts.damage_mitigation.toString())+'%' : ''}
533 ${['WEAPON','SPELL'].includes(item.type) ? '': generateProgressBar(item.currentAp, item.maxAp, '#7be67b')}
535 ${item.hasOwnProperty('id') ? `<div>${item.cost.toLocaleString()}G</div>` : ''}
537 <div class="store-actions">
543 function renderShopItem(item: ShopItem, action: (item: ShopItem) => string): string {
544 const player: Player = cache.get('player');
545 return `<div class="store-list">
547 <img src="https://via.placeholder.com/64x64">
549 <div class="details">
550 <div class="name">${item.name}${item.equipment_slot === 'TWO_HANDED' ? ' (2H)': ''}</div>
551 <div class="requirements">
552 ${item.requirements.level ? renderRequirement('LVL', item.requirements.level, player.level): ''}
553 ${item.requirements.strength ? renderRequirement('STR', item.requirements.strength, player.strength): ''}
554 ${item.requirements.constitution ? renderRequirement('CON', item.requirements.constitution, player.constitution): ''}
555 ${item.requirements.dexterity ? renderRequirement('DEX', item.requirements.dexterity, player.dexterity): ''}
556 ${item.requirements.intelligence ? renderRequirement('INT', item.requirements.intelligence, player.intelligence): ''}
557 ${renderRequirement('PRF', item.profession)}
559 <div class="stat-mods">
560 ${item.boosts.strength ? renderStatBoost('STR', item.boosts.strength) : ''}
561 ${item.boosts.constitution ? renderStatBoost('CON', item.boosts.constitution) : ''}
562 ${item.boosts.dexterity ? renderStatBoost('DEX', item.boosts.dexterity) : ''}
563 ${item.boosts.intelligence ? renderStatBoost('INT', item.boosts.intelligence) : ''}
564 ${item.boosts.damage ? renderStatBoost(item.affectedSkills.includes('restoration_magic') ? 'HP' : 'DMG', item.boosts.damage) : ''}
565 ${item.boosts.damage_mitigation ? renderStatBoost('MIT', item.boosts.damage_mitigation.toString())+'%' : ''}
566 ${['WEAPON','SPELL'].includes(item.type) ? '' : renderStatBoost('AP', item.maxAp.toString())}
568 ${item.hasOwnProperty('id') ? `<div>${item.cost.toLocaleString()}G</div>` : ''}
570 <div class="store-actions">
577 socket.on('city:stores', (data: ShopItem[]) => {
578 let html = `<div class="shop-inventory-listing">
580 return renderShopItem(item, i => {
581 const id = `data-id="${i.id}"`;
582 return `<button type="button" class="purchase-item" ${id} data-type="${i.type}" data-equipment-slot="${i.equipment_slot}" data-cost="${i.cost}">Buy</button>`
588 $('#map').html(html);
592 $('body').on('click', '.purchase-item', e => {
596 const player = cache.get('player');
597 const cost = parseInt($(e.target).data('cost'));
600 const id = $(e.target).data('id');
601 if(player.gold < cost) {
602 events.emit('alert', [{
604 text: 'You don\'t have enough gold!'
609 const type = $(e.target).data('type');
610 socket.emit('purchase', {
616 $('body').on('click', '.emit-event', e => {
617 const $el = $(e.target);
619 const eventName = $el.data('event');
620 const args = $el.data('args');
622 console.log(`Sending event ${eventName}`, { args });
623 socket.emit(eventName, { args });
626 $('body').on('click', '.city-emit-event', e => {
627 const $el = $(e.target);
629 const eventName = $el.data('event');
630 const args = $el.data('args');
632 console.log(`Sending event ${eventName}`, { args });
633 socket.emit(eventName, { args });
636 $('body').on('click', '.emit-event-internal', e => {
637 const $el = $(e.target);
639 const eventName = $el.data('event');
640 const args: string[] = $el.data('args')?.toString().split('|');
642 console.log(`Trigger internal event [${eventName}]`);
643 events.emit(eventName, args);
647 socket.on('explore:fights', (monsters: MonsterForList[]) => {
648 const lastSelectedMonster = cache.get('last-selected-monster');
649 if(monsters.length) {
650 let sel = `<form id="fight-selector"><select id="monster-selector">
651 ${monsters.map(monster => {
652 return `<option value="${monster.id}" ${lastSelectedMonster == monster.id ? 'selected': ''}>${monster.name}</option>`;
654 </select> <button type="submit">Fight</button></option>`;
660 events.on('tab:explore', async () => {
661 const state = cache.get('state');
662 if(cache.get('player').hp <= 0 || (!state.fight && !state.travel)) {
663 // get the details of the city
665 let data: {city: City, locations: Location[], paths: Path[]};
666 if(!cache.has(('currentMapHTML')) || cache.get('player').hp <= 0) {
667 data = await http.get(`/city/${cache.get('player').city_id}`);
669 events.emit('renderMap', [data, state.travel]);
672 else if(state.fight) {
673 setMapBackground(state.closestTown);
674 $('#map').html(renderFight(state.fight));
676 else if(state.travel) {
678 events.emit('renderTravel', [state.travel]);
682 function renderTravel(data: TravelDTO) {
683 setMapBackground(data.closestTown);
684 let html = `<button class="emit-event" data-event="travel:step">Keep Walking</button>`;
687 if(data.things.length) {
688 // ok you found something, for now we only support
689 // monsters, but eventually that will change
690 html += `<button class="emit-event-internal" data-event="startFight" data-args="${data.things[0].id}|travel">Fight</button>`;
691 html += `<p>You see a ${data.things[0].name}.</p>`;
694 else if(data.walkingText) {
695 html += `<p>${data.walkingText}</p>`;
698 $('#map').html(html);
701 events.on('renderTravel', renderTravel);
703 function renderFight(monster: MonsterForFight | Fight) {
704 const hpPercent = Math.floor((monster.hp / monster.maxHp) * 100);
706 let html = `<div id="fight-container">
707 <div id="defender-info">
708 <div class="avatar-container">
709 <img id="avatar" src="https://via.placeholder.com/64x64">
711 <div id="defender-stat-bars">
712 <div id="defender-name">${monster.name}</div>
713 <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>
716 <div id="fight-actions">
717 <select id="fight-target">
718 <option value="head">Head</option>
719 <option value="body">Body</option>
720 <option value="arms">Arms</option>
721 <option value="legs">Legs</option>
723 <button type="button" class="fight-action" data-action="attack">Attack</button>
724 <button type="button" class="fight-action" data-action="cast">Cast</button>
725 <button type="button" class="fight-action" data-action="flee">Flee</button>
727 <div id="fight-results"></div>
733 socket.on('updatePlayer', (player: Player) => {
734 cache.set('player', player);
738 socket.on('fight-over', (data: {roundData: FightRound, monsters: MonsterForFight[]}) => {
739 const { roundData, monsters } = data;
740 cache.set('player', roundData.player);
743 $('#map').html(renderFight(roundData.monster));
745 let html: string[] = roundData.roundDetails.map(d => `<div>${d}</div>`);
747 if(roundData.winner === 'player') {
748 html.push(`<div>You defeated the ${roundData.monster.name}!</div>`);
749 if(roundData.rewards.gold) {
750 html.push(`<div>You gained ${roundData.rewards.gold} gold`);
752 if(roundData.rewards.exp) {
753 html.push(`<div>You gained ${roundData.rewards.exp} exp`);
755 if(roundData.rewards.levelIncrease) {
756 html.push(`<div>You gained a level! ${roundData.player.level}`);
760 if(roundData.player.hp === 0) {
761 // prompt to return to town and don't let them do anything
762 html.push(`<p>You were killed...</p>`);
763 html.push('<p><button class="emit-event-internal" data-event="tab:explore" data-args="">Back to Town</button></p>');
766 switch(roundData.fightTrigger) {
768 if(monsters.length) {
769 const lastSelectedMonster = cache.get('last-selected-monster');
770 // put this above the fight details
771 html.unshift(`<h2>Fight Again</h2><form id="fight-selector"><select id="monster-selector">
772 ${monsters.map(monster => {
773 return `<option value="${monster.id}" ${lastSelectedMonster == monster.id ? 'selected': ''}>${monster.name}</option>`;
775 </select> <button type="submit">Fight</button></option>
776 </select></form><hr>`);
780 html.push(`<p><button class="emit-event" data-event="travel:step">Keep Walking</button></p>`);
783 console.error(`Unknown fight trigger [${roundData.fightTrigger}]`, roundData);
790 $('#fight-results').html(html.join("\n"));
791 $('#fight-actions').html('');
795 socket.on('fight-round', (data: FightRound) => {
796 $('.fight-action').prop('disabled', false);
797 cache.set('player', data.player);
800 $('#map').html(renderFight(data.monster));
802 $('#fight-results').html(data.roundDetails.map(d => `<div>${d}</div>`).join("\n"));
805 async function startFight(monsterId: string, fightTrigger: FightTrigger = 'explore') {
806 // check your HP first
807 if(cache.get('player').hp <= 0) {
808 events.emit('alert', [{
810 text: 'You don\'t have enough HP to go looking for a fight'
815 cache.set('last-selected-monster', monsterId);
818 const monster: MonsterForFight = await http.post('/fight', {
823 $('#map').html(renderFight(monster));
826 events.emit('alert', [{
828 text: 'Sorry, you can\'t start that fight'
833 events.on('startFight', startFight);
835 $('body').on('submit', '#fight-selector', async e => {
839 const monsterId = $('#monster-selector option:selected').val();
842 startFight(monsterId.toString());
845 console.error(`Invalid monster id [${monsterId}]`);
850 $('body').on('click', '.fight-action', e => {
854 const action = $(e.target).data('action');
855 const target = $('#fight-target option:selected').val();
856 $('.fight-action').prop('disabled', true);
858 socket.emit('fight', { action, target });
861 $('body').on('submit', '#signup', async e => {
865 const data: Record<string, string> = {};
867 $(e.target).serializeArray().forEach(v => data[v.name] = v.value);
869 const res = await http.post('/signup', data);
872 events.emit('alert', [{
878 cache.set('player', res.player);
880 $('#signup-prompt').remove();
885 $('body').on('click', '#login', async e => {
889 const data: Record<string, string> = {};
891 $(e.target).closest('form').serializeArray().forEach(v => data[v.name] = v.value);
893 if(data.username && data.password) {
894 const res = await http.post('/login', data);
896 events.emit('alert', [{type: 'error', text: res.error}]);
899 localStorage.setItem('authToken', res.player.id);
900 window.location.reload();
905 $('body').on('click', '#logout', async e => {
911 const player = cache.get('player');
912 if(/^Player[\d]+$/.test(player.username)) {
913 const clear = confirm('Are you sure? You will not be able to retrieve this character unless you set up an email/password');
926 socket.emit('logout');
927 localStorage.clear();
928 window.location.reload();
933 function bootstrap() {
934 console.log('Server connection verified');
935 socket.emit('inventory');
936 $('nav a').first().click();