chore(release): 0.1.0
[risinglegends.git] / src / client / index.ts
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, 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
19
20 const time = new TimeManager();
21 const cache = new Map<string, any>();
22 const events = new CustomEventManager();
23 const socket = io({
24   extraHeaders: {
25     'x-authtoken': authToken()
26   }
27 });
28
29 configureChat(socket);
30
31 function setTimeGradient() {
32   const gradientName = time.gradientName();
33   const $body = $('body');
34   $body.removeClass(Array.from($body[0].classList)).addClass(gradientName);
35   if(time.isNight()) {
36     $body.addClass('night');
37   }
38 }
39
40 setTimeGradient();
41 setInterval(setTimeGradient, 60 * 1000);
42
43 function icon(name: string): string {
44   return `<img src="/assets/img/${name}.png" class="icon">`;
45 }
46
47
48 function generateProgressBar(current: number, max: number, color: string, displayPercent: boolean = true): string {
49   let percent = 0;
50   if(max > 0) {
51     percent = Math.floor((current / max) * 100);
52   }
53   const display = `${displayPercent? `${percent}% - `: ''}`;
54   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>`;
55 }
56
57 function progressBar(current: number, max: number, el: string, color: string) {
58   let percent = 0;
59   if(max > 0) {
60     percent = Math.floor((current / max) * 100);
61   }
62   $(`#${el}`).css(
63     'background',
64     `linear-gradient(to right, ${color}, ${color} ${percent}%, transparent ${percent}%, transparent)`
65   ).attr('title', `${percent}% - ${current}/${max}`).html(`${current}/${max} - ${percent}%`);
66 }
67
68 function updatePlayer() {
69   const player: Player = cache.get('player');
70
71   $('#username').html(`${player.username}, level ${player.level} ${player.profession}`);
72
73   progressBar(
74     player.hp,
75     maxHp(player.constitution, player.level),
76     'hp-bar',
77     '#ff7070'
78   );
79
80   progressBar(
81     player.exp,
82     expToLevel(player.level + 1),
83     'exp-bar',
84     '#5997f9'
85   );
86
87   ['strength', 'constitution', 'dexterity', 'intelligence','hp','exp'].forEach(s => {
88     $(`.${s}`).html(player[s]);
89   });
90
91   $('.maxHp').html(maxHp(player.constitution, player.level).toString());
92   $('.expToLevel').html(expToLevel(player.level + 1).toString());
93   $('.gold').html(player.gold.toLocaleString());
94
95   if(player.account_type === 'session') {
96     $('#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>
97           <form id="signup">
98             <div class="form-group">
99               <label>Username:</label>
100               <input type="text" name="username">
101             </div>
102             <div class="form-group">
103               <label>Password:</label>
104               <input type="password" name="password">
105             </div>
106             <button type="submit" class="success">Create your Account</button>
107             <button type="button" id="login">Login To Existing Account</button>
108           </form></p>`).removeClass('hidden');
109   }
110
111   $('#extra-inventory-info').html(renderStatDetails());
112 }
113
114 socket.on('connect', () => {
115   console.log(`Connected: ${socket.id}`);
116 });
117
118 socket.on('ready', () => {
119   console.log('Server connection verified');
120   socket.emit('inventory');
121 });
122
123 socket.on('server-stats', (data: {onlinePlayers: number}) => {
124   $('#server-stats').html(`${data.onlinePlayers} players online`);
125 });
126
127 each(EventList, event => {
128   console.log(`Binding Event ${event.eventName}`);
129   if(event instanceof SocketEvent) {
130     socket.on(event.eventName, event.handler.bind(null, {
131       cache,
132       socket,
133       events
134     }));
135   }
136   else {
137     console.log('Skipped binding', event);
138   }
139 });
140
141 socket.on('calc:ap', (data: {ap: Record<EquipmentSlot, { currentAp: number, maxAp: number}>}) => {
142   const { ap } = data;
143   const html = `
144   <div>
145     ${icon('helm')}
146     ${generateProgressBar(ap.HEAD?.currentAp || 0, ap.HEAD?.maxAp || 0, '#7be67b')}
147   </div>
148   <div>
149     ${icon('arms')}
150     ${generateProgressBar(ap.ARMS?.currentAp || 0, ap.ARMS?.maxAp || 0, '#7be67b')}
151   </div>
152   <div>
153     ${icon('chest')}
154     ${generateProgressBar(ap.CHEST?.currentAp || 0, ap.CHEST?.maxAp || 0, '#7be67b')}
155   </div>
156   <div>
157     ${icon('legs')}
158     ${generateProgressBar(ap.LEGS?.currentAp || 0, ap.LEGS?.maxAp || 0, '#7be67b')}
159   </div>
160   `;
161   $('#ap-bar').html(html);
162 });
163
164 events.on('tab:skills', () => {
165   $('#skills').html('');
166   socket.emit('skills');
167 });
168
169 socket.on('skills', (data: {skills: Skill[]}) => {
170   let html = `<table id="skill-list">
171   ${data.skills.map((skill: Skill) => {
172     const definition = Skills.get(skill.id);
173     const percent = skill.exp / definition.expToLevel(skill.level + 1);
174     return `
175     <tr>
176     <td class="skill-level">${skill.level.toLocaleString()}</td>
177     <td class="skill-description" title="Total Exp: ${skill.exp.toLocaleString()}/${definition.expToLevel(skill.level + 1).toLocaleString()}">
178       <span class="skill-exp">${(percent * 100).toPrecision(2)}% to next level</span>
179       <b>${definition.display}</b>
180       <p>${definition.description}</p>
181     </td>
182     </tr>
183     `;
184   }).join("\n")}
185   </table>`;
186
187   $('#skills').html(html);
188 });
189
190 events.on('alert', (data: {type: string, text: string}) => {
191   let id = uuid();
192   $('#alerts').append(`<div class="alert ${data.type}" id="alert-${id}">${data.text}</div>`);
193
194   setTimeout(() => {
195     $(`#alert-${id}`).remove();
196   }, 3000);
197
198 });
199
200 socket.on('alert', data => {
201   events.emit('alert', [data]);
202 });
203
204 socket.on('authToken', (authToken: string) => {
205   console.log(`recv auth token ${authToken}`);
206   localStorage.setItem('authToken', authToken);
207 });
208
209
210 socket.on('player', (player: Player) => {
211   cache.set('player', player);
212   updatePlayer();
213 });
214
215
216 $('nav a').on('click', e => {
217   e.preventDefault();
218   e.stopPropagation();
219
220   const $tabContainer = $(`#${$(e.target).data('container')}`);
221
222   $tabContainer.find('.tab').removeClass('active');
223
224   $(`#${$(e.target).data('section')}`).addClass('active');
225
226   $(e.target).closest('nav').find('a').removeClass('active');
227   $(e.target).addClass('active');
228
229   events.emit(`tab:${$(e.target).data('section')}`);
230 });
231
232 events.on('tab:inventory', () => {
233   socket.emit('inventory');
234 });
235
236 function renderEquipmentPlacementGrid(items: EquippedItemDetails[]) {
237   const placeholder = 'https://via.placeholder.com/64x64';
238   // @ts-ignore
239   const map: Record<EquipmentSlot, EquippedItemDetails> = items.filter(item => item.is_equipped).reduce((acc, item) => {
240     acc[item.equipment_slot] = item;
241     return acc;
242   }, {});
243
244   const html = `
245   <table id="character-equipment-placement">
246   <tr>
247     <td>
248     </td>
249     <td style="background-image: url('${placeholder}');" title="${map.HEAD ? map.HEAD.name : 'Empty'}">
250     ${map.HEAD ? map.HEAD.name : 'HEAD'}
251     </td>
252     <td style="background-image: url('${placeholder}');" title="${map.ARMS ? map.ARMS.name : 'Empty'}">
253     ${map.ARMS ? map.ARMS.name : 'ARMS'}
254     </td>
255   </tr>
256   <tr>
257     <td style="background-image: url('${placeholder}');" title="${map.LEFT_HAND ? map.LEFT_HAND.name : (map.TWO_HANDED ? map.TWO_HANDED.name : '')}">
258     ${map.LEFT_HAND ? map.LEFT_HAND.name : (map.TWO_HANDED ? map.TWO_HANDED.name : 'L_HAND')}
259     </td>
260     <td style="background-image: url('${placeholder}');" title="${map.CHEST ? map.CHEST.name : ''}">
261     ${map.CHEST ? map.CHEST.name : 'CHEST'}
262     </td>
263     <td style="background-image: url('${placeholder}');" title="${map.RIGHT_HAND ? map.RIGHT_HAND.name : (map.TWO_HANDED ? map.TWO_HANDED.name : '')}">
264     ${map.RIGHT_HAND ? map.RIGHT_HAND.name : (map.TWO_HANDED ? map.TWO_HANDED.name : 'R_HAND')}
265     </td>
266   </tr>
267   <tr>
268     <td>
269     </td>
270     <td style="background-image: url('${placeholder}');" title="${map.LEGS ? map.LEGS.name : ''}">
271     ${map.LEGS ? map.LEGS.name : 'LEGS'}
272     </td>
273     <td>
274     </td>
275   </tr>
276   </table>
277   `;
278
279   return html;
280 }
281 function statPointIncreaser(stat: StatDisplay) {
282   return `<button class="increase-stat emit-event" data-event="spend-stat-point" data-args="${stat.id}">+</button>`;
283 }
284 function renderStatDetails() {
285   const player: Player = cache.get('player');
286   let html = '<table id="stat-breakdown">';
287
288   StatDef.forEach(stat => {
289     html += `<tr>
290       <th>${stat.display}</th>
291       <td class="${stat.id}">
292         ${player[stat.id]}
293         ${player.stat_points ? statPointIncreaser(stat) : ''}
294       </td>
295     </tr>`;
296   });
297
298   html += `<tr><th>Stat Points</th><td class="stat_points">${player.stat_points}</td></tr>`;
299
300   html += '</table>';
301
302   return html;
303 }
304
305 $('body').on('click', 'nav.filter', e => {
306   e.preventDefault();
307   e.stopPropagation();
308
309   const $target = $(e.target);
310   const filter = $target.data('filter');
311
312   $('.filter-result').removeClass('active').addClass('hidden');
313   $(`#filter_${filter}`).addClass('active').removeClass('hidden');
314
315   $target.closest('nav').find('a').removeClass('active');
316   $target.addClass('active');
317
318   cache.set('active-inventory-section', filter);
319 });
320
321 function renderInventorySection(inventory: EquippedItemDetails[]): string {
322   return inventory.map(item => {
323     return renderInventoryItem(item, item => {
324       if(item.is_equipped) {
325         return `<button type="button" class="unequip-item error" data-id="${item.item_id}">Unequip</button>`;
326       }
327       else {
328         if(item.equipment_slot === 'ANY_HAND') {
329           return `<button type="button" class="equip-item" data-id="${item.item_id}" data-slot="LEFT_HAND">Equip L</button>
330           <button type="button" class="equip-item" data-id="${item.item_id}" data-slot="RIGHT_HAND">Equip R</button>`;
331         }
332         else if(item.equipment_slot === 'LEFT_HAND') {
333           return `<button type="button" class="equip-item" data-id="${item.item_id}" data-slot="${item.equipment_slot}">Equip Left</button>`;
334         }
335         else if(item.equipment_slot === 'RIGHT_HAND') {
336           return `<button type="button" class="equip-item" data-id="${item.item_id}" data-slot="${item.equipment_slot}">Equip Right</button>`;
337         }
338         else if(item.equipment_slot === 'TWO_HANDED') {
339           return `<button type="button" class="equip-item" data-id="${item.item_id}" data-slot="${item.equipment_slot}">Equip</button>`;
340         }
341         else {
342           return `<button type="button" class="equip-item" data-id="${item.item_id}" data-slot="${item.equipment_slot}">Equip</button>`;
343         }
344       }
345     })
346   }).join("\n");
347 }
348
349 socket.on('inventory', (data: {inventory: EquippedItemDetails[]}) => {
350   const player: Player = cache.get('player');
351   const activeSection = cache.get('active-inventory-section') || 'ARMOUR';
352   // split the inventory into sections!
353   const sectionedInventory: {ARMOUR: EquippedItemDetails[], WEAPON: EquippedItemDetails[], SPELL: EquippedItemDetails[]} = {
354     ARMOUR: [],
355     WEAPON: [],
356     SPELL: []
357   };
358
359   data.inventory.forEach(item => {
360     sectionedInventory[item.type].push(item);
361   });
362
363   const html = `
364   <div id="inventory-page">
365     <div id="character-summary">
366     ${renderEquipmentPlacementGrid(data.inventory)}
367       <div id="extra-inventory-info">
368         ${renderStatDetails()}
369       </div>
370     </div>
371     <div id="inventory-section">
372       <nav class="filter">
373         <a href="#" data-filter="ARMOUR" class="${activeSection === 'ARMOUR' ? 'active': ''}">Armour</a>
374         <a href="#" data-filter="WEAPON" class="${activeSection === 'WEAPON' ? 'active': ''}">Weapons</a>
375         <a href="#" data-filter="SPELL" class="${activeSection === 'SPELL' ? 'active': ''}">Spells</a>
376       </nav>
377       <div class="inventory-listing">
378         <div class="filter-result ${activeSection === 'ARMOUR' ? 'active' : 'hidden'}" id="filter_ARMOUR">
379           ${renderInventorySection(sectionedInventory.ARMOUR)}
380         </div>
381         <div class="filter-result ${activeSection === 'WEAPON' ? 'active' : 'hidden'}" id="filter_WEAPON">
382           ${renderInventorySection(sectionedInventory.WEAPON)}
383         </div>
384         <div class="filter-result ${activeSection === 'SPELL' ? 'active' : 'hidden'}" id="filter_SPELL">
385           ${renderInventorySection(sectionedInventory.SPELL)}
386         </div>
387       </div>
388     </div>
389   </div>
390   `;
391   $('#inventory').html(html);
392 });
393
394 $('body').on('click', '.equip-item', e => {
395   e.preventDefault();
396   e.stopPropagation();
397
398   const $target = $(e.target);
399   const id = $target.data('id');
400   const slot = $target.data('slot');
401
402   socket.emit('equip', {id, slot});
403 });
404
405 $('body').on('click', '.unequip-item', e => {
406   e.preventDefault();
407   e.stopPropagation();
408
409   socket.emit('unequip', { id: $(e.target).data('id') });
410 });
411
412 events.on('renderMap', async function renderMap(data: { city: City, locations: Location[], paths: Path[]}) {
413   if(!data || cache.has('currentMapHTML')) {
414     $('#map').html(cache.get('currentMapHTML'));
415     return;
416   }
417
418   if(!data) {
419     console.error('oh no.. this got triggered without any city data');
420   }
421
422   $('#explore').css({
423     '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/${data.city.id}.jpeg")`
424   });
425
426
427   const servicesParsed: Record<LocationType, string[]> = {
428     'SERVICES': [],
429     'STORES': [],
430     'EXPLORE': []
431   };
432
433   data.locations.forEach(l => {
434     servicesParsed[l.type].push(`<a href="#" class="city-emit-event" data-event="${l.event_name}" data-args="${l.id}">${l.name}</a>`);
435   });
436
437   let html = `<h1>${data.city.name}</h1>
438   <div class="city-details">`;
439
440   if(servicesParsed.SERVICES.length) {
441     html += `<div><h3>Services</h3>${servicesParsed.SERVICES.join("<br>")}</div>`
442   }
443   if(servicesParsed.STORES.length) {
444     html += `<div><h3>Stores</h3>${servicesParsed.STORES.join("<br>")}</div>`
445   }
446   if(servicesParsed.EXPLORE.length) {
447     html += `<div><h3>Explore</h3>${servicesParsed.EXPLORE.join("<br>")}</div>`
448   }
449   html += `
450     <div>
451       <h3>Travel</h3>
452       ${data.paths.map(path => {
453         return `<a href="#" class="city-emit-event" data-event="city:travel" data-args="${path.ending_city}">${path.ending_city_name}</a>`
454       }).join("<br>")}
455     </div>
456   </div>
457   `;
458
459   cache.set('currentMapHTML', html);
460
461   $('#map').html(html);
462 });
463
464 function renderRequirement(name: string, val: number | string, currentVal?: number): string {
465   let colorIndicator = '';
466   if(currentVal) {
467     colorIndicator = currentVal >= val ? 'success' : 'error';
468   }
469   return `<span class="requirement-title">${name}</span>: <span class="requirement-value ${colorIndicator}">${val.toLocaleString()}</span>`;
470 }
471
472 function renderStatBoost(name: string, val: number | string): string {
473   let valSign: string = '';
474   if(typeof val === 'number') {
475     valSign = val > 0 ? '+' : '-';
476   }
477   return `<span class="requirement-title">${name}</span>: <span class="requirement-value ${typeof val === 'number' && val > 0 ? "success": "error"}">${valSign}${val}</span>`;
478 }
479
480 function renderInventoryItem(item: EquippedItemDetails , action: (item: EquippedItemDetails) => string): string {
481     return `<div class="store-list">
482     <div>
483       <img src="https://via.placeholder.com/64x64">
484     </div>
485     <div class="details">
486       <div class="name">${item.name}</div>
487       <div class="requirements">
488       ${item.requirements.level ? renderRequirement('LVL', item.requirements.level): ''}
489       ${item.requirements.strength ? renderRequirement('STR', item.requirements.strength): ''}
490       ${item.requirements.constitution ? renderRequirement('CON', item.requirements.constitution): ''}
491       ${item.requirements.dexterity ? renderRequirement('DEX', item.requirements.dexterity): ''}
492       ${item.requirements.intelligence ? renderRequirement('INT', item.requirements.intelligence): ''}
493       ${renderRequirement('PRF', item.profession)}
494       </div>
495       <div class="stat-mods">
496       ${item.boosts.strength ? renderStatBoost('STR', item.boosts.strength) : ''}
497       ${item.boosts.constitution ? renderStatBoost('CON', item.boosts.constitution) : ''}
498       ${item.boosts.dexterity ? renderStatBoost('DEX', item.boosts.dexterity) : ''}
499       ${item.boosts.intelligence ? renderStatBoost('INT', item.boosts.intelligence) : ''}
500       ${item.boosts.damage ? renderStatBoost('DMG', item.boosts.damage) : ''}
501       ${item.boosts.damage_mitigation ? renderStatBoost('MIT', item.boosts.damage_mitigation)+'%' : ''}
502       ${['WEAPON','SPELL'].includes(item.type) ? '': generateProgressBar(item.currentAp, item.maxAp, '#7be67b')}
503       </div>
504       ${item.hasOwnProperty('id') ? `<div>${item.cost.toLocaleString()}G</div>` : ''}
505     </div>
506     <div class="store-actions">
507       ${action(item)}
508     </div>
509     </div>`;
510 }
511
512 function renderShopItem(item: ShopItem, action: (item: ShopItem) => string): string {
513   const player: Player = cache.get('player');
514     return `<div class="store-list">
515     <div>
516       <img src="https://via.placeholder.com/64x64">
517     </div>
518     <div class="details">
519       <div class="name">${item.name}${item.equipment_slot === 'TWO_HANDED' ? ' (2H)': ''}</div>
520       <div class="requirements">
521       ${item.requirements.level ? renderRequirement('LVL', item.requirements.level, player.level): ''}
522       ${item.requirements.strength ? renderRequirement('STR', item.requirements.strength, player.strength): ''}
523       ${item.requirements.constitution ? renderRequirement('CON', item.requirements.constitution, player.constitution): ''}
524       ${item.requirements.dexterity ? renderRequirement('DEX', item.requirements.dexterity, player.dexterity): ''}
525       ${item.requirements.intelligence ? renderRequirement('INT', item.requirements.intelligence, player.intelligence): ''}
526       ${renderRequirement('PRF', item.profession)}
527       </div>
528       <div class="stat-mods">
529       ${item.boosts.strength ? renderStatBoost('STR', item.boosts.strength) : ''}
530       ${item.boosts.constitution ? renderStatBoost('CON', item.boosts.constitution) : ''}
531       ${item.boosts.dexterity ? renderStatBoost('DEX', item.boosts.dexterity) : ''}
532       ${item.boosts.intelligence ? renderStatBoost('INT', item.boosts.intelligence) : ''}
533       ${item.boosts.damage ? renderStatBoost(item.affectedSkills.includes('restoration_magic') ? 'HP' : 'DMG', item.boosts.damage) : ''}
534       ${item.boosts.damage_mitigation ? renderStatBoost('MIT', item.boosts.damage_mitigation)+'%' : ''}
535       ${['WEAPON','SPELL'].includes(item.type) ? '' : renderStatBoost('AP', item.maxAp)}
536       </div>
537       ${item.hasOwnProperty('id') ? `<div>${item.cost.toLocaleString()}G</div>` : ''}
538     </div>
539     <div class="store-actions">
540       ${action(item)}
541     </div>
542     </div>`;
543
544 }
545
546 socket.on('city:stores', (data: ShopItem[]) => {
547   let html = `<div class="shop-inventory-listing">
548   ${data.map(item => {
549     return renderShopItem(item, i => {
550       const id = `data-id="${i.id}"`;
551       return `<button type="button" class="purchase-item" ${id} data-type="${i.type}" data-equipment-slot="${i.equipment_slot}" data-cost="${i.cost}">Buy</button>`
552     })
553   }).join("\n")}
554   </div>
555   `;
556
557   $('#map').html(html);
558
559 });
560
561 $('body').on('click', '.purchase-item', e => {
562   e.preventDefault();
563   e.stopPropagation();
564
565   const player = cache.get('player');
566   const cost = parseInt($(e.target).data('cost'));
567
568
569   const id = $(e.target).data('id');
570   if(player.gold < cost) {
571     events.emit('alert', [{
572       type: 'error',
573       text: 'You don\'t have enough gold!'
574     }]);
575     return;
576   }
577   else {
578     const type = $(e.target).data('type');
579     socket.emit('purchase', {
580       id
581     });
582   }
583 });
584
585 $('body').on('click', '.emit-event', e => {
586   const $el = $(e.target);
587
588   const eventName = $el.data('event');
589   const args = $el.data('args');
590
591   console.log(`Sending event ${eventName}`, { args });
592   socket.emit(eventName, { args });
593 });
594
595 $('body').on('click', '.city-emit-event', e => {
596   const $el = $(e.target);
597
598   const eventName = $el.data('event');
599   const args = $el.data('args');
600
601   console.log(`Sending event ${eventName}`, { args });
602   socket.emit(eventName, { args });
603 });
604
605
606 socket.on('explore:fights', (monsters: MonsterForList[]) => {
607   const lastSelectedMonster = cache.get('last-selected-monster');
608   if(monsters.length) {
609     let sel = `<form id="fight-selector"><select id="monster-selector">
610     ${monsters.map(monster => {
611       return `<option value="${monster.id}" ${lastSelectedMonster == monster.id ? 'selected': ''}>${monster.name}</option>`;
612     }).join("\n")}
613     </select> <button type="submit">Fight</button></option>`;
614
615     $('#map').html(sel);
616   }
617 });
618
619 events.on('tab:explore', async () => {
620   const res = await http.get('/fight');
621   if(!res) {
622     // get the details of the city
623     // render the map!
624     let data: {city: City, locations: Location[], paths: Path[]};
625     if(!cache.has(('currentMapHTML'))) {
626       data = await http.get(`/city/${cache.get('player').city_id}`);
627     }
628     events.emit('renderMap', [data]);
629   }
630   else {
631     $('#map').html(renderFight(res));
632   }
633 });
634
635 function renderFight(monster: MonsterForFight | Fight) {
636   const hpPercent = Math.floor((monster.hp / monster.maxHp) * 100);
637
638   let html = `<div id="fight-container">
639     <div id="defender-info">
640       <div class="avatar-container">
641         <img id="avatar" src="https://via.placeholder.com/64x64">
642       </div>
643       <div id="defender-stat-bars">
644         <div id="defender-name">${monster.name}</div>
645         <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>
646       </div>
647     </div>
648     <div id="fight-actions">
649       <select id="fight-target">
650         <option value="head">Head</option>
651         <option value="body">Body</option>
652         <option value="arms">Arms</option>
653         <option value="legs">Legs</option>
654       </select>
655       <button type="button" class="fight-action" data-action="attack">Attack</button>
656       <button type="button" class="fight-action" data-action="cast">Cast</button>
657       <button type="button" class="fight-action" data-action="flee">Flee</button>
658     </div>
659     <div id="fight-results"></div>
660   </div>`;
661
662   return html;
663 }
664
665 socket.on('updatePlayer', (player: Player) => {
666   cache.set('player', player);
667   updatePlayer();
668 });
669
670 socket.on('fight-over', (data: {roundData: FightRound, monsters: MonsterForFight[]}) => {
671   const { roundData, monsters } = data;
672   cache.set('player', roundData.player);
673   updatePlayer();
674
675   $('#map').html(renderFight(roundData.monster));
676
677   let html: string[] = roundData.roundDetails.map(d => `<div>${d}</div>`);
678
679   if(roundData.winner === 'player') {
680     html.push(`<div>You defeated the ${roundData.monster.name}!</div>`);
681     if(roundData.rewards.gold) {
682       html.push(`<div>You gained ${roundData.rewards.gold} gold`);
683     }
684     if(roundData.rewards.exp) {
685       html.push(`<div>You gained ${roundData.rewards.exp} exp`);
686     }
687     if(roundData.rewards.levelIncrease) {
688       html.push(`<div>You gained a level! ${roundData.player.level}`);
689     }
690   }
691
692   if(monsters.length) {
693     const lastSelectedMonster = cache.get('last-selected-monster');
694     // put this above the fight details
695     html.unshift(`<h2>Fight Again</h2><form id="fight-selector"><select id="monster-selector">
696       ${monsters.map(monster => {
697         return `<option value="${monster.id}" ${lastSelectedMonster == monster.id ? 'selected': ''}>${monster.name}</option>`;
698       }).join("\n")}
699       </select> <button type="submit">Fight</button></option>
700     </select></form><hr>`);
701   }
702
703   $('#fight-results').html(html.join("\n"));
704   $('#fight-actions').html('');
705
706 });
707
708 socket.on('fight-round', (data: FightRound) => {
709   $('.fight-action').prop('disabled', false);
710   cache.set('player', data.player);
711   updatePlayer();
712
713   $('#map').html(renderFight(data.monster));
714
715   $('#fight-results').html(data.roundDetails.map(d => `<div>${d}</div>`).join("\n"));
716 });
717
718 $('body').on('submit', '#fight-selector', async e => {
719   e.preventDefault();
720   e.stopPropagation();
721
722   const monsterId = $('#monster-selector option:selected').val();
723
724   cache.set('last-selected-monster', monsterId);
725
726   const monster: MonsterForFight = await http.post('/fight', {
727     monsterId,
728   });
729
730
731   $('#map').html(renderFight(monster));
732 });
733
734 $('body').on('click', '.fight-action', e => {
735   e.preventDefault();
736   e.stopPropagation();
737
738   const action = $(e.target).data('action');
739   const target = $('#fight-target option:selected').val();
740   $('.fight-action').prop('disabled', true);
741
742   socket.emit('fight', { action, target });
743 });
744
745 $('body').on('submit', '#signup', async e => {
746   e.preventDefault();
747   e.stopPropagation();
748
749   const data: Record<string, string> = {}; 
750
751   $(e.target).serializeArray().forEach(v => data[v.name] = v.value);
752
753   const res = await http.post('/signup', data);
754
755   if(res.error) {
756     events.emit('alert', [{
757       type: 'error',
758       text: res.error
759     }]);
760   }
761   else {
762     cache.set('player', res.player);
763     updatePlayer();
764     $('#signup-prompt').remove();
765   }
766
767 });
768
769 $('body').on('click', '#login', async e => {
770   e.preventDefault();
771   e.stopPropagation();
772
773   const data: Record<string, string> = {}; 
774
775   $(e.target).closest('form').serializeArray().forEach(v => data[v.name] = v.value);
776
777   if(data.username && data.password) {
778     const res = await http.post('/login', data);
779     if(res.error) {
780       events.emit('alert', [{type: 'error', text: res.error}]);
781     }
782     else {
783       localStorage.setItem('authToken', res.player.id);
784       window.location.reload();
785     }
786   }
787 });