| 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 | const selectedCard = document.querySelectorAll('#memberSelectionGrid .kobold-card')[index]; |
| 329 | selectedCard.classList.toggle('selected'); |
| 330 | |
| 331 | if (force) |
| 332 | { |
| 333 | selectedCard.id = "tribeLeader"; |
| 334 | } |
| 335 | |
| 336 | const selected = document.querySelectorAll('#memberSelectionGrid .kobold-card.selected').length; |
| 337 | document.getElementById('memberCount').textContent = `${selected} / 5 selected`; |
| 338 | |
| 339 | if (selected === 5) |
| 340 | { |
| 341 | document.getElementById('finishTribeBtn').disabled = false; |
| 342 | } else |
| 343 | { |
| 344 | document.getElementById('finishTribeBtn').disabled = true; |
| 345 | } |
| 346 | } |
| 347 | } |
| 348 | |
| 349 | async selectLeader () |
| 350 | { |
| 351 | const leaderName = document.getElementById('leaderName').value; |
| 352 | |
| 353 | if (!leaderName) |
| 354 | { |
| 355 | alert('Please enter a leader name'); |
| 356 | return; |
| 357 | } |
| 358 | |
| 359 | // Proceed to member selection |
| 360 | document.getElementById('setupStep2').classList.add('hidden'); |
| 361 | document.getElementById('setupStep3').classList.remove('hidden'); |
| 362 | |
| 363 | // For now, just display remaining kobolds (in real implementation, filter out leader) |
| 364 | } |
| 365 | |
| 366 | async finishTribe () |
| 367 | { |
| 368 | const leaderIndex = document.getElementById('selectLeaderBtn').dataset.leaderIndex; |
| 369 | const selectedMembers = document.querySelectorAll('#memberSelectionGrid .kobold-card.selected'); |
| 370 | |
| 371 | const memberIndices = Array.from(selectedMembers).map(card => |
| 372 | { |
| 373 | return Array.from(card.parentElement.children).indexOf(card); |
| 374 | }); |
| 375 | |
| 376 | // Load the game |
| 377 | try |
| 378 | { |
| 379 | const response = await fetch('api/game/save', { |
| 380 | method: 'POST', |
| 381 | headers: { |
| 382 | 'Content-Type': 'application/json', |
| 383 | 'Authorization': `Bearer ${this.currentUser.token}` |
| 384 | }, |
| 385 | body: JSON.stringify({ |
| 386 | userId: this.currentUser.id, |
| 387 | saveId: this.currentSave.id, |
| 388 | leaderName: document.getElementById('leaderName').value, |
| 389 | memberIndices: memberIndices, |
| 390 | leaderId: leaderIndex |
| 391 | }) |
| 392 | }); |
| 393 | |
| 394 | const dataText = await response.text() |
| 395 | const data = JSON.parse(dataText); |
| 396 | |
| 397 | if (data.success) |
| 398 | { |
| 399 | this.loadGame(this.currentSave.id); |
| 400 | } |
| 401 | } catch (error) |
| 402 | { |
| 403 | alert('Failed to finish tribe setup'); |
| 404 | console.error(error); |
| 405 | } |
| 406 | } |
| 407 | |
| 408 | async loadGame (saveId) |
| 409 | { |
| 410 | try |
| 411 | { |
| 412 | const response = await fetch(`api/game/load?saveId=${saveId}&userId=${this.currentUser.id}`, { |
| 413 | method: 'GET', |
| 414 | headers: { 'Authorization': `Bearer ${this.currentUser.token}` } |
| 415 | }); |
| 416 | |
| 417 | const dataText = await response.text() |
| 418 | const data = JSON.parse(dataText); |
| 419 | |
| 420 | if (data.success) |
| 421 | { |
| 422 | this.currentSave = data.save; |
| 423 | this.currentTribe = data.tribe; |
| 424 | this.showGameScreen(); |
| 425 | } |
| 426 | } catch (error) |
| 427 | { |
| 428 | alert('Failed to load game'); |
| 429 | console.error(error); |
| 430 | } |
| 431 | } |
| 432 | |
| 433 | showGameScreen () |
| 434 | { |
| 435 | this.hideAll(); |
| 436 | document.getElementById('gameScreen').classList.remove('hidden'); |
| 437 | this.renderGame(); |
| 438 | } |
| 439 | |
| 440 | renderGame () |
| 441 | { |
| 442 | document.getElementById('tribeName').textContent = this.currentSave.name; |
| 443 | document.getElementById('monthDisplay').textContent = `Month ${this.currentSave.current_month}`; |
| 444 | document.getElementById('seasonDisplay').textContent = this.capitalizeFirst(this.currentSave.current_season); |
| 445 | |
| 446 | this.renderStorage(); |
| 447 | this.renderTribeList(); |
| 448 | this.renderEvents(); |
| 449 | } |
| 450 | |
| 451 | renderTribeList () |
| 452 | { |
| 453 | const list = document.getElementById('tribeList'); |
| 454 | list.innerHTML = ''; |
| 455 | |
| 456 | this.currentTribe.kobolds.forEach(kobold => |
| 457 | { |
| 458 | const spriteUrl = `api/game/sprite?userId=${this.currentUser.id}&koboldId=${kobold.id}&age=${kobold.ageCategory}`; |
| 459 | const item = document.createElement('div'); |
| 460 | const isInjured = kobold.injuries && kobold.injuries.length > 0; |
| 461 | item.className = `tribe-item ${isInjured ? 'injured' : ''}`; |
| 462 | item.innerHTML = ` |
| 463 | <table style="width:100%"> |
| 464 | <td> |
| 465 | <img src="${spriteUrl}"/> |
| 466 | </td> |
| 467 | <td> |
| 468 | <div> |
| 469 | <div class="tribe-item-name">${kobold.name}</div> |
| 470 | <div class="tribe-item-age">${(kobold.age > 0 ? kobold.age : 0)} years</div> |
| 471 | </div> |
| 472 | </td> |
| 473 | </table> |
| 474 | `; |
| 475 | item.addEventListener('click', () => this.showKoboldModal(kobold)); |
| 476 | list.appendChild(item); |
| 477 | }); |
| 478 | } |
| 479 | |
| 480 | renderEvents () |
| 481 | { |
| 482 | const list = document.getElementById('eventsList'); |
| 483 | list.innerHTML = ''; |
| 484 | |
| 485 | const events = ['Hunting', 'Exploration', 'Farming']; |
| 486 | |
| 487 | events.forEach(evt => |
| 488 | { |
| 489 | const item = document.createElement('div'); |
| 490 | item.className = 'event-item'; |
| 491 | item.textContent = evt; |
| 492 | item.addEventListener('click', () => this.showParticipantModal(evt)); |
| 493 | list.appendChild(item); |
| 494 | }); |
| 495 | } |
| 496 | |
| 497 | async executeEvent (eventType) |
| 498 | { |
| 499 | // Deprecated direct execution; use participant modal instead |
| 500 | this.showParticipantModal(eventType); |
| 501 | } |
| 502 | |
| 503 | showParticipantModal (eventType) |
| 504 | { |
| 505 | this.currentEventType = eventType; |
| 506 | const modal = document.getElementById('participantModal'); |
| 507 | document.getElementById('participantModalTitle').textContent = `Select participants for ${eventType}`; |
| 508 | |
| 509 | const list = document.getElementById('participantsList'); |
| 510 | list.innerHTML = ''; |
| 511 | |
| 512 | // Default limits and minimum age (server also enforces). Adjust per event if needed. |
| 513 | const eventConfig = { |
| 514 | 'Exploration': { min: 1, max: 3, minAge: 0 }, |
| 515 | 'Hunting': { min: 1, max: 3, minAge: 0 }, |
| 516 | 'Farming': { min: 1, max: 3, minAge: 0 } |
| 517 | }; |
| 518 | const config = eventConfig[eventType] || { min: 1, max: 3, minAge: 0 }; |
| 519 | this.participantMin = config.min; |
| 520 | this.participantMax = config.max; |
| 521 | this.participantMinAge = config.minAge; |
| 522 | |
| 523 | // Helper: check if kobold is eligible |
| 524 | const isEligible = (kobold) => |
| 525 | { |
| 526 | const ageCategory = (kobold.ageCategory || '').toLowerCase(); |
| 527 | if (ageCategory === 'egg') return false; // eggs cannot participate |
| 528 | if (!kobold.isAlive && kobold.isDead) return false; // dead cannot participate (if available from backend) |
| 529 | if (kobold.age < this.participantMinAge) return false; // too young |
| 530 | return true; |
| 531 | }; |
| 532 | |
| 533 | // Render kobolds with eligibility status |
| 534 | this.currentTribe.kobolds.forEach(kobold => |
| 535 | { |
| 536 | const ageCategory = (kobold.ageCategory || '').toLowerCase(); |
| 537 | const eligible = isEligible(kobold); |
| 538 | let reason = ''; |
| 539 | |
| 540 | if (ageCategory === 'egg') |
| 541 | reason = '(eggs cannot participate)'; |
| 542 | else if (kobold.age < this.participantMinAge) |
| 543 | reason = `(too young, needs age ${this.participantMinAge}+)`; |
| 544 | |
| 545 | const row = document.createElement('div'); |
| 546 | row.className = `participant-row ${eligible ? 'eligible' : 'ineligible'}`; |
| 547 | |
| 548 | if (eligible) |
| 549 | { |
| 550 | row.innerHTML = ` |
| 551 | <label> |
| 552 | <input type="checkbox" class="participant-checkbox" data-id="${kobold.id}"> |
| 553 | <strong>${kobold.name}</strong> (${kobold.age}y - ${kobold.ageCategory}) |
| 554 | </label> |
| 555 | `; |
| 556 | const cb = row.querySelector('.participant-checkbox'); |
| 557 | cb.addEventListener('change', () => this._updateParticipantButtons()); |
| 558 | } else |
| 559 | { |
| 560 | row.innerHTML = ` |
| 561 | <div class="participant-disabled"> |
| 562 | <span>${kobold.name} (${kobold.age}y - ${kobold.ageCategory})</span> |
| 563 | <span class="disabled-reason">${reason}</span> |
| 564 | </div> |
| 565 | `; |
| 566 | } |
| 567 | |
| 568 | list.appendChild(row); |
| 569 | }); |
| 570 | |
| 571 | document.getElementById('participantCount').textContent = `0 selected`; |
| 572 | |
| 573 | // cancel/start handlers |
| 574 | const cancelBtn = document.getElementById('cancelParticipantsBtn'); |
| 575 | const startBtn = document.getElementById('startEventBtn'); |
| 576 | |
| 577 | cancelBtn.onclick = () => { modal.classList.add('hidden'); }; |
| 578 | startBtn.onclick = async () => { await this.startEventWithParticipants(); }; |
| 579 | |
| 580 | // initial state |
| 581 | this._updateParticipantButtons(); |
| 582 | |
| 583 | modal.classList.remove('hidden'); |
| 584 | } |
| 585 | |
| 586 | _updateParticipantButtons () |
| 587 | { |
| 588 | const list = document.getElementById('participantsList'); |
| 589 | const selected = Array.from(list.querySelectorAll('.participant-checkbox:checked')).map(cb => cb.dataset.id); |
| 590 | const count = selected.length; |
| 591 | document.getElementById('participantCount').textContent = `${count} selected`; |
| 592 | |
| 593 | const startBtn = document.getElementById('startEventBtn'); |
| 594 | if (count >= (this.participantMin || 1) && count <= (this.participantMax || 3)) |
| 595 | { |
| 596 | startBtn.disabled = false; |
| 597 | } else |
| 598 | { |
| 599 | startBtn.disabled = true; |
| 600 | } |
| 601 | } |
| 602 | |
| 603 | async startEventWithParticipants () |
| 604 | { |
| 605 | const modal = document.getElementById('participantModal'); |
| 606 | const list = document.getElementById('participantsList'); |
| 607 | const selected = Array.from(list.querySelectorAll('.participant-checkbox:checked')).map(cb => cb.dataset.id); |
| 608 | |
| 609 | if (!selected || selected.length === 0) return; |
| 610 | |
| 611 | try |
| 612 | { |
| 613 | const resp = await fetch('api/game/event', { |
| 614 | method: 'POST', |
| 615 | headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser.token}` }, |
| 616 | body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, eventType: this.currentEventType, participants: selected }) |
| 617 | }); |
| 618 | |
| 619 | const dataText = await resp.text() |
| 620 | const data = JSON.parse(dataText); |
| 621 | |
| 622 | if (data.success) |
| 623 | { |
| 624 | typeText(document.getElementById('eventStory'), data.story); |
| 625 | this.showEventModal(); |
| 626 | modal.classList.add('hidden'); |
| 627 | await this.loadGame(this.currentSave.id); |
| 628 | } else |
| 629 | { |
| 630 | alert(data.error || 'Failed to start event'); |
| 631 | } |
| 632 | } catch (err) |
| 633 | { |
| 634 | console.error(err); |
| 635 | alert('Failed to start event'); |
| 636 | } |
| 637 | } |
| 638 | |
| 639 | async endMonth () |
| 640 | { |
| 641 | try |
| 642 | { |
| 643 | const response = await fetch('api/game/endMonth', { |
| 644 | method: 'POST', |
| 645 | headers: { |
| 646 | 'Content-Type': 'application/json', |
| 647 | 'Authorization': `Bearer ${this.currentUser.token}` |
| 648 | }, |
| 649 | body: JSON.stringify({ |
| 650 | userId: this.currentUser.id, saveId: this.currentSave.id |
| 651 | }) |
| 652 | }); |
| 653 | |
| 654 | const dataT = await response.text(); |
| 655 | const data = JSON.parse(dataT); |
| 656 | |
| 657 | if (data.success) |
| 658 | { |
| 659 | this.currentSave = data.save; |
| 660 | typeText(document.getElementById('eventStory'), data.monthStory); |
| 661 | this.showEventModal(); |
| 662 | } |
| 663 | } catch (error) |
| 664 | { |
| 665 | alert('Failed to end month'); |
| 666 | console.error(error); |
| 667 | } |
| 668 | } |
| 669 | |
| 670 | showEventModal () |
| 671 | { |
| 672 | document.getElementById('eventModal').classList.remove('hidden'); |
| 673 | } |
| 674 | |
| 675 | hideEventModal () |
| 676 | { |
| 677 | if (!doneTyping) return; |
| 678 | document.getElementById('eventModal').classList.add('hidden'); |
| 679 | this.renderGame(); |
| 680 | } |
| 681 | |
| 682 | renderStorage () |
| 683 | { |
| 684 | const foodDisplay = document.getElementById('foodDisplay'); |
| 685 | foodDisplay.textContent = `Food: ${this.currentSave.food_count}`; |
| 686 | |
| 687 | const storageItems = document.getElementById('storageItems'); |
| 688 | storageItems.innerHTML = ''; |
| 689 | |
| 690 | if (!this.currentTribe.storage || this.currentTribe.storage.length === 0) |
| 691 | { |
| 692 | storageItems.innerHTML = '<div style="text-align: center; color: #999; padding: 10px;">No items in storage</div>'; |
| 693 | return; |
| 694 | } |
| 695 | |
| 696 | this.currentTribe.storage.forEach(item => |
| 697 | { |
| 698 | const itemEl = document.createElement('div'); |
| 699 | itemEl.className = 'storage-item'; |
| 700 | itemEl.innerHTML = `<div class="storage-item-name">${item.name}</div>`; |
| 701 | itemEl.addEventListener('click', () => this.showItemModal(item)); |
| 702 | storageItems.appendChild(itemEl); |
| 703 | }); |
| 704 | } |
| 705 | |
| 706 | showItemModal (item) |
| 707 | { |
| 708 | const modal = document.getElementById('itemModal'); |
| 709 | document.getElementById('itemModalName').textContent = item.name; |
| 710 | document.getElementById('itemModalDescription').textContent = item.description || 'No description'; |
| 711 | |
| 712 | // Show stat modifications (handle both camelCase and snake_case) |
| 713 | const statMods = document.getElementById('itemModalStatMods'); |
| 714 | statMods.innerHTML = ''; |
| 715 | |
| 716 | const modifications = item.stat_modifications || item.statModifications || {}; |
| 717 | if (Object.keys(modifications).length > 0) |
| 718 | { |
| 719 | Object.entries(modifications).forEach(([stat, value]) => |
| 720 | { |
| 721 | if (value !== 0) |
| 722 | { |
| 723 | const modEl = document.createElement('div'); |
| 724 | modEl.className = `stat-mod ${value > 0 ? 'positive' : 'negative'}`; |
| 725 | modEl.innerHTML = `<span>${this.capitalizeFirst(stat)}</span><span>${value > 0 ? '+' : ''}${value}</span>`; |
| 726 | statMods.appendChild(modEl); |
| 727 | } |
| 728 | }); |
| 729 | } else |
| 730 | { |
| 731 | statMods.innerHTML = '<div style="color: #999; font-size: 0.9em;">No stat modifications</div>'; |
| 732 | } |
| 733 | |
| 734 | // Restore item modal actions to storage version |
| 735 | const actions = document.querySelector('.item-modal-actions'); |
| 736 | actions.innerHTML = ''; |
| 737 | |
| 738 | const select = document.createElement('select'); |
| 739 | select.id = 'itemKoboldSelect'; |
| 740 | select.className = 'kobold-select'; |
| 741 | select.innerHTML = '<option value="">Select a Kobold...</option>'; |
| 742 | this.currentTribe.kobolds.forEach(kobold => |
| 743 | { |
| 744 | const option = document.createElement('option'); |
| 745 | option.value = kobold.id; |
| 746 | option.textContent = kobold.name; |
| 747 | select.appendChild(option); |
| 748 | }); |
| 749 | |
| 750 | const giveBtn = document.createElement('button'); |
| 751 | giveBtn.id = 'giveItemBtn'; |
| 752 | giveBtn.className = 'primary'; |
| 753 | giveBtn.textContent = 'Give Item'; |
| 754 | giveBtn.disabled = true; |
| 755 | |
| 756 | select.addEventListener('change', (e) => |
| 757 | { |
| 758 | giveBtn.disabled = !e.target.value; |
| 759 | }); |
| 760 | |
| 761 | giveBtn.addEventListener('click', () => this.giveItemToKobold(item, select.value)); |
| 762 | |
| 763 | actions.appendChild(select); |
| 764 | actions.appendChild(giveBtn); |
| 765 | |
| 766 | modal.classList.remove('hidden'); |
| 767 | } |
| 768 | |
| 769 | async giveItemToKobold (item, koboldId) |
| 770 | { |
| 771 | try |
| 772 | { |
| 773 | const resp = await fetch('api/game/giveItem', { |
| 774 | method: 'POST', |
| 775 | headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser?.token}` }, |
| 776 | body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, koboldId: koboldId, itemId: item.id }) |
| 777 | }); |
| 778 | |
| 779 | const dataText = await resp.text() |
| 780 | const data = JSON.parse(dataText); |
| 781 | if (data.success) |
| 782 | { |
| 783 | typeText(document.getElementById('eventStory'), data.story); |
| 784 | this.showEventModal(); |
| 785 | // Refresh game state |
| 786 | await this.loadGame(this.currentSave.id); |
| 787 | const kob = this.currentTribe.kobolds.find(k => k.id === koboldId); |
| 788 | } else |
| 789 | { |
| 790 | alert(data.error || 'Failed to give item'); |
| 791 | } |
| 792 | } catch (err) |
| 793 | { |
| 794 | console.error(err); |
| 795 | alert('Failed to give item'); |
| 796 | } finally |
| 797 | { |
| 798 | this.hideItemModal(); |
| 799 | } |
| 800 | } |
| 801 | |
| 802 | hideItemModal () |
| 803 | { |
| 804 | document.getElementById('itemModal').classList.add('hidden'); |
| 805 | } |
| 806 | |
| 807 | hideKoboldModal () |
| 808 | { |
| 809 | const modal = document.getElementById('koboldModal'); |
| 810 | modal.classList.add('hidden'); |
| 811 | } |
| 812 | |
| 813 | showKoboldModal (kobold) |
| 814 | { |
| 815 | const modal = document.getElementById('koboldModal'); |
| 816 | document.getElementById('koboldModalName').textContent = kobold.name; |
| 817 | |
| 818 | const a = (kobold.ageCategory == "old" || kobold.ageCategory == "adult") ? "An" : "A"; |
| 819 | |
| 820 | if (kobold.ageCategory == "egg") |
| 821 | { |
| 822 | document.getElementById('koboldModalAge').textContent = `Not yet hatched`; |
| 823 | document.getElementById('koboldModalDescription').textContent = `An egg.`; |
| 824 | } |
| 825 | else |
| 826 | { |
| 827 | document.getElementById('koboldModalAge').textContent = `${kobold.age} years old`; |
| 828 | document.getElementById('koboldModalDescription').textContent = `${a} ${kobold.ageCategory} ${(kobold.male ? "male" : "female")} Kobold.`; |
| 829 | } |
| 830 | |
| 831 | this.renderKoboldStats(kobold); |
| 832 | this.renderKoboldInventory(kobold); |
| 833 | this.renderKoboldInjuries(kobold); |
| 834 | |
| 835 | // Setup tab buttons |
| 836 | document.querySelectorAll('.kobold-tab-btn').forEach(btn => |
| 837 | { |
| 838 | btn.classList.remove('active'); |
| 839 | btn.addEventListener('click', (e) => this.switchKoboldTab(e.target.dataset.tab)); |
| 840 | }); |
| 841 | document.querySelector('.kobold-tab-btn[data-tab="stats"]').classList.add('active'); |
| 842 | |
| 843 | // Hide all tabs |
| 844 | document.querySelectorAll('.kobold-tab-content').forEach(tab => tab.classList.remove('active')); |
| 845 | document.getElementById('koboldStatsTab').classList.add('active'); |
| 846 | |
| 847 | // Store current kobold for inventory actions |
| 848 | this.selectedKobold = kobold; |
| 849 | |
| 850 | modal.classList.remove('hidden'); |
| 851 | } |
| 852 | |
| 853 | renderKoboldStats (kobold) |
| 854 | { |
| 855 | const statsGrid = document.getElementById('koboldStats'); |
| 856 | statsGrid.innerHTML = ''; |
| 857 | |
| 858 | const stats = ['vitality', 'intelligence', 'tinkering', 'medicine', 'crafting', 'personality', 'will', 'fighting']; |
| 859 | stats.forEach(stat => |
| 860 | { |
| 861 | const value = kobold.stats[stat]; |
| 862 | const label = this.getStatLabel(value); |
| 863 | const statEl = document.createElement('div'); |
| 864 | statEl.className = 'stat-item'; |
| 865 | statEl.innerHTML = ` |
| 866 | <div class="stat-name">${stat}</div> |
| 867 | <div class="stat-value">${label}</div> |
| 868 | `; |
| 869 | statsGrid.appendChild(statEl); |
| 870 | }); |
| 871 | } |
| 872 | |
| 873 | renderKoboldInventory (kobold) |
| 874 | { |
| 875 | const inventory = document.getElementById('koboldInventory'); |
| 876 | inventory.innerHTML = ''; |
| 877 | |
| 878 | if (!kobold.items || kobold.items.length === 0) |
| 879 | { |
| 880 | inventory.innerHTML = '<div class="kobold-inventory-empty">No items in inventory</div>'; |
| 881 | return; |
| 882 | } |
| 883 | |
| 884 | kobold.items.forEach(item => |
| 885 | { |
| 886 | const itemEl = document.createElement('div'); |
| 887 | itemEl.className = 'kobold-inventory-item'; |
| 888 | itemEl.innerHTML = `<div class="kobold-item-name">${item.name}</div>`; |
| 889 | itemEl.addEventListener('click', () => this.showKoboldItemModal(item, kobold)); |
| 890 | inventory.appendChild(itemEl); |
| 891 | }); |
| 892 | } |
| 893 | |
| 894 | renderKoboldInjuries (kobold) |
| 895 | { |
| 896 | const container = document.getElementById('koboldInjuries'); |
| 897 | container.innerHTML = ''; |
| 898 | |
| 899 | if (!kobold.injuries || kobold.injuries.length === 0) |
| 900 | { |
| 901 | container.innerHTML = '<div class="kobold-inventory-empty">No injuries</div>'; |
| 902 | return; |
| 903 | } |
| 904 | |
| 905 | // Mapping of injury category to required cure item (matches PHP Injury::$cureMap) |
| 906 | const cureMap = { |
| 907 | 'wound': 'basic_medicine', |
| 908 | 'fracture': 'bone-setting', |
| 909 | 'infection': 'healing_herbs', |
| 910 | 'poison': 'antidote', |
| 911 | 'burn': 'burn_salve', |
| 912 | 'malnourished': 'food', |
| 913 | 'old-age': null |
| 914 | }; |
| 915 | |
| 916 | kobold.injuries.forEach(injury => |
| 917 | { |
| 918 | const el = document.createElement('div'); |
| 919 | el.className = 'injury-item'; |
| 920 | const name = injury.injury_type || injury.injuryType || 'Injury'; |
| 921 | const desc = injury.description || ''; |
| 922 | const severity = injury.severity ?? injury.severity ?? 1; |
| 923 | |
| 924 | el.innerHTML = ` |
| 925 | <div class="injury-name">${name} (Severity: ${severity})</div> |
| 926 | <div class="injury-desc">${desc}</div> |
| 927 | `; |
| 928 | |
| 929 | const actions = document.createElement('div'); |
| 930 | actions.className = 'injury-actions'; |
| 931 | |
| 932 | // malnourished has no cure button here |
| 933 | if (injury.category !== 'malnourished' && injury.category !== 'old-age') |
| 934 | { |
| 935 | // Get required medicine from server or calculate from cureMap |
| 936 | let required = injury.required_medicine || injury.requiredMedicine || null; |
| 937 | if (!required && injury.category) |
| 938 | { |
| 939 | required = cureMap[injury.category] || null; |
| 940 | } |
| 941 | |
| 942 | if (required) |
| 943 | { |
| 944 | // check if kobold has item with this id |
| 945 | const hasItem = (kobold.items || []).some(it => it.id === required); |
| 946 | if (hasItem) |
| 947 | { |
| 948 | const btn = document.createElement('button'); |
| 949 | btn.className = 'primary'; |
| 950 | btn.textContent = `Cure using ${required}`; |
| 951 | btn.addEventListener('click', async () => |
| 952 | { |
| 953 | try |
| 954 | { |
| 955 | const resp = await fetch('api/game/cureInjury', { |
| 956 | method: 'POST', |
| 957 | headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser?.token}` }, |
| 958 | body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, koboldId: kobold.id, injuryId: injury.id, itemId: required }) |
| 959 | }); |
| 960 | const dataText = await resp.text() |
| 961 | const data = JSON.parse(dataText); |
| 962 | if (data.success) |
| 963 | { |
| 964 | this.hideKoboldModal(); |
| 965 | typeText(document.getElementById('eventStory'), data.story); |
| 966 | this.showEventModal(); |
| 967 | // Refresh game state |
| 968 | await this.loadGame(this.currentSave.id); |
| 969 | // reopen kobold modal after refresh |
| 970 | const refreshed = this.currentTribe.kobolds.find(k => k.id === kobold.id); |
| 971 | |
| 972 | } else |
| 973 | { |
| 974 | alert(data.error || 'Failed to cure injury'); |
| 975 | } |
| 976 | } catch (err) |
| 977 | { |
| 978 | console.error(err); |
| 979 | alert('Failed to cure injury'); |
| 980 | } |
| 981 | }); |
| 982 | actions.appendChild(btn); |
| 983 | } else |
| 984 | { |
| 985 | const note = document.createElement('div'); |
| 986 | note.style.color = '#999'; |
| 987 | note.textContent = `Needs: ${required}`; |
| 988 | actions.appendChild(note); |
| 989 | } |
| 990 | } |
| 991 | } |
| 992 | |
| 993 | el.appendChild(actions); |
| 994 | container.appendChild(el); |
| 995 | }); |
| 996 | } |
| 997 | |
| 998 | showKoboldItemModal (item, kobold) |
| 999 | { |
| 1000 | const modal = document.getElementById('itemModal'); |
| 1001 | document.getElementById('itemModalName').textContent = item.name; |
| 1002 | document.getElementById('itemModalDescription').textContent = item.description || 'No description'; |
| 1003 | |
| 1004 | // Show stat modifications (handle both camelCase and snake_case) |
| 1005 | const statMods = document.getElementById('itemModalStatMods'); |
| 1006 | statMods.innerHTML = ''; |
| 1007 | |
| 1008 | const modifications = item.stat_modifications || item.statModifications || {}; |
| 1009 | if (Object.keys(modifications).length > 0) |
| 1010 | { |
| 1011 | Object.entries(modifications).forEach(([stat, value]) => |
| 1012 | { |
| 1013 | if (value !== 0) |
| 1014 | { |
| 1015 | const modEl = document.createElement('div'); |
| 1016 | modEl.className = `stat-mod ${value > 0 ? 'positive' : 'negative'}`; |
| 1017 | modEl.innerHTML = `<span>${this.capitalizeFirst(stat)}</span><span>${value > 0 ? '+' : ''}${value}</span>`; |
| 1018 | statMods.appendChild(modEl); |
| 1019 | } |
| 1020 | }); |
| 1021 | } else |
| 1022 | { |
| 1023 | statMods.innerHTML = '<div style="color: #999; font-size: 0.9em;">No stat modifications</div>'; |
| 1024 | } |
| 1025 | |
| 1026 | // Change button to return item |
| 1027 | const actions = document.querySelector('.item-modal-actions'); |
| 1028 | actions.innerHTML = ''; |
| 1029 | |
| 1030 | const returnBtn = document.createElement('button'); |
| 1031 | returnBtn.className = 'secondary'; |
| 1032 | returnBtn.textContent = 'Return to Storage'; |
| 1033 | returnBtn.addEventListener('click', () => this.returnItemToStorage(item, kobold)); |
| 1034 | actions.appendChild(returnBtn); |
| 1035 | |
| 1036 | modal.classList.remove('hidden'); |
| 1037 | this.selectedKobold = kobold; |
| 1038 | } |
| 1039 | |
| 1040 | async returnItemToStorage (item, kobold) |
| 1041 | { |
| 1042 | try |
| 1043 | { |
| 1044 | const resp = await fetch('api/game/returnItem', { |
| 1045 | method: 'POST', |
| 1046 | headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.currentUser?.token}` }, |
| 1047 | body: JSON.stringify({ userId: this.currentUser.id, saveId: this.currentSave.id, koboldId: kobold.id, itemId: item.id }) |
| 1048 | }); |
| 1049 | |
| 1050 | const dataText = await resp.text() |
| 1051 | const data = JSON.parse(dataText); |
| 1052 | if (data.success) |
| 1053 | { |
| 1054 | typeText(document.getElementById('eventStory'), data.story); |
| 1055 | this.showEventModal(); |
| 1056 | // Refresh game state |
| 1057 | await this.loadGame(this.currentSave.id); |
| 1058 | const refreshed = this.currentTribe.kobolds.find(k => k.id === kobold.id); |
| 1059 | } else |
| 1060 | { |
| 1061 | alert(data.error || 'Failed to return item'); |
| 1062 | } |
| 1063 | } catch (err) |
| 1064 | { |
| 1065 | console.error(err); |
| 1066 | alert('Failed to return item'); |
| 1067 | } finally |
| 1068 | { |
| 1069 | this.hideItemModal(); |
| 1070 | } |
| 1071 | } |
| 1072 | |
| 1073 | switchKoboldTab (tabName) |
| 1074 | { |
| 1075 | // Hide all tabs |
| 1076 | document.querySelectorAll('.kobold-tab-content').forEach(tab => tab.classList.remove('active')); |
| 1077 | document.querySelectorAll('.kobold-tab-btn').forEach(btn => btn.classList.remove('active')); |
| 1078 | |
| 1079 | // Show selected tab |
| 1080 | const tabId = 'kobold' + this.capitalizeFirst(tabName) + 'Tab'; |
| 1081 | document.getElementById(tabId).classList.add('active'); |
| 1082 | document.querySelector(`[data-tab="${tabName}"]`).classList.add('active'); |
| 1083 | } |
| 1084 | |
| 1085 | getStatLabel (statValue) |
| 1086 | { |
| 1087 | if (statValue >= 90) return 'godlike'; |
| 1088 | if (statValue >= 80) return 'divine'; |
| 1089 | if (statValue >= 70) return 'master'; |
| 1090 | if (statValue >= 60) return 'fantastic'; |
| 1091 | if (statValue >= 50) return 'excellent'; |
| 1092 | if (statValue >= 40) return 'good'; |
| 1093 | if (statValue >= 30) return 'decent'; |
| 1094 | if (statValue >= 20) return 'unskilled'; |
| 1095 | if (statValue >= 10) return 'bad'; |
| 1096 | return 'terrible'; |
| 1097 | } |
| 1098 | |
| 1099 | hideAll () |
| 1100 | { |
| 1101 | document.querySelectorAll('.screen').forEach(screen => screen.classList.add('hidden')); |
| 1102 | } |
| 1103 | |
| 1104 | capitalizeFirst (str) |
| 1105 | { |
| 1106 | return str.charAt(0).toUpperCase() + str.slice(1); |
| 1107 | } |
| 1108 | } |
| 1109 | |
| 1110 | // Initialize app when DOM is ready |
| 1111 | document.addEventListener('DOMContentLoaded', () => |
| 1112 | { |
| 1113 | window.app = new TribeGenApp(); |
| 1114 | }); |
| 1115 | |
| 1116 | function typeText (element, text, minDelay = 3, maxDelay = 65) |
| 1117 | { |
| 1118 | doneTyping = false; |
| 1119 | element.textContent = ""; |
| 1120 | let index = 0; |
| 1121 | let timerId = null; |
| 1122 | |
| 1123 | const randDelay = () => |
| 1124 | Math.floor(Math.random() * (maxDelay - minDelay + 1)) + minDelay; |
| 1125 | |
| 1126 | const shouldStop = () => |
| 1127 | { |
| 1128 | if (!element.isConnected) return true; |
| 1129 | if (getComputedStyle(element).display === "none") return true; |
| 1130 | return false; |
| 1131 | }; |
| 1132 | |
| 1133 | return new Promise((resolve) => |
| 1134 | { |
| 1135 | function tick () |
| 1136 | { |
| 1137 | if (shouldStop()) |
| 1138 | { |
| 1139 | if (timerId) clearTimeout(timerId); |
| 1140 | doneTyping = true; |
| 1141 | resolve(false); // stopped early |
| 1142 | return; |
| 1143 | } |
| 1144 | |
| 1145 | if (index >= text.length) |
| 1146 | { |
| 1147 | doneTyping = true; |
| 1148 | resolve(true); // finished normally |
| 1149 | return; |
| 1150 | } |
| 1151 | |
| 1152 | element.textContent += text[index++]; |
| 1153 | timerId = setTimeout(tick, randDelay()); |
| 1154 | } |
| 1155 | |
| 1156 | tick(); |
| 1157 | }); |
| 1158 | } |
| 1159 | |