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