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