| 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 |
| 44 | document.querySelector('.modal-close').addEventListener('click', () => this.hideEventModal()); |
| 45 | document.getElementById('eventContinueBtn').addEventListener('click', () => this.hideEventModal()); |
| 46 | } |
| 47 | |
| 48 | switchTab (tabName) |
| 49 | { |
| 50 | document.querySelectorAll('.tab-content').forEach(tab => tab.classList.remove('active')); |
| 51 | document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active')); |
| 52 | document.getElementById(tabName + 'Tab').classList.add('active'); |
| 53 | event.target.classList.add('active'); |
| 54 | } |
| 55 | |
| 56 | async checkAuth () |
| 57 | { |
| 58 | // Check if user is logged in |
| 59 | const savedUser = localStorage.getItem('currentUser'); |
| 60 | if (savedUser) |
| 61 | { |
| 62 | this.currentUser = JSON.parse(savedUser); |
| 63 | this.showMainMenu(); |
| 64 | } else |
| 65 | { |
| 66 | this.showAuthScreen(); |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | async handleLogin (e) |
| 71 | { |
| 72 | e.preventDefault(); |
| 73 | const email = document.querySelector('#loginForm input[name="email"]').value; |
| 74 | const password = document.querySelector('#loginForm input[name="password"]').value; |
| 75 | |
| 76 | try |
| 77 | { |
| 78 | const response = await fetch('api/auth/login', { |
| 79 | method: 'POST', |
| 80 | headers: { 'Content-Type': 'application/json' }, |
| 81 | body: JSON.stringify({ email, password }) |
| 82 | }); |
| 83 | |
| 84 | const dataJson = await response; |
| 85 | const dataText = await dataJson.text(); |
| 86 | const data = JSON.parse(dataText); |
| 87 | |
| 88 | if (data.success) |
| 89 | { |
| 90 | this.currentUser = data.user; |
| 91 | localStorage.setItem('currentUser', JSON.stringify(data.user)); |
| 92 | this.showMainMenu(); |
| 93 | } else |
| 94 | { |
| 95 | this.showAuthError(data.error); |
| 96 | } |
| 97 | } catch (error) |
| 98 | { |
| 99 | this.showAuthError('Login failed'); |
| 100 | console.error(error); |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | async handleRegister (e) |
| 105 | { |
| 106 | e.preventDefault(); |
| 107 | const email = document.querySelector('#registerForm input[name="email"]').value; |
| 108 | const password = document.querySelector('#registerForm input[name="password"]').value; |
| 109 | const passwordConfirm = document.querySelector('#registerForm input[name="passwordConfirm"]').value; |
| 110 | |
| 111 | if (password !== passwordConfirm) |
| 112 | { |
| 113 | this.showAuthError('Passwords do not match'); |
| 114 | return; |
| 115 | } |
| 116 | |
| 117 | try |
| 118 | { |
| 119 | const response = await fetch('api/auth/register', { |
| 120 | method: 'POST', |
| 121 | headers: { 'Content-Type': 'application/json' }, |
| 122 | body: JSON.stringify({ email, password }) |
| 123 | }); |
| 124 | |
| 125 | const dataRaw = await response; |
| 126 | const dataText = await dataRaw.text(); |
| 127 | const data = JSON.parse(dataText); |
| 128 | |
| 129 | if (data.success) |
| 130 | { |
| 131 | this.currentUser = data.user; |
| 132 | localStorage.setItem('currentUser', JSON.stringify(data.user)); |
| 133 | this.showMainMenu(); |
| 134 | } else |
| 135 | { |
| 136 | this.showAuthError(data.error); |
| 137 | } |
| 138 | } catch (error) |
| 139 | { |
| 140 | this.showAuthError('Registration failed'); |
| 141 | console.error(error); |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | handleLogout () |
| 146 | { |
| 147 | this.currentUser = null; |
| 148 | localStorage.removeItem('currentUser'); |
| 149 | this.showAuthScreen(); |
| 150 | } |
| 151 | |
| 152 | showAuthError (error) |
| 153 | { |
| 154 | const errorDiv = document.getElementById('authError'); |
| 155 | errorDiv.textContent = error; |
| 156 | errorDiv.classList.add('show'); |
| 157 | setTimeout(() => errorDiv.classList.remove('show'), 5000); |
| 158 | } |
| 159 | |
| 160 | showAuthScreen () |
| 161 | { |
| 162 | this.hideAll(); |
| 163 | document.getElementById('authScreen').classList.remove('hidden'); |
| 164 | } |
| 165 | |
| 166 | showMainMenu () |
| 167 | { |
| 168 | this.hideAll(); |
| 169 | document.getElementById('mainMenuScreen').classList.remove('hidden'); |
| 170 | document.getElementById('userEmail').textContent = this.currentUser.email; |
| 171 | this.loadSaves(); |
| 172 | } |
| 173 | |
| 174 | async loadSaves () |
| 175 | { |
| 176 | try |
| 177 | { |
| 178 | const response = await fetch('api/game/list', { |
| 179 | method: 'GET', |
| 180 | headers: { 'Authorization': `Bearer ${this.currentUser.token}` } |
| 181 | }); |
| 182 | |
| 183 | const data = await response.json(); |
| 184 | |
| 185 | const savesList = document.getElementById('savesList'); |
| 186 | savesList.innerHTML = ''; |
| 187 | |
| 188 | if (data.saves && data.saves.length > 0) |
| 189 | { |
| 190 | data.saves.forEach(save => |
| 191 | { |
| 192 | const card = document.createElement('div'); |
| 193 | card.className = 'save-card'; |
| 194 | card.innerHTML = ` |
| 195 | <h3>${save.name}</h3> |
| 196 | <p>Month: ${save.current_month}</p> |
| 197 | <p>Season: ${save.current_season}</p> |
| 198 | `; |
| 199 | card.addEventListener('click', () => this.loadGame(save.id)); |
| 200 | savesList.appendChild(card); |
| 201 | }); |
| 202 | } |
| 203 | } catch (error) |
| 204 | { |
| 205 | console.error('Failed to load saves:', error); |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | startGameSetup () |
| 210 | { |
| 211 | this.hideAll(); |
| 212 | document.getElementById('gameSetupScreen').classList.remove('hidden'); |
| 213 | document.getElementById('setupStep1').classList.remove('hidden'); |
| 214 | document.getElementById('setupStep2').classList.add('hidden'); |
| 215 | document.getElementById('setupStep3').classList.add('hidden'); |
| 216 | } |
| 217 | |
| 218 | async generateKobolds () |
| 219 | { |
| 220 | const tribeName = document.getElementById('tribeName').value; |
| 221 | |
| 222 | if (!tribeName) |
| 223 | { |
| 224 | alert('Please enter a tribe name'); |
| 225 | return; |
| 226 | } |
| 227 | |
| 228 | try |
| 229 | { |
| 230 | const response = await fetch('api/game/generation', { |
| 231 | method: 'POST', |
| 232 | headers: { |
| 233 | 'Content-Type': 'application/json', |
| 234 | 'Authorization': `Bearer ${this.currentUser.token}` |
| 235 | }, |
| 236 | body: JSON.stringify({ |
| 237 | saveName: tribeName, |
| 238 | userId: this.currentUser.id |
| 239 | }) |
| 240 | }); |
| 241 | |
| 242 | const dataText = await response.text(); |
| 243 | const data = JSON.parse(dataText); |
| 244 | |
| 245 | if (data.success) |
| 246 | { |
| 247 | this.currentSave = data.save; |
| 248 | this.displayKobolds(data.kobolds, 'leader'); |
| 249 | this.displayKobolds(data.kobolds, 'member'); |
| 250 | |
| 251 | document.getElementById('setupStep1').classList.add('hidden'); |
| 252 | document.getElementById('setupStep2').classList.remove('hidden'); |
| 253 | } |
| 254 | } catch (error) |
| 255 | { |
| 256 | alert('Failed to generate kobolds'); |
| 257 | console.error(error); |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | displayKobolds (kobolds, type) |
| 262 | { |
| 263 | const container = type === 'leader' |
| 264 | ? document.getElementById('leaderSelectionGrid') |
| 265 | : document.getElementById('memberSelectionGrid'); |
| 266 | |
| 267 | container.innerHTML = ''; |
| 268 | |
| 269 | kobolds.forEach((kobold, index) => |
| 270 | { |
| 271 | const card = document.createElement('div'); |
| 272 | card.className = 'kobold-card'; |
| 273 | |
| 274 | const spriteUrl = `api/game/sprite?userId=${this.currentUser.id}&koboldId=${kobold.id}&age=${kobold.ageCategory}`; |
| 275 | |
| 276 | card.innerHTML = ` |
| 277 | <img src="${spriteUrl}" alt="Kobold sprite" class="kobold-sprite"> |
| 278 | <div class="kobold-name">${kobold.age} years</div> |
| 279 | <div class="kobold-stats"> |
| 280 | <div>Vitality: ${kobold.stats.vitality}</div> |
| 281 | </div> |
| 282 | `; |
| 283 | |
| 284 | if (type === 'member') |
| 285 | { |
| 286 | card.addEventListener('click', () => this.toggleMemberSelection(card, index)); |
| 287 | } else |
| 288 | { |
| 289 | card.addEventListener('click', () => this.selectLeaderCard(card, index)); |
| 290 | } |
| 291 | |
| 292 | container.appendChild(card); |
| 293 | }); |
| 294 | } |
| 295 | |
| 296 | async selectLeaderCard (card, index) |
| 297 | { |
| 298 | const leaderName = document.getElementById('leaderName').value; |
| 299 | |
| 300 | if (!leaderName) |
| 301 | { |
| 302 | alert('Please enter a leader name'); |
| 303 | return; |
| 304 | } |
| 305 | |
| 306 | document.querySelectorAll('#leaderSelectionGrid .kobold-card').forEach(c => c.classList.remove('selected')); |
| 307 | card.classList.add('selected'); |
| 308 | document.getElementById('selectLeaderBtn').dataset.leaderIndex = index; |
| 309 | |
| 310 | this.toggleMemberSelection(card, index, true); |
| 311 | await this.selectLeader(); |
| 312 | } |
| 313 | |
| 314 | toggleMemberSelection (card, index, force) |
| 315 | { |
| 316 | const leaderIndex = document.getElementById('selectLeaderBtn').dataset.leaderIndex; |
| 317 | if (force || leaderIndex != index) |
| 318 | { |
| 319 | document.querySelectorAll('#memberSelectionGrid .kobold-card')[index].classList.toggle('selected'); |
| 320 | |
| 321 | const selected = document.querySelectorAll('#memberSelectionGrid .kobold-card.selected').length; |
| 322 | document.getElementById('memberCount').textContent = `${selected} / 5 selected`; |
| 323 | |
| 324 | if (selected === 5) |
| 325 | { |
| 326 | document.getElementById('finishTribeBtn').disabled = false; |
| 327 | } else |
| 328 | { |
| 329 | document.getElementById('finishTribeBtn').disabled = true; |
| 330 | } |
| 331 | } |
| 332 | } |
| 333 | |
| 334 | async selectLeader () |
| 335 | { |
| 336 | const leaderIndex = document.getElementById('selectLeaderBtn').dataset.leaderIndex; |
| 337 | const leaderName = document.getElementById('leaderName').value; |
| 338 | |
| 339 | if (!leaderName) |
| 340 | { |
| 341 | alert('Please enter a leader name'); |
| 342 | return; |
| 343 | } |
| 344 | |
| 345 | // Proceed to member selection |
| 346 | document.getElementById('setupStep2').classList.add('hidden'); |
| 347 | document.getElementById('setupStep3').classList.remove('hidden'); |
| 348 | |
| 349 | // For now, just display remaining kobolds (in real implementation, filter out leader) |
| 350 | } |
| 351 | |
| 352 | async finishTribe () |
| 353 | { |
| 354 | const selectedMembers = document.querySelectorAll('#memberSelectionGrid .kobold-card.selected'); |
| 355 | const memberIndices = Array.from(selectedMembers).map(card => |
| 356 | { |
| 357 | return Array.from(card.parentElement.children).indexOf(card); |
| 358 | }); |
| 359 | |
| 360 | // Load the game |
| 361 | try |
| 362 | { |
| 363 | const response = await fetch('api/game/save', { |
| 364 | method: 'POST', |
| 365 | headers: { |
| 366 | 'Content-Type': 'application/json', |
| 367 | 'Authorization': `Bearer ${this.currentUser.token}` |
| 368 | }, |
| 369 | body: JSON.stringify({ |
| 370 | userId: this.currentUser.id, |
| 371 | saveId: this.currentSave.id, |
| 372 | leaderName: document.getElementById('leaderName').value, |
| 373 | memberIndices: memberIndices |
| 374 | }) |
| 375 | }); |
| 376 | |
| 377 | const data = await response.json(); |
| 378 | |
| 379 | if (data.success) |
| 380 | { |
| 381 | this.loadGame(this.currentSave.id); |
| 382 | } |
| 383 | } catch (error) |
| 384 | { |
| 385 | alert('Failed to finish tribe setup'); |
| 386 | console.error(error); |
| 387 | } |
| 388 | } |
| 389 | |
| 390 | async loadGame (saveId) |
| 391 | { |
| 392 | try |
| 393 | { |
| 394 | const response = await fetch(`api/game/load?saveId=${saveId}`, { |
| 395 | method: 'GET', |
| 396 | headers: { 'Authorization': `Bearer ${this.currentUser.token}` } |
| 397 | }); |
| 398 | |
| 399 | const data = await response.json(); |
| 400 | |
| 401 | if (data.success) |
| 402 | { |
| 403 | this.currentSave = data.save; |
| 404 | this.currentTribe = data.tribe; |
| 405 | this.showGameScreen(); |
| 406 | } |
| 407 | } catch (error) |
| 408 | { |
| 409 | alert('Failed to load game'); |
| 410 | console.error(error); |
| 411 | } |
| 412 | } |
| 413 | |
| 414 | showGameScreen () |
| 415 | { |
| 416 | this.hideAll(); |
| 417 | document.getElementById('gameScreen').classList.remove('hidden'); |
| 418 | this.renderGame(); |
| 419 | } |
| 420 | |
| 421 | renderGame () |
| 422 | { |
| 423 | document.getElementById('tribeName').textContent = this.currentSave.name; |
| 424 | document.getElementById('monthDisplay').textContent = `Month ${this.currentSave.current_month}`; |
| 425 | document.getElementById('seasonDisplay').textContent = this.capitalizeFirst(this.currentSave.current_season); |
| 426 | |
| 427 | this.renderTribeList(); |
| 428 | this.renderEvents(); |
| 429 | } |
| 430 | |
| 431 | renderTribeList () |
| 432 | { |
| 433 | const list = document.getElementById('tribeList'); |
| 434 | list.innerHTML = ''; |
| 435 | |
| 436 | this.currentTribe.kobolds.forEach(kobold => |
| 437 | { |
| 438 | const item = document.createElement('div'); |
| 439 | item.className = 'tribe-item'; |
| 440 | item.innerHTML = ` |
| 441 | <div> |
| 442 | <div class="tribe-item-name">${kobold.name}</div> |
| 443 | <div class="tribe-item-age">${kobold.age} years</div> |
| 444 | </div> |
| 445 | `; |
| 446 | list.appendChild(item); |
| 447 | }); |
| 448 | } |
| 449 | |
| 450 | renderEvents () |
| 451 | { |
| 452 | const list = document.getElementById('eventsList'); |
| 453 | list.innerHTML = ''; |
| 454 | |
| 455 | const events = ['Hunting', 'Exploration', 'Farming']; |
| 456 | |
| 457 | events.forEach(event => |
| 458 | { |
| 459 | const item = document.createElement('div'); |
| 460 | item.className = 'event-item'; |
| 461 | item.textContent = event; |
| 462 | item.addEventListener('click', () => this.executeEvent(event)); |
| 463 | list.appendChild(item); |
| 464 | }); |
| 465 | } |
| 466 | |
| 467 | async executeEvent (eventType) |
| 468 | { |
| 469 | try |
| 470 | { |
| 471 | const response = await fetch('api/game/event', { |
| 472 | method: 'POST', |
| 473 | headers: { |
| 474 | 'Content-Type': 'application/json', |
| 475 | 'Authorization': `Bearer ${this.currentUser.token}` |
| 476 | }, |
| 477 | body: JSON.stringify({ |
| 478 | userId: this.currentUser.id, |
| 479 | saveId: this.currentSave.id, |
| 480 | eventType: eventType |
| 481 | }) |
| 482 | }); |
| 483 | |
| 484 | const data = await response.json(); |
| 485 | |
| 486 | if (data.success) |
| 487 | { |
| 488 | typeText(document.getElementById('eventStory'), data.story); |
| 489 | this.showEventModal(); |
| 490 | } |
| 491 | } catch (error) |
| 492 | { |
| 493 | alert('Failed to execute event'); |
| 494 | console.error(error); |
| 495 | } |
| 496 | } |
| 497 | |
| 498 | async endMonth () |
| 499 | { |
| 500 | try |
| 501 | { |
| 502 | const response = await fetch('api/game/endMonth', { |
| 503 | method: 'POST', |
| 504 | headers: { |
| 505 | 'Content-Type': 'application/json', |
| 506 | 'Authorization': `Bearer ${this.currentUser.token}` |
| 507 | }, |
| 508 | body: JSON.stringify({ |
| 509 | userId: this.currentUser.id, saveId: this.currentSave.id |
| 510 | }) |
| 511 | }); |
| 512 | |
| 513 | const dataT = await response.text(); |
| 514 | const data = JSON.parse(dataT); |
| 515 | |
| 516 | if (data.success) |
| 517 | { |
| 518 | this.currentSave = data.save; |
| 519 | typeText(document.getElementById('eventStory'), data.monthStory); |
| 520 | this.showEventModal(); |
| 521 | } |
| 522 | } catch (error) |
| 523 | { |
| 524 | alert('Failed to end month'); |
| 525 | console.error(error); |
| 526 | } |
| 527 | } |
| 528 | |
| 529 | showEventModal () |
| 530 | { |
| 531 | document.getElementById('eventModal').classList.remove('hidden'); |
| 532 | } |
| 533 | |
| 534 | hideEventModal () |
| 535 | { |
| 536 | if (!doneTyping) return; |
| 537 | document.getElementById('eventModal').classList.add('hidden'); |
| 538 | this.renderGame(); |
| 539 | } |
| 540 | |
| 541 | hideAll () |
| 542 | { |
| 543 | document.querySelectorAll('.screen').forEach(screen => screen.classList.add('hidden')); |
| 544 | } |
| 545 | |
| 546 | capitalizeFirst (str) |
| 547 | { |
| 548 | return str.charAt(0).toUpperCase() + str.slice(1); |
| 549 | } |
| 550 | } |
| 551 | |
| 552 | // Initialize app when DOM is ready |
| 553 | document.addEventListener('DOMContentLoaded', () => |
| 554 | { |
| 555 | window.app = new TribeGenApp(); |
| 556 | }); |
| 557 | |
| 558 | function typeText (element, text, minDelay = 3, maxDelay = 65) |
| 559 | { |
| 560 | doneTyping = false; |
| 561 | element.textContent = ""; |
| 562 | let index = 0; |
| 563 | let timerId = null; |
| 564 | |
| 565 | const randDelay = () => |
| 566 | Math.floor(Math.random() * (maxDelay - minDelay + 1)) + minDelay; |
| 567 | |
| 568 | const shouldStop = () => |
| 569 | { |
| 570 | if (!element.isConnected) return true; |
| 571 | if (getComputedStyle(element).display === "none") return true; |
| 572 | return false; |
| 573 | }; |
| 574 | |
| 575 | return new Promise((resolve) => |
| 576 | { |
| 577 | function tick () |
| 578 | { |
| 579 | if (shouldStop()) |
| 580 | { |
| 581 | if (timerId) clearTimeout(timerId); |
| 582 | doneTyping = true; |
| 583 | resolve(false); // stopped early |
| 584 | return; |
| 585 | } |
| 586 | |
| 587 | if (index >= text.length) |
| 588 | { |
| 589 | doneTyping = true; |
| 590 | resolve(true); // finished normally |
| 591 | return; |
| 592 | } |
| 593 | |
| 594 | element.textContent += text[index++]; |
| 595 | timerId = setTimeout(tick, randDelay()); |
| 596 | } |
| 597 | |
| 598 | tick(); |
| 599 | }); |
| 600 | } |
| 601 | |