| 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.environments = []; |
| 13 | this.environmentMap = {}; |
| 14 | this.environmentPreviewTimer = null; |
| 15 | this.selectedEnvironmentId = null; |
| 16 | this.pendingSetup = null; |
| 17 | this.lastPlacementKey = null; |
| 18 | this.init(); |
| 19 | } |
| 20 | |
| 21 | async init () |
| 22 | { |
| 23 | this.setupEventListeners(); |
| 24 | this.checkAuth(); |
| 25 | } |
| 26 | |
| 27 | setupEventListeners () |
| 28 | { |
| 29 | // Auth Events |
| 30 | document.getElementById('loginForm').addEventListener('submit', (e) => this.handleLogin(e)); |
| 31 | document.getElementById('registerForm').addEventListener('submit', (e) => this.handleRegister(e)); |
| 32 | document.getElementById('logoutBtn').addEventListener('click', () => this.handleLogout()); |
| 33 | |
| 34 | // Tab switching |
| 35 | document.querySelectorAll('.tab-btn').forEach(btn => |
| 36 | { |
| 37 | btn.addEventListener('click', (e) => this.switchTab(e.target.dataset.tab)); |
| 38 | }); |
| 39 | |
| 40 | // Main Menu |
| 41 | document.getElementById('newGameBtn').addEventListener('click', () => this.startGameSetup()); |
| 42 | |
| 43 | // Game Setup |
| 44 | document.getElementById('startGenerationBtn').addEventListener('click', () => this.generateKobolds()); |
| 45 | document.getElementById('selectLeaderBtn').addEventListener('click', () => this.selectLeader()); |
| 46 | document.getElementById('finishTribeBtn').addEventListener('click', () => this.finishTribe()); |
| 47 | const envSelect = document.getElementById('environmentSelect'); |
| 48 | if (envSelect) |
| 49 | { |
| 50 | envSelect.addEventListener('change', () => this.handleEnvironmentSelection()); |
| 51 | } |
| 52 | const confirmEnvBtn = document.getElementById('confirmEnvironmentBtn'); |
| 53 | if (confirmEnvBtn) |
| 54 | { |
| 55 | confirmEnvBtn.addEventListener('click', () => this.confirmEnvironment()); |
| 56 | } |
| 57 | |
| 58 | // Game Screen |
| 59 | document.getElementById('endMonthBtn').addEventListener('click', () => this.endMonth()); |
| 60 | const environmentEl = document.getElementById('environment'); |
| 61 | if (environmentEl) |
| 62 | { |
| 63 | environmentEl.addEventListener('click', (e) => this.logEnvironmentClick(e)); |
| 64 | } |
| 65 | |
| 66 | // Modal close buttons |
| 67 | document.querySelectorAll('.modal-close').forEach(btn => |
| 68 | { |
| 69 | btn.addEventListener('click', (e) => |
| 70 | { |
| 71 | const modal = e.target.closest('.modal'); |
| 72 | if (modal) modal.classList.add('hidden'); |
| 73 | }); |
| 74 | }); |
| 75 | |
| 76 | document.getElementById('eventContinueBtn').addEventListener('click', () => this.hideEventModal()); |
| 77 | } |
| 78 | |
| 79 | switchTab (tabName) |
| 80 | { |
| 81 | document.querySelectorAll('.tab-content').forEach(tab => tab.classList.remove('active')); |
| 82 | document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active')); |
| 83 | document.getElementById(tabName + 'Tab').classList.add('active'); |
| 84 | event.target.classList.add('active'); |
| 85 | } |
| 86 | |
| 87 | async checkAuth () |
| 88 | { |
| 89 | // Check if user is logged in |
| 90 | const savedUser = localStorage.getItem('currentUser'); |
| 91 | if (savedUser) |
| 92 | { |
| 93 | this.currentUser = JSON.parse(savedUser); |
| 94 | this.showMainMenu(); |
| 95 | } else |
| 96 | { |
| 97 | this.showAuthScreen(); |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | async handleLogin (e) |
| 102 | { |
| 103 | e.preventDefault(); |
| 104 | const email = document.querySelector('#loginForm input[name="email"]').value; |
| 105 | const password = document.querySelector('#loginForm input[name="password"]').value; |
| 106 | let dataText = "Request failed altogether"; |
| 107 | try |
| 108 | { |
| 109 | const response = await fetch('api/auth/login', { |
| 110 | method: 'POST', |
| 111 | headers: { 'Content-Type': 'application/json' }, |
| 112 | body: JSON.stringify({ email, password }) |
| 113 | }); |
| 114 | |
| 115 | const dataJson = await response; |
| 116 | dataText = await dataJson.text(); |
| 117 | const data = JSON.parse(dataText); |
| 118 | |
| 119 | if (data.success) |
| 120 | { |
| 121 | this.currentUser = data.user; |
| 122 | localStorage.setItem('currentUser', JSON.stringify(data.user)); |
| 123 | this.showMainMenu(); |
| 124 | } else |
| 125 | { |
| 126 | this.showAuthError(data.error); |
| 127 | } |
| 128 | } catch (error) |
| 129 | { |
| 130 | this.showAuthError('Login failed'); |
| 131 | console.error(error); |
| 132 | console.error('Response data:', dataText); |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | async handleRegister (e) |
| 137 | { |
| 138 | e.preventDefault(); |
| 139 | const email = document.querySelector('#registerForm input[name="email"]').value; |
| 140 | const password = document.querySelector('#registerForm input[name="password"]').value; |
| 141 | const passwordConfirm = document.querySelector('#registerForm input[name="passwordConfirm"]').value; |
| 142 | |
| 143 | if (password !== passwordConfirm) |
| 144 | { |
| 145 | this.showAuthError('Passwords do not match'); |
| 146 | return; |
| 147 | } |
| 148 | |
| 149 | let dataText = "Request failed altogether"; |
| 150 | try |
| 151 | { |
| 152 | const response = await fetch('api/auth/register', { |
| 153 | method: 'POST', |
| 154 | headers: { 'Content-Type': 'application/json' }, |
| 155 | body: JSON.stringify({ email, password }) |
| 156 | }); |
| 157 | |
| 158 | const dataRaw = await response; |
| 159 | dataText = await dataRaw.text(); |
| 160 | const data = JSON.parse(dataText); |
| 161 | |
| 162 | if (data.success) |
| 163 | { |
| 164 | this.currentUser = data.user; |
| 165 | localStorage.setItem('currentUser', JSON.stringify(data.user)); |
| 166 | this.showMainMenu(); |
| 167 | } else |
| 168 | { |
| 169 | this.showAuthError(data.error); |
| 170 | } |
| 171 | } catch (error) |
| 172 | { |
| 173 | this.showAuthError('Registration failed'); |
| 174 | console.error(error); |
| 175 | console.error('Response data:', dataText); |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | handleLogout () |
| 180 | { |
| 181 | this.currentUser = null; |
| 182 | localStorage.removeItem('currentUser'); |
| 183 | this.showAuthScreen(); |
| 184 | } |
| 185 | |
| 186 | showAuthError (error) |
| 187 | { |
| 188 | const errorDiv = document.getElementById('authError'); |
| 189 | errorDiv.textContent = error; |
| 190 | errorDiv.classList.add('show'); |
| 191 | setTimeout(() => errorDiv.classList.remove('show'), 5000); |
| 192 | } |
| 193 | |
| 194 | showAuthScreen () |
| 195 | { |
| 196 | this.hideAll(); |
| 197 | document.getElementById('authScreen').classList.remove('hidden'); |
| 198 | } |
| 199 | |
| 200 | showMainMenu () |
| 201 | { |
| 202 | this.hideAll(); |
| 203 | document.getElementById('mainMenuScreen').classList.remove('hidden'); |
| 204 | document.getElementById('userEmail').textContent = this.currentUser.email; |
| 205 | this.loadSaves(); |
| 206 | } |
| 207 | |
| 208 | async loadSaves () |
| 209 | { |
| 210 | let dataText = "Request failed altogether"; |
| 211 | try |
| 212 | { |
| 213 | const response = await fetch(`api/game/list?userId=${this.currentUser.email}`, { |
| 214 | method: 'GET', |
| 215 | headers: { 'Authorization': `Bearer ${this.currentUser.token}` } |
| 216 | }); |
| 217 | |
| 218 | dataText = await response.text(); |
| 219 | const data = JSON.parse(dataText); |
| 220 | |
| 221 | if (!data.success && data.error == "Not authenticated") |
| 222 | { |
| 223 | this.handleLogout(); |
| 224 | return; |
| 225 | } |
| 226 | |
| 227 | const savesList = document.getElementById('savesList'); |
| 228 | savesList.innerHTML = ''; |
| 229 | |
| 230 | if (data.saves && data.saves.length > 0) |
| 231 | { |
| 232 | data.saves.forEach(save => |
| 233 | { |
| 234 | const card = document.createElement('div'); |
| 235 | card.className = 'save-card'; |
| 236 | card.innerHTML = ` |
| 237 | <h3>${save.name}</h3> |
| 238 | <p>Month: ${save.current_month}</p> |
| 239 | <p>Season: ${save.current_season}</p> |
| 240 | `; |
| 241 | card.addEventListener('click', () => this.loadGame(save.id)); |
| 242 | savesList.appendChild(card); |
| 243 | }); |
| 244 | } |
| 245 | } catch (error) |
| 246 | { |
| 247 | console.error('Failed to load saves:', error); |
| 248 | console.error('Response data:', dataText); |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | startGameSetup () |
| 253 | { |
| 254 | this.hideAll(); |
| 255 | document.getElementById('gameSetupScreen').classList.remove('hidden'); |
| 256 | document.getElementById('setupStep1').classList.remove('hidden'); |
| 257 | document.getElementById('setupStep2').classList.add('hidden'); |
| 258 | document.getElementById('setupStep3').classList.add('hidden'); |
| 259 | document.getElementById('setupStep4').classList.add('hidden'); |
| 260 | this.selectedEnvironmentId = null; |
| 261 | this.pendingSetup = null; |
| 262 | } |
| 263 | |
| 264 | async generateKobolds () |
| 265 | { |
| 266 | const tribeName = document.getElementById('tribeName').value; |
| 267 | |
| 268 | if (!tribeName) |
| 269 | { |
| 270 | alert('Please enter a tribe name'); |
| 271 | return; |
| 272 | } |
| 273 | |
| 274 | let dataText = "Request failed altogether"; |
| 275 | try |
| 276 | { |
| 277 | const response = await fetch('api/game/generation', { |
| 278 | method: 'POST', |
| 279 | headers: { |
| 280 | 'Content-Type': 'application/json', |
| 281 | 'Authorization': `Bearer ${this.currentUser.token}` |
| 282 | }, |
| 283 | body: JSON.stringify({ |
| 284 | saveName: tribeName, |
| 285 | userId: this.currentUser.email |
| 286 | }) |
| 287 | }); |
| 288 | |
| 289 | dataText = await response.text(); |
| 290 | const data = JSON.parse(dataText); |
| 291 | |
| 292 | if (data.success) |
| 293 | { |
| 294 | this.currentSave = data.save; |
| 295 | this.displayKobolds(data.kobolds, 'leader'); |
| 296 | this.displayKobolds(data.kobolds, 'member'); |
| 297 | |
| 298 | document.getElementById('setupStep1').classList.add('hidden'); |
| 299 | document.getElementById('setupStep2').classList.remove('hidden'); |
| 300 | } |
| 301 | } catch (error) |
| 302 | { |
| 303 | alert('Failed to generate kobolds'); |
| 304 | console.error(error); |
| 305 | console.error('Response data:', dataText); |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | displayKobolds (kobolds, type) |
| 310 | { |
| 311 | const container = type === 'leader' |
| 312 | ? document.getElementById('leaderSelectionGrid') |
| 313 | : document.getElementById('memberSelectionGrid'); |
| 314 | |
| 315 | container.innerHTML = ''; |
| 316 | |
| 317 | kobolds.forEach((kobold, index) => |
| 318 | { |
| 319 | const card = document.createElement('div'); |
| 320 | card.className = 'kobold-card'; |
| 321 | |
| 322 | const spriteUrl = `api/game/sprite?userId=${this.currentUser.email}&koboldId=${kobold.id}&age=${kobold.ageCategory}`; |
| 323 | |
| 324 | card.innerHTML = ` |
| 325 | <img src="${spriteUrl}" alt="Kobold sprite" class="kobold-sprite"> |
| 326 | <div class="kobold-name">${kobold.age} years</div> |
| 327 | <div class="kobold-stats"> |
| 328 | <div>Vitality: ${kobold.stats.vitality}</div> |
| 329 | </div> |
| 330 | `; |
| 331 | |
| 332 | if (type === 'member') |
| 333 | { |
| 334 | card.addEventListener('click', () => this.toggleMemberSelection(card, index)); |
| 335 | } else |
| 336 | { |
| 337 | card.addEventListener('click', () => this.selectLeaderCard(card, index)); |
| 338 | } |
| 339 | |
| 340 | container.appendChild(card); |
| 341 | }); |
| 342 | } |
| 343 | |
| 344 | async selectLeaderCard (card, index) |
| 345 | { |
| 346 | const leaderName = document.getElementById('leaderName').value; |
| 347 | |
| 348 | if (!leaderName) |
| 349 | { |
| 350 | alert('Please enter a leader name'); |
| 351 | return; |
| 352 | } |
| 353 | |
| 354 | document.querySelectorAll('#leaderSelectionGrid .kobold-card').forEach(c => c.classList.remove('selected')); |
| 355 | card.classList.add('selected'); |
| 356 | document.getElementById('selectLeaderBtn').dataset.leaderIndex = index; |
| 357 | |
| 358 | this.toggleMemberSelection(card, index, true); |
| 359 | await this.selectLeader(); |
| 360 | } |
| 361 | |
| 362 | toggleMemberSelection (card, index, force) |
| 363 | { |
| 364 | const leaderIndex = document.getElementById('selectLeaderBtn').dataset.leaderIndex; |
| 365 | if (force || leaderIndex != index) |
| 366 | { |
| 367 | const selectedCard = document.querySelectorAll('#memberSelectionGrid .kobold-card')[index]; |
| 368 | selectedCard.classList.toggle('selected'); |
| 369 | |
| 370 | if (force) |
| 371 | { |
| 372 | selectedCard.id = "tribeLeader"; |
| 373 | } |
| 374 | |
| 375 | const selected = document.querySelectorAll('#memberSelectionGrid .kobold-card.selected').length; |
| 376 | document.getElementById('memberCount').textContent = `${selected} / 5 selected`; |
| 377 | |
| 378 | if (selected === 5) |
| 379 | { |
| 380 | document.getElementById('finishTribeBtn').disabled = false; |
| 381 | } else |
| 382 | { |
| 383 | document.getElementById('finishTribeBtn').disabled = true; |
| 384 | } |
| 385 | } |
| 386 | } |
| 387 | |
| 388 | async selectLeader () |
| 389 | { |
| 390 | const leaderName = document.getElementById('leaderName').value; |
| 391 | |
| 392 | if (!leaderName) |
| 393 | { |
| 394 | alert('Please enter a leader name'); |
| 395 | return; |
| 396 | } |
| 397 | |
| 398 | // Proceed to member selection |
| 399 | document.getElementById('setupStep2').classList.add('hidden'); |
| 400 | document.getElementById('setupStep3').classList.remove('hidden'); |
| 401 | |
| 402 | // For now, just display remaining kobolds (in real implementation, filter out leader) |
| 403 | } |
| 404 | |
| 405 | async finishTribe () |
| 406 | { |
| 407 | const leaderIndex = document.getElementById('selectLeaderBtn').dataset.leaderIndex; |
| 408 | const selectedMembers = document.querySelectorAll('#memberSelectionGrid .kobold-card.selected'); |
| 409 | |
| 410 | const memberIndices = Array.from(selectedMembers).map(card => |
| 411 | { |
| 412 | return Array.from(card.parentElement.children).indexOf(card); |
| 413 | }); |
| 414 | |
| 415 | this.pendingSetup = { |
| 416 | leaderIndex: leaderIndex, |
| 417 | memberIndices: memberIndices, |
| 418 | leaderName: document.getElementById('leaderName').value |
| 419 | }; |
| 420 | |
| 421 | await this.showEnvironmentStep(); |
| 422 | } |
| 423 | |
| 424 | async showEnvironmentStep () |
| 425 | { |
| 426 | await this.ensureEnvironmentsLoaded(); |
| 427 | this.renderEnvironmentOptions(); |
| 428 | const select = document.getElementById('environmentSelect'); |
| 429 | if (select) |
| 430 | { |
| 431 | select.value = ''; |
| 432 | } |
| 433 | document.getElementById('setupStep3').classList.add('hidden'); |
| 434 | document.getElementById('setupStep4').classList.remove('hidden'); |
| 435 | this.selectedEnvironmentId = null; |
| 436 | const confirmEnvBtn = document.getElementById('confirmEnvironmentBtn'); |
| 437 | if (confirmEnvBtn) |
| 438 | { |
| 439 | confirmEnvBtn.disabled = true; |
| 440 | } |
| 441 | this.stopEnvironmentPreview(); |
| 442 | const preview = document.getElementById('environmentPreview'); |
| 443 | if (preview) |
| 444 | { |
| 445 | preview.removeAttribute('src'); |
| 446 | } |
| 447 | const desc = document.getElementById('environmentDescription'); |
| 448 | if (desc) |
| 449 | { |
| 450 | desc.textContent = ''; |
| 451 | } |
| 452 | } |
| 453 | |
| 454 | async ensureEnvironmentsLoaded () |
| 455 | { |
| 456 | if (this.environments && this.environments.length > 0) |
| 457 | { |
| 458 | return; |
| 459 | } |
| 460 | |
| 461 | await this.loadEnvironments(); |
| 462 | } |
| 463 | |
| 464 | async loadEnvironments () |
| 465 | { |
| 466 | let dataText = "Request failed altogether"; |
| 467 | try |
| 468 | { |
| 469 | const response = await fetch('api/game/environments', { |
| 470 | method: 'GET' |
| 471 | }); |
| 472 | |
| 473 | dataText = await response.text(); |
| 474 | const data = JSON.parse(dataText); |
| 475 | |
| 476 | if (data.success) |
| 477 | { |
| 478 | this.environments = data.environments || []; |
| 479 | this.environmentMap = {}; |
| 480 | this.environments.forEach(env => |
| 481 | { |
| 482 | if (env && env.id) |
| 483 | { |
| 484 | this.environmentMap[env.id] = env; |
| 485 | } |
| 486 | }); |
| 487 | } |
| 488 | } catch (error) |
| 489 | { |
| 490 | console.error('Failed to load environments', error); |
| 491 | console.error('Response data:', dataText); |
| 492 | } |
| 493 | } |
| 494 | |
| 495 | renderEnvironmentOptions () |
| 496 | { |
| 497 | const select = document.getElementById('environmentSelect'); |
| 498 | if (!select) |
| 499 | { |
| 500 | return; |
| 501 | } |
| 502 | |
| 503 | select.innerHTML = '<option value="">Select an environment...</option>'; |
| 504 | this.environments.forEach(env => |
| 505 | { |
| 506 | const option = document.createElement('option'); |
| 507 | option.value = env.id; |
| 508 | option.textContent = env.name || env.id; |
| 509 | select.appendChild(option); |
| 510 | }); |
| 511 | } |
| 512 | |
| 513 | handleEnvironmentSelection () |
| 514 | { |
| 515 | const select = document.getElementById('environmentSelect'); |
| 516 | const envId = select ? select.value : ''; |
| 517 | this.selectedEnvironmentId = envId || null; |
| 518 | |
| 519 | const env = this.environmentMap[envId]; |
| 520 | const desc = document.getElementById('environmentDescription'); |
| 521 | if (desc) |
| 522 | { |
| 523 | desc.textContent = env && env.description ? env.description : ''; |
| 524 | } |
| 525 | |
| 526 | const confirmEnvBtn = document.getElementById('confirmEnvironmentBtn'); |
| 527 | if (confirmEnvBtn) |
| 528 | { |
| 529 | confirmEnvBtn.disabled = !envId; |
| 530 | } |
| 531 | |
| 532 | if (env && Array.isArray(env.images)) |
| 533 | { |
| 534 | this.startEnvironmentPreview(env.images); |
| 535 | } else |
| 536 | { |
| 537 | this.stopEnvironmentPreview(); |
| 538 | } |
| 539 | } |
| 540 | |
| 541 | startEnvironmentPreview (images) |
| 542 | { |
| 543 | this.stopEnvironmentPreview(); |
| 544 | const preview = document.getElementById('environmentPreview'); |
| 545 | if (!preview || !images || images.length === 0) |
| 546 | { |
| 547 | return; |
| 548 | } |
| 549 | |
| 550 | let index = 0; |
| 551 | preview.src = images[index]; |
| 552 | this.environmentPreviewTimer = setInterval(() => |
| 553 | { |
| 554 | index = (index + 1) % images.length; |
| 555 | preview.src = images[index]; |
| 556 | }, 2000); |
| 557 | } |
| 558 | |
| 559 | stopEnvironmentPreview () |
| 560 | { |
| 561 | if (this.environmentPreviewTimer) |
| 562 | { |
| 563 | clearInterval(this.environmentPreviewTimer); |
| 564 | this.environmentPreviewTimer = null; |
| 565 | } |
| 566 | } |
| 567 | |
| 568 | async confirmEnvironment () |
| 569 | { |
| 570 | if (!this.pendingSetup) |
| 571 | { |
| 572 | alert('Missing tribe setup data. Please start again.'); |
| 573 | return; |
| 574 | } |
| 575 | |
| 576 | if (!this.selectedEnvironmentId) |
| 577 | { |
| 578 | alert('Please select an environment'); |
| 579 | return; |
| 580 | } |
| 581 | |
| 582 | let dataText = "Request failed altogether"; |
| 583 | try |
| 584 | { |
| 585 | const response = await fetch('api/game/save', { |
| 586 | method: 'POST', |
| 587 | headers: { |
| 588 | 'Content-Type': 'application/json', |
| 589 | 'Authorization': `Bearer ${this.currentUser.token}` |
| 590 | }, |
| 591 | body: JSON.stringify({ |
| 592 | userId: this.currentUser.email, |
| 593 | saveId: this.currentSave.id, |
| 594 | leaderName: this.pendingSetup.leaderName, |
| 595 | memberIndices: this.pendingSetup.memberIndices, |
| 596 | leaderId: this.pendingSetup.leaderIndex, |
| 597 | environmentId: this.selectedEnvironmentId |
| 598 | }) |
| 599 | }); |
| 600 | |
| 601 | dataText = await response.text(); |
| 602 | const data = JSON.parse(dataText); |
| 603 | |
| 604 | if (data.success) |
| 605 | { |
| 606 | this.stopEnvironmentPreview(); |
| 607 | this.loadGame(this.currentSave.id); |
| 608 | } |
| 609 | } catch (error) |
| 610 | { |
| 611 | alert('Failed to finish tribe setup'); |
| 612 | console.error(error); |
| 613 | console.error('Response data:', dataText); |
| 614 | } |
| 615 | } |
| 616 | |
| 617 | async loadGame (saveId) |
| 618 | { |
| 619 | let dataText = "Request failed altogether"; |
| 620 | try |
| 621 | { |
| 622 | const response = await fetch(`api/game/load?saveId=${saveId}&userId=${this.currentUser.email}`, { |
| 623 | method: 'GET', |
| 624 | headers: { 'Authorization': `Bearer ${this.currentUser.token}` } |
| 625 | }); |
| 626 | |
| 627 | dataText = await response.text(); |
| 628 | const data = JSON.parse(dataText); |
| 629 | |
| 630 | if (data.success) |
| 631 | { |
| 632 | this.currentSave = data.save; |
| 633 | this.currentTribe = data.tribe; |
| 634 | this.cleanupLikes(); |
| 635 | await this.ensureEnvironmentsLoaded(); |
| 636 | await this.fetchAvailableEvents(); |
| 637 | this.showGameScreen(); |
| 638 | } |
| 639 | } catch (error) |
| 640 | { |
| 641 | alert('Failed to load game'); |
| 642 | console.error(error); |
| 643 | console.error('Response data:', dataText); |
| 644 | } |
| 645 | } |
| 646 | |
| 647 | showGameScreen () |
| 648 | { |
| 649 | this.hideAll(); |
| 650 | document.getElementById('gameScreen').classList.remove('hidden'); |
| 651 | this.renderGame(); |
| 652 | } |
| 653 | |
| 654 | renderGame () |
| 655 | { |
| 656 | document.getElementById('tribeName').textContent = this.currentSave.name; |
| 657 | document.getElementById('monthDisplay').textContent = `Month ${this.currentSave.current_month}`; |
| 658 | document.getElementById('seasonDisplay').textContent = this.capitalizeFirst(this.currentSave.current_season); |
| 659 | |
| 660 | this.renderEnvironment(); |
| 661 | this.renderStorage(); |
| 662 | this.renderTribeList(); |
| 663 | this.renderEvents(); |
| 664 | } |
| 665 | |
| 666 | renderEnvironment () |
| 667 | { |
| 668 | const envElement = document.getElementById('environment'); |
| 669 | if (!envElement) |
| 670 | { |
| 671 | return; |
| 672 | } |
| 673 | |
| 674 | const envId = this.getActiveEnvironmentId(); |
| 675 | if (!envId) |
| 676 | { |
| 677 | envElement.style.backgroundImage = ''; |
| 678 | const placements = document.getElementById('koboldPlacements'); |
| 679 | if (placements) |
| 680 | { |
| 681 | placements.innerHTML = ''; |
| 682 | } |
| 683 | return; |
| 684 | } |
| 685 | |
| 686 | const season = (this.currentSave.current_season || 'spring').toLowerCase(); |
| 687 | let imageUrl = `assets/environments/${envId}/${season}.png`; |
| 688 | const env = this.environmentMap[envId]; |
| 689 | if (env && Array.isArray(env.images) && env.images.length > 0) |
| 690 | { |
| 691 | const seasonMatch = env.images.find(img => img.includes(`/${season}.png`)); |
| 692 | if (seasonMatch) |
| 693 | { |
| 694 | imageUrl = seasonMatch; |
| 695 | } else |
| 696 | { |
| 697 | imageUrl = env.images[0]; |
| 698 | } |
| 699 | } |
| 700 | |
| 701 | envElement.style.backgroundImage = `url('${imageUrl}')`; |
| 702 | this.renderEnvironmentPlacements(envId); |
| 703 | } |
| 704 | |
| 705 | renderEnvironmentPlacements (envId) |
| 706 | { |
| 707 | const placements = document.getElementById('koboldPlacements'); |
| 708 | if (!placements) |
| 709 | { |
| 710 | return; |
| 711 | } |
| 712 | |
| 713 | const placementKey = `${this.currentSave?.id ?? 'save'}-${envId}-${this.currentSave?.current_month ?? 0}`; |
| 714 | if (this.lastPlacementKey === placementKey && placements.children.length > 0) |
| 715 | { |
| 716 | return; |
| 717 | } |
| 718 | |
| 719 | this.lastPlacementKey = placementKey; |
| 720 | placements.innerHTML = ''; |
| 721 | const env = this.environmentMap[envId]; |
| 722 | if (!env || !Array.isArray(env.koboldLocations)) |
| 723 | { |
| 724 | return; |
| 725 | } |
| 726 | |
| 727 | const spots = env.koboldLocations |
| 728 | .map(loc => ({ |
| 729 | x: loc ? Number(loc.x) : NaN, |
| 730 | y: loc ? Number(loc.y) : NaN |
| 731 | })) |
| 732 | .filter(loc => Number.isFinite(loc.x) && Number.isFinite(loc.y)); |
| 733 | |
| 734 | if (spots.length === 0 || !this.currentTribe || !Array.isArray(this.currentTribe.kobolds)) |
| 735 | { |
| 736 | return; |
| 737 | } |
| 738 | |
| 739 | let availableSpots = this.shuffleArray(spots.slice()); |
| 740 | if (availableSpots.length > 30) |
| 741 | { |
| 742 | availableSpots = availableSpots.slice(0, 30); |
| 743 | } |
| 744 | |
| 745 | let leader = this.currentTribe.kobolds.find(k => k.is_leader); |
| 746 | if (!leader) |
| 747 | { |
| 748 | leader = this.currentTribe.kobolds[0]; |
| 749 | } |
| 750 | |
| 751 | if (!leader) |
| 752 | { |
| 753 | return; |
| 754 | } |
| 755 | |
| 756 | const leaderSpotIndex = Math.floor(Math.random() * availableSpots.length); |
| 757 | const leaderSpot = availableSpots.splice(leaderSpotIndex, 1)[0]; |
| 758 | const placementList = [{ kobold: leader, spot: leaderSpot }]; |
| 759 | |
| 760 | const others = this.currentTribe.kobolds.filter(k => k.id !== leader.id); |
| 761 | const shuffledOthers = this.shuffleArray(others.slice()); |
| 762 | const maxOthers = Math.min(availableSpots.length, 29, shuffledOthers.length); |
| 763 | |
| 764 | for (let i = 0; i < maxOthers; i++) |
| 765 | { |
| 766 | placementList.push({ kobold: shuffledOthers[i], spot: availableSpots[i] }); |
| 767 | } |
| 768 | |
| 769 | placementList.sort((a, b) => a.spot.y - b.spot.y); |
| 770 | |
| 771 | placementList.forEach(entry => |
| 772 | { |
| 773 | const spriteUrl = `api/game/sprite?userId=${this.currentUser.email}&koboldId=${entry.kobold.id}&age=${entry.kobold.ageCategory}`; |
| 774 | const img = document.createElement('img'); |
| 775 | img.src = spriteUrl; |
| 776 | img.alt = entry.kobold.name; |
| 777 | img.className = 'kobold-placement'; |
| 778 | if (Math.random() < 0.5) |
| 779 | { |
| 780 | img.classList.add('flipped'); |
| 781 | } |
| 782 | img.style.left = `${entry.spot.x * 100}%`; |
| 783 | img.style.top = `${entry.spot.y * 100}%`; |
| 784 | img.style.zIndex = Math.round(entry.spot.y * 1000).toString(); |
| 785 | img.addEventListener('click', (event) => |
| 786 | { |
| 787 | event.stopPropagation(); |
| 788 | this.showKoboldModal(entry.kobold); |
| 789 | }); |
| 790 | placements.appendChild(img); |
| 791 | }); |
| 792 | } |
| 793 | |
| 794 | getActiveEnvironmentId () |
| 795 | { |
| 796 | if (this.currentSave && this.currentSave.environment_id) |
| 797 | { |
| 798 | return this.currentSave.environment_id; |
| 799 | } |
| 800 | if (this.selectedEnvironmentId) |
| 801 | { |
| 802 | return this.selectedEnvironmentId; |
| 803 | } |
| 804 | if (this.environments && this.environments.length > 0) |
| 805 | { |
| 806 | return this.environments[0].id; |
| 807 | } |
| 808 | return null; |
| 809 | } |
| 810 | |
| 811 | logEnvironmentClick (event) |
| 812 | { |
| 813 | const envElement = document.getElementById('environment'); |
| 814 | if (!envElement) |
| 815 | { |
| 816 | return; |
| 817 | } |
| 818 | |
| 819 | if (event.target && event.target.closest && event.target.closest('.kobold-placement')) |
| 820 | { |
| 821 | return; |
| 822 | } |
| 823 | |
| 824 | const rect = envElement.getBoundingClientRect(); |
| 825 | const x = (event.clientX - rect.left) / rect.width; |
| 826 | const y = (event.clientY - rect.top) / rect.height; |
| 827 | const normalizedX = Math.max(0, Math.min(1, x)); |
| 828 | const normalizedY = Math.max(0, Math.min(1, y)); |
| 829 | console.log('Environment click:', { |
| 830 | x: Number(normalizedX.toFixed(3)), |
| 831 | y: Number(normalizedY.toFixed(3)) |
| 832 | }); |
| 833 | } |
| 834 | |
| 835 | shuffleArray (array) |
| 836 | { |
| 837 | for (let i = array.length - 1; i > 0; i--) |
| 838 | { |
| 839 | const j = Math.floor(Math.random() * (i + 1)); |
| 840 | [array[i], array[j]] = [array[j], array[i]]; |
| 841 | } |
| 842 | return array; |
| 843 | } |
| 844 | |
| 845 | renderTribeList () |
| 846 | { |
| 847 | const list = document.getElementById('tribeList'); |
| 848 | list.innerHTML = ''; |
| 849 | |
| 850 | if (!this.currentTribe || !Array.isArray(this.currentTribe.kobolds)) |
| 851 | { |
| 852 | return; |
| 853 | } |
| 854 | |
| 855 | const table = document.createElement('table'); |
| 856 | table.className = 'tribe-table'; |
| 857 | const tbody = document.createElement('tbody'); |
| 858 | table.appendChild(tbody); |
| 859 | |
| 860 | let currentRow = null; |
| 861 | |
| 862 | this.currentTribe.kobolds.forEach((kobold, index) => |
| 863 | { |
| 864 | if (index % 2 === 0) |
| 865 | { |
| 866 | currentRow = document.createElement('tr'); |
| 867 | tbody.appendChild(currentRow); |
| 868 | } |
| 869 | |
| 870 | const cell = document.createElement('td'); |
| 871 | const spriteUrl = `api/game/sprite?userId=${this.currentUser.email}&koboldId=${kobold.id}&age=${kobold.ageCategory}`; |
| 872 | const item = document.createElement('div'); |
| 873 | const isInjured = kobold.injuries && kobold.injuries.length > 0; |
| 874 | item.className = `tribe-item ${isInjured ? 'injured' : ''}`; |
| 875 | item.innerHTML = ` |
| 876 | <div class="tribe-item-content"> |
| 877 | <img class="kobold-list-sprite" src="${spriteUrl}"/> |
| 878 | <div> |
| 879 | <span class="tribe-item-name">${kobold.name}</span><br/><span class="tribe-item-title">${kobold.title != '' ? (kobold.title) : ''}</span> |
| 880 | </div> |
| 881 | </div> |
| 882 | `; |
| 883 | item.addEventListener('click', () => this.showKoboldModal(kobold)); |
| 884 | cell.appendChild(item); |
| 885 | currentRow.appendChild(cell); |
| 886 | }); |
| 887 | |
| 888 | if (currentRow && currentRow.children.length === 1) |
| 889 | { |
| 890 | const emptyCell = document.createElement('td'); |
| 891 | emptyCell.className = 'tribe-cell-empty'; |
| 892 | currentRow.appendChild(emptyCell); |
| 893 | } |
| 894 | |
| 895 | list.appendChild(table); |
| 896 | } |
| 897 | |
| 898 | renderEvents () |
| 899 | { |
| 900 | const list = document.getElementById('eventsList'); |
| 901 | list.innerHTML = ''; |
| 902 | |
| 903 | this.availableEvents = this.availableEvents || []; |
| 904 | this.availableEvents = this.availableEvents.filter(evt => !!evt.available); |
| 905 | |
| 906 | if (!this.availableEvents || this.availableEvents.length === 0) |
| 907 | { |
| 908 | const empty = document.createElement('div'); |
| 909 | empty.className = 'event-item disabled'; |
| 910 | empty.textContent = 'No events available'; |
| 911 | list.appendChild(empty); |
| 912 | return; |
| 913 | } |
| 914 | |
| 915 | this.availableEvents.forEach(evt => |
| 916 | { |
| 917 | function costToText (cost) |
| 918 | { |
| 919 | if (cost >= 95) return "impossible"; |
| 920 | if (cost >= 80) return "near impossible"; |
| 921 | if (cost >= 70) return "extreme"; |
| 922 | if (cost >= 60) return "brutal"; |
| 923 | if (cost >= 50) return "very hard"; |
| 924 | if (cost >= 40) return "hard"; |
| 925 | if (cost >= 30) return "difficult"; |
| 926 | if (cost >= 20) return "moderate"; |
| 927 | if (cost >= 10) return "easy"; |
| 928 | return "trivial"; |
| 929 | } |
| 930 | |
| 931 | const item = document.createElement('div'); |
| 932 | const isAvailable = !!evt.available; |
| 933 | item.className = `event-item ${isAvailable ? '' : 'disabled'}`.trim(); |
| 934 | const costText = Number.isFinite(Number(evt.cost)) ? ` (${costToText(Number(evt.cost))})` : ''; |
| 935 | item.textContent = `${evt.name || evt.type}${costText}${isAvailable ? '' : ' (Unavailable)'}`; |
| 936 | if (isAvailable) |
| 937 | { |
| 938 | item.addEventListener('click', () => this.showParticipantModal(evt.type)); |
| 939 | } |
| 940 | list.appendChild(item); |
| 941 | }); |
| 942 | } |
| 943 | |
| 944 | async fetchAvailableEvents () |
| 945 | { |
| 946 | this.availableEvents = []; |
| 947 | this.availableEventsByType = {}; |
| 948 | |
| 949 | if (!this.currentUser || !this.currentSave) |
| 950 | return; |
| 951 | |
| 952 | let dataText = "Request failed altogether"; |
| 953 | try |
| 954 | { |
| 955 | const response = await fetch(`api/game/events?saveId=${this.currentSave.id}&userId=${this.currentUser.email}`, { |
| 956 | method: 'GET', |
| 957 | headers: { 'Authorization': `Bearer ${this.currentUser.token}` } |
| 958 | }); |
| 959 | |
| 960 | dataText = await response.text(); |
| 961 | const data = JSON.parse(dataText); |
| 962 | |
| 963 | if (data.success && Array.isArray(data.events)) |
| 964 | { |
| 965 | this.availableEvents = data.events; |
| 966 | data.events.forEach(evt => |
| 967 | { |
| 968 | if (evt && evt.type) |
| 969 | this.availableEventsByType[evt.type] = evt; |
| 970 | }); |
| 971 | } |
| 972 | } catch (error) |
| 973 | { |
| 974 | console.error('Failed to load events:', error); |
| 975 | console.error('Response data:', dataText); |
| 976 | } |
| 977 | } |
| 978 | |
| 979 | async executeEvent (eventType) |
| 980 | { |
| 981 | // Deprecated direct execution; use participant modal instead |
| 982 | this.showParticipantModal(eventType); |
| 983 | } |
| 984 | |
| 985 | showParticipantModal (eventType) |
| 986 | { |
| 987 | this.currentEventType = eventType; |
| 988 | const modal = document.getElementById('participantModal'); |
| 989 | const eventData = this.availableEventsByType[eventType] || {}; |
| 990 | const eventLabel = eventData.name || eventType; |
| 991 | document.getElementById('participantModalTitle').textContent = `Select participants for ${eventLabel}`; |
| 992 | |
| 993 | const list = document.getElementById('participantsList'); |
| 994 | list.innerHTML = ''; |
| 995 | |
| 996 | this.participantMin = eventData.min_participants ?? 1; |
| 997 | this.participantMax = eventData.max_participants ?? 3; |
| 998 | this.participantMinAge = eventData.min_age ?? 0; |
| 999 | this.participantCost = eventData.cost || 0; |
| 1000 | |
| 1001 | // Helper: check if kobold is eligible |
| 1002 | const isEligible = (kobold) => |
| 1003 | { |
| 1004 | const ageCategory = (kobold.ageCategory || '').toLowerCase(); |
| 1005 | if (ageCategory === 'egg') return false; // eggs cannot participate |
| 1006 | if (!kobold.isAlive && kobold.isDead) return false; // dead cannot participate (if available from backend) |
| 1007 | if (kobold.age < this.participantMinAge) return false; // too young |
| 1008 | const fatigue = Number(kobold.fatigue || 0); |
| 1009 | const vitality = Number(kobold.stats?.vitality || 0); |
| 1010 | if ((fatigue + this.participantCost) > vitality) return false; |
| 1011 | return true; |
| 1012 | }; |
| 1013 | |
| 1014 | // Render kobolds with eligibility status |
| 1015 | this.currentTribe.kobolds.forEach(kobold => |
| 1016 | { |
| 1017 | const ageCategory = (kobold.ageCategory || '').toLowerCase(); |
| 1018 | const eligible = isEligible(kobold); |
| 1019 | let reason = ''; |
| 1020 | |
| 1021 | if (ageCategory === 'egg') |
| 1022 | reason = '(eggs cannot participate)'; |
| 1023 | else if (kobold.age < this.participantMinAge) |
| 1024 | reason = `(too young, needs age ${this.participantMinAge}+)`; |
| 1025 | else if (this.participantCost > Number(kobold.stats?.vitality || 0)) |
| 1026 | reason = '(too weak)'; |
| 1027 | else if ((Number(kobold.fatigue || 0) + this.participantCost) > Number(kobold.stats?.vitality || 0)) |
| 1028 | reason = '(too tired)'; |
| 1029 | |
| 1030 | const row = document.createElement('div'); |
| 1031 | row.className = `participant-row ${eligible ? 'eligible' : 'ineligible'}`; |
| 1032 | |
| 1033 | const fatigueValue = Number(kobold.fatigue || 0); |
| 1034 | const vitalityValue = Number(kobold.stats?.vitality || 0); |
| 1035 | const fatigueLabel = kobold.fatigue_label || this.getFatigueLabel(fatigueValue, vitalityValue); |
| 1036 | |
| 1037 | if (eligible) |
| 1038 | { |
| 1039 | row.innerHTML = ` |
| 1040 | <label> |
| 1041 | <input type="checkbox" class="participant-checkbox" data-id="${kobold.id}"> |
| 1042 | <strong>${kobold.name}</strong> (${kobold.ageCategory != "egg" ? fatigueLabel : 'egg'}) |
| 1043 | </label> |
| 1044 | `; |
| 1045 | const cb = row.querySelector('.participant-checkbox'); |
| 1046 | cb.addEventListener('change', () => this._updateParticipantButtons()); |
| 1047 | } else |
| 1048 | { |
| 1049 | row.innerHTML = ` |
| 1050 | <div class="participant-disabled"> |
| 1051 | <span>${kobold.name} (${kobold.ageCategory != "egg" ? fatigueLabel : 'egg'})</span> |
| 1052 | <span class="disabled-reason">${reason}</span> |
| 1053 | </div> |
| 1054 | `; |
| 1055 | } |
| 1056 | |
| 1057 | list.appendChild(row); |
| 1058 | }); |
| 1059 | |
| 1060 | document.getElementById('participantCount').textContent = `0 selected`; |
| 1061 | |
| 1062 | // cancel/start handlers |
| 1063 | const cancelBtn = document.getElementById('cancelParticipantsBtn'); |
| 1064 | const startBtn = document.getElementById('startEventBtn'); |
| 1065 | |
| 1066 | cancelBtn.onclick = () => { modal.classList.add('hidden'); }; |
| 1067 | startBtn.onclick = async () => { await this.startEventWithParticipants(); }; |
| 1068 | |
| 1069 | // initial state |
| 1070 | this._updateParticipantButtons(); |
| 1071 | |
| 1072 | modal.classList.remove('hidden'); |
| 1073 | } |
| 1074 | |
| 1075 | _updateParticipantButtons () |
| 1076 | { |
| 1077 | const list = document.getElementById('participantsList'); |
| 1078 | const selected = Array.from(list.querySelectorAll('.participant-checkbox:checked')).map(cb => cb.dataset.id); |
| 1079 | const count = selected.length; |
| 1080 | const participantCount = document.getElementById('participantCount'); |
| 1081 | const minRequired = this.participantMin || 1; |
| 1082 | const maxAllowed = this.participantMax || 3; |
| 1083 | let warning = ''; |
| 1084 | if (count < minRequired) |
| 1085 | { |
| 1086 | warning = `need at least ${minRequired}`; |
| 1087 | } else if (count > maxAllowed) |
| 1088 | { |
| 1089 | warning = `${count - maxAllowed} too many`; |
| 1090 | } |
| 1091 | |
| 1092 | const warningHtml = warning ? `<br><span style="color:#d9534f;">${warning.trim()}</span>` : ''; |
| 1093 | participantCount.innerHTML = `${count} selected${warningHtml}`; |
| 1094 | |
| 1095 | const startBtn = document.getElementById('startEventBtn'); |
| 1096 | if (count >= (this.participantMin || 1) && count <= (this.participantMax || 3)) |
| 1097 | { |
| 1098 | startBtn.disabled = false; |
| 1099 | } else |
| 1100 | { |
| 1101 | startBtn.disabled = true; |
| 1102 | } |
| 1103 | } |
| 1104 | |
| 1105 | async startEventWithParticipants () |
| 1106 | { |
| 1107 | const modal = document.getElementById('participantModal'); |
| 1108 | const list = document.getElementById('participantsList'); |
| 1109 | const selected = Array.from(list.querySelectorAll('.participant-checkbox:checked')).map(cb => cb.dataset.id); |
| 1110 | |
| 1111 | if (!selected || selected.length === 0) return; |
| 1112 | |
| 1113 | let dataText = "Request failed altogether"; |
| 1114 | try |
| 1115 | { |
| 1116 | const resp = await fetch('api/game/event', { |
| 1117 | method: 'POST', |
| 1118 | headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser.token}` }, |
| 1119 | body: JSON.stringify({ userId: this.currentUser.email, saveId: this.currentSave.id, eventType: this.currentEventType, participants: selected }) |
| 1120 | }); |
| 1121 | |
| 1122 | dataText = await resp.text(); |
| 1123 | const data = JSON.parse(dataText); |
| 1124 | |
| 1125 | if (data.success) |
| 1126 | { |
| 1127 | typeText(document.getElementById('eventStory'), data.story); |
| 1128 | this.showEventModal(); |
| 1129 | modal.classList.add('hidden'); |
| 1130 | await this.loadGame(this.currentSave.id); |
| 1131 | } else |
| 1132 | { |
| 1133 | alert(data.error || 'Failed to start event'); |
| 1134 | console.error('Event error:', data); |
| 1135 | } |
| 1136 | } catch (err) |
| 1137 | { |
| 1138 | console.error(err); |
| 1139 | console.error('Response data:', dataText); |
| 1140 | } |
| 1141 | } |
| 1142 | |
| 1143 | async endMonth () |
| 1144 | { |
| 1145 | let dataT = "Request failed altogether"; |
| 1146 | try |
| 1147 | { |
| 1148 | const response = await fetch('api/game/endMonth', { |
| 1149 | method: 'POST', |
| 1150 | headers: { |
| 1151 | 'Content-Type': 'application/json', |
| 1152 | 'Authorization': `Bearer ${this.currentUser.token}` |
| 1153 | }, |
| 1154 | body: JSON.stringify({ |
| 1155 | userId: this.currentUser.email, saveId: this.currentSave.id |
| 1156 | }) |
| 1157 | }); |
| 1158 | |
| 1159 | dataT = await response.text(); |
| 1160 | const data = JSON.parse(dataT); |
| 1161 | |
| 1162 | if (data.success) |
| 1163 | { |
| 1164 | this.currentSave = data.save; |
| 1165 | typeText(document.getElementById('eventStory'), data.monthStory); |
| 1166 | this.showEventModal(); |
| 1167 | await this.loadGame(this.currentSave.id); |
| 1168 | } |
| 1169 | } catch (error) |
| 1170 | { |
| 1171 | alert('Failed to end month'); |
| 1172 | console.error(error); |
| 1173 | console.error('Response data:', dataT); |
| 1174 | } |
| 1175 | } |
| 1176 | |
| 1177 | showEventModal () |
| 1178 | { |
| 1179 | document.getElementById('eventModal').classList.remove('hidden'); |
| 1180 | } |
| 1181 | |
| 1182 | hideEventModal () |
| 1183 | { |
| 1184 | if (!doneTyping) return; |
| 1185 | document.getElementById('eventModal').classList.add('hidden'); |
| 1186 | this.renderGame(); |
| 1187 | } |
| 1188 | |
| 1189 | renderStorage () |
| 1190 | { |
| 1191 | const foodDisplay = document.getElementById('foodDisplay'); |
| 1192 | const timeLeft = this.currentSave.food_time_remaining; |
| 1193 | if (timeLeft !== undefined && timeLeft !== null) |
| 1194 | { |
| 1195 | const label = timeLeft; |
| 1196 | foodDisplay.textContent = `Food: ${label}`; |
| 1197 | } else |
| 1198 | { |
| 1199 | foodDisplay.textContent = `Food: ${this.currentSave.food_count}`; |
| 1200 | } |
| 1201 | |
| 1202 | const storageItems = document.getElementById('storageItems'); |
| 1203 | storageItems.innerHTML = ''; |
| 1204 | |
| 1205 | if (!this.currentTribe.storage || this.currentTribe.storage.length === 0) |
| 1206 | { |
| 1207 | storageItems.innerHTML = '<div style="text-align: center; color: #999; padding: 10px;">No items in storage</div>'; |
| 1208 | return; |
| 1209 | } |
| 1210 | |
| 1211 | this.currentTribe.storage.forEach(item => |
| 1212 | { |
| 1213 | const itemEl = document.createElement('div'); |
| 1214 | itemEl.className = 'storage-item'; |
| 1215 | itemEl.innerHTML = `<div class="storage-item-name">${item.name}</div>`; |
| 1216 | itemEl.addEventListener('click', () => this.showItemModal(item)); |
| 1217 | storageItems.appendChild(itemEl); |
| 1218 | }); |
| 1219 | } |
| 1220 | |
| 1221 | showItemModal (item) |
| 1222 | { |
| 1223 | const modal = document.getElementById('itemModal'); |
| 1224 | document.getElementById('itemModalName').textContent = item.name; |
| 1225 | document.getElementById('itemModalDescription').textContent = item.description || 'No description'; |
| 1226 | |
| 1227 | // Show stat modifications (handle both camelCase and snake_case) |
| 1228 | const statMods = document.getElementById('itemModalStatMods'); |
| 1229 | statMods.innerHTML = ''; |
| 1230 | |
| 1231 | const modifications = item.stat_modifications || item.statModifications || {}; |
| 1232 | if (Object.keys(modifications).length > 0) |
| 1233 | { |
| 1234 | Object.entries(modifications).forEach(([stat, value]) => |
| 1235 | { |
| 1236 | if (value !== 0) |
| 1237 | { |
| 1238 | const modEl = document.createElement('div'); |
| 1239 | modEl.className = `stat-mod ${value > 0 ? 'positive' : 'negative'}`; |
| 1240 | modEl.innerHTML = `<span>${this.capitalizeFirst(stat)}</span><span>${value > 0 ? '+' : ''}${value}</span>`; |
| 1241 | statMods.appendChild(modEl); |
| 1242 | } |
| 1243 | }); |
| 1244 | } else |
| 1245 | { |
| 1246 | statMods.innerHTML = '<div style="color: #999; font-size: 0.9em;">No stat modifications</div>'; |
| 1247 | } |
| 1248 | |
| 1249 | // Restore item modal actions to storage version |
| 1250 | const actions = document.querySelector('.item-modal-actions'); |
| 1251 | actions.innerHTML = ''; |
| 1252 | |
| 1253 | const select = document.createElement('select'); |
| 1254 | select.id = 'itemKoboldSelect'; |
| 1255 | select.className = 'kobold-select'; |
| 1256 | select.innerHTML = '<option value="">Select a Kobold...</option>'; |
| 1257 | this.currentTribe.kobolds.forEach(kobold => |
| 1258 | { |
| 1259 | const option = document.createElement('option'); |
| 1260 | option.value = kobold.id; |
| 1261 | option.textContent = kobold.name; |
| 1262 | select.appendChild(option); |
| 1263 | }); |
| 1264 | |
| 1265 | const giveBtn = document.createElement('button'); |
| 1266 | giveBtn.id = 'giveItemBtn'; |
| 1267 | giveBtn.className = 'primary'; |
| 1268 | giveBtn.textContent = 'Give Item'; |
| 1269 | giveBtn.disabled = true; |
| 1270 | |
| 1271 | select.addEventListener('change', (e) => |
| 1272 | { |
| 1273 | giveBtn.disabled = !e.target.value; |
| 1274 | }); |
| 1275 | |
| 1276 | giveBtn.addEventListener('click', () => this.giveItemToKobold(item, select.value)); |
| 1277 | |
| 1278 | actions.appendChild(select); |
| 1279 | actions.appendChild(giveBtn); |
| 1280 | |
| 1281 | modal.classList.remove('hidden'); |
| 1282 | } |
| 1283 | |
| 1284 | async giveItemToKobold (item, koboldId) |
| 1285 | { |
| 1286 | let dataText = "Request failed altogether"; |
| 1287 | try |
| 1288 | { |
| 1289 | const resp = await fetch('api/game/giveItem', { |
| 1290 | method: 'POST', |
| 1291 | headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser?.token}` }, |
| 1292 | body: JSON.stringify({ userId: this.currentUser.email, saveId: this.currentSave.id, koboldId: koboldId, itemId: item.id }) |
| 1293 | }); |
| 1294 | |
| 1295 | dataText = await resp.text(); |
| 1296 | const data = JSON.parse(dataText); |
| 1297 | if (data.success) |
| 1298 | { |
| 1299 | typeText(document.getElementById('eventStory'), data.story); |
| 1300 | this.showEventModal(); |
| 1301 | // Refresh game state |
| 1302 | await this.loadGame(this.currentSave.id); |
| 1303 | const kob = this.currentTribe.kobolds.find(k => k.id === koboldId); |
| 1304 | } else |
| 1305 | { |
| 1306 | alert(data.error || 'Failed to give item'); |
| 1307 | console.error('Give item error:', data); |
| 1308 | } |
| 1309 | } catch (err) |
| 1310 | { |
| 1311 | console.error(err); |
| 1312 | alert('Failed to give item'); |
| 1313 | console.error('Response data:', dataText); |
| 1314 | } finally |
| 1315 | { |
| 1316 | this.hideItemModal(); |
| 1317 | } |
| 1318 | } |
| 1319 | |
| 1320 | hideItemModal () |
| 1321 | { |
| 1322 | document.getElementById('itemModal').classList.add('hidden'); |
| 1323 | } |
| 1324 | |
| 1325 | hideKoboldModal () |
| 1326 | { |
| 1327 | const modal = document.getElementById('koboldModal'); |
| 1328 | modal.classList.add('hidden'); |
| 1329 | } |
| 1330 | |
| 1331 | showKoboldModal (kobold) |
| 1332 | { |
| 1333 | const modal = document.getElementById('koboldModal'); |
| 1334 | document.getElementById('koboldModalName').textContent = kobold.name; |
| 1335 | const titleEl = document.getElementById('koboldModalTitle'); |
| 1336 | if (titleEl) |
| 1337 | { |
| 1338 | titleEl.textContent = kobold.title || ''; |
| 1339 | } |
| 1340 | |
| 1341 | const a = (kobold.ageCategory == "old" || kobold.ageCategory == "adult") ? "An" : "A"; |
| 1342 | |
| 1343 | if (kobold.ageCategory == "egg") |
| 1344 | { |
| 1345 | document.getElementById('koboldModalAge').textContent = `Not yet hatched`; |
| 1346 | document.getElementById('koboldModalDescription').textContent = `An egg.`; |
| 1347 | } |
| 1348 | else |
| 1349 | { |
| 1350 | document.getElementById('koboldModalAge').textContent = `${kobold.age} years old`; |
| 1351 | document.getElementById('koboldModalDescription').textContent = `${a} ${kobold.ageCategory} ${(kobold.male ? "male" : "female")} Kobold.`; |
| 1352 | } |
| 1353 | |
| 1354 | this.renderKoboldStats(kobold); |
| 1355 | this.renderKoboldInventory(kobold); |
| 1356 | this.renderKoboldInjuries(kobold); |
| 1357 | this.renderKoboldRelationships(kobold); |
| 1358 | |
| 1359 | // Setup tab buttons |
| 1360 | document.querySelectorAll('.kobold-tab-btn').forEach(btn => |
| 1361 | { |
| 1362 | btn.classList.remove('active'); |
| 1363 | btn.addEventListener('click', (e) => this.switchKoboldTab(e.target.dataset.tab)); |
| 1364 | }); |
| 1365 | document.querySelector('.kobold-tab-btn[data-tab="stats"]').classList.add('active'); |
| 1366 | |
| 1367 | // Hide all tabs |
| 1368 | document.querySelectorAll('.kobold-tab-content').forEach(tab => tab.classList.remove('active')); |
| 1369 | document.getElementById('koboldStatsTab').classList.add('active'); |
| 1370 | |
| 1371 | // Store current kobold for inventory actions |
| 1372 | this.selectedKobold = kobold; |
| 1373 | |
| 1374 | modal.classList.remove('hidden'); |
| 1375 | } |
| 1376 | |
| 1377 | renderKoboldStats (kobold) |
| 1378 | { |
| 1379 | const statsGrid = document.getElementById('koboldStats'); |
| 1380 | statsGrid.innerHTML = ''; |
| 1381 | |
| 1382 | const stats = ['vitality', 'intelligence', 'medicine', 'crafting', 'personality', 'will', 'fighting']; |
| 1383 | stats.forEach(stat => |
| 1384 | { |
| 1385 | const value = kobold.stats[stat]; |
| 1386 | const label = this.getStatLabel(value); |
| 1387 | const statEl = document.createElement('div'); |
| 1388 | statEl.className = 'stat-item'; |
| 1389 | statEl.innerHTML = ` |
| 1390 | <div class="stat-name">${stat}</div> |
| 1391 | <div class="stat-value">${label}</div> |
| 1392 | `; |
| 1393 | statsGrid.appendChild(statEl); |
| 1394 | }); |
| 1395 | |
| 1396 | const fatigueValue = Number(kobold.fatigue || 0); |
| 1397 | const vitalityValue = Number(kobold.stats?.vitality || 0); |
| 1398 | const fatigueLabel = kobold.fatigue_label || this.getFatigueLabel(fatigueValue, vitalityValue); |
| 1399 | const fatigueEl = document.createElement('div'); |
| 1400 | fatigueEl.className = 'stat-item'; |
| 1401 | fatigueEl.innerHTML = ` |
| 1402 | <div class="stat-name">energy</div> |
| 1403 | <div class="stat-value">${fatigueLabel}</div> |
| 1404 | `; |
| 1405 | statsGrid.appendChild(fatigueEl); |
| 1406 | } |
| 1407 | |
| 1408 | renderKoboldInventory (kobold) |
| 1409 | { |
| 1410 | const inventory = document.getElementById('koboldInventory'); |
| 1411 | inventory.innerHTML = ''; |
| 1412 | |
| 1413 | if (!kobold.items || kobold.items.length === 0) |
| 1414 | { |
| 1415 | inventory.innerHTML = '<div class="kobold-inventory-empty">No items in inventory</div>'; |
| 1416 | return; |
| 1417 | } |
| 1418 | |
| 1419 | kobold.items.forEach(item => |
| 1420 | { |
| 1421 | const itemEl = document.createElement('div'); |
| 1422 | itemEl.className = 'kobold-inventory-item'; |
| 1423 | itemEl.innerHTML = `<div class="kobold-item-name">${item.name}</div>`; |
| 1424 | itemEl.addEventListener('click', () => this.showKoboldItemModal(item, kobold)); |
| 1425 | inventory.appendChild(itemEl); |
| 1426 | }); |
| 1427 | } |
| 1428 | |
| 1429 | renderKoboldInjuries (kobold) |
| 1430 | { |
| 1431 | const container = document.getElementById('koboldInjuries'); |
| 1432 | container.innerHTML = ''; |
| 1433 | |
| 1434 | if (!kobold.injuries || kobold.injuries.length === 0) |
| 1435 | { |
| 1436 | container.innerHTML = '<div class="kobold-inventory-empty">No injuries</div>'; |
| 1437 | return; |
| 1438 | } |
| 1439 | |
| 1440 | // Mapping of injury category to required cure item (matches PHP Injury::$cureMap) |
| 1441 | const cureMap = { |
| 1442 | 'wound': 'basic_medicine', |
| 1443 | 'fracture': 'bone-setting', |
| 1444 | 'infection': 'healing_herbs', |
| 1445 | 'poison': 'antidote', |
| 1446 | 'burn': 'burn_salve', |
| 1447 | 'malnourished': 'food', |
| 1448 | 'old-age': null |
| 1449 | }; |
| 1450 | |
| 1451 | kobold.injuries.forEach(injury => |
| 1452 | { |
| 1453 | const el = document.createElement('div'); |
| 1454 | el.className = 'injury-item'; |
| 1455 | const name = injury.injury_type || injury.injuryType || 'Injury'; |
| 1456 | const desc = injury.description || ''; |
| 1457 | const severity = injury.severity ?? injury.severity ?? 1; |
| 1458 | |
| 1459 | el.innerHTML = ` |
| 1460 | <div class="injury-name">${name}</div> |
| 1461 | <div class="injury-desc">${desc}</div> |
| 1462 | `; |
| 1463 | |
| 1464 | const actions = document.createElement('div'); |
| 1465 | actions.className = 'injury-actions'; |
| 1466 | |
| 1467 | // malnourished has no cure button here |
| 1468 | if (injury.category !== 'malnourished' && injury.category !== 'old-age') |
| 1469 | { |
| 1470 | // Get required medicine from server or calculate from cureMap |
| 1471 | let required = injury.required_medicine || injury.requiredMedicine || null; |
| 1472 | if (!required && injury.category) |
| 1473 | { |
| 1474 | required = cureMap[injury.category] || null; |
| 1475 | } |
| 1476 | |
| 1477 | if (required) |
| 1478 | { |
| 1479 | const requiredStatRaw = injury.stat_required_to_cure ?? injury.statRequiredToCure ?? null; |
| 1480 | const requiredStat = Number(requiredStatRaw); |
| 1481 | const hasRequiredStat = Number.isFinite(requiredStat); |
| 1482 | |
| 1483 | let doctor = null; |
| 1484 | if (hasRequiredStat) |
| 1485 | { |
| 1486 | const others = (this.currentTribe?.kobolds || []).filter(k => k.id !== kobold.id); |
| 1487 | const bestOther = others.reduce((best, k) => |
| 1488 | { |
| 1489 | const med = Number(k.stats?.medicine || 0); |
| 1490 | if (med >= requiredStat && (!best || med > Number(best.stats?.medicine || 0))) |
| 1491 | { |
| 1492 | return k; |
| 1493 | } |
| 1494 | return best; |
| 1495 | }, null); |
| 1496 | |
| 1497 | if (bestOther) |
| 1498 | { |
| 1499 | doctor = bestOther; |
| 1500 | } else |
| 1501 | { |
| 1502 | const selfMed = Number(kobold.stats?.medicine || 0); |
| 1503 | if (selfMed >= requiredStat) |
| 1504 | { |
| 1505 | doctor = kobold; |
| 1506 | } |
| 1507 | } |
| 1508 | } else |
| 1509 | { |
| 1510 | doctor = kobold; |
| 1511 | } |
| 1512 | |
| 1513 | if (hasRequiredStat && !doctor) |
| 1514 | { |
| 1515 | const label = this.getStatLabel(requiredStat); |
| 1516 | const note = document.createElement('div'); |
| 1517 | note.style.color = '#999'; |
| 1518 | note.textContent = `Requires ${label} doctor`; |
| 1519 | actions.appendChild(note); |
| 1520 | } else |
| 1521 | { |
| 1522 | const hasItemSelf = (kobold.items || []).some(it => it.id === required); |
| 1523 | const hasItemDoctor = doctor && doctor.id !== kobold.id |
| 1524 | ? (doctor.items || []).some(it => it.id === required) |
| 1525 | : false; |
| 1526 | const hasItemStorage = (this.currentTribe?.storage || []).some(it => it.id === required); |
| 1527 | |
| 1528 | if (hasItemSelf || hasItemDoctor || hasItemStorage) |
| 1529 | { |
| 1530 | const btn = document.createElement('button'); |
| 1531 | btn.className = 'primary'; |
| 1532 | btn.textContent = `Cure using ${required}`; |
| 1533 | btn.addEventListener('click', async () => |
| 1534 | { |
| 1535 | let dataText = "Request failed altogether"; |
| 1536 | try |
| 1537 | { |
| 1538 | const resp = await fetch('api/game/cureInjury', { |
| 1539 | method: 'POST', |
| 1540 | headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser?.token}` }, |
| 1541 | body: JSON.stringify({ userId: this.currentUser.email, saveId: this.currentSave.id, koboldId: kobold.id, injuryId: injury.id, itemId: required }) |
| 1542 | }); |
| 1543 | dataText = await resp.text(); |
| 1544 | const data = JSON.parse(dataText); |
| 1545 | if (data.success) |
| 1546 | { |
| 1547 | this.hideKoboldModal(); |
| 1548 | typeText(document.getElementById('eventStory'), data.story); |
| 1549 | this.showEventModal(); |
| 1550 | // Refresh game state |
| 1551 | await this.loadGame(this.currentSave.id); |
| 1552 | // reopen kobold modal after refresh |
| 1553 | const refreshed = this.currentTribe.kobolds.find(k => k.id === kobold.id); |
| 1554 | |
| 1555 | } else |
| 1556 | { |
| 1557 | alert(data.error || 'Failed to cure injury'); |
| 1558 | console.error('Cure injury error:', data); |
| 1559 | } |
| 1560 | } catch (err) |
| 1561 | { |
| 1562 | console.error(err); |
| 1563 | alert('Failed to cure injury'); |
| 1564 | console.error('Response data:', dataText); |
| 1565 | } |
| 1566 | }); |
| 1567 | actions.appendChild(btn); |
| 1568 | } else |
| 1569 | { |
| 1570 | const note = document.createElement('div'); |
| 1571 | note.style.color = '#999'; |
| 1572 | note.textContent = `Needs: ${required}`; |
| 1573 | actions.appendChild(note); |
| 1574 | } |
| 1575 | } |
| 1576 | } |
| 1577 | } |
| 1578 | |
| 1579 | el.appendChild(actions); |
| 1580 | container.appendChild(el); |
| 1581 | }); |
| 1582 | } |
| 1583 | |
| 1584 | showKoboldItemModal (item, kobold) |
| 1585 | { |
| 1586 | const modal = document.getElementById('itemModal'); |
| 1587 | document.getElementById('itemModalName').textContent = item.name; |
| 1588 | document.getElementById('itemModalDescription').textContent = item.description || 'No description'; |
| 1589 | |
| 1590 | this.hideKoboldModal(); |
| 1591 | // Show stat modifications (handle both camelCase and snake_case) |
| 1592 | const statMods = document.getElementById('itemModalStatMods'); |
| 1593 | statMods.innerHTML = ''; |
| 1594 | |
| 1595 | const modifications = item.stat_modifications || item.statModifications || {}; |
| 1596 | if (Object.keys(modifications).length > 0) |
| 1597 | { |
| 1598 | Object.entries(modifications).forEach(([stat, value]) => |
| 1599 | { |
| 1600 | if (value !== 0) |
| 1601 | { |
| 1602 | const modEl = document.createElement('div'); |
| 1603 | modEl.className = `stat-mod ${value > 0 ? 'positive' : 'negative'}`; |
| 1604 | modEl.innerHTML = `<span>${this.capitalizeFirst(stat)}</span><span>${value > 0 ? '+' : ''}${value}</span>`; |
| 1605 | statMods.appendChild(modEl); |
| 1606 | } |
| 1607 | }); |
| 1608 | } else |
| 1609 | { |
| 1610 | statMods.innerHTML = '<div style="color: #999; font-size: 0.9em;">No stat modifications</div>'; |
| 1611 | } |
| 1612 | |
| 1613 | // Change button to return item |
| 1614 | const actions = document.querySelector('.item-modal-actions'); |
| 1615 | actions.innerHTML = ''; |
| 1616 | |
| 1617 | const returnBtn = document.createElement('button'); |
| 1618 | returnBtn.className = 'secondary'; |
| 1619 | returnBtn.textContent = 'Return to Storage'; |
| 1620 | returnBtn.addEventListener('click', () => |
| 1621 | { |
| 1622 | this.hideKoboldModal(); |
| 1623 | this.returnItemToStorage(item, kobold); |
| 1624 | }); |
| 1625 | |
| 1626 | actions.appendChild(returnBtn); |
| 1627 | |
| 1628 | modal.classList.remove('hidden'); |
| 1629 | this.selectedKobold = kobold; |
| 1630 | } |
| 1631 | |
| 1632 | async returnItemToStorage (item, kobold) |
| 1633 | { |
| 1634 | let dataText = "Request failed altogether"; |
| 1635 | try |
| 1636 | { |
| 1637 | const resp = await fetch('api/game/returnItem', { |
| 1638 | method: 'POST', |
| 1639 | headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser?.token}` }, |
| 1640 | body: JSON.stringify({ userId: this.currentUser.email, saveId: this.currentSave.id, koboldId: kobold.id, itemId: item.id }) |
| 1641 | }); |
| 1642 | |
| 1643 | dataText = await resp.text(); |
| 1644 | const data = JSON.parse(dataText); |
| 1645 | if (data.success) |
| 1646 | { |
| 1647 | typeText(document.getElementById('eventStory'), data.story); |
| 1648 | this.showEventModal(); |
| 1649 | // Refresh game state |
| 1650 | await this.loadGame(this.currentSave.id); |
| 1651 | const refreshed = this.currentTribe.kobolds.find(k => k.id === kobold.id); |
| 1652 | } else |
| 1653 | { |
| 1654 | alert(data.error || 'Failed to return item'); |
| 1655 | console.error('Return item error:', data); |
| 1656 | } |
| 1657 | } catch (err) |
| 1658 | { |
| 1659 | console.error(err); |
| 1660 | alert('Failed to return item'); |
| 1661 | console.error('Response data:', dataText); |
| 1662 | } finally |
| 1663 | { |
| 1664 | this.hideItemModal(); |
| 1665 | } |
| 1666 | } |
| 1667 | |
| 1668 | switchKoboldTab (tabName) |
| 1669 | { |
| 1670 | // Hide all tabs |
| 1671 | document.querySelectorAll('.kobold-tab-content').forEach(tab => tab.classList.remove('active')); |
| 1672 | document.querySelectorAll('.kobold-tab-btn').forEach(btn => btn.classList.remove('active')); |
| 1673 | |
| 1674 | // Show selected tab |
| 1675 | const tabId = 'kobold' + this.capitalizeFirst(tabName) + 'Tab'; |
| 1676 | document.getElementById(tabId).classList.add('active'); |
| 1677 | document.querySelector(`[data-tab="${tabName}"]`).classList.add('active'); |
| 1678 | } |
| 1679 | |
| 1680 | getLikeDescriptor (likeValue) |
| 1681 | { |
| 1682 | const val = Number(likeValue || 0); |
| 1683 | |
| 1684 | if (val <= -40) return { text: 'terrible', color: '#d9534f' }; |
| 1685 | if (val <= -30) return { text: 'awful', color: '#e74c3c' }; |
| 1686 | if (val <= -20) return { text: 'poor', color: '#e8765d' }; |
| 1687 | if (val <= -10) return { text: 'bad', color: '#ec8a6a' }; |
| 1688 | if (val < 0) return { text: 'cold', color: '#f0a080' }; |
| 1689 | if (val === 0) return { text: 'neutral', color: '#999' }; |
| 1690 | if (val < 10) return { text: 'okay', color: '#95b9a5' }; |
| 1691 | if (val < 20) return { text: 'good', color: '#7cb87b' }; |
| 1692 | if (val < 30) return { text: 'nice', color: '#63b76f' }; |
| 1693 | if (val < 40) return { text: 'great', color: '#51a859' }; |
| 1694 | return { text: 'wonderful', color: '#27ae60' }; |
| 1695 | } |
| 1696 | |
| 1697 | cleanupLikes () |
| 1698 | { |
| 1699 | if (!this.currentTribe || !Array.isArray(this.currentTribe.kobolds)) |
| 1700 | { |
| 1701 | return; |
| 1702 | } |
| 1703 | |
| 1704 | const koboldIds = new Set( |
| 1705 | this.currentTribe.kobolds |
| 1706 | .map(k => k?.id) |
| 1707 | .filter(id => typeof id === 'string' && id.length > 0) |
| 1708 | ); |
| 1709 | |
| 1710 | const rivalList = Array.isArray(this.currentSave?.rivals) |
| 1711 | ? this.currentSave.rivals |
| 1712 | : Object.values(this.currentSave?.rivals || {}); |
| 1713 | |
| 1714 | const rivalIds = new Set( |
| 1715 | rivalList |
| 1716 | .map(r => r?.id) |
| 1717 | .filter(id => typeof id === 'string' && id.length > 0) |
| 1718 | ); |
| 1719 | |
| 1720 | this.currentTribe.kobolds.forEach(kobold => |
| 1721 | { |
| 1722 | const likes = kobold?.likes; |
| 1723 | if (!likes || typeof likes !== 'object') |
| 1724 | { |
| 1725 | kobold.likes = {}; |
| 1726 | return; |
| 1727 | } |
| 1728 | |
| 1729 | if (Array.isArray(likes)) |
| 1730 | { |
| 1731 | kobold.likes = {}; |
| 1732 | return; |
| 1733 | } |
| 1734 | |
| 1735 | const cleaned = {}; |
| 1736 | Object.entries(likes).forEach(([targetId, value]) => |
| 1737 | { |
| 1738 | if (koboldIds.has(targetId) || rivalIds.has(targetId)) |
| 1739 | { |
| 1740 | cleaned[targetId] = value; |
| 1741 | } |
| 1742 | }); |
| 1743 | |
| 1744 | kobold.likes = cleaned; |
| 1745 | }); |
| 1746 | } |
| 1747 | |
| 1748 | renderKoboldRelationships (kobold) |
| 1749 | { |
| 1750 | const container = document.getElementById('koboldRelationships'); |
| 1751 | container.innerHTML = ''; |
| 1752 | |
| 1753 | const likes = kobold.likes || {}; |
| 1754 | |
| 1755 | // Separate tribe members and rivals |
| 1756 | const tribeMembers = []; |
| 1757 | const rivals = []; |
| 1758 | |
| 1759 | for (const [targetId, likeValue] of Object.entries(likes)) |
| 1760 | { |
| 1761 | if (likeValue === 0) continue; // Skip neutral relationships |
| 1762 | |
| 1763 | // Check if it's a tribe member |
| 1764 | const tribeMember = this.currentTribe.kobolds.find(k => k.id === targetId); |
| 1765 | if (tribeMember) |
| 1766 | { |
| 1767 | tribeMembers.push({ id: targetId, name: tribeMember.name, likeValue }); |
| 1768 | } else |
| 1769 | { |
| 1770 | // Check if it's a rival |
| 1771 | const rivalData = Array.isArray(this.currentSave?.rivals) |
| 1772 | ? this.currentSave.rivals |
| 1773 | : Object.values(this.currentSave?.rivals || {}); |
| 1774 | const rival = rivalData.find(r => r?.id === targetId); |
| 1775 | if (rival) |
| 1776 | { |
| 1777 | rivals.push({ id: targetId, name: rival.name, likeValue }); |
| 1778 | } |
| 1779 | } |
| 1780 | } |
| 1781 | |
| 1782 | // Sort by like value (descending) |
| 1783 | const sort = (a, b) => b.likeValue - a.likeValue; |
| 1784 | tribeMembers.sort(sort); |
| 1785 | rivals.sort(sort); |
| 1786 | |
| 1787 | // Render tribe members |
| 1788 | if (tribeMembers.length > 0) |
| 1789 | { |
| 1790 | const tribeSection = document.createElement('div'); |
| 1791 | tribeSection.className = 'relationships-section'; |
| 1792 | |
| 1793 | const tribeTitle = document.createElement('h4'); |
| 1794 | tribeTitle.textContent = 'Tribe Members'; |
| 1795 | tribeSection.appendChild(tribeTitle); |
| 1796 | |
| 1797 | tribeMembers.forEach(member => |
| 1798 | { |
| 1799 | const descriptor = this.getLikeDescriptor(member.likeValue); |
| 1800 | const item = document.createElement('div'); |
| 1801 | item.className = 'relationship-item'; |
| 1802 | item.innerHTML = ` |
| 1803 | <span class="relationship-name">${member.name}</span> |
| 1804 | <span class="relationship-descriptor" style="color: ${descriptor.color}">${descriptor.text}</span> |
| 1805 | `; |
| 1806 | tribeSection.appendChild(item); |
| 1807 | }); |
| 1808 | |
| 1809 | container.appendChild(tribeSection); |
| 1810 | } |
| 1811 | |
| 1812 | // Render rivals |
| 1813 | if (rivals.length > 0) |
| 1814 | { |
| 1815 | const rivalsSection = document.createElement('div'); |
| 1816 | rivalsSection.className = 'relationships-section'; |
| 1817 | |
| 1818 | const rivalsTitle = document.createElement('h4'); |
| 1819 | rivalsTitle.textContent = 'Rivals'; |
| 1820 | rivalsSection.appendChild(rivalsTitle); |
| 1821 | |
| 1822 | rivals.forEach(rival => |
| 1823 | { |
| 1824 | const descriptor = this.getLikeDescriptor(rival.likeValue); |
| 1825 | const item = document.createElement('div'); |
| 1826 | item.className = 'relationship-item'; |
| 1827 | item.innerHTML = ` |
| 1828 | <span class="relationship-name">${rival.name}</span> |
| 1829 | <span class="relationship-descriptor" style="color: ${descriptor.color}">${descriptor.text}</span> |
| 1830 | `; |
| 1831 | rivalsSection.appendChild(item); |
| 1832 | }); |
| 1833 | |
| 1834 | container.appendChild(rivalsSection); |
| 1835 | } |
| 1836 | |
| 1837 | // Show message if no relationships |
| 1838 | if (tribeMembers.length === 0 && rivals.length === 0) |
| 1839 | { |
| 1840 | const noRels = document.createElement('p'); |
| 1841 | noRels.style.color = '#999'; |
| 1842 | noRels.textContent = 'No relationships to display.'; |
| 1843 | container.appendChild(noRels); |
| 1844 | } |
| 1845 | } |
| 1846 | |
| 1847 | getStatLabel (statValue) |
| 1848 | { |
| 1849 | if (statValue >= 90) return 'godlike'; |
| 1850 | if (statValue >= 80) return 'divine'; |
| 1851 | if (statValue >= 70) return 'master'; |
| 1852 | if (statValue >= 60) return 'fantastic'; |
| 1853 | if (statValue >= 50) return 'excellent'; |
| 1854 | if (statValue >= 40) return 'good'; |
| 1855 | if (statValue >= 30) return 'decent'; |
| 1856 | if (statValue >= 20) return 'unskilled'; |
| 1857 | if (statValue >= 10) return 'bad'; |
| 1858 | return 'terrible'; |
| 1859 | } |
| 1860 | |
| 1861 | getFatigueLabel (fatigue, vitality) |
| 1862 | { |
| 1863 | const vit = Number(vitality || 0); |
| 1864 | const fat = Number(fatigue || 0); |
| 1865 | if (vit <= 0) return 'exhausted'; |
| 1866 | if (fat <= 0) return 'energetic'; |
| 1867 | const ratio = fat / Math.max(1, vit); |
| 1868 | if (ratio < 0.3) return 'fresh'; |
| 1869 | if (ratio < 0.6) return 'tired'; |
| 1870 | if (ratio < 0.85) return 'weary'; |
| 1871 | return 'exhausted'; |
| 1872 | } |
| 1873 | |
| 1874 | hideAll () |
| 1875 | { |
| 1876 | document.querySelectorAll('.screen').forEach(screen => screen.classList.add('hidden')); |
| 1877 | } |
| 1878 | |
| 1879 | capitalizeFirst (str) |
| 1880 | { |
| 1881 | return str.charAt(0).toUpperCase() + str.slice(1); |
| 1882 | } |
| 1883 | } |
| 1884 | |
| 1885 | // Initialize app when DOM is ready |
| 1886 | document.addEventListener('DOMContentLoaded', () => |
| 1887 | { |
| 1888 | window.app = new TribeGenApp(); |
| 1889 | }); |
| 1890 | |
| 1891 | function typeText (element, text, minDelay = 3, maxDelay = 65) |
| 1892 | { |
| 1893 | doneTyping = false; |
| 1894 | element.textContent = ""; |
| 1895 | let index = 0; |
| 1896 | let timerId = null; |
| 1897 | |
| 1898 | const randDelay = () => |
| 1899 | Math.floor(Math.random() * (maxDelay - minDelay + 1)) + minDelay; |
| 1900 | |
| 1901 | const shouldStop = () => |
| 1902 | { |
| 1903 | if (!element.isConnected) return true; |
| 1904 | if (getComputedStyle(element).display === "none") return true; |
| 1905 | return false; |
| 1906 | }; |
| 1907 | |
| 1908 | return new Promise((resolve) => |
| 1909 | { |
| 1910 | function tick () |
| 1911 | { |
| 1912 | if (shouldStop()) |
| 1913 | { |
| 1914 | if (timerId) clearTimeout(timerId); |
| 1915 | doneTyping = true; |
| 1916 | resolve(false); // stopped early |
| 1917 | return; |
| 1918 | } |
| 1919 | |
| 1920 | if (index >= text.length) |
| 1921 | { |
| 1922 | doneTyping = true; |
| 1923 | resolve(true); // finished normally |
| 1924 | return; |
| 1925 | } |
| 1926 | |
| 1927 | element.textContent += text[index++]; |
| 1928 | timerId = setTimeout(tick, randDelay()); |
| 1929 | } |
| 1930 | |
| 1931 | tick(); |
| 1932 | }); |
| 1933 | } |
| 1934 | |