| 1 | var doneTyping = true; |
| 2 | // Main Game App |
| 3 | class TribeGenApp |
| 4 | { |
| 5 | constructor () |
| 6 | { |
| 7 | this.currentUser = null; |
| 8 | this.currentSave = null; |
| 9 | this.currentTribe = null; |
| 10 | this.availableEvents = []; |
| 11 | this.availableEventsByType = {}; |
| 12 | this.init(); |
| 13 | } |
| 14 | |
| 15 | async init () |
| 16 | { |
| 17 | this.setupEventListeners(); |
| 18 | this.checkAuth(); |
| 19 | } |
| 20 | |
| 21 | setupEventListeners () |
| 22 | { |
| 23 | // Auth Events |
| 24 | document.getElementById('loginForm').addEventListener('submit', (e) => this.handleLogin(e)); |
| 25 | document.getElementById('registerForm').addEventListener('submit', (e) => this.handleRegister(e)); |
| 26 | document.getElementById('logoutBtn').addEventListener('click', () => this.handleLogout()); |
| 27 | |
| 28 | // Tab switching |
| 29 | document.querySelectorAll('.tab-btn').forEach(btn => |
| 30 | { |
| 31 | btn.addEventListener('click', (e) => this.switchTab(e.target.dataset.tab)); |
| 32 | }); |
| 33 | |
| 34 | // Main Menu |
| 35 | document.getElementById('newGameBtn').addEventListener('click', () => this.startGameSetup()); |
| 36 | |
| 37 | // Game Setup |
| 38 | document.getElementById('startGenerationBtn').addEventListener('click', () => this.generateKobolds()); |
| 39 | document.getElementById('selectLeaderBtn').addEventListener('click', () => this.selectLeader()); |
| 40 | document.getElementById('finishTribeBtn').addEventListener('click', () => this.finishTribe()); |
| 41 | |
| 42 | // Game Screen |
| 43 | document.getElementById('endMonthBtn').addEventListener('click', () => this.endMonth()); |
| 44 | |
| 45 | // Modal close buttons |
| 46 | document.querySelectorAll('.modal-close').forEach(btn => |
| 47 | { |
| 48 | btn.addEventListener('click', (e) => |
| 49 | { |
| 50 | const modal = e.target.closest('.modal'); |
| 51 | if (modal) modal.classList.add('hidden'); |
| 52 | }); |
| 53 | }); |
| 54 | |
| 55 | document.getElementById('eventContinueBtn').addEventListener('click', () => this.hideEventModal()); |
| 56 | } |
| 57 | |
| 58 | switchTab (tabName) |
| 59 | { |
| 60 | document.querySelectorAll('.tab-content').forEach(tab => tab.classList.remove('active')); |
| 61 | document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active')); |
| 62 | document.getElementById(tabName + 'Tab').classList.add('active'); |
| 63 | event.target.classList.add('active'); |
| 64 | } |
| 65 | |
| 66 | async checkAuth () |
| 67 | { |
| 68 | // Check if user is logged in |
| 69 | const savedUser = localStorage.getItem('currentUser'); |
| 70 | if (savedUser) |
| 71 | { |
| 72 | this.currentUser = JSON.parse(savedUser); |
| 73 | this.showMainMenu(); |
| 74 | } else |
| 75 | { |
| 76 | this.showAuthScreen(); |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | async handleLogin (e) |
| 81 | { |
| 82 | e.preventDefault(); |
| 83 | const email = document.querySelector('#loginForm input[name="email"]').value; |
| 84 | const password = document.querySelector('#loginForm input[name="password"]').value; |
| 85 | |
| 86 | try |
| 87 | { |
| 88 | const response = await fetch('api/auth/login', { |
| 89 | method: 'POST', |
| 90 | headers: { 'Content-Type': 'application/json' }, |
| 91 | body: JSON.stringify({ email, password }) |
| 92 | }); |
| 93 | |
| 94 | const dataJson = await response; |
| 95 | const dataText = await dataJson.text(); |
| 96 | const data = JSON.parse(dataText); |
| 97 | |
| 98 | if (data.success) |
| 99 | { |
| 100 | this.currentUser = data.user; |
| 101 | localStorage.setItem('currentUser', JSON.stringify(data.user)); |
| 102 | this.showMainMenu(); |
| 103 | } else |
| 104 | { |
| 105 | this.showAuthError(data.error); |
| 106 | } |
| 107 | } catch (error) |
| 108 | { |
| 109 | this.showAuthError('Login failed'); |
| 110 | console.error(error); |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | async handleRegister (e) |
| 115 | { |
| 116 | e.preventDefault(); |
| 117 | const email = document.querySelector('#registerForm input[name="email"]').value; |
| 118 | const password = document.querySelector('#registerForm input[name="password"]').value; |
| 119 | const passwordConfirm = document.querySelector('#registerForm input[name="passwordConfirm"]').value; |
| 120 | |
| 121 | if (password !== passwordConfirm) |
| 122 | { |
| 123 | this.showAuthError('Passwords do not match'); |
| 124 | return; |
| 125 | } |
| 126 | |
| 127 | try |
| 128 | { |
| 129 | const response = await fetch('api/auth/register', { |
| 130 | method: 'POST', |
| 131 | headers: { 'Content-Type': 'application/json' }, |
| 132 | body: JSON.stringify({ email, password }) |
| 133 | }); |
| 134 | |
| 135 | const dataRaw = await response; |
| 136 | const dataText = await dataRaw.text(); |
| 137 | const data = JSON.parse(dataText); |
| 138 | |
| 139 | if (data.success) |
| 140 | { |
| 141 | this.currentUser = data.user; |
| 142 | localStorage.setItem('currentUser', JSON.stringify(data.user)); |
| 143 | this.showMainMenu(); |
| 144 | } else |
| 145 | { |
| 146 | this.showAuthError(data.error); |
| 147 | } |
| 148 | } catch (error) |
| 149 | { |
| 150 | this.showAuthError('Registration failed'); |
| 151 | console.error(error); |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | handleLogout () |
| 156 | { |
| 157 | this.currentUser = null; |
| 158 | localStorage.removeItem('currentUser'); |
| 159 | this.showAuthScreen(); |
| 160 | } |
| 161 | |
| 162 | showAuthError (error) |
| 163 | { |
| 164 | const errorDiv = document.getElementById('authError'); |
| 165 | errorDiv.textContent = error; |
| 166 | errorDiv.classList.add('show'); |
| 167 | setTimeout(() => errorDiv.classList.remove('show'), 5000); |
| 168 | } |
| 169 | |
| 170 | showAuthScreen () |
| 171 | { |
| 172 | this.hideAll(); |
| 173 | document.getElementById('authScreen').classList.remove('hidden'); |
| 174 | } |
| 175 | |
| 176 | showMainMenu () |
| 177 | { |
| 178 | this.hideAll(); |
| 179 | document.getElementById('mainMenuScreen').classList.remove('hidden'); |
| 180 | document.getElementById('userEmail').textContent = this.currentUser.email; |
| 181 | this.loadSaves(); |
| 182 | } |
| 183 | |
| 184 | async loadSaves () |
| 185 | { |
| 186 | try |
| 187 | { |
| 188 | const response = await fetch('api/game/list', { |
| 189 | method: 'GET', |
| 190 | headers: { 'Authorization': `Bearer ${this.currentUser.token}` } |
| 191 | }); |
| 192 | |
| 193 | const dataText = await response.text(); |
| 194 | const data = JSON.parse(dataText); |
| 195 | |
| 196 | const savesList = document.getElementById('savesList'); |
| 197 | savesList.innerHTML = ''; |
| 198 | |
| 199 | if (data.saves && data.saves.length > 0) |
| 200 | { |
| 201 | data.saves.forEach(save => |
| 202 | { |
| 203 | const card = document.createElement('div'); |
| 204 | card.className = 'save-card'; |
| 205 | card.innerHTML = ` |
| 206 | <h3>${save.name}</h3> |
| 207 | <p>Month: ${save.current_month}</p> |
| 208 | <p>Season: ${save.current_season}</p> |
| 209 | `; |
| 210 | card.addEventListener('click', () => this.loadGame(save.id)); |
| 211 | savesList.appendChild(card); |
| 212 | }); |
| 213 | } |
| 214 | } catch (error) |
| 215 | { |
| 216 | console.error('Failed to load saves:', error); |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | startGameSetup () |
| 221 | { |
| 222 | this.hideAll(); |
| 223 | document.getElementById('gameSetupScreen').classList.remove('hidden'); |
| 224 | document.getElementById('setupStep1').classList.remove('hidden'); |
| 225 | document.getElementById('setupStep2').classList.add('hidden'); |
| 226 | document.getElementById('setupStep3').classList.add('hidden'); |
| 227 | } |
| 228 | |
| 229 | async generateKobolds () |
| 230 | { |
| 231 | const tribeName = document.getElementById('tribeName').value; |
| 232 | |
| 233 | if (!tribeName) |
| 234 | { |
| 235 | alert('Please enter a tribe name'); |
| 236 | return; |
| 237 | } |
| 238 | |
| 239 | try |
| 240 | { |
| 241 | const response = await fetch('api/game/generation', { |
| 242 | method: 'POST', |
| 243 | headers: { |
| 244 | 'Content-Type': 'application/json', |
| 245 | 'Authorization': `Bearer ${this.currentUser.token}` |
| 246 | }, |
| 247 | body: JSON.stringify({ |
| 248 | saveName: tribeName, |
| 249 | userId: this.currentUser.id |
| 250 | }) |
| 251 | }); |
| 252 | |
| 253 | const dataText = await response.text(); |
| 254 | const data = JSON.parse(dataText); |
| 255 | |
| 256 | if (data.success) |
| 257 | { |
| 258 | this.currentSave = data.save; |
| 259 | this.displayKobolds(data.kobolds, 'leader'); |
| 260 | this.displayKobolds(data.kobolds, 'member'); |
| 261 | |
| 262 | document.getElementById('setupStep1').classList.add('hidden'); |
| 263 | document.getElementById('setupStep2').classList.remove('hidden'); |
| 264 | } |
| 265 | } catch (error) |
| 266 | { |
| 267 | alert('Failed to generate kobolds'); |
| 268 | console.error(error); |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | displayKobolds (kobolds, type) |
| 273 | { |
| 274 | const container = type === 'leader' |
| 275 | ? document.getElementById('leaderSelectionGrid') |
| 276 | : document.getElementById('memberSelectionGrid'); |
| 277 | |
| 278 | container.innerHTML = ''; |
| 279 | |
| 280 | kobolds.forEach((kobold, index) => |
| 281 | { |
| 282 | const card = document.createElement('div'); |
| 283 | card.className = 'kobold-card'; |
| 284 | |
| 285 | const spriteUrl = `api/game/sprite?userId=${this.currentUser.id}&koboldId=${kobold.id}&age=${kobold.ageCategory}`; |
| 286 | |
| 287 | card.innerHTML = ` |
| 288 | <img src="${spriteUrl}" alt="Kobold sprite" class="kobold-sprite"> |
| 289 | <div class="kobold-name">${kobold.age} years</div> |
| 290 | <div class="kobold-stats"> |
| 291 | <div>Vitality: ${kobold.stats.vitality}</div> |
| 292 | </div> |
| 293 | `; |
| 294 | |
| 295 | if (type === 'member') |
| 296 | { |
| 297 | card.addEventListener('click', () => this.toggleMemberSelection(card, index)); |
| 298 | } else |
| 299 | { |
| 300 | card.addEventListener('click', () => this.selectLeaderCard(card, index)); |
| 301 | } |
| 302 | |
| 303 | container.appendChild(card); |
| 304 | }); |
| 305 | } |
| 306 | |
| 307 | async selectLeaderCard (card, index) |
| 308 | { |
| 309 | const leaderName = document.getElementById('leaderName').value; |
| 310 | |
| 311 | if (!leaderName) |
| 312 | { |
| 313 | alert('Please enter a leader name'); |
| 314 | return; |
| 315 | } |
| 316 | |
| 317 | document.querySelectorAll('#leaderSelectionGrid .kobold-card').forEach(c => c.classList.remove('selected')); |
| 318 | card.classList.add('selected'); |
| 319 | document.getElementById('selectLeaderBtn').dataset.leaderIndex = index; |
| 320 | |
| 321 | this.toggleMemberSelection(card, index, true); |
| 322 | await this.selectLeader(); |
| 323 | } |
| 324 | |
| 325 | toggleMemberSelection (card, index, force) |
| 326 | { |
| 327 | const leaderIndex = document.getElementById('selectLeaderBtn').dataset.leaderIndex; |
| 328 | if (force || leaderIndex != index) |
| 329 | { |
| 330 | const selectedCard = document.querySelectorAll('#memberSelectionGrid .kobold-card')[index]; |
| 331 | selectedCard.classList.toggle('selected'); |
| 332 | |
| 333 | if (force) |
| 334 | { |
| 335 | selectedCard.id = "tribeLeader"; |
| 336 | } |
| 337 | |
| 338 | const selected = document.querySelectorAll('#memberSelectionGrid .kobold-card.selected').length; |
| 339 | document.getElementById('memberCount').textContent = `${selected} / 5 selected`; |
| 340 | |
| 341 | if (selected === 5) |
| 342 | { |
| 343 | document.getElementById('finishTribeBtn').disabled = false; |
| 344 | } else |
| 345 | { |
| 346 | document.getElementById('finishTribeBtn').disabled = true; |
| 347 | } |
| 348 | } |
| 349 | } |
| 350 | |
| 351 | async selectLeader () |
| 352 | { |
| 353 | const leaderName = document.getElementById('leaderName').value; |
| 354 | |
| 355 | if (!leaderName) |
| 356 | { |
| 357 | alert('Please enter a leader name'); |
| 358 | return; |
| 359 | } |
| 360 | |
| 361 | // Proceed to member selection |
| 362 | document.getElementById('setupStep2').classList.add('hidden'); |
| 363 | document.getElementById('setupStep3').classList.remove('hidden'); |
| 364 | |
| 365 | // For now, just display remaining kobolds (in real implementation, filter out leader) |
| 366 | } |
| 367 | |
| 368 | async finishTribe () |
| 369 | { |
| 370 | const leaderIndex = document.getElementById('selectLeaderBtn').dataset.leaderIndex; |
| 371 | const selectedMembers = document.querySelectorAll('#memberSelectionGrid .kobold-card.selected'); |
| 372 | |
| 373 | const memberIndices = Array.from(selectedMembers).map(card => |
| 374 | { |
| 375 | return Array.from(card.parentElement.children).indexOf(card); |
| 376 | }); |
| 377 | |
| 378 | // Load the game |
| 379 | try |
| 380 | { |
| 381 | const response = await fetch('api/game/save', { |
| 382 | method: 'POST', |
| 383 | headers: { |
| 384 | 'Content-Type': 'application/json', |
| 385 | 'Authorization': `Bearer ${this.currentUser.token}` |
| 386 | }, |
| 387 | body: JSON.stringify({ |
| 388 | userId: this.currentUser.id, |
| 389 | saveId: this.currentSave.id, |
| 390 | leaderName: document.getElementById('leaderName').value, |
| 391 | memberIndices: memberIndices, |
| 392 | leaderId: leaderIndex |
| 393 | }) |
| 394 | }); |
| 395 | |
| 396 | const dataText = await response.text(); |
| 397 | const data = JSON.parse(dataText); |
| 398 | |
| 399 | if (data.success) |
| 400 | { |
| 401 | this.loadGame(this.currentSave.id); |
| 402 | } |
| 403 | } catch (error) |
| 404 | { |
| 405 | alert('Failed to finish tribe setup'); |
| 406 | console.error(error); |
| 407 | } |
| 408 | } |
| 409 | |
| 410 | async loadGame (saveId) |
| 411 | { |
| 412 | try |
| 413 | { |
| 414 | const response = await fetch(`api/game/load?saveId=${saveId}&userId=${this.currentUser.id}`, { |
| 415 | method: 'GET', |
| 416 | headers: { 'Authorization': `Bearer ${this.currentUser.token}` } |
| 417 | }); |
| 418 | |
| 419 | const dataText = await response.text(); |
| 420 | const data = JSON.parse(dataText); |
| 421 | |
| 422 | if (data.success) |
| 423 | { |
| 424 | this.currentSave = data.save; |
| 425 | this.currentTribe = data.tribe; |
| 426 | await this.fetchAvailableEvents(); |
| 427 | this.showGameScreen(); |
| 428 | } |
| 429 | } catch (error) |
| 430 | { |
| 431 | alert('Failed to load game'); |
| 432 | console.error(error); |
| 433 | } |
| 434 | } |
| 435 | |
| 436 | showGameScreen () |
| 437 | { |
| 438 | this.hideAll(); |
| 439 | document.getElementById('gameScreen').classList.remove('hidden'); |
| 440 | this.renderGame(); |
| 441 | } |
| 442 | |
| 443 | renderGame () |
| 444 | { |
| 445 | document.getElementById('tribeName').textContent = this.currentSave.name; |
| 446 | document.getElementById('monthDisplay').textContent = `Month ${this.currentSave.current_month}`; |
| 447 | document.getElementById('seasonDisplay').textContent = this.capitalizeFirst(this.currentSave.current_season); |
| 448 | |
| 449 | this.renderStorage(); |
| 450 | this.renderTribeList(); |
| 451 | this.renderEvents(); |
| 452 | } |
| 453 | |
| 454 | renderTribeList () |
| 455 | { |
| 456 | const list = document.getElementById('tribeList'); |
| 457 | list.innerHTML = ''; |
| 458 | |
| 459 | this.currentTribe.kobolds.forEach(kobold => |
| 460 | { |
| 461 | const spriteUrl = `api/game/sprite?userId=${this.currentUser.id}&koboldId=${kobold.id}&age=${kobold.ageCategory}`; |
| 462 | const item = document.createElement('div'); |
| 463 | const isInjured = kobold.injuries && kobold.injuries.length > 0; |
| 464 | item.className = `tribe-item ${isInjured ? 'injured' : ''}`; |
| 465 | item.innerHTML = ` |
| 466 | <table style="width:100%"> |
| 467 | <td> |
| 468 | <img src="${spriteUrl}"/> |
| 469 | </td> |
| 470 | <td> |
| 471 | <div> |
| 472 | <div class="tribe-item-name">${kobold.name}</div> |
| 473 | <div class="tribe-item-age">${(kobold.age > 0 ? kobold.age : 0)} years</div> |
| 474 | </div> |
| 475 | </td> |
| 476 | </table> |
| 477 | `; |
| 478 | item.addEventListener('click', () => this.showKoboldModal(kobold)); |
| 479 | list.appendChild(item); |
| 480 | }); |
| 481 | } |
| 482 | |
| 483 | renderEvents () |
| 484 | { |
| 485 | const list = document.getElementById('eventsList'); |
| 486 | list.innerHTML = ''; |
| 487 | |
| 488 | if (!this.availableEvents || this.availableEvents.length === 0) |
| 489 | { |
| 490 | const empty = document.createElement('div'); |
| 491 | empty.className = 'event-item disabled'; |
| 492 | empty.textContent = 'No events available'; |
| 493 | list.appendChild(empty); |
| 494 | return; |
| 495 | } |
| 496 | |
| 497 | this.availableEvents.forEach(evt => |
| 498 | { |
| 499 | const item = document.createElement('div'); |
| 500 | const isAvailable = !!evt.available; |
| 501 | item.className = `event-item ${isAvailable ? '' : 'disabled'}`.trim(); |
| 502 | const costText = Number.isFinite(Number(evt.cost)) ? ` (Cost: ${evt.cost})` : ''; |
| 503 | item.textContent = `${evt.name || evt.type}${costText}${isAvailable ? '' : ' (Unavailable)'}`; |
| 504 | if (isAvailable) |
| 505 | { |
| 506 | item.addEventListener('click', () => this.showParticipantModal(evt.type)); |
| 507 | } |
| 508 | list.appendChild(item); |
| 509 | }); |
| 510 | } |
| 511 | |
| 512 | async fetchAvailableEvents () |
| 513 | { |
| 514 | this.availableEvents = []; |
| 515 | this.availableEventsByType = {}; |
| 516 | |
| 517 | if (!this.currentUser || !this.currentSave) |
| 518 | return; |
| 519 | |
| 520 | try |
| 521 | { |
| 522 | const response = await fetch(`api/game/events?saveId=${this.currentSave.id}&userId=${this.currentUser.id}`, { |
| 523 | method: 'GET', |
| 524 | headers: { 'Authorization': `Bearer ${this.currentUser.token}` } |
| 525 | }); |
| 526 | |
| 527 | const dataText = await response.text(); |
| 528 | const data = JSON.parse(dataText); |
| 529 | |
| 530 | if (data.success && Array.isArray(data.events)) |
| 531 | { |
| 532 | this.availableEvents = data.events; |
| 533 | data.events.forEach(evt => |
| 534 | { |
| 535 | if (evt && evt.type) |
| 536 | this.availableEventsByType[evt.type] = evt; |
| 537 | }); |
| 538 | } |
| 539 | } catch (error) |
| 540 | { |
| 541 | console.error('Failed to load events:', error); |
| 542 | } |
| 543 | } |
| 544 | |
| 545 | async executeEvent (eventType) |
| 546 | { |
| 547 | // Deprecated direct execution; use participant modal instead |
| 548 | this.showParticipantModal(eventType); |
| 549 | } |
| 550 | |
| 551 | showParticipantModal (eventType) |
| 552 | { |
| 553 | this.currentEventType = eventType; |
| 554 | const modal = document.getElementById('participantModal'); |
| 555 | const eventData = this.availableEventsByType[eventType] || {}; |
| 556 | const eventLabel = eventData.name || eventType; |
| 557 | document.getElementById('participantModalTitle').textContent = `Select participants for ${eventLabel}`; |
| 558 | |
| 559 | const list = document.getElementById('participantsList'); |
| 560 | list.innerHTML = ''; |
| 561 | |
| 562 | this.participantMin = eventData.min_participants ?? 1; |
| 563 | this.participantMax = eventData.max_participants ?? 3; |
| 564 | this.participantMinAge = eventData.min_age ?? 0; |
| 565 | this.participantCost = eventData.cost || 0; |
| 566 | |
| 567 | // Helper: check if kobold is eligible |
| 568 | const isEligible = (kobold) => |
| 569 | { |
| 570 | const ageCategory = (kobold.ageCategory || '').toLowerCase(); |
| 571 | if (ageCategory === 'egg') return false; // eggs cannot participate |
| 572 | if (!kobold.isAlive && kobold.isDead) return false; // dead cannot participate (if available from backend) |
| 573 | if (kobold.age < this.participantMinAge) return false; // too young |
| 574 | const fatigue = Number(kobold.fatigue || 0); |
| 575 | const vitality = Number(kobold.stats?.vitality || 0); |
| 576 | if ((fatigue + this.participantCost) > vitality) return false; |
| 577 | return true; |
| 578 | }; |
| 579 | |
| 580 | // Render kobolds with eligibility status |
| 581 | this.currentTribe.kobolds.forEach(kobold => |
| 582 | { |
| 583 | const ageCategory = (kobold.ageCategory || '').toLowerCase(); |
| 584 | const eligible = isEligible(kobold); |
| 585 | let reason = ''; |
| 586 | |
| 587 | if (ageCategory === 'egg') |
| 588 | reason = '(eggs cannot participate)'; |
| 589 | else if (kobold.age < this.participantMinAge) |
| 590 | reason = `(too young, needs age ${this.participantMinAge}+)`; |
| 591 | else if (this.participantCost > Number(kobold.stats?.vitality || 0)) |
| 592 | reason = '(too weak)'; |
| 593 | else if ((Number(kobold.fatigue || 0) + this.participantCost) > Number(kobold.stats?.vitality || 0)) |
| 594 | reason = '(too tired)'; |
| 595 | |
| 596 | const row = document.createElement('div'); |
| 597 | row.className = `participant-row ${eligible ? 'eligible' : 'ineligible'}`; |
| 598 | |
| 599 | if (eligible) |
| 600 | { |
| 601 | row.innerHTML = ` |
| 602 | <label> |
| 603 | <input type="checkbox" class="participant-checkbox" data-id="${kobold.id}"> |
| 604 | <strong>${kobold.name}</strong> (${kobold.age}y - ${kobold.ageCategory}) |
| 605 | </label> |
| 606 | `; |
| 607 | const cb = row.querySelector('.participant-checkbox'); |
| 608 | cb.addEventListener('change', () => this._updateParticipantButtons()); |
| 609 | } else |
| 610 | { |
| 611 | row.innerHTML = ` |
| 612 | <div class="participant-disabled"> |
| 613 | <span>${kobold.name} (${kobold.age}y - ${kobold.ageCategory})</span> |
| 614 | <span class="disabled-reason">${reason}</span> |
| 615 | </div> |
| 616 | `; |
| 617 | } |
| 618 | |
| 619 | list.appendChild(row); |
| 620 | }); |
| 621 | |
| 622 | document.getElementById('participantCount').textContent = `0 selected`; |
| 623 | |
| 624 | // cancel/start handlers |
| 625 | const cancelBtn = document.getElementById('cancelParticipantsBtn'); |
| 626 | const startBtn = document.getElementById('startEventBtn'); |
| 627 | |
| 628 | cancelBtn.onclick = () => { modal.classList.add('hidden'); }; |
| 629 | startBtn.onclick = async () => { await this.startEventWithParticipants(); }; |
| 630 | |
| 631 | // initial state |
| 632 | this._updateParticipantButtons(); |
| 633 | |
| 634 | modal.classList.remove('hidden'); |
| 635 | } |
| 636 | |
| 637 | _updateParticipantButtons () |
| 638 | { |
| 639 | const list = document.getElementById('participantsList'); |
| 640 | const selected = Array.from(list.querySelectorAll('.participant-checkbox:checked')).map(cb => cb.dataset.id); |
| 641 | const count = selected.length; |
| 642 | document.getElementById('participantCount').textContent = `${count} selected`; |
| 643 | |
| 644 | const startBtn = document.getElementById('startEventBtn'); |
| 645 | if (count >= (this.participantMin || 1) && count <= (this.participantMax || 3)) |
| 646 | { |
| 647 | startBtn.disabled = false; |
| 648 | } else |
| 649 | { |
| 650 | startBtn.disabled = true; |
| 651 | } |
| 652 | } |
| 653 | |
| 654 | async startEventWithParticipants () |
| 655 | { |
| 656 | const modal = document.getElementById('participantModal'); |
| 657 | const list = document.getElementById('participantsList'); |
| 658 | const selected = Array.from(list.querySelectorAll('.participant-checkbox:checked')).map(cb => cb.dataset.id); |
| 659 | |
| 660 | if (!selected || selected.length === 0) return; |
| 661 | |
| 662 | try |
| 663 | { |
| 664 | const resp = await fetch('api/game/event', { |
| 665 | method: 'POST', |
| 666 | headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser.token}` }, |
| 667 | body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, eventType: this.currentEventType, participants: selected }) |
| 668 | }); |
| 669 | |
| 670 | const dataText = await resp.text(); |
| 671 | const data = JSON.parse(dataText); |
| 672 | |
| 673 | if (data.success) |
| 674 | { |
| 675 | typeText(document.getElementById('eventStory'), data.story); |
| 676 | this.showEventModal(); |
| 677 | modal.classList.add('hidden'); |
| 678 | await this.loadGame(this.currentSave.id); |
| 679 | } else |
| 680 | { |
| 681 | alert(data.error || 'Failed to start event'); |
| 682 | } |
| 683 | } catch (err) |
| 684 | { |
| 685 | console.error(err); |
| 686 | alert('Failed to start event'); |
| 687 | } |
| 688 | } |
| 689 | |
| 690 | async endMonth () |
| 691 | { |
| 692 | try |
| 693 | { |
| 694 | const response = await fetch('api/game/endMonth', { |
| 695 | method: 'POST', |
| 696 | headers: { |
| 697 | 'Content-Type': 'application/json', |
| 698 | 'Authorization': `Bearer ${this.currentUser.token}` |
| 699 | }, |
| 700 | body: JSON.stringify({ |
| 701 | userId: this.currentUser.id, saveId: this.currentSave.id |
| 702 | }) |
| 703 | }); |
| 704 | |
| 705 | const dataT = await response.text(); |
| 706 | const data = JSON.parse(dataT); |
| 707 | |
| 708 | if (data.success) |
| 709 | { |
| 710 | this.currentSave = data.save; |
| 711 | typeText(document.getElementById('eventStory'), data.monthStory); |
| 712 | this.showEventModal(); |
| 713 | await this.loadGame(this.currentSave.id); |
| 714 | } |
| 715 | } catch (error) |
| 716 | { |
| 717 | alert('Failed to end month'); |
| 718 | console.error(error); |
| 719 | } |
| 720 | } |
| 721 | |
| 722 | showEventModal () |
| 723 | { |
| 724 | document.getElementById('eventModal').classList.remove('hidden'); |
| 725 | } |
| 726 | |
| 727 | hideEventModal () |
| 728 | { |
| 729 | if (!doneTyping) return; |
| 730 | document.getElementById('eventModal').classList.add('hidden'); |
| 731 | this.renderGame(); |
| 732 | } |
| 733 | |
| 734 | renderStorage () |
| 735 | { |
| 736 | const foodDisplay = document.getElementById('foodDisplay'); |
| 737 | foodDisplay.textContent = `Food: ${this.currentSave.food_count}`; |
| 738 | |
| 739 | const storageItems = document.getElementById('storageItems'); |
| 740 | storageItems.innerHTML = ''; |
| 741 | |
| 742 | if (!this.currentTribe.storage || this.currentTribe.storage.length === 0) |
| 743 | { |
| 744 | storageItems.innerHTML = '<div style="text-align: center; color: #999; padding: 10px;">No items in storage</div>'; |
| 745 | return; |
| 746 | } |
| 747 | |
| 748 | this.currentTribe.storage.forEach(item => |
| 749 | { |
| 750 | const itemEl = document.createElement('div'); |
| 751 | itemEl.className = 'storage-item'; |
| 752 | itemEl.innerHTML = `<div class="storage-item-name">${item.name}</div>`; |
| 753 | itemEl.addEventListener('click', () => this.showItemModal(item)); |
| 754 | storageItems.appendChild(itemEl); |
| 755 | }); |
| 756 | } |
| 757 | |
| 758 | showItemModal (item) |
| 759 | { |
| 760 | const modal = document.getElementById('itemModal'); |
| 761 | document.getElementById('itemModalName').textContent = item.name; |
| 762 | document.getElementById('itemModalDescription').textContent = item.description || 'No description'; |
| 763 | |
| 764 | // Show stat modifications (handle both camelCase and snake_case) |
| 765 | const statMods = document.getElementById('itemModalStatMods'); |
| 766 | statMods.innerHTML = ''; |
| 767 | |
| 768 | const modifications = item.stat_modifications || item.statModifications || {}; |
| 769 | if (Object.keys(modifications).length > 0) |
| 770 | { |
| 771 | Object.entries(modifications).forEach(([stat, value]) => |
| 772 | { |
| 773 | if (value !== 0) |
| 774 | { |
| 775 | const modEl = document.createElement('div'); |
| 776 | modEl.className = `stat-mod ${value > 0 ? 'positive' : 'negative'}`; |
| 777 | modEl.innerHTML = `<span>${this.capitalizeFirst(stat)}</span><span>${value > 0 ? '+' : ''}${value}</span>`; |
| 778 | statMods.appendChild(modEl); |
| 779 | } |
| 780 | }); |
| 781 | } else |
| 782 | { |
| 783 | statMods.innerHTML = '<div style="color: #999; font-size: 0.9em;">No stat modifications</div>'; |
| 784 | } |
| 785 | |
| 786 | // Restore item modal actions to storage version |
| 787 | const actions = document.querySelector('.item-modal-actions'); |
| 788 | actions.innerHTML = ''; |
| 789 | |
| 790 | const select = document.createElement('select'); |
| 791 | select.id = 'itemKoboldSelect'; |
| 792 | select.className = 'kobold-select'; |
| 793 | select.innerHTML = '<option value="">Select a Kobold...</option>'; |
| 794 | this.currentTribe.kobolds.forEach(kobold => |
| 795 | { |
| 796 | const option = document.createElement('option'); |
| 797 | option.value = kobold.id; |
| 798 | option.textContent = kobold.name; |
| 799 | select.appendChild(option); |
| 800 | }); |
| 801 | |
| 802 | const giveBtn = document.createElement('button'); |
| 803 | giveBtn.id = 'giveItemBtn'; |
| 804 | giveBtn.className = 'primary'; |
| 805 | giveBtn.textContent = 'Give Item'; |
| 806 | giveBtn.disabled = true; |
| 807 | |
| 808 | select.addEventListener('change', (e) => |
| 809 | { |
| 810 | giveBtn.disabled = !e.target.value; |
| 811 | }); |
| 812 | |
| 813 | giveBtn.addEventListener('click', () => this.giveItemToKobold(item, select.value)); |
| 814 | |
| 815 | actions.appendChild(select); |
| 816 | actions.appendChild(giveBtn); |
| 817 | |
| 818 | modal.classList.remove('hidden'); |
| 819 | } |
| 820 | |
| 821 | async giveItemToKobold (item, koboldId) |
| 822 | { |
| 823 | try |
| 824 | { |
| 825 | const resp = await fetch('api/game/giveItem', { |
| 826 | method: 'POST', |
| 827 | headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser?.token}` }, |
| 828 | body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, koboldId: koboldId, itemId: item.id }) |
| 829 | }); |
| 830 | |
| 831 | const dataText = await resp.text(); |
| 832 | const data = JSON.parse(dataText); |
| 833 | if (data.success) |
| 834 | { |
| 835 | typeText(document.getElementById('eventStory'), data.story); |
| 836 | this.showEventModal(); |
| 837 | // Refresh game state |
| 838 | await this.loadGame(this.currentSave.id); |
| 839 | const kob = this.currentTribe.kobolds.find(k => k.id === koboldId); |
| 840 | } else |
| 841 | { |
| 842 | alert(data.error || 'Failed to give item'); |
| 843 | } |
| 844 | } catch (err) |
| 845 | { |
| 846 | console.error(err); |
| 847 | alert('Failed to give item'); |
| 848 | } finally |
| 849 | { |
| 850 | this.hideItemModal(); |
| 851 | } |
| 852 | } |
| 853 | |
| 854 | hideItemModal () |
| 855 | { |
| 856 | document.getElementById('itemModal').classList.add('hidden'); |
| 857 | } |
| 858 | |
| 859 | hideKoboldModal () |
| 860 | { |
| 861 | const modal = document.getElementById('koboldModal'); |
| 862 | modal.classList.add('hidden'); |
| 863 | } |
| 864 | |
| 865 | showKoboldModal (kobold) |
| 866 | { |
| 867 | const modal = document.getElementById('koboldModal'); |
| 868 | document.getElementById('koboldModalName').textContent = kobold.name; |
| 869 | |
| 870 | const a = (kobold.ageCategory == "old" || kobold.ageCategory == "adult") ? "An" : "A"; |
| 871 | |
| 872 | if (kobold.ageCategory == "egg") |
| 873 | { |
| 874 | document.getElementById('koboldModalAge').textContent = `Not yet hatched`; |
| 875 | document.getElementById('koboldModalDescription').textContent = `An egg.`; |
| 876 | } |
| 877 | else |
| 878 | { |
| 879 | document.getElementById('koboldModalAge').textContent = `${kobold.age} years old`; |
| 880 | document.getElementById('koboldModalDescription').textContent = `${a} ${kobold.ageCategory} ${(kobold.male ? "male" : "female")} Kobold.`; |
| 881 | } |
| 882 | |
| 883 | this.renderKoboldStats(kobold); |
| 884 | this.renderKoboldInventory(kobold); |
| 885 | this.renderKoboldInjuries(kobold); |
| 886 | |
| 887 | // Setup tab buttons |
| 888 | document.querySelectorAll('.kobold-tab-btn').forEach(btn => |
| 889 | { |
| 890 | btn.classList.remove('active'); |
| 891 | btn.addEventListener('click', (e) => this.switchKoboldTab(e.target.dataset.tab)); |
| 892 | }); |
| 893 | document.querySelector('.kobold-tab-btn[data-tab="stats"]').classList.add('active'); |
| 894 | |
| 895 | // Hide all tabs |
| 896 | document.querySelectorAll('.kobold-tab-content').forEach(tab => tab.classList.remove('active')); |
| 897 | document.getElementById('koboldStatsTab').classList.add('active'); |
| 898 | |
| 899 | // Store current kobold for inventory actions |
| 900 | this.selectedKobold = kobold; |
| 901 | |
| 902 | modal.classList.remove('hidden'); |
| 903 | } |
| 904 | |
| 905 | renderKoboldStats (kobold) |
| 906 | { |
| 907 | const statsGrid = document.getElementById('koboldStats'); |
| 908 | statsGrid.innerHTML = ''; |
| 909 | |
| 910 | const stats = ['vitality', 'intelligence', 'medicine', 'crafting', 'personality', 'will', 'fighting']; |
| 911 | stats.forEach(stat => |
| 912 | { |
| 913 | const value = kobold.stats[stat]; |
| 914 | const label = this.getStatLabel(value); |
| 915 | const statEl = document.createElement('div'); |
| 916 | statEl.className = 'stat-item'; |
| 917 | statEl.innerHTML = ` |
| 918 | <div class="stat-name">${stat}</div> |
| 919 | <div class="stat-value">${label}</div> |
| 920 | `; |
| 921 | statsGrid.appendChild(statEl); |
| 922 | }); |
| 923 | |
| 924 | const fatigueValue = Number(kobold.fatigue || 0); |
| 925 | const vitalityValue = Number(kobold.stats?.vitality || 0); |
| 926 | const fatigueLabel = kobold.fatigue_label || this.getFatigueLabel(fatigueValue, vitalityValue); |
| 927 | const fatigueEl = document.createElement('div'); |
| 928 | fatigueEl.className = 'stat-item'; |
| 929 | fatigueEl.innerHTML = ` |
| 930 | <div class="stat-name">energy</div> |
| 931 | <div class="stat-value">${fatigueLabel}</div> |
| 932 | `; |
| 933 | statsGrid.appendChild(fatigueEl); |
| 934 | } |
| 935 | |
| 936 | renderKoboldInventory (kobold) |
| 937 | { |
| 938 | const inventory = document.getElementById('koboldInventory'); |
| 939 | inventory.innerHTML = ''; |
| 940 | |
| 941 | if (!kobold.items || kobold.items.length === 0) |
| 942 | { |
| 943 | inventory.innerHTML = '<div class="kobold-inventory-empty">No items in inventory</div>'; |
| 944 | return; |
| 945 | } |
| 946 | |
| 947 | kobold.items.forEach(item => |
| 948 | { |
| 949 | const itemEl = document.createElement('div'); |
| 950 | itemEl.className = 'kobold-inventory-item'; |
| 951 | itemEl.innerHTML = `<div class="kobold-item-name">${item.name}</div>`; |
| 952 | itemEl.addEventListener('click', () => this.showKoboldItemModal(item, kobold)); |
| 953 | inventory.appendChild(itemEl); |
| 954 | }); |
| 955 | } |
| 956 | |
| 957 | renderKoboldInjuries (kobold) |
| 958 | { |
| 959 | const container = document.getElementById('koboldInjuries'); |
| 960 | container.innerHTML = ''; |
| 961 | |
| 962 | if (!kobold.injuries || kobold.injuries.length === 0) |
| 963 | { |
| 964 | container.innerHTML = '<div class="kobold-inventory-empty">No injuries</div>'; |
| 965 | return; |
| 966 | } |
| 967 | |
| 968 | // Mapping of injury category to required cure item (matches PHP Injury::$cureMap) |
| 969 | const cureMap = { |
| 970 | 'wound': 'basic_medicine', |
| 971 | 'fracture': 'bone-setting', |
| 972 | 'infection': 'healing_herbs', |
| 973 | 'poison': 'antidote', |
| 974 | 'burn': 'burn_salve', |
| 975 | 'malnourished': 'food', |
| 976 | 'old-age': null |
| 977 | }; |
| 978 | |
| 979 | kobold.injuries.forEach(injury => |
| 980 | { |
| 981 | const el = document.createElement('div'); |
| 982 | el.className = 'injury-item'; |
| 983 | const name = injury.injury_type || injury.injuryType || 'Injury'; |
| 984 | const desc = injury.description || ''; |
| 985 | const severity = injury.severity ?? injury.severity ?? 1; |
| 986 | |
| 987 | el.innerHTML = ` |
| 988 | <div class="injury-name">${name} (Severity: ${severity})</div> |
| 989 | <div class="injury-desc">${desc}</div> |
| 990 | `; |
| 991 | |
| 992 | const actions = document.createElement('div'); |
| 993 | actions.className = 'injury-actions'; |
| 994 | |
| 995 | // malnourished has no cure button here |
| 996 | if (injury.category !== 'malnourished' && injury.category !== 'old-age') |
| 997 | { |
| 998 | // Get required medicine from server or calculate from cureMap |
| 999 | let required = injury.required_medicine || injury.requiredMedicine || null; |
| 1000 | if (!required && injury.category) |
| 1001 | { |
| 1002 | required = cureMap[injury.category] || null; |
| 1003 | } |
| 1004 | |
| 1005 | if (required) |
| 1006 | { |
| 1007 | // check if kobold has item with this id |
| 1008 | const hasItem = (kobold.items || []).some(it => it.id === required); |
| 1009 | if (hasItem) |
| 1010 | { |
| 1011 | const btn = document.createElement('button'); |
| 1012 | btn.className = 'primary'; |
| 1013 | btn.textContent = `Cure using ${required}`; |
| 1014 | btn.addEventListener('click', async () => |
| 1015 | { |
| 1016 | try |
| 1017 | { |
| 1018 | const resp = await fetch('api/game/cureInjury', { |
| 1019 | method: 'POST', |
| 1020 | headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser?.token}` }, |
| 1021 | body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, koboldId: kobold.id, injuryId: injury.id, itemId: required }) |
| 1022 | }); |
| 1023 | const dataText = await resp.text(); |
| 1024 | const data = JSON.parse(dataText); |
| 1025 | if (data.success) |
| 1026 | { |
| 1027 | this.hideKoboldModal(); |
| 1028 | typeText(document.getElementById('eventStory'), data.story); |
| 1029 | this.showEventModal(); |
| 1030 | // Refresh game state |
| 1031 | await this.loadGame(this.currentSave.id); |
| 1032 | // reopen kobold modal after refresh |
| 1033 | const refreshed = this.currentTribe.kobolds.find(k => k.id === kobold.id); |
| 1034 | |
| 1035 | } else |
| 1036 | { |
| 1037 | alert(data.error || 'Failed to cure injury'); |
| 1038 | } |
| 1039 | } catch (err) |
| 1040 | { |
| 1041 | console.error(err); |
| 1042 | alert('Failed to cure injury'); |
| 1043 | } |
| 1044 | }); |
| 1045 | actions.appendChild(btn); |
| 1046 | } else |
| 1047 | { |
| 1048 | const note = document.createElement('div'); |
| 1049 | note.style.color = '#999'; |
| 1050 | note.textContent = `Needs: ${required}`; |
| 1051 | actions.appendChild(note); |
| 1052 | } |
| 1053 | } |
| 1054 | } |
| 1055 | |
| 1056 | el.appendChild(actions); |
| 1057 | container.appendChild(el); |
| 1058 | }); |
| 1059 | } |
| 1060 | |
| 1061 | showKoboldItemModal (item, kobold) |
| 1062 | { |
| 1063 | const modal = document.getElementById('itemModal'); |
| 1064 | document.getElementById('itemModalName').textContent = item.name; |
| 1065 | document.getElementById('itemModalDescription').textContent = item.description || 'No description'; |
| 1066 | |
| 1067 | // Show stat modifications (handle both camelCase and snake_case) |
| 1068 | const statMods = document.getElementById('itemModalStatMods'); |
| 1069 | statMods.innerHTML = ''; |
| 1070 | |
| 1071 | const modifications = item.stat_modifications || item.statModifications || {}; |
| 1072 | if (Object.keys(modifications).length > 0) |
| 1073 | { |
| 1074 | Object.entries(modifications).forEach(([stat, value]) => |
| 1075 | { |
| 1076 | if (value !== 0) |
| 1077 | { |
| 1078 | const modEl = document.createElement('div'); |
| 1079 | modEl.className = `stat-mod ${value > 0 ? 'positive' : 'negative'}`; |
| 1080 | modEl.innerHTML = `<span>${this.capitalizeFirst(stat)}</span><span>${value > 0 ? '+' : ''}${value}</span>`; |
| 1081 | statMods.appendChild(modEl); |
| 1082 | } |
| 1083 | }); |
| 1084 | } else |
| 1085 | { |
| 1086 | statMods.innerHTML = '<div style="color: #999; font-size: 0.9em;">No stat modifications</div>'; |
| 1087 | } |
| 1088 | |
| 1089 | // Change button to return item |
| 1090 | const actions = document.querySelector('.item-modal-actions'); |
| 1091 | actions.innerHTML = ''; |
| 1092 | |
| 1093 | const returnBtn = document.createElement('button'); |
| 1094 | returnBtn.className = 'secondary'; |
| 1095 | returnBtn.textContent = 'Return to Storage'; |
| 1096 | returnBtn.addEventListener('click', () => this.returnItemToStorage(item, kobold)); |
| 1097 | actions.appendChild(returnBtn); |
| 1098 | |
| 1099 | modal.classList.remove('hidden'); |
| 1100 | this.selectedKobold = kobold; |
| 1101 | } |
| 1102 | |
| 1103 | async returnItemToStorage (item, kobold) |
| 1104 | { |
| 1105 | try |
| 1106 | { |
| 1107 | const resp = await fetch('api/game/returnItem', { |
| 1108 | method: 'POST', |
| 1109 | headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser?.token}` }, |
| 1110 | body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, koboldId: kobold.id, itemId: item.id }) |
| 1111 | }); |
| 1112 | |
| 1113 | const dataText = await resp.text(); |
| 1114 | const data = JSON.parse(dataText); |
| 1115 | if (data.success) |
| 1116 | { |
| 1117 | typeText(document.getElementById('eventStory'), data.story); |
| 1118 | this.showEventModal(); |
| 1119 | // Refresh game state |
| 1120 | await this.loadGame(this.currentSave.id); |
| 1121 | const refreshed = this.currentTribe.kobolds.find(k => k.id === kobold.id); |
| 1122 | } else |
| 1123 | { |
| 1124 | alert(data.error || 'Failed to return item'); |
| 1125 | } |
| 1126 | } catch (err) |
| 1127 | { |
| 1128 | console.error(err); |
| 1129 | alert('Failed to return item'); |
| 1130 | } finally |
| 1131 | { |
| 1132 | this.hideItemModal(); |
| 1133 | } |
| 1134 | } |
| 1135 | |
| 1136 | switchKoboldTab (tabName) |
| 1137 | { |
| 1138 | // Hide all tabs |
| 1139 | document.querySelectorAll('.kobold-tab-content').forEach(tab => tab.classList.remove('active')); |
| 1140 | document.querySelectorAll('.kobold-tab-btn').forEach(btn => btn.classList.remove('active')); |
| 1141 | |
| 1142 | // Show selected tab |
| 1143 | const tabId = 'kobold' + this.capitalizeFirst(tabName) + 'Tab'; |
| 1144 | document.getElementById(tabId).classList.add('active'); |
| 1145 | document.querySelector(`[data-tab="${tabName}"]`).classList.add('active'); |
| 1146 | } |
| 1147 | |
| 1148 | getStatLabel (statValue) |
| 1149 | { |
| 1150 | if (statValue >= 90) return 'godlike'; |
| 1151 | if (statValue >= 80) return 'divine'; |
| 1152 | if (statValue >= 70) return 'master'; |
| 1153 | if (statValue >= 60) return 'fantastic'; |
| 1154 | if (statValue >= 50) return 'excellent'; |
| 1155 | if (statValue >= 40) return 'good'; |
| 1156 | if (statValue >= 30) return 'decent'; |
| 1157 | if (statValue >= 20) return 'unskilled'; |
| 1158 | if (statValue >= 10) return 'bad'; |
| 1159 | return 'terrible'; |
| 1160 | } |
| 1161 | |
| 1162 | getFatigueLabel (fatigue, vitality) |
| 1163 | { |
| 1164 | const vit = Number(vitality || 0); |
| 1165 | const fat = Number(fatigue || 0); |
| 1166 | if (vit <= 0) return 'exhausted'; |
| 1167 | if (fat <= 0) return 'energetic'; |
| 1168 | const ratio = fat / Math.max(1, vit); |
| 1169 | if (ratio < 0.3) return 'fresh'; |
| 1170 | if (ratio < 0.6) return 'tired'; |
| 1171 | if (ratio < 0.85) return 'weary'; |
| 1172 | return 'exhausted'; |
| 1173 | } |
| 1174 | |
| 1175 | hideAll () |
| 1176 | { |
| 1177 | document.querySelectorAll('.screen').forEach(screen => screen.classList.add('hidden')); |
| 1178 | } |
| 1179 | |
| 1180 | capitalizeFirst (str) |
| 1181 | { |
| 1182 | return str.charAt(0).toUpperCase() + str.slice(1); |
| 1183 | } |
| 1184 | } |
| 1185 | |
| 1186 | // Initialize app when DOM is ready |
| 1187 | document.addEventListener('DOMContentLoaded', () => |
| 1188 | { |
| 1189 | window.app = new TribeGenApp(); |
| 1190 | }); |
| 1191 | |
| 1192 | function typeText (element, text, minDelay = 3, maxDelay = 65) |
| 1193 | { |
| 1194 | doneTyping = false; |
| 1195 | element.textContent = ""; |
| 1196 | let index = 0; |
| 1197 | let timerId = null; |
| 1198 | |
| 1199 | const randDelay = () => |
| 1200 | Math.floor(Math.random() * (maxDelay - minDelay + 1)) + minDelay; |
| 1201 | |
| 1202 | const shouldStop = () => |
| 1203 | { |
| 1204 | if (!element.isConnected) return true; |
| 1205 | if (getComputedStyle(element).display === "none") return true; |
| 1206 | return false; |
| 1207 | }; |
| 1208 | |
| 1209 | return new Promise((resolve) => |
| 1210 | { |
| 1211 | function tick () |
| 1212 | { |
| 1213 | if (shouldStop()) |
| 1214 | { |
| 1215 | if (timerId) clearTimeout(timerId); |
| 1216 | doneTyping = true; |
| 1217 | resolve(false); // stopped early |
| 1218 | return; |
| 1219 | } |
| 1220 | |
| 1221 | if (index >= text.length) |
| 1222 | { |
| 1223 | doneTyping = true; |
| 1224 | resolve(true); // finished normally |
| 1225 | return; |
| 1226 | } |
| 1227 | |
| 1228 | element.textContent += text[index++]; |
| 1229 | timerId = setTimeout(tick, randDelay()); |
| 1230 | } |
| 1231 | |
| 1232 | tick(); |
| 1233 | }); |
| 1234 | } |
| 1235 | |