| 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 | await this.ensureEnvironmentsLoaded(); |
| 635 | await this.fetchAvailableEvents(); |
| 636 | this.showGameScreen(); |
| 637 | } |
| 638 | } catch (error) |
| 639 | { |
| 640 | alert('Failed to load game'); |
| 641 | console.error(error); |
| 642 | console.error('Response data:', dataText); |
| 643 | } |
| 644 | } |
| 645 | |
| 646 | showGameScreen () |
| 647 | { |
| 648 | this.hideAll(); |
| 649 | document.getElementById('gameScreen').classList.remove('hidden'); |
| 650 | this.renderGame(); |
| 651 | } |
| 652 | |
| 653 | renderGame () |
| 654 | { |
| 655 | document.getElementById('tribeName').textContent = this.currentSave.name; |
| 656 | document.getElementById('monthDisplay').textContent = `Month ${this.currentSave.current_month}`; |
| 657 | document.getElementById('seasonDisplay').textContent = this.capitalizeFirst(this.currentSave.current_season); |
| 658 | |
| 659 | this.renderEnvironment(); |
| 660 | this.renderStorage(); |
| 661 | this.renderTribeList(); |
| 662 | this.renderEvents(); |
| 663 | } |
| 664 | |
| 665 | renderEnvironment () |
| 666 | { |
| 667 | const envElement = document.getElementById('environment'); |
| 668 | if (!envElement) |
| 669 | { |
| 670 | return; |
| 671 | } |
| 672 | |
| 673 | const envId = this.getActiveEnvironmentId(); |
| 674 | if (!envId) |
| 675 | { |
| 676 | envElement.style.backgroundImage = ''; |
| 677 | const placements = document.getElementById('koboldPlacements'); |
| 678 | if (placements) |
| 679 | { |
| 680 | placements.innerHTML = ''; |
| 681 | } |
| 682 | return; |
| 683 | } |
| 684 | |
| 685 | const season = (this.currentSave.current_season || 'spring').toLowerCase(); |
| 686 | let imageUrl = `assets/environments/${envId}/${season}.png`; |
| 687 | const env = this.environmentMap[envId]; |
| 688 | if (env && Array.isArray(env.images) && env.images.length > 0) |
| 689 | { |
| 690 | const seasonMatch = env.images.find(img => img.includes(`/${season}.png`)); |
| 691 | if (seasonMatch) |
| 692 | { |
| 693 | imageUrl = seasonMatch; |
| 694 | } else |
| 695 | { |
| 696 | imageUrl = env.images[0]; |
| 697 | } |
| 698 | } |
| 699 | |
| 700 | envElement.style.backgroundImage = `url('${imageUrl}')`; |
| 701 | this.renderEnvironmentPlacements(envId); |
| 702 | } |
| 703 | |
| 704 | renderEnvironmentPlacements (envId) |
| 705 | { |
| 706 | const placements = document.getElementById('koboldPlacements'); |
| 707 | if (!placements) |
| 708 | { |
| 709 | return; |
| 710 | } |
| 711 | |
| 712 | const placementKey = `${this.currentSave?.id ?? 'save'}-${envId}-${this.currentSave?.current_month ?? 0}`; |
| 713 | if (this.lastPlacementKey === placementKey && placements.children.length > 0) |
| 714 | { |
| 715 | return; |
| 716 | } |
| 717 | |
| 718 | this.lastPlacementKey = placementKey; |
| 719 | placements.innerHTML = ''; |
| 720 | const env = this.environmentMap[envId]; |
| 721 | if (!env || !Array.isArray(env.koboldLocations)) |
| 722 | { |
| 723 | return; |
| 724 | } |
| 725 | |
| 726 | const spots = env.koboldLocations |
| 727 | .map(loc => ({ |
| 728 | x: loc ? Number(loc.x) : NaN, |
| 729 | y: loc ? Number(loc.y) : NaN |
| 730 | })) |
| 731 | .filter(loc => Number.isFinite(loc.x) && Number.isFinite(loc.y)); |
| 732 | |
| 733 | if (spots.length === 0 || !this.currentTribe || !Array.isArray(this.currentTribe.kobolds)) |
| 734 | { |
| 735 | return; |
| 736 | } |
| 737 | |
| 738 | let availableSpots = this.shuffleArray(spots.slice()); |
| 739 | if (availableSpots.length > 30) |
| 740 | { |
| 741 | availableSpots = availableSpots.slice(0, 30); |
| 742 | } |
| 743 | |
| 744 | let leader = this.currentTribe.kobolds.find(k => k.is_leader); |
| 745 | if (!leader) |
| 746 | { |
| 747 | leader = this.currentTribe.kobolds[0]; |
| 748 | } |
| 749 | |
| 750 | if (!leader) |
| 751 | { |
| 752 | return; |
| 753 | } |
| 754 | |
| 755 | const leaderSpotIndex = Math.floor(Math.random() * availableSpots.length); |
| 756 | const leaderSpot = availableSpots.splice(leaderSpotIndex, 1)[0]; |
| 757 | const placementList = [{ kobold: leader, spot: leaderSpot }]; |
| 758 | |
| 759 | const others = this.currentTribe.kobolds.filter(k => k.id !== leader.id); |
| 760 | const shuffledOthers = this.shuffleArray(others.slice()); |
| 761 | const maxOthers = Math.min(availableSpots.length, 29, shuffledOthers.length); |
| 762 | |
| 763 | for (let i = 0; i < maxOthers; i++) |
| 764 | { |
| 765 | placementList.push({ kobold: shuffledOthers[i], spot: availableSpots[i] }); |
| 766 | } |
| 767 | |
| 768 | placementList.sort((a, b) => a.spot.y - b.spot.y); |
| 769 | |
| 770 | placementList.forEach(entry => |
| 771 | { |
| 772 | const spriteUrl = `api/game/sprite?userId=${this.currentUser.email}&koboldId=${entry.kobold.id}&age=${entry.kobold.ageCategory}`; |
| 773 | const img = document.createElement('img'); |
| 774 | img.src = spriteUrl; |
| 775 | img.alt = entry.kobold.name; |
| 776 | img.className = 'kobold-placement'; |
| 777 | if (Math.random() < 0.5) |
| 778 | { |
| 779 | img.classList.add('flipped'); |
| 780 | } |
| 781 | img.style.left = `${entry.spot.x * 100}%`; |
| 782 | img.style.top = `${entry.spot.y * 100}%`; |
| 783 | img.style.zIndex = Math.round(entry.spot.y * 1000).toString(); |
| 784 | img.addEventListener('click', (event) => |
| 785 | { |
| 786 | event.stopPropagation(); |
| 787 | this.showKoboldModal(entry.kobold); |
| 788 | }); |
| 789 | placements.appendChild(img); |
| 790 | }); |
| 791 | } |
| 792 | |
| 793 | getActiveEnvironmentId () |
| 794 | { |
| 795 | if (this.currentSave && this.currentSave.environment_id) |
| 796 | { |
| 797 | return this.currentSave.environment_id; |
| 798 | } |
| 799 | if (this.selectedEnvironmentId) |
| 800 | { |
| 801 | return this.selectedEnvironmentId; |
| 802 | } |
| 803 | if (this.environments && this.environments.length > 0) |
| 804 | { |
| 805 | return this.environments[0].id; |
| 806 | } |
| 807 | return null; |
| 808 | } |
| 809 | |
| 810 | logEnvironmentClick (event) |
| 811 | { |
| 812 | const envElement = document.getElementById('environment'); |
| 813 | if (!envElement) |
| 814 | { |
| 815 | return; |
| 816 | } |
| 817 | |
| 818 | if (event.target && event.target.closest && event.target.closest('.kobold-placement')) |
| 819 | { |
| 820 | return; |
| 821 | } |
| 822 | |
| 823 | const rect = envElement.getBoundingClientRect(); |
| 824 | const x = (event.clientX - rect.left) / rect.width; |
| 825 | const y = (event.clientY - rect.top) / rect.height; |
| 826 | const normalizedX = Math.max(0, Math.min(1, x)); |
| 827 | const normalizedY = Math.max(0, Math.min(1, y)); |
| 828 | console.log('Environment click:', { |
| 829 | x: Number(normalizedX.toFixed(3)), |
| 830 | y: Number(normalizedY.toFixed(3)) |
| 831 | }); |
| 832 | } |
| 833 | |
| 834 | shuffleArray (array) |
| 835 | { |
| 836 | for (let i = array.length - 1; i > 0; i--) |
| 837 | { |
| 838 | const j = Math.floor(Math.random() * (i + 1)); |
| 839 | [array[i], array[j]] = [array[j], array[i]]; |
| 840 | } |
| 841 | return array; |
| 842 | } |
| 843 | |
| 844 | renderTribeList () |
| 845 | { |
| 846 | const list = document.getElementById('tribeList'); |
| 847 | list.innerHTML = ''; |
| 848 | |
| 849 | this.currentTribe.kobolds.forEach(kobold => |
| 850 | { |
| 851 | const spriteUrl = `api/game/sprite?userId=${this.currentUser.email}&koboldId=${kobold.id}&age=${kobold.ageCategory}`; |
| 852 | const item = document.createElement('div'); |
| 853 | const isInjured = kobold.injuries && kobold.injuries.length > 0; |
| 854 | item.className = `tribe-item ${isInjured ? 'injured' : ''}`; |
| 855 | item.innerHTML = ` |
| 856 | <table style="width:100%"> |
| 857 | <td> |
| 858 | <img class="kobold-list-sprite" src="${spriteUrl}"/> |
| 859 | </td> |
| 860 | <td> |
| 861 | <div> |
| 862 | <div class="tribe-item-name">${kobold.name}</div> |
| 863 | <div class="tribe-item-age">${(kobold.age > 0 ? kobold.age : 0)} years</div> |
| 864 | </div> |
| 865 | </td> |
| 866 | </table> |
| 867 | `; |
| 868 | item.addEventListener('click', () => this.showKoboldModal(kobold)); |
| 869 | list.appendChild(item); |
| 870 | }); |
| 871 | } |
| 872 | |
| 873 | renderEvents () |
| 874 | { |
| 875 | const list = document.getElementById('eventsList'); |
| 876 | list.innerHTML = ''; |
| 877 | |
| 878 | this.availableEvents = this.availableEvents || []; |
| 879 | this.availableEvents = this.availableEvents.filter(evt => !!evt.available); |
| 880 | |
| 881 | if (!this.availableEvents || this.availableEvents.length === 0) |
| 882 | { |
| 883 | const empty = document.createElement('div'); |
| 884 | empty.className = 'event-item disabled'; |
| 885 | empty.textContent = 'No events available'; |
| 886 | list.appendChild(empty); |
| 887 | return; |
| 888 | } |
| 889 | |
| 890 | this.availableEvents.forEach(evt => |
| 891 | { |
| 892 | function costToText (cost) |
| 893 | { |
| 894 | if (cost >= 95) return "impossible"; |
| 895 | if (cost >= 80) return "near impossible"; |
| 896 | if (cost >= 70) return "extreme"; |
| 897 | if (cost >= 60) return "brutal"; |
| 898 | if (cost >= 50) return "very hard"; |
| 899 | if (cost >= 40) return "hard"; |
| 900 | if (cost >= 30) return "difficult"; |
| 901 | if (cost >= 20) return "moderate"; |
| 902 | if (cost >= 10) return "easy"; |
| 903 | return "trivial"; |
| 904 | } |
| 905 | |
| 906 | const item = document.createElement('div'); |
| 907 | const isAvailable = !!evt.available; |
| 908 | item.className = `event-item ${isAvailable ? '' : 'disabled'}`.trim(); |
| 909 | const costText = Number.isFinite(Number(evt.cost)) ? ` (${costToText(Number(evt.cost))})` : ''; |
| 910 | item.textContent = `${evt.name || evt.type}${costText}${isAvailable ? '' : ' (Unavailable)'}`; |
| 911 | if (isAvailable) |
| 912 | { |
| 913 | item.addEventListener('click', () => this.showParticipantModal(evt.type)); |
| 914 | } |
| 915 | list.appendChild(item); |
| 916 | }); |
| 917 | } |
| 918 | |
| 919 | async fetchAvailableEvents () |
| 920 | { |
| 921 | this.availableEvents = []; |
| 922 | this.availableEventsByType = {}; |
| 923 | |
| 924 | if (!this.currentUser || !this.currentSave) |
| 925 | return; |
| 926 | |
| 927 | let dataText = "Request failed altogether"; |
| 928 | try |
| 929 | { |
| 930 | const response = await fetch(`api/game/events?saveId=${this.currentSave.id}&userId=${this.currentUser.email}`, { |
| 931 | method: 'GET', |
| 932 | headers: { 'Authorization': `Bearer ${this.currentUser.token}` } |
| 933 | }); |
| 934 | |
| 935 | dataText = await response.text(); |
| 936 | const data = JSON.parse(dataText); |
| 937 | |
| 938 | if (data.success && Array.isArray(data.events)) |
| 939 | { |
| 940 | this.availableEvents = data.events; |
| 941 | data.events.forEach(evt => |
| 942 | { |
| 943 | if (evt && evt.type) |
| 944 | this.availableEventsByType[evt.type] = evt; |
| 945 | }); |
| 946 | } |
| 947 | } catch (error) |
| 948 | { |
| 949 | console.error('Failed to load events:', error); |
| 950 | console.error('Response data:', dataText); |
| 951 | } |
| 952 | } |
| 953 | |
| 954 | async executeEvent (eventType) |
| 955 | { |
| 956 | // Deprecated direct execution; use participant modal instead |
| 957 | this.showParticipantModal(eventType); |
| 958 | } |
| 959 | |
| 960 | showParticipantModal (eventType) |
| 961 | { |
| 962 | this.currentEventType = eventType; |
| 963 | const modal = document.getElementById('participantModal'); |
| 964 | const eventData = this.availableEventsByType[eventType] || {}; |
| 965 | const eventLabel = eventData.name || eventType; |
| 966 | document.getElementById('participantModalTitle').textContent = `Select participants for ${eventLabel}`; |
| 967 | |
| 968 | const list = document.getElementById('participantsList'); |
| 969 | list.innerHTML = ''; |
| 970 | |
| 971 | this.participantMin = eventData.min_participants ?? 1; |
| 972 | this.participantMax = eventData.max_participants ?? 3; |
| 973 | this.participantMinAge = eventData.min_age ?? 0; |
| 974 | this.participantCost = eventData.cost || 0; |
| 975 | |
| 976 | // Helper: check if kobold is eligible |
| 977 | const isEligible = (kobold) => |
| 978 | { |
| 979 | const ageCategory = (kobold.ageCategory || '').toLowerCase(); |
| 980 | if (ageCategory === 'egg') return false; // eggs cannot participate |
| 981 | if (!kobold.isAlive && kobold.isDead) return false; // dead cannot participate (if available from backend) |
| 982 | if (kobold.age < this.participantMinAge) return false; // too young |
| 983 | const fatigue = Number(kobold.fatigue || 0); |
| 984 | const vitality = Number(kobold.stats?.vitality || 0); |
| 985 | if ((fatigue + this.participantCost) > vitality) return false; |
| 986 | return true; |
| 987 | }; |
| 988 | |
| 989 | // Render kobolds with eligibility status |
| 990 | this.currentTribe.kobolds.forEach(kobold => |
| 991 | { |
| 992 | const ageCategory = (kobold.ageCategory || '').toLowerCase(); |
| 993 | const eligible = isEligible(kobold); |
| 994 | let reason = ''; |
| 995 | |
| 996 | if (ageCategory === 'egg') |
| 997 | reason = '(eggs cannot participate)'; |
| 998 | else if (kobold.age < this.participantMinAge) |
| 999 | reason = `(too young, needs age ${this.participantMinAge}+)`; |
| 1000 | else if (this.participantCost > Number(kobold.stats?.vitality || 0)) |
| 1001 | reason = '(too weak)'; |
| 1002 | else if ((Number(kobold.fatigue || 0) + this.participantCost) > Number(kobold.stats?.vitality || 0)) |
| 1003 | reason = '(too tired)'; |
| 1004 | |
| 1005 | const row = document.createElement('div'); |
| 1006 | row.className = `participant-row ${eligible ? 'eligible' : 'ineligible'}`; |
| 1007 | |
| 1008 | const fatigueValue = Number(kobold.fatigue || 0); |
| 1009 | const vitalityValue = Number(kobold.stats?.vitality || 0); |
| 1010 | const fatigueLabel = kobold.fatigue_label || this.getFatigueLabel(fatigueValue, vitalityValue); |
| 1011 | |
| 1012 | if (eligible) |
| 1013 | { |
| 1014 | row.innerHTML = ` |
| 1015 | <label> |
| 1016 | <input type="checkbox" class="participant-checkbox" data-id="${kobold.id}"> |
| 1017 | <strong>${kobold.name}</strong> (${kobold.ageCategory != "egg" ? fatigueLabel : 'egg'}) |
| 1018 | </label> |
| 1019 | `; |
| 1020 | const cb = row.querySelector('.participant-checkbox'); |
| 1021 | cb.addEventListener('change', () => this._updateParticipantButtons()); |
| 1022 | } else |
| 1023 | { |
| 1024 | row.innerHTML = ` |
| 1025 | <div class="participant-disabled"> |
| 1026 | <span>${kobold.name} (${kobold.ageCategory != "egg" ? fatigueLabel : 'egg'})</span> |
| 1027 | <span class="disabled-reason">${reason}</span> |
| 1028 | </div> |
| 1029 | `; |
| 1030 | } |
| 1031 | |
| 1032 | list.appendChild(row); |
| 1033 | }); |
| 1034 | |
| 1035 | document.getElementById('participantCount').textContent = `0 selected`; |
| 1036 | |
| 1037 | // cancel/start handlers |
| 1038 | const cancelBtn = document.getElementById('cancelParticipantsBtn'); |
| 1039 | const startBtn = document.getElementById('startEventBtn'); |
| 1040 | |
| 1041 | cancelBtn.onclick = () => { modal.classList.add('hidden'); }; |
| 1042 | startBtn.onclick = async () => { await this.startEventWithParticipants(); }; |
| 1043 | |
| 1044 | // initial state |
| 1045 | this._updateParticipantButtons(); |
| 1046 | |
| 1047 | modal.classList.remove('hidden'); |
| 1048 | } |
| 1049 | |
| 1050 | _updateParticipantButtons () |
| 1051 | { |
| 1052 | const list = document.getElementById('participantsList'); |
| 1053 | const selected = Array.from(list.querySelectorAll('.participant-checkbox:checked')).map(cb => cb.dataset.id); |
| 1054 | const count = selected.length; |
| 1055 | const participantCount = document.getElementById('participantCount'); |
| 1056 | const minRequired = this.participantMin || 1; |
| 1057 | const maxAllowed = this.participantMax || 3; |
| 1058 | let warning = ''; |
| 1059 | if (count < minRequired) |
| 1060 | { |
| 1061 | warning = `need at least ${minRequired}`; |
| 1062 | } else if (count > maxAllowed) |
| 1063 | { |
| 1064 | warning = `${count - maxAllowed} too many`; |
| 1065 | } |
| 1066 | |
| 1067 | const warningHtml = warning ? `<br><span style="color:#d9534f;">${warning.trim()}</span>` : ''; |
| 1068 | participantCount.innerHTML = `${count} selected${warningHtml}`; |
| 1069 | |
| 1070 | const startBtn = document.getElementById('startEventBtn'); |
| 1071 | if (count >= (this.participantMin || 1) && count <= (this.participantMax || 3)) |
| 1072 | { |
| 1073 | startBtn.disabled = false; |
| 1074 | } else |
| 1075 | { |
| 1076 | startBtn.disabled = true; |
| 1077 | } |
| 1078 | } |
| 1079 | |
| 1080 | async startEventWithParticipants () |
| 1081 | { |
| 1082 | const modal = document.getElementById('participantModal'); |
| 1083 | const list = document.getElementById('participantsList'); |
| 1084 | const selected = Array.from(list.querySelectorAll('.participant-checkbox:checked')).map(cb => cb.dataset.id); |
| 1085 | |
| 1086 | if (!selected || selected.length === 0) return; |
| 1087 | |
| 1088 | let dataText = "Request failed altogether"; |
| 1089 | try |
| 1090 | { |
| 1091 | const resp = await fetch('api/game/event', { |
| 1092 | method: 'POST', |
| 1093 | headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser.token}` }, |
| 1094 | body: JSON.stringify({ userId: this.currentUser.email, saveId: this.currentSave.id, eventType: this.currentEventType, participants: selected }) |
| 1095 | }); |
| 1096 | |
| 1097 | dataText = await resp.text(); |
| 1098 | const data = JSON.parse(dataText); |
| 1099 | |
| 1100 | if (data.success) |
| 1101 | { |
| 1102 | typeText(document.getElementById('eventStory'), data.story); |
| 1103 | this.showEventModal(); |
| 1104 | modal.classList.add('hidden'); |
| 1105 | await this.loadGame(this.currentSave.id); |
| 1106 | } else |
| 1107 | { |
| 1108 | alert(data.error || 'Failed to start event'); |
| 1109 | console.error('Event error:', data); |
| 1110 | } |
| 1111 | } catch (err) |
| 1112 | { |
| 1113 | console.error(err); |
| 1114 | console.error('Response data:', dataText); |
| 1115 | } |
| 1116 | } |
| 1117 | |
| 1118 | async endMonth () |
| 1119 | { |
| 1120 | let dataT = "Request failed altogether"; |
| 1121 | try |
| 1122 | { |
| 1123 | const response = await fetch('api/game/endMonth', { |
| 1124 | method: 'POST', |
| 1125 | headers: { |
| 1126 | 'Content-Type': 'application/json', |
| 1127 | 'Authorization': `Bearer ${this.currentUser.token}` |
| 1128 | }, |
| 1129 | body: JSON.stringify({ |
| 1130 | userId: this.currentUser.email, saveId: this.currentSave.id |
| 1131 | }) |
| 1132 | }); |
| 1133 | |
| 1134 | dataT = await response.text(); |
| 1135 | const data = JSON.parse(dataT); |
| 1136 | |
| 1137 | if (data.success) |
| 1138 | { |
| 1139 | this.currentSave = data.save; |
| 1140 | typeText(document.getElementById('eventStory'), data.monthStory); |
| 1141 | this.showEventModal(); |
| 1142 | await this.loadGame(this.currentSave.id); |
| 1143 | } |
| 1144 | } catch (error) |
| 1145 | { |
| 1146 | alert('Failed to end month'); |
| 1147 | console.error(error); |
| 1148 | console.error('Response data:', dataT); |
| 1149 | } |
| 1150 | } |
| 1151 | |
| 1152 | showEventModal () |
| 1153 | { |
| 1154 | document.getElementById('eventModal').classList.remove('hidden'); |
| 1155 | } |
| 1156 | |
| 1157 | hideEventModal () |
| 1158 | { |
| 1159 | if (!doneTyping) return; |
| 1160 | document.getElementById('eventModal').classList.add('hidden'); |
| 1161 | this.renderGame(); |
| 1162 | } |
| 1163 | |
| 1164 | renderStorage () |
| 1165 | { |
| 1166 | const foodDisplay = document.getElementById('foodDisplay'); |
| 1167 | const timeLeft = this.currentSave.food_time_remaining; |
| 1168 | if (timeLeft !== undefined && timeLeft !== null) |
| 1169 | { |
| 1170 | const label = timeLeft; |
| 1171 | foodDisplay.textContent = `Food: ${label}`; |
| 1172 | } else |
| 1173 | { |
| 1174 | foodDisplay.textContent = `Food: ${this.currentSave.food_count}`; |
| 1175 | } |
| 1176 | |
| 1177 | const storageItems = document.getElementById('storageItems'); |
| 1178 | storageItems.innerHTML = ''; |
| 1179 | |
| 1180 | if (!this.currentTribe.storage || this.currentTribe.storage.length === 0) |
| 1181 | { |
| 1182 | storageItems.innerHTML = '<div style="text-align: center; color: #999; padding: 10px;">No items in storage</div>'; |
| 1183 | return; |
| 1184 | } |
| 1185 | |
| 1186 | this.currentTribe.storage.forEach(item => |
| 1187 | { |
| 1188 | const itemEl = document.createElement('div'); |
| 1189 | itemEl.className = 'storage-item'; |
| 1190 | itemEl.innerHTML = `<div class="storage-item-name">${item.name}</div>`; |
| 1191 | itemEl.addEventListener('click', () => this.showItemModal(item)); |
| 1192 | storageItems.appendChild(itemEl); |
| 1193 | }); |
| 1194 | } |
| 1195 | |
| 1196 | showItemModal (item) |
| 1197 | { |
| 1198 | const modal = document.getElementById('itemModal'); |
| 1199 | document.getElementById('itemModalName').textContent = item.name; |
| 1200 | document.getElementById('itemModalDescription').textContent = item.description || 'No description'; |
| 1201 | |
| 1202 | // Show stat modifications (handle both camelCase and snake_case) |
| 1203 | const statMods = document.getElementById('itemModalStatMods'); |
| 1204 | statMods.innerHTML = ''; |
| 1205 | |
| 1206 | const modifications = item.stat_modifications || item.statModifications || {}; |
| 1207 | if (Object.keys(modifications).length > 0) |
| 1208 | { |
| 1209 | Object.entries(modifications).forEach(([stat, value]) => |
| 1210 | { |
| 1211 | if (value !== 0) |
| 1212 | { |
| 1213 | const modEl = document.createElement('div'); |
| 1214 | modEl.className = `stat-mod ${value > 0 ? 'positive' : 'negative'}`; |
| 1215 | modEl.innerHTML = `<span>${this.capitalizeFirst(stat)}</span><span>${value > 0 ? '+' : ''}${value}</span>`; |
| 1216 | statMods.appendChild(modEl); |
| 1217 | } |
| 1218 | }); |
| 1219 | } else |
| 1220 | { |
| 1221 | statMods.innerHTML = '<div style="color: #999; font-size: 0.9em;">No stat modifications</div>'; |
| 1222 | } |
| 1223 | |
| 1224 | // Restore item modal actions to storage version |
| 1225 | const actions = document.querySelector('.item-modal-actions'); |
| 1226 | actions.innerHTML = ''; |
| 1227 | |
| 1228 | const select = document.createElement('select'); |
| 1229 | select.id = 'itemKoboldSelect'; |
| 1230 | select.className = 'kobold-select'; |
| 1231 | select.innerHTML = '<option value="">Select a Kobold...</option>'; |
| 1232 | this.currentTribe.kobolds.forEach(kobold => |
| 1233 | { |
| 1234 | const option = document.createElement('option'); |
| 1235 | option.value = kobold.id; |
| 1236 | option.textContent = kobold.name; |
| 1237 | select.appendChild(option); |
| 1238 | }); |
| 1239 | |
| 1240 | const giveBtn = document.createElement('button'); |
| 1241 | giveBtn.id = 'giveItemBtn'; |
| 1242 | giveBtn.className = 'primary'; |
| 1243 | giveBtn.textContent = 'Give Item'; |
| 1244 | giveBtn.disabled = true; |
| 1245 | |
| 1246 | select.addEventListener('change', (e) => |
| 1247 | { |
| 1248 | giveBtn.disabled = !e.target.value; |
| 1249 | }); |
| 1250 | |
| 1251 | giveBtn.addEventListener('click', () => this.giveItemToKobold(item, select.value)); |
| 1252 | |
| 1253 | actions.appendChild(select); |
| 1254 | actions.appendChild(giveBtn); |
| 1255 | |
| 1256 | modal.classList.remove('hidden'); |
| 1257 | } |
| 1258 | |
| 1259 | async giveItemToKobold (item, koboldId) |
| 1260 | { |
| 1261 | let dataText = "Request failed altogether"; |
| 1262 | try |
| 1263 | { |
| 1264 | const resp = await fetch('api/game/giveItem', { |
| 1265 | method: 'POST', |
| 1266 | headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser?.token}` }, |
| 1267 | body: JSON.stringify({ userId: this.currentUser.email, saveId: this.currentSave.id, koboldId: koboldId, itemId: item.id }) |
| 1268 | }); |
| 1269 | |
| 1270 | dataText = await resp.text(); |
| 1271 | const data = JSON.parse(dataText); |
| 1272 | if (data.success) |
| 1273 | { |
| 1274 | typeText(document.getElementById('eventStory'), data.story); |
| 1275 | this.showEventModal(); |
| 1276 | // Refresh game state |
| 1277 | await this.loadGame(this.currentSave.id); |
| 1278 | const kob = this.currentTribe.kobolds.find(k => k.id === koboldId); |
| 1279 | } else |
| 1280 | { |
| 1281 | alert(data.error || 'Failed to give item'); |
| 1282 | console.error('Give item error:', data); |
| 1283 | } |
| 1284 | } catch (err) |
| 1285 | { |
| 1286 | console.error(err); |
| 1287 | alert('Failed to give item'); |
| 1288 | console.error('Response data:', dataText); |
| 1289 | } finally |
| 1290 | { |
| 1291 | this.hideItemModal(); |
| 1292 | } |
| 1293 | } |
| 1294 | |
| 1295 | hideItemModal () |
| 1296 | { |
| 1297 | document.getElementById('itemModal').classList.add('hidden'); |
| 1298 | } |
| 1299 | |
| 1300 | hideKoboldModal () |
| 1301 | { |
| 1302 | const modal = document.getElementById('koboldModal'); |
| 1303 | modal.classList.add('hidden'); |
| 1304 | } |
| 1305 | |
| 1306 | showKoboldModal (kobold) |
| 1307 | { |
| 1308 | const modal = document.getElementById('koboldModal'); |
| 1309 | document.getElementById('koboldModalName').textContent = kobold.name; |
| 1310 | |
| 1311 | const a = (kobold.ageCategory == "old" || kobold.ageCategory == "adult") ? "An" : "A"; |
| 1312 | |
| 1313 | if (kobold.ageCategory == "egg") |
| 1314 | { |
| 1315 | document.getElementById('koboldModalAge').textContent = `Not yet hatched`; |
| 1316 | document.getElementById('koboldModalDescription').textContent = `An egg.`; |
| 1317 | } |
| 1318 | else |
| 1319 | { |
| 1320 | document.getElementById('koboldModalAge').textContent = `${kobold.age} years old`; |
| 1321 | document.getElementById('koboldModalDescription').textContent = `${a} ${kobold.ageCategory} ${(kobold.male ? "male" : "female")} Kobold.`; |
| 1322 | } |
| 1323 | |
| 1324 | this.renderKoboldStats(kobold); |
| 1325 | this.renderKoboldInventory(kobold); |
| 1326 | this.renderKoboldInjuries(kobold); |
| 1327 | |
| 1328 | // Setup tab buttons |
| 1329 | document.querySelectorAll('.kobold-tab-btn').forEach(btn => |
| 1330 | { |
| 1331 | btn.classList.remove('active'); |
| 1332 | btn.addEventListener('click', (e) => this.switchKoboldTab(e.target.dataset.tab)); |
| 1333 | }); |
| 1334 | document.querySelector('.kobold-tab-btn[data-tab="stats"]').classList.add('active'); |
| 1335 | |
| 1336 | // Hide all tabs |
| 1337 | document.querySelectorAll('.kobold-tab-content').forEach(tab => tab.classList.remove('active')); |
| 1338 | document.getElementById('koboldStatsTab').classList.add('active'); |
| 1339 | |
| 1340 | // Store current kobold for inventory actions |
| 1341 | this.selectedKobold = kobold; |
| 1342 | |
| 1343 | modal.classList.remove('hidden'); |
| 1344 | } |
| 1345 | |
| 1346 | renderKoboldStats (kobold) |
| 1347 | { |
| 1348 | const statsGrid = document.getElementById('koboldStats'); |
| 1349 | statsGrid.innerHTML = ''; |
| 1350 | |
| 1351 | const stats = ['vitality', 'intelligence', 'medicine', 'crafting', 'personality', 'will', 'fighting']; |
| 1352 | stats.forEach(stat => |
| 1353 | { |
| 1354 | const value = kobold.stats[stat]; |
| 1355 | const label = this.getStatLabel(value); |
| 1356 | const statEl = document.createElement('div'); |
| 1357 | statEl.className = 'stat-item'; |
| 1358 | statEl.innerHTML = ` |
| 1359 | <div class="stat-name">${stat}</div> |
| 1360 | <div class="stat-value">${label}</div> |
| 1361 | `; |
| 1362 | statsGrid.appendChild(statEl); |
| 1363 | }); |
| 1364 | |
| 1365 | const fatigueValue = Number(kobold.fatigue || 0); |
| 1366 | const vitalityValue = Number(kobold.stats?.vitality || 0); |
| 1367 | const fatigueLabel = kobold.fatigue_label || this.getFatigueLabel(fatigueValue, vitalityValue); |
| 1368 | const fatigueEl = document.createElement('div'); |
| 1369 | fatigueEl.className = 'stat-item'; |
| 1370 | fatigueEl.innerHTML = ` |
| 1371 | <div class="stat-name">energy</div> |
| 1372 | <div class="stat-value">${fatigueLabel}</div> |
| 1373 | `; |
| 1374 | statsGrid.appendChild(fatigueEl); |
| 1375 | } |
| 1376 | |
| 1377 | renderKoboldInventory (kobold) |
| 1378 | { |
| 1379 | const inventory = document.getElementById('koboldInventory'); |
| 1380 | inventory.innerHTML = ''; |
| 1381 | |
| 1382 | if (!kobold.items || kobold.items.length === 0) |
| 1383 | { |
| 1384 | inventory.innerHTML = '<div class="kobold-inventory-empty">No items in inventory</div>'; |
| 1385 | return; |
| 1386 | } |
| 1387 | |
| 1388 | kobold.items.forEach(item => |
| 1389 | { |
| 1390 | const itemEl = document.createElement('div'); |
| 1391 | itemEl.className = 'kobold-inventory-item'; |
| 1392 | itemEl.innerHTML = `<div class="kobold-item-name">${item.name}</div>`; |
| 1393 | itemEl.addEventListener('click', () => this.showKoboldItemModal(item, kobold)); |
| 1394 | inventory.appendChild(itemEl); |
| 1395 | }); |
| 1396 | } |
| 1397 | |
| 1398 | renderKoboldInjuries (kobold) |
| 1399 | { |
| 1400 | const container = document.getElementById('koboldInjuries'); |
| 1401 | container.innerHTML = ''; |
| 1402 | |
| 1403 | if (!kobold.injuries || kobold.injuries.length === 0) |
| 1404 | { |
| 1405 | container.innerHTML = '<div class="kobold-inventory-empty">No injuries</div>'; |
| 1406 | return; |
| 1407 | } |
| 1408 | |
| 1409 | // Mapping of injury category to required cure item (matches PHP Injury::$cureMap) |
| 1410 | const cureMap = { |
| 1411 | 'wound': 'basic_medicine', |
| 1412 | 'fracture': 'bone-setting', |
| 1413 | 'infection': 'healing_herbs', |
| 1414 | 'poison': 'antidote', |
| 1415 | 'burn': 'burn_salve', |
| 1416 | 'malnourished': 'food', |
| 1417 | 'old-age': null |
| 1418 | }; |
| 1419 | |
| 1420 | kobold.injuries.forEach(injury => |
| 1421 | { |
| 1422 | const el = document.createElement('div'); |
| 1423 | el.className = 'injury-item'; |
| 1424 | const name = injury.injury_type || injury.injuryType || 'Injury'; |
| 1425 | const desc = injury.description || ''; |
| 1426 | const severity = injury.severity ?? injury.severity ?? 1; |
| 1427 | |
| 1428 | el.innerHTML = ` |
| 1429 | <div class="injury-name">${name}</div> |
| 1430 | <div class="injury-desc">${desc}</div> |
| 1431 | `; |
| 1432 | |
| 1433 | const actions = document.createElement('div'); |
| 1434 | actions.className = 'injury-actions'; |
| 1435 | |
| 1436 | // malnourished has no cure button here |
| 1437 | if (injury.category !== 'malnourished' && injury.category !== 'old-age') |
| 1438 | { |
| 1439 | // Get required medicine from server or calculate from cureMap |
| 1440 | let required = injury.required_medicine || injury.requiredMedicine || null; |
| 1441 | if (!required && injury.category) |
| 1442 | { |
| 1443 | required = cureMap[injury.category] || null; |
| 1444 | } |
| 1445 | |
| 1446 | if (required) |
| 1447 | { |
| 1448 | // check if kobold has item with this id |
| 1449 | const hasItem = (kobold.items || []).some(it => it.id === required); |
| 1450 | if (hasItem) |
| 1451 | { |
| 1452 | const btn = document.createElement('button'); |
| 1453 | btn.className = 'primary'; |
| 1454 | btn.textContent = `Cure using ${required}`; |
| 1455 | btn.addEventListener('click', async () => |
| 1456 | { |
| 1457 | let dataText = "Request failed altogether"; |
| 1458 | try |
| 1459 | { |
| 1460 | const resp = await fetch('api/game/cureInjury', { |
| 1461 | method: 'POST', |
| 1462 | headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser?.token}` }, |
| 1463 | body: JSON.stringify({ userId: this.currentUser.email, saveId: this.currentSave.id, koboldId: kobold.id, injuryId: injury.id, itemId: required }) |
| 1464 | }); |
| 1465 | dataText = await resp.text(); |
| 1466 | const data = JSON.parse(dataText); |
| 1467 | if (data.success) |
| 1468 | { |
| 1469 | this.hideKoboldModal(); |
| 1470 | typeText(document.getElementById('eventStory'), data.story); |
| 1471 | this.showEventModal(); |
| 1472 | // Refresh game state |
| 1473 | await this.loadGame(this.currentSave.id); |
| 1474 | // reopen kobold modal after refresh |
| 1475 | const refreshed = this.currentTribe.kobolds.find(k => k.id === kobold.id); |
| 1476 | |
| 1477 | } else |
| 1478 | { |
| 1479 | alert(data.error || 'Failed to cure injury'); |
| 1480 | console.error('Cure injury error:', data); |
| 1481 | } |
| 1482 | } catch (err) |
| 1483 | { |
| 1484 | console.error(err); |
| 1485 | alert('Failed to cure injury'); |
| 1486 | console.error('Response data:', dataText); |
| 1487 | } |
| 1488 | }); |
| 1489 | actions.appendChild(btn); |
| 1490 | } else |
| 1491 | { |
| 1492 | const note = document.createElement('div'); |
| 1493 | note.style.color = '#999'; |
| 1494 | note.textContent = `Needs: ${required}`; |
| 1495 | actions.appendChild(note); |
| 1496 | } |
| 1497 | } |
| 1498 | } |
| 1499 | |
| 1500 | el.appendChild(actions); |
| 1501 | container.appendChild(el); |
| 1502 | }); |
| 1503 | } |
| 1504 | |
| 1505 | showKoboldItemModal (item, kobold) |
| 1506 | { |
| 1507 | const modal = document.getElementById('itemModal'); |
| 1508 | document.getElementById('itemModalName').textContent = item.name; |
| 1509 | document.getElementById('itemModalDescription').textContent = item.description || 'No description'; |
| 1510 | |
| 1511 | this.hideKoboldModal(); |
| 1512 | // Show stat modifications (handle both camelCase and snake_case) |
| 1513 | const statMods = document.getElementById('itemModalStatMods'); |
| 1514 | statMods.innerHTML = ''; |
| 1515 | |
| 1516 | const modifications = item.stat_modifications || item.statModifications || {}; |
| 1517 | if (Object.keys(modifications).length > 0) |
| 1518 | { |
| 1519 | Object.entries(modifications).forEach(([stat, value]) => |
| 1520 | { |
| 1521 | if (value !== 0) |
| 1522 | { |
| 1523 | const modEl = document.createElement('div'); |
| 1524 | modEl.className = `stat-mod ${value > 0 ? 'positive' : 'negative'}`; |
| 1525 | modEl.innerHTML = `<span>${this.capitalizeFirst(stat)}</span><span>${value > 0 ? '+' : ''}${value}</span>`; |
| 1526 | statMods.appendChild(modEl); |
| 1527 | } |
| 1528 | }); |
| 1529 | } else |
| 1530 | { |
| 1531 | statMods.innerHTML = '<div style="color: #999; font-size: 0.9em;">No stat modifications</div>'; |
| 1532 | } |
| 1533 | |
| 1534 | // Change button to return item |
| 1535 | const actions = document.querySelector('.item-modal-actions'); |
| 1536 | actions.innerHTML = ''; |
| 1537 | |
| 1538 | const returnBtn = document.createElement('button'); |
| 1539 | returnBtn.className = 'secondary'; |
| 1540 | returnBtn.textContent = 'Return to Storage'; |
| 1541 | returnBtn.addEventListener('click', () => |
| 1542 | { |
| 1543 | this.hideKoboldModal(); |
| 1544 | this.returnItemToStorage(item, kobold); |
| 1545 | }); |
| 1546 | |
| 1547 | actions.appendChild(returnBtn); |
| 1548 | |
| 1549 | modal.classList.remove('hidden'); |
| 1550 | this.selectedKobold = kobold; |
| 1551 | } |
| 1552 | |
| 1553 | async returnItemToStorage (item, kobold) |
| 1554 | { |
| 1555 | let dataText = "Request failed altogether"; |
| 1556 | try |
| 1557 | { |
| 1558 | const resp = await fetch('api/game/returnItem', { |
| 1559 | method: 'POST', |
| 1560 | headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser?.token}` }, |
| 1561 | body: JSON.stringify({ userId: this.currentUser.email, saveId: this.currentSave.id, koboldId: kobold.id, itemId: item.id }) |
| 1562 | }); |
| 1563 | |
| 1564 | dataText = await resp.text(); |
| 1565 | const data = JSON.parse(dataText); |
| 1566 | if (data.success) |
| 1567 | { |
| 1568 | typeText(document.getElementById('eventStory'), data.story); |
| 1569 | this.showEventModal(); |
| 1570 | // Refresh game state |
| 1571 | await this.loadGame(this.currentSave.id); |
| 1572 | const refreshed = this.currentTribe.kobolds.find(k => k.id === kobold.id); |
| 1573 | } else |
| 1574 | { |
| 1575 | alert(data.error || 'Failed to return item'); |
| 1576 | console.error('Return item error:', data); |
| 1577 | } |
| 1578 | } catch (err) |
| 1579 | { |
| 1580 | console.error(err); |
| 1581 | alert('Failed to return item'); |
| 1582 | console.error('Response data:', dataText); |
| 1583 | } finally |
| 1584 | { |
| 1585 | this.hideItemModal(); |
| 1586 | } |
| 1587 | } |
| 1588 | |
| 1589 | switchKoboldTab (tabName) |
| 1590 | { |
| 1591 | // Hide all tabs |
| 1592 | document.querySelectorAll('.kobold-tab-content').forEach(tab => tab.classList.remove('active')); |
| 1593 | document.querySelectorAll('.kobold-tab-btn').forEach(btn => btn.classList.remove('active')); |
| 1594 | |
| 1595 | // Show selected tab |
| 1596 | const tabId = 'kobold' + this.capitalizeFirst(tabName) + 'Tab'; |
| 1597 | document.getElementById(tabId).classList.add('active'); |
| 1598 | document.querySelector(`[data-tab="${tabName}"]`).classList.add('active'); |
| 1599 | } |
| 1600 | |
| 1601 | getStatLabel (statValue) |
| 1602 | { |
| 1603 | if (statValue >= 90) return 'godlike'; |
| 1604 | if (statValue >= 80) return 'divine'; |
| 1605 | if (statValue >= 70) return 'master'; |
| 1606 | if (statValue >= 60) return 'fantastic'; |
| 1607 | if (statValue >= 50) return 'excellent'; |
| 1608 | if (statValue >= 40) return 'good'; |
| 1609 | if (statValue >= 30) return 'decent'; |
| 1610 | if (statValue >= 20) return 'unskilled'; |
| 1611 | if (statValue >= 10) return 'bad'; |
| 1612 | return 'terrible'; |
| 1613 | } |
| 1614 | |
| 1615 | getFatigueLabel (fatigue, vitality) |
| 1616 | { |
| 1617 | const vit = Number(vitality || 0); |
| 1618 | const fat = Number(fatigue || 0); |
| 1619 | if (vit <= 0) return 'exhausted'; |
| 1620 | if (fat <= 0) return 'energetic'; |
| 1621 | const ratio = fat / Math.max(1, vit); |
| 1622 | if (ratio < 0.3) return 'fresh'; |
| 1623 | if (ratio < 0.6) return 'tired'; |
| 1624 | if (ratio < 0.85) return 'weary'; |
| 1625 | return 'exhausted'; |
| 1626 | } |
| 1627 | |
| 1628 | hideAll () |
| 1629 | { |
| 1630 | document.querySelectorAll('.screen').forEach(screen => screen.classList.add('hidden')); |
| 1631 | } |
| 1632 | |
| 1633 | capitalizeFirst (str) |
| 1634 | { |
| 1635 | return str.charAt(0).toUpperCase() + str.slice(1); |
| 1636 | } |
| 1637 | } |
| 1638 | |
| 1639 | // Initialize app when DOM is ready |
| 1640 | document.addEventListener('DOMContentLoaded', () => |
| 1641 | { |
| 1642 | window.app = new TribeGenApp(); |
| 1643 | }); |
| 1644 | |
| 1645 | function typeText (element, text, minDelay = 3, maxDelay = 65) |
| 1646 | { |
| 1647 | doneTyping = false; |
| 1648 | element.textContent = ""; |
| 1649 | let index = 0; |
| 1650 | let timerId = null; |
| 1651 | |
| 1652 | const randDelay = () => |
| 1653 | Math.floor(Math.random() * (maxDelay - minDelay + 1)) + minDelay; |
| 1654 | |
| 1655 | const shouldStop = () => |
| 1656 | { |
| 1657 | if (!element.isConnected) return true; |
| 1658 | if (getComputedStyle(element).display === "none") return true; |
| 1659 | return false; |
| 1660 | }; |
| 1661 | |
| 1662 | return new Promise((resolve) => |
| 1663 | { |
| 1664 | function tick () |
| 1665 | { |
| 1666 | if (shouldStop()) |
| 1667 | { |
| 1668 | if (timerId) clearTimeout(timerId); |
| 1669 | doneTyping = true; |
| 1670 | resolve(false); // stopped early |
| 1671 | return; |
| 1672 | } |
| 1673 | |
| 1674 | if (index >= text.length) |
| 1675 | { |
| 1676 | doneTyping = true; |
| 1677 | resolve(true); // finished normally |
| 1678 | return; |
| 1679 | } |
| 1680 | |
| 1681 | element.textContent += text[index++]; |
| 1682 | timerId = setTimeout(tick, randDelay()); |
| 1683 | } |
| 1684 | |
| 1685 | tick(); |
| 1686 | }); |
| 1687 | } |
| 1688 | |