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