| 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 | const fatigueValue = Number(kobold.fatigue || 0); |
| 600 | const vitalityValue = Number(kobold.stats?.vitality || 0); |
| 601 | const fatigueLabel = kobold.fatigue_label || this.getFatigueLabel(fatigueValue, vitalityValue); |
| 602 | |
| 603 | if (eligible) |
| 604 | { |
| 605 | row.innerHTML = ` |
| 606 | <label> |
| 607 | <input type="checkbox" class="participant-checkbox" data-id="${kobold.id}"> |
| 608 | <strong>${kobold.name}</strong> (${kobold.ageCategory != "egg" ? fatigueLabel : 'egg'}) |
| 609 | </label> |
| 610 | `; |
| 611 | const cb = row.querySelector('.participant-checkbox'); |
| 612 | cb.addEventListener('change', () => this._updateParticipantButtons()); |
| 613 | } else |
| 614 | { |
| 615 | row.innerHTML = ` |
| 616 | <div class="participant-disabled"> |
| 617 | <span>${kobold.name} (${kobold.ageCategory != "egg" ? fatigueLabel : 'egg'})</span> |
| 618 | <span class="disabled-reason">${reason}</span> |
| 619 | </div> |
| 620 | `; |
| 621 | } |
| 622 | |
| 623 | list.appendChild(row); |
| 624 | }); |
| 625 | |
| 626 | document.getElementById('participantCount').textContent = `0 selected`; |
| 627 | |
| 628 | // cancel/start handlers |
| 629 | const cancelBtn = document.getElementById('cancelParticipantsBtn'); |
| 630 | const startBtn = document.getElementById('startEventBtn'); |
| 631 | |
| 632 | cancelBtn.onclick = () => { modal.classList.add('hidden'); }; |
| 633 | startBtn.onclick = async () => { await this.startEventWithParticipants(); }; |
| 634 | |
| 635 | // initial state |
| 636 | this._updateParticipantButtons(); |
| 637 | |
| 638 | modal.classList.remove('hidden'); |
| 639 | } |
| 640 | |
| 641 | _updateParticipantButtons () |
| 642 | { |
| 643 | const list = document.getElementById('participantsList'); |
| 644 | const selected = Array.from(list.querySelectorAll('.participant-checkbox:checked')).map(cb => cb.dataset.id); |
| 645 | const count = selected.length; |
| 646 | const participantCount = document.getElementById('participantCount'); |
| 647 | const minRequired = this.participantMin || 1; |
| 648 | const maxAllowed = this.participantMax || 3; |
| 649 | let warning = ''; |
| 650 | if (count < minRequired) |
| 651 | { |
| 652 | warning = `need at least ${minRequired}`; |
| 653 | } else if (count > maxAllowed) |
| 654 | { |
| 655 | warning = `${count - maxAllowed} too many`; |
| 656 | } |
| 657 | |
| 658 | const warningHtml = warning ? `<br><span style="color:#d9534f;">${warning.trim()}</span>` : ''; |
| 659 | participantCount.innerHTML = `${count} selected${warningHtml}`; |
| 660 | |
| 661 | const startBtn = document.getElementById('startEventBtn'); |
| 662 | if (count >= (this.participantMin || 1) && count <= (this.participantMax || 3)) |
| 663 | { |
| 664 | startBtn.disabled = false; |
| 665 | } else |
| 666 | { |
| 667 | startBtn.disabled = true; |
| 668 | } |
| 669 | } |
| 670 | |
| 671 | async startEventWithParticipants () |
| 672 | { |
| 673 | const modal = document.getElementById('participantModal'); |
| 674 | const list = document.getElementById('participantsList'); |
| 675 | const selected = Array.from(list.querySelectorAll('.participant-checkbox:checked')).map(cb => cb.dataset.id); |
| 676 | |
| 677 | if (!selected || selected.length === 0) return; |
| 678 | |
| 679 | try |
| 680 | { |
| 681 | const resp = await fetch('api/game/event', { |
| 682 | method: 'POST', |
| 683 | headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser.token}` }, |
| 684 | body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, eventType: this.currentEventType, participants: selected }) |
| 685 | }); |
| 686 | |
| 687 | const dataText = await resp.text(); |
| 688 | const data = JSON.parse(dataText); |
| 689 | |
| 690 | if (data.success) |
| 691 | { |
| 692 | typeText(document.getElementById('eventStory'), data.story); |
| 693 | this.showEventModal(); |
| 694 | modal.classList.add('hidden'); |
| 695 | await this.loadGame(this.currentSave.id); |
| 696 | } else |
| 697 | { |
| 698 | alert(data.error || 'Failed to start event'); |
| 699 | } |
| 700 | } catch (err) |
| 701 | { |
| 702 | console.error(err); |
| 703 | alert('Failed to start event'); |
| 704 | } |
| 705 | } |
| 706 | |
| 707 | async endMonth () |
| 708 | { |
| 709 | try |
| 710 | { |
| 711 | const response = await fetch('api/game/endMonth', { |
| 712 | method: 'POST', |
| 713 | headers: { |
| 714 | 'Content-Type': 'application/json', |
| 715 | 'Authorization': `Bearer ${this.currentUser.token}` |
| 716 | }, |
| 717 | body: JSON.stringify({ |
| 718 | userId: this.currentUser.id, saveId: this.currentSave.id |
| 719 | }) |
| 720 | }); |
| 721 | |
| 722 | const dataT = await response.text(); |
| 723 | const data = JSON.parse(dataT); |
| 724 | |
| 725 | if (data.success) |
| 726 | { |
| 727 | this.currentSave = data.save; |
| 728 | typeText(document.getElementById('eventStory'), data.monthStory); |
| 729 | this.showEventModal(); |
| 730 | await this.loadGame(this.currentSave.id); |
| 731 | } |
| 732 | } catch (error) |
| 733 | { |
| 734 | alert('Failed to end month'); |
| 735 | console.error(error); |
| 736 | } |
| 737 | } |
| 738 | |
| 739 | showEventModal () |
| 740 | { |
| 741 | document.getElementById('eventModal').classList.remove('hidden'); |
| 742 | } |
| 743 | |
| 744 | hideEventModal () |
| 745 | { |
| 746 | if (!doneTyping) return; |
| 747 | document.getElementById('eventModal').classList.add('hidden'); |
| 748 | this.renderGame(); |
| 749 | } |
| 750 | |
| 751 | renderStorage () |
| 752 | { |
| 753 | const foodDisplay = document.getElementById('foodDisplay'); |
| 754 | const monthsLeft = this.currentSave.food_months_remaining; |
| 755 | if (monthsLeft !== undefined && monthsLeft !== null) |
| 756 | { |
| 757 | const label = Number(monthsLeft) === 1 ? 'month' : 'months'; |
| 758 | foodDisplay.textContent = `Food: ${monthsLeft} ${label}`; |
| 759 | } else |
| 760 | { |
| 761 | foodDisplay.textContent = `Food: ${this.currentSave.food_count}`; |
| 762 | } |
| 763 | |
| 764 | const storageItems = document.getElementById('storageItems'); |
| 765 | storageItems.innerHTML = ''; |
| 766 | |
| 767 | if (!this.currentTribe.storage || this.currentTribe.storage.length === 0) |
| 768 | { |
| 769 | storageItems.innerHTML = '<div style="text-align: center; color: #999; padding: 10px;">No items in storage</div>'; |
| 770 | return; |
| 771 | } |
| 772 | |
| 773 | this.currentTribe.storage.forEach(item => |
| 774 | { |
| 775 | const itemEl = document.createElement('div'); |
| 776 | itemEl.className = 'storage-item'; |
| 777 | itemEl.innerHTML = `<div class="storage-item-name">${item.name}</div>`; |
| 778 | itemEl.addEventListener('click', () => this.showItemModal(item)); |
| 779 | storageItems.appendChild(itemEl); |
| 780 | }); |
| 781 | } |
| 782 | |
| 783 | showItemModal (item) |
| 784 | { |
| 785 | const modal = document.getElementById('itemModal'); |
| 786 | document.getElementById('itemModalName').textContent = item.name; |
| 787 | document.getElementById('itemModalDescription').textContent = item.description || 'No description'; |
| 788 | |
| 789 | // Show stat modifications (handle both camelCase and snake_case) |
| 790 | const statMods = document.getElementById('itemModalStatMods'); |
| 791 | statMods.innerHTML = ''; |
| 792 | |
| 793 | const modifications = item.stat_modifications || item.statModifications || {}; |
| 794 | if (Object.keys(modifications).length > 0) |
| 795 | { |
| 796 | Object.entries(modifications).forEach(([stat, value]) => |
| 797 | { |
| 798 | if (value !== 0) |
| 799 | { |
| 800 | const modEl = document.createElement('div'); |
| 801 | modEl.className = `stat-mod ${value > 0 ? 'positive' : 'negative'}`; |
| 802 | modEl.innerHTML = `<span>${this.capitalizeFirst(stat)}</span><span>${value > 0 ? '+' : ''}${value}</span>`; |
| 803 | statMods.appendChild(modEl); |
| 804 | } |
| 805 | }); |
| 806 | } else |
| 807 | { |
| 808 | statMods.innerHTML = '<div style="color: #999; font-size: 0.9em;">No stat modifications</div>'; |
| 809 | } |
| 810 | |
| 811 | // Restore item modal actions to storage version |
| 812 | const actions = document.querySelector('.item-modal-actions'); |
| 813 | actions.innerHTML = ''; |
| 814 | |
| 815 | const select = document.createElement('select'); |
| 816 | select.id = 'itemKoboldSelect'; |
| 817 | select.className = 'kobold-select'; |
| 818 | select.innerHTML = '<option value="">Select a Kobold...</option>'; |
| 819 | this.currentTribe.kobolds.forEach(kobold => |
| 820 | { |
| 821 | const option = document.createElement('option'); |
| 822 | option.value = kobold.id; |
| 823 | option.textContent = kobold.name; |
| 824 | select.appendChild(option); |
| 825 | }); |
| 826 | |
| 827 | const giveBtn = document.createElement('button'); |
| 828 | giveBtn.id = 'giveItemBtn'; |
| 829 | giveBtn.className = 'primary'; |
| 830 | giveBtn.textContent = 'Give Item'; |
| 831 | giveBtn.disabled = true; |
| 832 | |
| 833 | select.addEventListener('change', (e) => |
| 834 | { |
| 835 | giveBtn.disabled = !e.target.value; |
| 836 | }); |
| 837 | |
| 838 | giveBtn.addEventListener('click', () => this.giveItemToKobold(item, select.value)); |
| 839 | |
| 840 | actions.appendChild(select); |
| 841 | actions.appendChild(giveBtn); |
| 842 | |
| 843 | modal.classList.remove('hidden'); |
| 844 | } |
| 845 | |
| 846 | async giveItemToKobold (item, koboldId) |
| 847 | { |
| 848 | try |
| 849 | { |
| 850 | const resp = await fetch('api/game/giveItem', { |
| 851 | method: 'POST', |
| 852 | headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser?.token}` }, |
| 853 | body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, koboldId: koboldId, itemId: item.id }) |
| 854 | }); |
| 855 | |
| 856 | const dataText = await resp.text(); |
| 857 | const data = JSON.parse(dataText); |
| 858 | if (data.success) |
| 859 | { |
| 860 | typeText(document.getElementById('eventStory'), data.story); |
| 861 | this.showEventModal(); |
| 862 | // Refresh game state |
| 863 | await this.loadGame(this.currentSave.id); |
| 864 | const kob = this.currentTribe.kobolds.find(k => k.id === koboldId); |
| 865 | } else |
| 866 | { |
| 867 | alert(data.error || 'Failed to give item'); |
| 868 | } |
| 869 | } catch (err) |
| 870 | { |
| 871 | console.error(err); |
| 872 | alert('Failed to give item'); |
| 873 | } finally |
| 874 | { |
| 875 | this.hideItemModal(); |
| 876 | } |
| 877 | } |
| 878 | |
| 879 | hideItemModal () |
| 880 | { |
| 881 | document.getElementById('itemModal').classList.add('hidden'); |
| 882 | } |
| 883 | |
| 884 | hideKoboldModal () |
| 885 | { |
| 886 | const modal = document.getElementById('koboldModal'); |
| 887 | modal.classList.add('hidden'); |
| 888 | } |
| 889 | |
| 890 | showKoboldModal (kobold) |
| 891 | { |
| 892 | const modal = document.getElementById('koboldModal'); |
| 893 | document.getElementById('koboldModalName').textContent = kobold.name; |
| 894 | |
| 895 | const a = (kobold.ageCategory == "old" || kobold.ageCategory == "adult") ? "An" : "A"; |
| 896 | |
| 897 | if (kobold.ageCategory == "egg") |
| 898 | { |
| 899 | document.getElementById('koboldModalAge').textContent = `Not yet hatched`; |
| 900 | document.getElementById('koboldModalDescription').textContent = `An egg.`; |
| 901 | } |
| 902 | else |
| 903 | { |
| 904 | document.getElementById('koboldModalAge').textContent = `${kobold.age} years old`; |
| 905 | document.getElementById('koboldModalDescription').textContent = `${a} ${kobold.ageCategory} ${(kobold.male ? "male" : "female")} Kobold.`; |
| 906 | } |
| 907 | |
| 908 | this.renderKoboldStats(kobold); |
| 909 | this.renderKoboldInventory(kobold); |
| 910 | this.renderKoboldInjuries(kobold); |
| 911 | |
| 912 | // Setup tab buttons |
| 913 | document.querySelectorAll('.kobold-tab-btn').forEach(btn => |
| 914 | { |
| 915 | btn.classList.remove('active'); |
| 916 | btn.addEventListener('click', (e) => this.switchKoboldTab(e.target.dataset.tab)); |
| 917 | }); |
| 918 | document.querySelector('.kobold-tab-btn[data-tab="stats"]').classList.add('active'); |
| 919 | |
| 920 | // Hide all tabs |
| 921 | document.querySelectorAll('.kobold-tab-content').forEach(tab => tab.classList.remove('active')); |
| 922 | document.getElementById('koboldStatsTab').classList.add('active'); |
| 923 | |
| 924 | // Store current kobold for inventory actions |
| 925 | this.selectedKobold = kobold; |
| 926 | |
| 927 | modal.classList.remove('hidden'); |
| 928 | } |
| 929 | |
| 930 | renderKoboldStats (kobold) |
| 931 | { |
| 932 | const statsGrid = document.getElementById('koboldStats'); |
| 933 | statsGrid.innerHTML = ''; |
| 934 | |
| 935 | const stats = ['vitality', 'intelligence', 'medicine', 'crafting', 'personality', 'will', 'fighting']; |
| 936 | stats.forEach(stat => |
| 937 | { |
| 938 | const value = kobold.stats[stat]; |
| 939 | const label = this.getStatLabel(value); |
| 940 | const statEl = document.createElement('div'); |
| 941 | statEl.className = 'stat-item'; |
| 942 | statEl.innerHTML = ` |
| 943 | <div class="stat-name">${stat}</div> |
| 944 | <div class="stat-value">${label}</div> |
| 945 | `; |
| 946 | statsGrid.appendChild(statEl); |
| 947 | }); |
| 948 | |
| 949 | const fatigueValue = Number(kobold.fatigue || 0); |
| 950 | const vitalityValue = Number(kobold.stats?.vitality || 0); |
| 951 | const fatigueLabel = kobold.fatigue_label || this.getFatigueLabel(fatigueValue, vitalityValue); |
| 952 | const fatigueEl = document.createElement('div'); |
| 953 | fatigueEl.className = 'stat-item'; |
| 954 | fatigueEl.innerHTML = ` |
| 955 | <div class="stat-name">energy</div> |
| 956 | <div class="stat-value">${fatigueLabel}</div> |
| 957 | `; |
| 958 | statsGrid.appendChild(fatigueEl); |
| 959 | } |
| 960 | |
| 961 | renderKoboldInventory (kobold) |
| 962 | { |
| 963 | const inventory = document.getElementById('koboldInventory'); |
| 964 | inventory.innerHTML = ''; |
| 965 | |
| 966 | if (!kobold.items || kobold.items.length === 0) |
| 967 | { |
| 968 | inventory.innerHTML = '<div class="kobold-inventory-empty">No items in inventory</div>'; |
| 969 | return; |
| 970 | } |
| 971 | |
| 972 | kobold.items.forEach(item => |
| 973 | { |
| 974 | const itemEl = document.createElement('div'); |
| 975 | itemEl.className = 'kobold-inventory-item'; |
| 976 | itemEl.innerHTML = `<div class="kobold-item-name">${item.name}</div>`; |
| 977 | itemEl.addEventListener('click', () => this.showKoboldItemModal(item, kobold)); |
| 978 | inventory.appendChild(itemEl); |
| 979 | }); |
| 980 | } |
| 981 | |
| 982 | renderKoboldInjuries (kobold) |
| 983 | { |
| 984 | const container = document.getElementById('koboldInjuries'); |
| 985 | container.innerHTML = ''; |
| 986 | |
| 987 | if (!kobold.injuries || kobold.injuries.length === 0) |
| 988 | { |
| 989 | container.innerHTML = '<div class="kobold-inventory-empty">No injuries</div>'; |
| 990 | return; |
| 991 | } |
| 992 | |
| 993 | // Mapping of injury category to required cure item (matches PHP Injury::$cureMap) |
| 994 | const cureMap = { |
| 995 | 'wound': 'basic_medicine', |
| 996 | 'fracture': 'bone-setting', |
| 997 | 'infection': 'healing_herbs', |
| 998 | 'poison': 'antidote', |
| 999 | 'burn': 'burn_salve', |
| 1000 | 'malnourished': 'food', |
| 1001 | 'old-age': null |
| 1002 | }; |
| 1003 | |
| 1004 | kobold.injuries.forEach(injury => |
| 1005 | { |
| 1006 | const el = document.createElement('div'); |
| 1007 | el.className = 'injury-item'; |
| 1008 | const name = injury.injury_type || injury.injuryType || 'Injury'; |
| 1009 | const desc = injury.description || ''; |
| 1010 | const severity = injury.severity ?? injury.severity ?? 1; |
| 1011 | |
| 1012 | el.innerHTML = ` |
| 1013 | <div class="injury-name">${name}</div> |
| 1014 | <div class="injury-desc">${desc}</div> |
| 1015 | `; |
| 1016 | |
| 1017 | const actions = document.createElement('div'); |
| 1018 | actions.className = 'injury-actions'; |
| 1019 | |
| 1020 | // malnourished has no cure button here |
| 1021 | if (injury.category !== 'malnourished' && injury.category !== 'old-age') |
| 1022 | { |
| 1023 | // Get required medicine from server or calculate from cureMap |
| 1024 | let required = injury.required_medicine || injury.requiredMedicine || null; |
| 1025 | if (!required && injury.category) |
| 1026 | { |
| 1027 | required = cureMap[injury.category] || null; |
| 1028 | } |
| 1029 | |
| 1030 | if (required) |
| 1031 | { |
| 1032 | // check if kobold has item with this id |
| 1033 | const hasItem = (kobold.items || []).some(it => it.id === required); |
| 1034 | if (hasItem) |
| 1035 | { |
| 1036 | const btn = document.createElement('button'); |
| 1037 | btn.className = 'primary'; |
| 1038 | btn.textContent = `Cure using ${required}`; |
| 1039 | btn.addEventListener('click', async () => |
| 1040 | { |
| 1041 | try |
| 1042 | { |
| 1043 | const resp = await fetch('api/game/cureInjury', { |
| 1044 | method: 'POST', |
| 1045 | headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser?.token}` }, |
| 1046 | body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, koboldId: kobold.id, injuryId: injury.id, itemId: required }) |
| 1047 | }); |
| 1048 | const dataText = await resp.text(); |
| 1049 | const data = JSON.parse(dataText); |
| 1050 | if (data.success) |
| 1051 | { |
| 1052 | this.hideKoboldModal(); |
| 1053 | typeText(document.getElementById('eventStory'), data.story); |
| 1054 | this.showEventModal(); |
| 1055 | // Refresh game state |
| 1056 | await this.loadGame(this.currentSave.id); |
| 1057 | // reopen kobold modal after refresh |
| 1058 | const refreshed = this.currentTribe.kobolds.find(k => k.id === kobold.id); |
| 1059 | |
| 1060 | } else |
| 1061 | { |
| 1062 | alert(data.error || 'Failed to cure injury'); |
| 1063 | } |
| 1064 | } catch (err) |
| 1065 | { |
| 1066 | console.error(err); |
| 1067 | alert('Failed to cure injury'); |
| 1068 | } |
| 1069 | }); |
| 1070 | actions.appendChild(btn); |
| 1071 | } else |
| 1072 | { |
| 1073 | const note = document.createElement('div'); |
| 1074 | note.style.color = '#999'; |
| 1075 | note.textContent = `Needs: ${required}`; |
| 1076 | actions.appendChild(note); |
| 1077 | } |
| 1078 | } |
| 1079 | } |
| 1080 | |
| 1081 | el.appendChild(actions); |
| 1082 | container.appendChild(el); |
| 1083 | }); |
| 1084 | } |
| 1085 | |
| 1086 | showKoboldItemModal (item, kobold) |
| 1087 | { |
| 1088 | const modal = document.getElementById('itemModal'); |
| 1089 | document.getElementById('itemModalName').textContent = item.name; |
| 1090 | document.getElementById('itemModalDescription').textContent = item.description || 'No description'; |
| 1091 | |
| 1092 | this.hideKoboldModal(); |
| 1093 | // Show stat modifications (handle both camelCase and snake_case) |
| 1094 | const statMods = document.getElementById('itemModalStatMods'); |
| 1095 | statMods.innerHTML = ''; |
| 1096 | |
| 1097 | const modifications = item.stat_modifications || item.statModifications || {}; |
| 1098 | if (Object.keys(modifications).length > 0) |
| 1099 | { |
| 1100 | Object.entries(modifications).forEach(([stat, value]) => |
| 1101 | { |
| 1102 | if (value !== 0) |
| 1103 | { |
| 1104 | const modEl = document.createElement('div'); |
| 1105 | modEl.className = `stat-mod ${value > 0 ? 'positive' : 'negative'}`; |
| 1106 | modEl.innerHTML = `<span>${this.capitalizeFirst(stat)}</span><span>${value > 0 ? '+' : ''}${value}</span>`; |
| 1107 | statMods.appendChild(modEl); |
| 1108 | } |
| 1109 | }); |
| 1110 | } else |
| 1111 | { |
| 1112 | statMods.innerHTML = '<div style="color: #999; font-size: 0.9em;">No stat modifications</div>'; |
| 1113 | } |
| 1114 | |
| 1115 | // Change button to return item |
| 1116 | const actions = document.querySelector('.item-modal-actions'); |
| 1117 | actions.innerHTML = ''; |
| 1118 | |
| 1119 | const returnBtn = document.createElement('button'); |
| 1120 | returnBtn.className = 'secondary'; |
| 1121 | returnBtn.textContent = 'Return to Storage'; |
| 1122 | returnBtn.addEventListener('click', () => |
| 1123 | { |
| 1124 | this.hideKoboldModal(); |
| 1125 | this.returnItemToStorage(item, kobold); |
| 1126 | }); |
| 1127 | |
| 1128 | actions.appendChild(returnBtn); |
| 1129 | |
| 1130 | modal.classList.remove('hidden'); |
| 1131 | this.selectedKobold = kobold; |
| 1132 | } |
| 1133 | |
| 1134 | async returnItemToStorage (item, kobold) |
| 1135 | { |
| 1136 | try |
| 1137 | { |
| 1138 | const resp = await fetch('api/game/returnItem', { |
| 1139 | method: 'POST', |
| 1140 | headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser?.token}` }, |
| 1141 | body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, koboldId: kobold.id, itemId: item.id }) |
| 1142 | }); |
| 1143 | |
| 1144 | const dataText = await resp.text(); |
| 1145 | const data = JSON.parse(dataText); |
| 1146 | if (data.success) |
| 1147 | { |
| 1148 | typeText(document.getElementById('eventStory'), data.story); |
| 1149 | this.showEventModal(); |
| 1150 | // Refresh game state |
| 1151 | await this.loadGame(this.currentSave.id); |
| 1152 | const refreshed = this.currentTribe.kobolds.find(k => k.id === kobold.id); |
| 1153 | } else |
| 1154 | { |
| 1155 | alert(data.error || 'Failed to return item'); |
| 1156 | } |
| 1157 | } catch (err) |
| 1158 | { |
| 1159 | console.error(err); |
| 1160 | alert('Failed to return item'); |
| 1161 | } finally |
| 1162 | { |
| 1163 | this.hideItemModal(); |
| 1164 | } |
| 1165 | } |
| 1166 | |
| 1167 | switchKoboldTab (tabName) |
| 1168 | { |
| 1169 | // Hide all tabs |
| 1170 | document.querySelectorAll('.kobold-tab-content').forEach(tab => tab.classList.remove('active')); |
| 1171 | document.querySelectorAll('.kobold-tab-btn').forEach(btn => btn.classList.remove('active')); |
| 1172 | |
| 1173 | // Show selected tab |
| 1174 | const tabId = 'kobold' + this.capitalizeFirst(tabName) + 'Tab'; |
| 1175 | document.getElementById(tabId).classList.add('active'); |
| 1176 | document.querySelector(`[data-tab="${tabName}"]`).classList.add('active'); |
| 1177 | } |
| 1178 | |
| 1179 | getStatLabel (statValue) |
| 1180 | { |
| 1181 | if (statValue >= 90) return 'godlike'; |
| 1182 | if (statValue >= 80) return 'divine'; |
| 1183 | if (statValue >= 70) return 'master'; |
| 1184 | if (statValue >= 60) return 'fantastic'; |
| 1185 | if (statValue >= 50) return 'excellent'; |
| 1186 | if (statValue >= 40) return 'good'; |
| 1187 | if (statValue >= 30) return 'decent'; |
| 1188 | if (statValue >= 20) return 'unskilled'; |
| 1189 | if (statValue >= 10) return 'bad'; |
| 1190 | return 'terrible'; |
| 1191 | } |
| 1192 | |
| 1193 | getFatigueLabel (fatigue, vitality) |
| 1194 | { |
| 1195 | const vit = Number(vitality || 0); |
| 1196 | const fat = Number(fatigue || 0); |
| 1197 | if (vit <= 0) return 'exhausted'; |
| 1198 | if (fat <= 0) return 'energetic'; |
| 1199 | const ratio = fat / Math.max(1, vit); |
| 1200 | if (ratio < 0.3) return 'fresh'; |
| 1201 | if (ratio < 0.6) return 'tired'; |
| 1202 | if (ratio < 0.85) return 'weary'; |
| 1203 | return 'exhausted'; |
| 1204 | } |
| 1205 | |
| 1206 | hideAll () |
| 1207 | { |
| 1208 | document.querySelectorAll('.screen').forEach(screen => screen.classList.add('hidden')); |
| 1209 | } |
| 1210 | |
| 1211 | capitalizeFirst (str) |
| 1212 | { |
| 1213 | return str.charAt(0).toUpperCase() + str.slice(1); |
| 1214 | } |
| 1215 | } |
| 1216 | |
| 1217 | // Initialize app when DOM is ready |
| 1218 | document.addEventListener('DOMContentLoaded', () => |
| 1219 | { |
| 1220 | window.app = new TribeGenApp(); |
| 1221 | }); |
| 1222 | |
| 1223 | function typeText (element, text, minDelay = 3, maxDelay = 65) |
| 1224 | { |
| 1225 | doneTyping = false; |
| 1226 | element.textContent = ""; |
| 1227 | let index = 0; |
| 1228 | let timerId = null; |
| 1229 | |
| 1230 | const randDelay = () => |
| 1231 | Math.floor(Math.random() * (maxDelay - minDelay + 1)) + minDelay; |
| 1232 | |
| 1233 | const shouldStop = () => |
| 1234 | { |
| 1235 | if (!element.isConnected) return true; |
| 1236 | if (getComputedStyle(element).display === "none") return true; |
| 1237 | return false; |
| 1238 | }; |
| 1239 | |
| 1240 | return new Promise((resolve) => |
| 1241 | { |
| 1242 | function tick () |
| 1243 | { |
| 1244 | if (shouldStop()) |
| 1245 | { |
| 1246 | if (timerId) clearTimeout(timerId); |
| 1247 | doneTyping = true; |
| 1248 | resolve(false); // stopped early |
| 1249 | return; |
| 1250 | } |
| 1251 | |
| 1252 | if (index >= text.length) |
| 1253 | { |
| 1254 | doneTyping = true; |
| 1255 | resolve(true); // finished normally |
| 1256 | return; |
| 1257 | } |
| 1258 | |
| 1259 | element.textContent += text[index++]; |
| 1260 | timerId = setTimeout(tick, randDelay()); |
| 1261 | } |
| 1262 | |
| 1263 | tick(); |
| 1264 | }); |
| 1265 | } |
| 1266 | |