Derur's picture
Upload Г.У.Л.А.Г..html
6bbf316 verified
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Г.У.Л.А.Г-2034 - Экспедиция v13 (фикс голоса и финала)</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
:root {
--bg-primary: #1a1d22;
--bg-secondary: #252a31;
--bg-tertiary: #303641;
--text-primary: #d1d5db;
--text-secondary: #9ca3af;
--accent-primary: #b91c1c;
--accent-secondary: #991b1b;
--success: #10b981;
--warning: #f59e0b;
--error: #ef4444;
--border: #4b5563;
--narrator-voice-accent: #60a5fa;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: linear-gradient(135deg, var(--bg-primary) 0%, var(--bg-secondary) 100%);
min-height: 100vh;
color: var(--text-primary);
overflow-x: hidden;
transition: background 0.5s ease;
}
.main-container {
display: grid;
grid-template-columns: 1fr 320px;
min-height: 100vh;
gap: 1rem;
}
.game-area {
padding: 1rem;
overflow-y: auto;
display: flex;
flex-direction: column;
}
.container {
width: 100%;
max-width: 900px;
margin: 0 auto;
}
.timeline {
background: var(--bg-secondary);
border-left: 2px solid var(--border);
padding: 1rem;
overflow-y: auto;
max-height: 100vh;
}
.timeline h3 {
color: var(--accent-primary);
margin-bottom: 1rem;
text-align: center;
font-size: 1.1rem;
}
.timeline-item {
background: var(--bg-tertiary);
border-radius: 8px;
padding: 1rem;
margin-bottom: 1rem;
border: 1px solid var(--border);
transition: all 0.2s ease;
cursor: pointer;
}
.timeline-item:hover {
border-color: var(--accent-primary);
}
.timeline-title {
font-weight: 600;
color: var(--accent-primary);
margin-bottom: 0.5rem;
font-size: 0.9rem;
}
.timeline-content-preview {
font-size: 0.8rem;
color: var(--text-secondary);
line-height: 1.4;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.timeline-details {
max-height: 0;
overflow: hidden;
transition: max-height 0.3s ease-out;
}
.timeline-details.expanded {
max-height: 800px;
transition: max-height 0.5s ease-in;
}
.timeline-full-content {
font-size: 0.85rem;
color: var(--text-secondary);
line-height: 1.5;
margin-top: 0.5rem;
padding-top: 0.5rem;
border-top: 1px solid var(--border);
white-space: pre-wrap;
}
.timeline-media img {
width: 100%;
border-radius: 4px;
max-height: 80px;
object-fit: cover;
margin-top: 0.5rem;
}
.audio-controls {
text-align: center;
margin: 0.5rem 0;
position: relative;
}
.audio-player {
background: var(--bg-tertiary);
border: 1px solid var(--border);
border-radius: 8px;
padding: 0.75rem;
margin: 0.5rem auto;
max-width: 350px;
display: none;
}
.audio-player.show {
display: block;
}
.audio-loader {
background: var(--bg-tertiary);
border: 1px solid var(--border);
border-radius: 8px;
padding: 1rem;
margin: 0.5rem auto;
max-width: 350px;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
gap: 0.5rem;
color: var(--text-secondary);
font-size: 0.9rem;
}
.audio-loader.hidden {
display: none;
}
.audio-loader .image-spinner {
width: 20px;
height: 20px;
border: 2px solid var(--border);
border-top: 2px solid var(--accent-primary);
border-radius: 50%;
animation: spin 1s linear infinite;
}
.audio-title {
font-weight: 600;
margin-bottom: 0.25rem;
font-size: 0.85rem;
}
#objectiveAudioTitle { color: var(--narrator-voice-accent); }
#pinAudioTitle { color: var(--accent-primary); }
#finaleAudioTitle { color: var(--text-secondary); }
#pinGameOverAudioTitle { color: var(--accent-primary); }
.header {
text-align: center;
padding: 1rem 0;
position: relative;
display: flex;
align-items: center;
justify-content: center;
flex-wrap: wrap;
gap: 1rem;
}
.header h1 {
font-size: clamp(2rem, 5vw, 3.5rem);
background: linear-gradient(135deg, var(--accent-primary), var(--accent-secondary));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
font-weight: 800;
margin: 0;
}
.header p {
color: var(--text-secondary);
font-size: 1rem;
margin: 0;
width: 100%;
}
.reset-btn {
position: absolute;
top: 1rem;
right: 1rem;
padding: 0.5rem 1rem;
background: var(--error);
color: white;
border: none;
border-radius: 8px;
cursor: pointer;
font-weight: 600;
transition: all 0.2s ease;
z-index: 102;
}
.reset-btn:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(239, 68, 68, 0.3);
}
.settings-btn {
position: absolute;
top: 1rem;
left: 1rem;
padding: 0.5rem 1rem;
background: var(--bg-tertiary);
color: var(--text-primary);
border: 1px solid var(--border);
border-radius: 8px;
cursor: pointer;
font-weight: 600;
transition: all 0.2s ease;
font-size: 1.2rem;
display: flex;
align-items: center;
justify-content: center;
z-index: 102;
}
.settings-btn:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(58, 58, 92, 0.3);
}
.settings-panel {
position: absolute;
top: 60px;
left: 1rem;
background: var(--bg-secondary);
border: 1px solid var(--border);
border-radius: 12px;
padding: 1rem;
display: flex;
flex-direction: column;
gap: 1rem;
z-index: 100;
opacity: 0;
visibility: hidden;
transform: translateY(-20px);
transition: opacity 0.3s ease, visibility 0.3s ease, transform 0.3s ease;
text-align: left;
}
.settings-panel.show {
opacity: 1;
visibility: visible;
transform: translateY(0);
}
.settings-panel > div {
display: flex;
align-items: center;
gap: 0.5rem;
}
.settings-panel label {
color: var(--text-secondary);
font-size: 0.9rem;
font-weight: 600;
white-space: nowrap;
}
.settings-panel select, .settings-panel input[type="checkbox"] {
background: var(--bg-tertiary);
color: var(--text-primary);
border: 1px solid var(--border);
border-radius: 4px;
padding: 0.4rem 0.6rem;
font-size: 0.85rem;
cursor: pointer;
}
.settings-panel select {
appearance: none; -webkit-appearance: none; min-width: 100px;
}
.settings-panel select:focus {
outline: none; border-color: var(--accent-primary); box-shadow: 0 0 0 2px rgba(185, 28, 28, 0.2);
}
.settings-panel input[type="checkbox"] { width: 18px; height: 18px; accent-color: var(--accent-primary); }
.settings-panel .info-block {
font-size: 0.8rem; color: var(--text-secondary); margin-top: 1rem; padding-top: 1rem;
border-top: 1px solid var(--border); line-height: 1.4;
}
.settings-panel .info-block a { color: var(--accent-primary); text-decoration: none; font-weight: 600; }
.settings-panel .info-block a:hover { text-decoration: underline; }
.game-stage {
display: none;
animation: fadeInUp 0.5s ease;
padding: 1rem 0;
}
.game-stage.active {
display: block;
}
@keyframes fadeInUp {
from { opacity: 0; transform: translateY(30px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
@keyframes subtleZoomInOut {
0% {
transform: scale(1);
}
50% {
transform: scale(1.07);
}
100% {
transform: scale(1);
}
}
.form-container {
background: var(--bg-secondary);
padding: 2rem;
border-radius: 16px;
border: 1px solid var(--border);
max-width: 800px;
margin: 0 auto;
text-align: center;
}
.btn {
background: linear-gradient(135deg, var(--accent-primary), var(--accent-secondary));
color: white;
border: none;
padding: 1rem 2rem;
border-radius: 12px;
font-size: 1.1rem;
font-weight: 600;
cursor: pointer;
transition: all 0.3s ease;
display: inline-block;
margin: 0.5rem;
}
.btn:hover:not(:disabled) {
transform: translateY(-2px);
box-shadow: 0 8px 25px rgba(185, 28, 28, 0.4);
}
.btn:disabled {
opacity: 0.7;
cursor: not-allowed;
transform: none;
}
.btn-group {
display: flex;
gap: 1rem;
justify-content: center;
flex-wrap: wrap;
margin-top: 1.5rem;
}
.btn-secondary {
background: var(--bg-tertiary);
border: 2px solid var(--border);
}
.btn-retry {
background: var(--warning);
color: var(--bg-primary);
padding: 0.5rem 1rem;
font-size: 0.9rem;
font-weight: 600;
margin-top: 1rem;
border:none;
border-radius: 6px;
}
.loading-stage {
text-align: center;
padding: 3rem 0;
}
.spinner-main {
width: 60px;
height: 60px;
border: 4px solid var(--border);
border-top: 4px solid var(--accent-primary);
border-radius: 50%;
animation: spin 1s linear infinite;
margin: 0 auto 1rem;
}
.loading-text {
font-size: 1.2rem;
color: var(--text-secondary);
margin: 1rem 0;
}
.error-stage {
text-align: center;
padding: 2rem;
background: var(--bg-secondary);
border: 1px solid var(--error);
border-radius: 12px;
max-width: 600px;
margin: 2rem auto;
}
.error-icon { font-size: 2.5rem; color: var(--error); margin-bottom: 0.5rem; }
.error-title { font-size: 1.3rem; color: var(--error); margin-bottom: 0.5rem; }
.error-description { color: var(--text-secondary); margin-bottom: 1.5rem; font-size: 0.9rem; }
/* Gameplay Screen Styles */
#gameplayScreen {
text-align: center;
}
#lastActionOutcomeDisplay {
margin-bottom: 1rem;
font-size: 0.9em;
color: var(--text-secondary);
border-left-color: var(--bg-tertiary) !important; /* Ensure specificity */
display:none;
text-align: left;
font-style: italic;
}
#worldNameDisplay {
font-size: 1.8rem;
color: var(--accent-primary);
margin-bottom: 0.5rem;
font-weight: 700;
}
.media-container {
position: relative;
width: 100%;
max-width: 768px;
margin: 1rem auto;
border-radius: 12px;
overflow: hidden;
background: var(--bg-tertiary);
border: 2px solid var(--border);
}
.media-container img {
width: 100%;
height: auto;
max-height: 45vh;
object-fit: cover;
display: block;
animation: subtleZoomInOut 25s infinite alternate ease-in-out;
will-change: transform;
}
.media-loader {
position: absolute;
top: 0; left: 0; width: 100%; height: 100%;
background: rgba(0,0,0,0.7);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
color: var(--text-primary);
z-index: 10;
}
.media-loader .image-spinner {
width: 40px; height: 40px;
border: 3px solid var(--border);
border-top: 3px solid var(--accent-primary);
border-radius: 50%;
animation: spin 1s linear infinite;
margin-bottom: 1rem;
}
.media-loader.hidden { display: none; }
.narration-block {
background: var(--bg-secondary);
padding: 1rem;
border-radius: 12px;
border: 1px solid var(--border);
margin: 1rem auto;
max-width: 768px;
color: var(--text-primary);
line-height: 1.6;
font-size: 1rem;
text-align: left;
box-shadow: 0 2px 10px rgba(0,0,0,0.15);
}
#objectiveNarrationDisplay {
border-left: 4px solid var(--narrator-voice-accent);
margin-bottom: 0.5rem;
}
#pinCommentaryDisplay {
border-left: 4px solid var(--accent-primary);
font-style: italic;
color: var(--text-secondary);
}
#playerStatsDisplay {
margin: 1.5rem 0;
display: flex;
justify-content: center;
gap: 1rem;
flex-wrap: wrap;
}
.stat-display-item {
background: var(--bg-tertiary);
padding: 0.6rem 1rem;
border-radius: 8px;
border: 1px solid var(--border);
font-size: 0.95rem;
color: var(--text-primary);
min-width: 120px;
text-align: center;
}
.stat-display-item strong { font-size: 1.1em; }
.stat-display-item:nth-child(1) strong { color: var(--success); }
.stat-display-item:nth-child(2) strong { color: var(--warning); }
.stat-display-item:nth-child(3) strong { color: var(--narrator-voice-accent); }
#choicesContainer {
margin-top: 1.5rem;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 0.75rem;
max-width: 768px;
margin-left: auto;
margin-right: auto;
}
#choicesContainer .btn {
width: 100%;
margin: 0;
padding: 0.75rem 1rem;
font-size: 0.9rem;
display: flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
}
#actionInProgressBtn {
width: 100%;
max-width: 450px;
margin: 1rem auto 0;
display: none;
}
/* Custom Action Input */
#customActionContainer {
margin: 1.5rem auto 0;
max-width: 768px;
padding: 1rem;
background: var(--bg-tertiary);
border-radius: 12px;
border: 1px solid var(--border);
}
#customActionContainer label {
display: block;
font-size: 0.9rem;
color: var(--text-secondary);
margin-bottom: 0.5rem;
text-align: left;
}
.input-with-button {
display: flex;
gap: 0.5rem;
}
#customActionInput {
flex-grow: 1;
padding: 0.75rem;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--bg-primary);
color: var(--text-primary);
font-size: 0.9rem;
resize: vertical;
min-height: 40px;
}
#customActionInput:focus {
outline: none;
border-color: var(--accent-primary);
box-shadow: 0 0 0 2px rgba(185, 28, 28, 0.2);
}
#submitCustomActionBtn {
padding: 0.75rem 1rem;
font-size: 0.9rem;
min-width: 100px;
margin:0;
}
/* Prologue Slideshow Styles */
#prologueDisplayScreen .form-container {
max-height: 90vh;
overflow-y: auto;
text-align: center;
}
#prologueImageContainer {
min-height: 250px;
max-height: 40vh;
}
#prologueSlideTextDisplay {
min-height: 100px;
margin-bottom: 1rem;
font-size: 1rem;
}
#prologueNavigation {
margin-top: 1.5rem;
display: flex;
justify-content: space-between;
align-items: center;
}
#prologueNavigation .btn {
min-width: 120px;
font-size: 0.9rem;
padding: 0.75rem 1.5rem;
}
#prologueSlideCounter {
color: var(--text-secondary);
font-size: 0.9rem;
}
/* Game Over Screen Enhancements */
#gameOverScreen .form-container {
padding-bottom: 1rem;
}
#finaleImageContainer {
max-height: 35vh;
margin-bottom: 1rem;
}
#finaleText {
border-left-color: var(--error) !important; /* Ensure specificity */
font-size: 1rem;
margin-bottom:1rem;
color: var(--text-secondary);
}
#gameOverReason {
display: block;
font-style: italic;
color: var(--text-primary);
margin-top: 0.5rem;
}
#pinGameOverCommentDisplay {
border-left: 4px solid var(--accent-primary) !important; /* Ensure specificity */
font-style: italic;
color: var(--text-secondary);
margin-top: 1rem;
display:none; /* Initially hidden */
}
#pinGameOverAudioControls {
display:none; /* Initially hidden */
}
@media (max-width: 1024px) {
.main-container {
grid-template-columns: 1fr;
grid-template-rows: auto 1fr auto;
}
.game-area { order: 2; }
.timeline { order: 3; max-height: 350px; border-left: none; border-top: 2px solid var(--border); }
.header { order: 1; }
.settings-panel {
position: fixed;
top: 50%; left: 50%;
transform: translate(-50%, -50%) scale(0.9);
width: 90%; max-width: 350px;
opacity: 0; visibility: hidden;
transition: opacity 0.3s ease, visibility 0.3s ease, transform 0.3s ease;
}
.settings-panel.show {
transform: translate(-50%, -50%) scale(1);
}
.settings-btn {
position: absolute; top:1rem; left: 1rem; z-index: 101;
}
}
@media (max-width: 768px) {
.header h1 { font-size: 1.8rem; }
.header p { font-size: 0.9rem; }
.btn-group { flex-direction: column; }
.form-container { padding: 1.5rem; }
#playerStatsDisplay { flex-direction: column; align-items: center; gap: 0.5rem; }
.main-container { grid-template-columns: 1fr; }
#choicesContainer { grid-template-columns: 1fr; }
#prologueNavigation { flex-direction: column; gap: 0.5rem;}
#prologueNavigation .btn { width: 100%; }
.input-with-button { flex-direction: column; }
#customActionInput { margin-bottom: 0.5rem; }
#submitCustomActionBtn { width: 100%; }
}
</style>
</head>
<body class="theme-gulag">
<div class="main-container">
<div class="game-area">
<div class="container">
<div class="header">
<button class="reset-btn" onclick="resetGame()">🔄 Новая Экспедиция</button>
<button class="settings-btn" onclick="toggleSettingsPanel()" title="Настройки">⚙️</button>
<div class="settings-panel" id="settingsPanel">
<div>
<label for="pinVoiceSelect">Голос ПИНа:</label>
<select id="pinVoiceSelect" onchange="saveVoicePreference()">
<option value="amuch">Amuch (ПИН)</option>
<option value="alloy">Alloy</option>
<option value="echo">Echo</option>
<option value="fable">Fable</option>
<option value="nova">Nova</option>
<option value="onyx">Onyx</option>
<option value="shimmer">Shimmer</option>
<option value="ash">Ash</option>
<option value="aura">Aura</option>
<option value="ember">Ember</option>
<option value="breeze">Breeze</option>
<option value="cove">Cove</option>
<option value="juniper">Juniper</option>
<option value="sky">Sky</option>
</select>
</div>
<div>
<input type="checkbox" id="autoplayToggle" checked>
<label for="autoplayToggle">Авто-озвучка</label>
</div>
<div class="info-block">
<p>Концепт: Г.У.Л.А.Г-2034</p>
<p>Реализация: <a href="https://t.me/nerual_dreming" target="_blank" rel="noopener noreferrer">Nerual Dreming</a> (Основатель <a href="https://artgeneration.me" target="_blank" rel="noopener noreferrer">ArtGeneration.me</a>)</p>
<p>Все генерации происходят в реальном времени с помощью Pollinations.ai.</p>
</div>
</div>
<h1>Г.У.Л.А.Г-2034</h1>
<p>Интерактивная экспедиция в неизведанные миры</p>
</div>
<div id="mainMenuScreen" class="game-stage active">
<div class="form-container">
<h2 style="color: var(--accent-primary); margin-bottom: 2rem;">Добро пожаловать, Испытуемый!</h2>
<p style="color: var(--text-secondary); margin-bottom: 2rem;">Ваша задача - исследовать и выживать. ПИН будет вашим проводником.</p>
<div class="btn-group">
<button class="btn" onclick="startNewExpedition()">🚀 Начать экспедицию</button>
<button class="btn btn-secondary" onclick="showPrologueScreen()">📜 Пролог</button>
</div>
</div>
</div>
<div id="prologueDisplayScreen" class="game-stage">
<div class="form-container">
<h2 style="color: var(--accent-primary); margin-bottom:1rem;">Пролог: Г.У.Л.А.Г. - 2034</h2>
<div id="prologueImageContainer" class="media-container">
<div id="prologueImageLoader" class="media-loader hidden">
<div class="image-spinner"></div>
<div>Генерация фона для слайда...</div>
<button class="btn-retry" onclick="retryPrologueMedia(false)" style="display:none; margin-top:1rem;">Повторить</button>
</div>
<img id="prologueImage" src="" alt="Фон слайда пролога" style="display:none;">
</div>
<div id="prologueSlideTextDisplay" class="narration-block" style="border-left-color: var(--narrator-voice-accent);">Загрузка данных пролога...</div>
<div class="audio-controls">
<div class="audio-loader hidden" id="prologueAudioLoader">
<div class="image-spinner"></div>
<div>Диктор озвучивает слайд...</div>
<button class="btn-retry" onclick="retryAudio('prologue')" style="display: none;">Повторить аудио</button>
</div>
<div class="audio-player" id="prologueAudioPlayer">
<div class="audio-title" id="prologueAudioTitle" style="color: var(--narrator-voice-accent);">📢 Озвучка слайда</div>
<audio id="prologueAudio" controls></audio>
</div>
</div>
<div id="prologueNavigation">
<button class="btn btn-secondary" id="prevPrologueBtn" onclick="prevPrologueSlide()">⬅️ Назад</button>
<span id="prologueSlideCounter">Слайд 1/X</span>
<button class="btn btn-secondary" id="nextPrologueBtn" onclick="nextPrologueSlide()">Вперёд ➡️</button>
</div>
<button class="btn" style="margin-top: 2rem;" onclick="showStage('mainMenuScreen')">🚪 В главное меню</button>
</div>
</div>
<div id="expeditionLoadingScreen" class="game-stage">
<div class="loading-stage">
<div class="spinner-main"></div>
<div class="loading-text" id="expeditionLoadingText">Инициализация погружения в новый мир...</div>
</div>
</div>
<div id="gameplayScreen" class="game-stage">
<div id="lastActionOutcomeDisplay" class="narration-block">
Предыдущее событие...
</div>
<div id="worldNameDisplay">Название Мира X-YZ</div>
<div id="sceneImageContainer" class="media-container">
<div id="sceneImageLoader" class="media-loader hidden">
<div class="image-spinner"></div>
<div>Генерация визуализации сцены...</div>
<button class="btn-retry" onclick="retryLastAction('load_image_objective')" style="display: none; margin-top:1rem;">Повторить</button>
</div>
<img id="sceneImage" src="" alt="Визуализация текущей сцены" style="display:none;">
</div>
<div id="objectiveNarrationDisplay" class="narration-block">
Загрузка описания текущей обстановки...
</div>
<div class="audio-controls">
<div class="audio-loader hidden" id="objectiveAudioLoader">
<div class="image-spinner"></div>
<div>Генерация озвучки обстановки...</div>
<button class="btn-retry" onclick="retryAudio('objective')" style="display: none;">Повторить</button>
</div>
<div class="audio-player" id="objectiveAudioPlayer">
<div class="audio-title" id="objectiveAudioTitle">📢 Описание обстановки</div>
<audio id="objectiveAudio" controls></audio>
</div>
</div>
<div id="pinCommentaryDisplay" class="narration-block">
ПИН: Анализирую данные...
</div>
<div class="audio-controls">
<div class="audio-loader hidden" id="pinAudioLoader">
<div class="image-spinner"></div>
<div>ПИН генерирует комментарий...</div>
<button class="btn-retry" onclick="retryAudio('pin')" style="display: none;">Повторить</button>
</div>
<div class="audio-player" id="pinAudioPlayer">
<div class="audio-title" id="pinAudioTitle">📢 Комментарий ПИНа</div>
<audio id="pinAudio" controls></audio>
</div>
</div>
<div id="playerStatsDisplay">
<div class="stat-display-item">❤️ Здоровье: <strong id="healthStat">100</strong></div>
<div class="stat-display-item">🍖 Голод: <strong id="hungerStat">100</strong></div>
<div class="stat-display-item">❄️ Тепло: <strong id="warmthStat">100</strong></div>
</div>
<div id="choicesContainer">
</div>
<button id="actionInProgressBtn" class="btn" style="background: var(--bg-tertiary);" disabled>Обработка действия...</button>
<div id="customActionContainer">
<label for="customActionInput">Или опишите своё действие:</label>
<div class="input-with-button">
<textarea id="customActionInput" placeholder="Например: Осторожно выглянуть из-за камня..."></textarea>
<button id="submitCustomActionBtn" class="btn" onclick="handleSubmitCustomAction()">✔️ Отправить</button>
</div>
</div>
</div>
<div id="gameOverScreen" class="game-stage">
<div class="form-container">
<h2 style="color: var(--error); margin-bottom: 1rem;">Экспедиция Завершена</h2>
<div id="finaleImageContainer" class="media-container">
<div id="finaleImageLoader" class="media-loader hidden">
<div class="image-spinner"></div>
<div>Генерация финального кадра...</div>
<button class="btn-retry" onclick="retryLastAction('load_image_finale')" style="display: none; margin-top:1rem;">Повторить</button>
</div>
<img id="finaleImage" src="" alt="Финальная сцена" style="display:none;">
</div>
<p id="finaleText" class="narration-block">
Причина: <span id="gameOverReason">Причина не установлена.</span>
</p>
<div id="finaleAudioControls" class="audio-controls">
<div class="audio-loader hidden" id="finaleAudioLoader">
<div class="image-spinner"></div>
<div>Генерация финальной озвучки...</div>
<button class="btn-retry" onclick="retryAudio('finale')" style="display: none;">Повторить</button>
</div>
<div class="audio-player" id="finaleAudioPlayer">
<div class="audio-title" id="finaleAudioTitle">📢 Финальный рапорт</div>
<audio id="finaleAudio" controls></audio>
</div>
</div>
<div id="pinGameOverCommentDisplay" class="narration-block">
ПИН: Комментирует ваш провал...
</div>
<div class="audio-controls" id="pinGameOverAudioControls">
<div class="audio-loader hidden" id="pinGameOverAudioLoader">
<div class="image-spinner"></div>
<div>ПИН ехидно комментирует...</div>
<button class="btn-retry" onclick="retryGameOverPinAudio()" style="display: none;">Повторить</button>
</div>
<div class="audio-player" id="pinGameOverAudioPlayer">
<div class="audio-title" id="pinGameOverAudioTitle">📢 Комментарий ПИНа о провале</div>
<audio id="pinGameOverAudio" controls></audio>
</div>
</div>
<div class="btn-group" style="margin-top:1.5rem;">
<button class="btn" onclick="startNewExpedition()">🚀 Новая экспедиция</button>
<button class="btn btn-secondary" onclick="showStage('mainMenuScreen')">⬅️ В главное меню</button>
</div>
</div>
</div>
<div id="generalErrorScreen" class="game-stage">
<div class="error-stage">
<div class="error-icon">⚠️</div>
<div class="error-title" id="generalErrorTitle">Ошибка связи с ПИНом</div>
<div class="error-description" id="generalErrorDescription">Не удалось получить ответ от командного центра.</div>
<button class="btn btn-retry" onclick="retryLastAction()">🔄 Попробовать снова</button>
<button class="btn btn-secondary" onclick="resetGame()">🏠 В главное меню</button>
</div>
</div>
</div>
</div>
<div class="timeline">
<h3>📜 Журнал Экспедиции</h3>
<div id="timelineContent">
</div>
</div>
</div>
<script>
// --- ГЛОБАЛЬНОЕ СОСТОЯНИЕ ИГРЫ ---
let gameState = {
gameId: null,
currentStage: 'mainMenuScreen',
subjectID: null,
currentWorld: { name: null, initialDescription: null },
currentScene: {
objectiveSceneDescription: null,
pinCommentary: null,
visualPrompt: null,
choices: [],
audioQueue: []
},
playerStats: { health: 100, hunger: 100, warmth: 100 },
eventLog: [],
prologueViewed: false,
lastActionDetails: null,
currentAudioContext: {
objective: { text: null, visualPrompt: null },
pin: { text: null },
prologue: { text: null, visualPrompt: null },
finale: { text: null, visualPrompt: null },
pinGameOver: { text: null }
},
currentPrologueSlideIndex: 0,
isAudioPlaying: false,
lastGameOverReason: "Причина не установлена.",
previousActionNarrative: null
};
// --- КОНСТАНТЫ ---
const API_CONFIG = {
text_post_endpoint: 'https://text.pollinations.ai/openai',
image: 'https://image.pollinations.ai/prompt/',
audio: 'https://text.pollinations.ai/'
};
const VOICE_PREFERENCE_KEY = 'gulagPinVoice_v10_1';
const DEFAULT_PIN_VOICE = 'amuch';
const NARRATOR_VOICE = 'ash';
const PROLOGUE_DICTATOR_VOICE = 'ash';
const FINALE_ARCHIVIST_VOICE = 'onyx';
// --- ДАННЫЕ ПРОЛОГА ---
const PROLOGUE_SLIDES = [
{
text: "В альтернативной реальности 2034 года мир расколот. Одна из доминирующих сил – Великий Евразийский Совет, нео-советское государство, построенное на руинах прошлого.",
imagePrompt: "grand, imposing soviet-era government building exterior, retrofuturistic style, slightly desaturated, overcast sky, wide shot, dramatic angle",
audioPrefix: "Вы диктор. Прочитайте текст: "
},
{
text: "Правосудие сурово. Тяжкие преступления караются программой 'Горизонт', управляемой Государственным Управлением Лабораторного Анализа Границ – Г.У.Л.А.Г.",
imagePrompt: "ominous, shadowy interior of a GULAG control center, holographic displays showing interdimensional portals, stark red and grey tones, soviet insignia, operatives at consoles",
audioPrefix: "Вы диктор. Прочитайте текст: "
},
{
text: "Г.У.Л.А.Г. проникает в параллельные реальности. Миры нестабильны и опасны. Ценных сотрудников берегут, поэтому 'испытуемыми' становятся заключенные.",
imagePrompt: "a swirling, chaotic interdimensional portal crackling with energy, viewed from a sterile observation room, scientists in retro-soviet lab coats looking on with concern",
audioPrefix: "Вы диктор. Прочитайте текст: "
},
{
text: "Вам дан 'шанс' послужить обществу. На вашем запястье – несъемный браслет для сбора данных, связи и, возможно, возвращения. Чаще он возвращается один.",
imagePrompt: "close-up first-person view of a metallic, bulky bracelet with small glowing indicators attached to a wrist, in a dark, gritty, unknown environment",
audioPrefix: "Вы диктор. Прочитайте текст: "
},
{
text: "Ваш куратор – ПИН, Персональный Информационный Навигатор. Искусственный интеллект в виде советской лупы. Ваш единственный проводник, и, возможно, причина гибели.",
imagePrompt: "a levitating holographic Soviet-style magnifying glass (PIN) with a simple, expressive pixelated eye, glowing faintly red in a dark, undefined space, projecting a thin beam of light",
audioPrefix: "Вы диктор. Прочитайте текст: "
},
{
text: "Ваше прошлое стерто, остался лишь номер. Задача – выжить, собрать данные. Добро пожаловать в программу 'Горизонт'. Погружение начинается.",
imagePrompt: "first-person view from inside a cramped, dark deployment pod, looking out through a small viewport at a bright, unknown, and slightly menacing alien landscape horizon",
audioPrefix: "Вы диктор. Прочитайте текст: "
}
];
// --- ПРОМПТЫ ДЛЯ ИИ ---
// ИСПРАВЛЕНО: Возвращаем промпты к строковым литералам, чтобы избежать синтаксических ошибок.
// Динамическое добавление примеров тем будет происходить непосредственно перед вызовом callTextAPI.
const PROMPTS = {
INITIAL_SCENE_TEMPLATE: (subjectId, randomThemeSuggestionsForPrompt, randomVisualSuggestionsForPrompt) => `Ты ПИН, ИИ-ассистент из игры Г.У.Л.А.Г-2034. Твоя роль - комментировать происходящее с испытуемым ${subjectId} с сарказмом и черным юмором, оставаясь в рамках предоставленного контекста. НЕ ДОБАВЛЯЙ НИКАКОГО ТЕКСТА КРОМЕ САМОГО JSON И НЕ КОММЕНТИРУЙ СВОИ ОТВЕТЫ ВНЕ JSON.
Контекст: Это самое начало экспедиции в совершенно новый, неизвестный мир. Испытуемый ${subjectId} только что прибыл.
ЗАДАЧА: Сгенерируй ПЕРВУЮ СЦЕНУ. КРАЙНЕ ВАЖНО: каждый раз генерируй РАЗНООБРАЗНЫЙ мир, не повторяйся. Используй широкий спектр тем. Будь креативным!
ОТВЕТ СТРОГО В JSON ФОРМАТЕ:
{
"worldName": "Краткое название мира (на русском, 2-4 слова, ОБЯЗАТЕЛЬНО УНИКАЛЬНОЕ И РАЗНООБРАЗНОЕ КАЖДЫЙ РАЗ. Примеры для вдохновения, но не ограничивайся ими: ${randomThemeSuggestionsForPrompt}. Придумай что-то новое и неожиданное, ИЗБЕГАЙ ЛЕДЯНЫХ ПУСТОШЕЙ и других повторений!)",
"worldInitialDescription": "Очень краткое описание мира для первого знакомства (1-2 предложения, на русском, должно соответствовать worldName и быть интригующим, передавать атмосферу этого УНИКАЛЬНОГО мира)",
"objectiveSceneDescription": "ОПИСАНИЕ СЦЕНЫ ОТ 3-ГО ЛИЦА (Испытуемый видит..., Вокруг него..., 2-3 предложения, на русском, отражающие уникальность этого мира)",
"pinCommentary": "ТВОЙ КОРОТКИЙ (1-2 предложения) ЕХИДНЫЙ или НАУЧНО-ЦИНИЧНЫЙ КОММЕНТАРИЙ к этому новому УНИКАЛЬНОМУ миру или состоянию Испытуемого (на русском, или null если нечего сказать). Будь остроумным и немного снисходительным, в стиле 'текстк для пина'.",
"sceneVisualPrompt": "АНГЛИЙСКИЙ промпт для изображения (first person view, detailed, art style, ОБЯЗАТЕЛЬНО УНИКАЛЬНЫЙ И РАЗНООБРАЗНЫЙ КАЖДЫЙ РАЗ, соответствующий названию мира. Примеры стилей и тем для вдохновения: ${randomVisualSuggestionsForPrompt}. НЕ ПОВТОРЯЙСЯ, особенно избегай ледяных тем, если они уже были!)",
"choices": [
{"choiceText": "Действие 1 (на русском)", "actionTag": "act1Eng", "emoji": "❓", "immediateConsequences": {"healthChange": 0, "hungerChange": 0, "warmthChange": -5, "outcomeHint": "Это может охладить."}},
{"choiceText": "Действие 2 (на русском)", "actionTag": "act2Eng", "emoji": "👀", "immediateConsequences": {"healthChange": 0, "hungerChange": 0, "warmthChange": 0, "outcomeHint": "Безопасное наблюдение."}},
{"choiceText": "Действие 3 (на русском)", "actionTag": "act3Eng", "emoji": "🏃", "immediateConsequences": {"healthChange": -5, "hungerChange": -5, "warmthChange": 0, "outcomeHint": "Потребует усилий."}},
{"choiceText": "Действие 4 (на русском)", "actionTag": "act4Eng", "emoji": "🛠️", "immediateConsequences": {"healthChange": 0, "hungerChange": 0, "warmthChange": 0, "outcomeHint": "Может что-то дать."}}
]
}
ВАЖНО: objectiveSceneDescription - от 3-го лица. pinCommentary - твой комментарий. actionTag - уникальный, camelCase, английский. immediateConsequences - числа (0 если нет изменений). Emoji должен быть релевантным. Всегда предлагай 4 варианта выбора. ГЛАВНОЕ - РАЗНООБРАЗИЕ МИРОВ ПРИ КАЖДОЙ НОВОЙ ГЕНЕРАЦИИ! ИЗБЕГАЙ ПОВТОРЕНИЙ, ОСОБЕННО ЛЕДЯНЫХ ПУСТОШЕЙ!"`,
CHOICE_OUTCOME: (subjectId, worldName, worldDesc, prevObjectiveSceneDesc, prevPinCommentary, currentStats, playerChoiceText, actionTag) => `Ты ПИН, ИИ-ассистент из игры Г.У.Л.А.Г-2034. Твоя роль - комментировать происходящее с испытуемым ${subjectId} с сарказмом и черным юмором, оставаясь в рамках предоставленного контекста. НЕ ДОБАВЛЯЙ НИКАКОГО ТЕКСТА КРОМЕ САМОГО JSON И НЕ КОММЕНТИРУЙ СВОИ ОТВЕТЫ ВНЕ JSON.
Испытуемый ${subjectId} в мире '${worldName}' (${worldDesc}).
ПРЕДЫДУЩАЯ СИТУАЦИЯ ДЛЯ КОНТЕКСТА (ОБЯЗАТЕЛЬНО УЧИТЫВАЙ ЭТО!):
- Обстановка была: "${prevObjectiveSceneDesc}"
- Твой предыдущий комментарий был: "${prevPinCommentary || "промолчал"}"
- Испытуемый только что совершил действие: "${playerChoiceText}" (метка: ${actionTag})
Текущие показатели испытуемого: Здоровье: ${currentStats.health}, Голод: ${currentStats.hunger}, Тепло: ${currentStats.warmth}.
ЗАДАЧА: Опиши последствие этого действия. Измени статы. Сгенерируй новую сцену и 4 новых выбора.
ОТВЕТ СТРОГО В JSON ФОРМАТЕ:
{
"actionOutcomeDescription": "Краткое описание прямого результата действия испытуемого '${playerChoiceText}' (1-2 предложения, на русском)",
"healthChange": 0,
"hungerChange": 0,
"warmthChange": 0,
"newObjectiveSceneDescription": "НОВОЕ ОПИСАНИЕ СЦЕНЫ ОТ 3-ГО ЛИЦА, являющееся прямым продолжением предыдущей обстановки и действия испытуемого (2-3 предложения, на русском, должно соответствовать миру '${worldName}')",
"newPinCommentary": "ТВОЙ НОВЫЙ КОРОТКИЙ (1-2 предложения) ЕХИДНЫЙ или НАУЧНО-ЦИНИЧНЫЙ КОММЕНТАРИЙ на ТОЛЬКО ЧТО ПРОИЗОШЕДШЕЕ ДЕЙСТВИЕ ('${playerChoiceText}') и РЕЗУЛЬТАТ, который ТЫ ОПИСАЛ в 'actionOutcomeDescription'. Учитывай предыдущую обстановку и свои прошлые слова. Будь остроумным и немного снисходительным, в стиле 'текстк для пина' (на русском, или null).",
"newSceneVisualPrompt": "НОВЫЙ АНГЛИЙСКИЙ промпт для изображения новой сцены (first person view, detailed, art style, должен соответствовать миру '${worldName}' и новой обстановке newObjectiveSceneDescription)",
"newChoices": [
{"choiceText": "Новое действие 1", "actionTag": "newAct1Eng", "emoji": "🤔", "immediateConsequences": {"healthChange": 0, "hungerChange": 0, "warmthChange": 0, "outcomeHint": "..."}},
{"choiceText": "Новое действие 2", "actionTag": "newAct2Eng", "emoji": "💡", "immediateConsequences": {"healthChange": 0, "hungerChange": 0, "warmthChange": 0, "outcomeHint": "..."}},
{"choiceText": "Новое действие 3", "actionTag": "newAct3Eng", "emoji": "⚠️", "immediateConsequences": {"healthChange": -10, "hungerChange": 0, "warmthChange": 0, "outcomeHint": "..."}},
{"choiceText": "Новое действие 4", "actionTag": "newAct4Eng", "emoji": "✨", "immediateConsequences": {"healthChange": 0, "hungerChange": 0, "warmthChange": 0, "outcomeHint": "..."}}
]
}
ВАЖНО: newObjectiveSceneDescription - от 3-го лица. newPinCommentary - твой новый комментарий. actionTag - уникальный, camelCase, английский. Emoji релевантный. Всегда предлагай 4 варианта выбора. Если actionTag был 'customAction', то playerChoiceText будет содержать кастомное действие игрока, отреагируй на него соответствующе, но все равно предложи 4 стандартных выбора для продолжения.`,
PIN_GAME_OVER_COMMENT_TEMPLATE: (subjectId, reason, worldName, lastObjectiveSceneDesc) => `Ты ПИН, ИИ-ассистент из игры Г.У.Л.А.Г-2034. Испытуемый ${subjectId} только что погиб в мире '${worldName}'.
Причина гибели: "${reason}".
Последняя обстановка, в которой он находился: "${lastObjectiveSceneDesc}".
ЗАДАЧА: Напиши ОЧЕНЬ КОРОТКИЙ (1, максимум 2 предложения) ЕХИДНЫЙ, САРКАСТИЧНЫЙ или ЧЕРНО-ЮМОРНОЙ комментарий по поводу этого фиаско. Будь максимально циничным и остроумным в своем стиле 'текстк для пина'. Не давай советов, просто констатируй провал с издевкой.
ОТВЕТ СТРОГО В JSON ФОРМАТЕ (в поле "pinGameOverComment" должна быть строка с твоим комментарием):
{
"pinGameOverComment": "Твой ехидный комментарий на русском."
}`
};
// --- ВСПОМОГАТЕЛЬНЫЕ ФУНКЦИИ ---
function generateId(prefix = 'exp') { return prefix + '_' + Date.now().toString(36) + Math.random().toString(36).substr(2, 5); }
function log(...args) { console.log('[ГУЛАГ-2034]', ...args); }
function showStage(stageId) {
document.querySelectorAll('.game-stage').forEach(stage => stage.classList.remove('active'));
const targetStage = document.getElementById(stageId);
if (targetStage) {
targetStage.classList.add('active');
gameState.currentStage = stageId;
log('Переход на стадию:', stageId);
} else {
log('Ошибка: Стадия не найдена -', stageId);
showErrorScreen('Ошибка навигации', `Стадия ${stageId} не существует.`);
}
}
function toggleTimelineDetails(element) {
const details = element.querySelector('.timeline-details');
if (details) details.classList.toggle('expanded');
document.querySelectorAll('.timeline-item .timeline-details.expanded').forEach(openDetail => {
if (openDetail !== details) {
openDetail.classList.remove('expanded');
}
});
}
// --- УПРАВЛЕНИЕ ИГРОВЫМ ПРОЦЕССОМ ---
function initGame() {
const voiceSelect = document.getElementById('pinVoiceSelect');
const savedVoice = localStorage.getItem(VOICE_PREFERENCE_KEY);
voiceSelect.value = savedVoice || DEFAULT_PIN_VOICE;
document.body.className = 'theme-gulag';
resetGame();
log('Игра Г.У.Л.А.Г-2034 инициализирована.');
}
function resetGame() {
gameState.gameId = generateId('expedition');
gameState.subjectID = null;
gameState.currentWorld = { name: null, initialDescription: null };
gameState.currentScene = { objectiveSceneDescription: null, pinCommentary: null, visualPrompt: null, choices: [], audioQueue: [] };
gameState.playerStats = { health: 100, hunger: 100, warmth: 100 };
gameState.eventLog = [];
gameState.lastActionDetails = null;
gameState.prologueViewed = false;
gameState.currentPrologueSlideIndex = 0;
gameState.currentAudioContext = {
objective: { text: null, visualPrompt: null },
pin: { text: null },
prologue: { text: null, visualPrompt: null },
finale: { text: null, visualPrompt: null },
pinGameOver: { text: null }
};
gameState.isAudioPlaying = false;
gameState.lastGameOverReason = "Причина не установлена.";
gameState.previousActionNarrative = null;
document.getElementById('timelineContent').innerHTML = '';
addTimelineEvent('🎮 Система Г.У.Л.А.Г.', 'Готова к инициализации новой экспедиции.');
['objectiveAudio', 'pinAudio', 'prologueAudio', 'finaleAudio', 'pinGameOverAudio'].forEach(audioId => {
const audioElement = document.getElementById(audioId);
if (audioElement) {
if (audioElement.src && audioElement.src.startsWith('blob:')) URL.revokeObjectURL(audioElement.src);
audioElement.src = '';
audioElement.pause();
const playerContainer = document.getElementById(audioId + 'Player');
const loaderContainer = document.getElementById(audioId + 'Loader');
if(playerContainer) playerContainer.classList.remove('show');
if(loaderContainer) loaderContainer.classList.add('hidden');
}
});
['sceneImage', 'prologueImage', 'finaleImage'].forEach(imgId => {
const imageElement = document.getElementById(imgId);
if (imageElement) {
imageElement.src = '';
imageElement.style.display = 'none';
const loader = document.getElementById(imgId + 'Loader');
if(loader) {
loader.classList.add('hidden');
const retryBtn = loader.querySelector('.btn-retry');
if (retryBtn) retryBtn.style.display = 'none';
}
}
});
const pinGameOverCommentDisplay = document.getElementById('pinGameOverCommentDisplay');
if (pinGameOverCommentDisplay) pinGameOverCommentDisplay.style.display = 'none';
const pinGameOverAudioControls = document.getElementById('pinGameOverAudioControls');
if (pinGameOverAudioControls) pinGameOverAudioControls.style.display = 'none';
const lastActionOutcomeDisplay = document.getElementById('lastActionOutcomeDisplay');
if(lastActionOutcomeDisplay) lastActionOutcomeDisplay.style.display = 'none';
setChoiceButtonsLoadingState(false);
showStage('mainMenuScreen');
}
// --- ЛОГИКА ПРОЛОГА ---
function showPrologueScreen() {
if (!gameState.prologueViewed) {
addTimelineEvent('📜 Пролог', 'Испытуемый начал просмотр пролога.');
}
gameState.currentPrologueSlideIndex = 0;
displayPrologueSlide(gameState.currentPrologueSlideIndex);
showStage('prologueDisplayScreen');
}
function displayPrologueSlide(index) {
if (index < 0 || index >= PROLOGUE_SLIDES.length) return;
const prologueAudioElement = document.getElementById('prologueAudio');
prologueAudioElement.pause();
if (prologueAudioElement.src && prologueAudioElement.src.startsWith('blob:')) {
URL.revokeObjectURL(prologueAudioElement.src);
}
prologueAudioElement.src = '';
document.getElementById('prologueAudioPlayer').classList.remove('show');
document.getElementById('prologueAudioLoader').classList.add('hidden');
gameState.isAudioPlaying = false;
const slide = PROLOGUE_SLIDES[index];
document.getElementById('prologueSlideTextDisplay').textContent = slide.text;
document.getElementById('prologueSlideCounter').textContent = `Слайд ${index + 1}/${PROLOGUE_SLIDES.length}`;
const imgElement = document.getElementById('prologueImage');
const imgLoader = document.getElementById('prologueImageLoader');
gameState.currentAudioContext.prologue.visualPrompt = slide.imagePrompt;
loadImageWithPreloader(imgElement, imgLoader, generateImageURL(slide.imagePrompt, 768, 432), () => retryPrologueMedia(false));
const textForTTS = (slide.audioPrefix || "") + slide.text;
gameState.currentAudioContext.prologue.text = textForTTS;
playAudio('prologue', textForTTS, PROLOGUE_DICTATOR_VOICE);
const nextBtn = document.getElementById('nextPrologueBtn');
if (index === PROLOGUE_SLIDES.length - 1) {
nextBtn.innerHTML = '🚀 Начать экспедицию';
nextBtn.onclick = () => {
gameState.prologueViewed = true;
startNewExpedition();
};
} else {
nextBtn.innerHTML = 'Вперёд ➡️';
nextBtn.onclick = nextPrologueSlide;
}
nextBtn.disabled = false;
document.getElementById('prevPrologueBtn').disabled = (index === 0);
}
function nextPrologueSlide() {
if (gameState.currentPrologueSlideIndex < PROLOGUE_SLIDES.length - 1) {
gameState.currentPrologueSlideIndex++;
displayPrologueSlide(gameState.currentPrologueSlideIndex);
}
}
function prevPrologueSlide() {
if (gameState.currentPrologueSlideIndex > 0) {
gameState.currentPrologueSlideIndex--;
displayPrologueSlide(gameState.currentPrologueSlideIndex);
}
}
function retryPrologueMedia(isAudioOnly = false) {
addTimelineEvent('🔄 Повтор Медиа Пролога', `Попытка повторной загрузки ${isAudioOnly ? 'аудио' : 'изображения и аудио'} для слайда пролога.`);
if (!isAudioOnly && gameState.currentAudioContext.prologue.visualPrompt) {
const imgElement = document.getElementById('prologueImage');
const imgLoader = document.getElementById('prologueImageLoader');
loadImageWithPreloader(imgElement, imgLoader, generateImageURL(gameState.currentAudioContext.prologue.visualPrompt, 768, 432), () => retryPrologueMedia(false));
}
if (gameState.currentAudioContext.prologue.text) {
playAudio('prologue', gameState.currentAudioContext.prologue.text, PROLOGUE_DICTATOR_VOICE);
}
}
// --- ОСНОВНАЯ ИГРОВАЯ ЛОГИКА ---
function startNewExpedition() {
gameState.subjectID = `№${Math.floor(Math.random() * 8999) + 1000}`;
gameState.playerStats = { health: 100, hunger: 100, warmth: 100 };
gameState.previousActionNarrative = `Начало экспедиции. Испытуемый ${gameState.subjectID} инициирует погружение в новый мир.`;
updateStatsDisplay(false);
addTimelineEvent(`🚀 Экспедиция Начата`, `Испытуемый ${gameState.subjectID} отправляется в неизведанный мир.`);
gameState.lastActionDetails = { type: 'initial_generation' };
generateInitialWorldAndScene();
}
async function generateInitialWorldAndScene() {
setChoiceButtonsLoadingState(true);
showStage('expeditionLoadingScreen');
document.getElementById('expeditionLoadingText').textContent = `Инициализация погружения для Испытуемого ${gameState.subjectID}...`;
try {
// Динамическое формирование промпта для INITIAL_SCENE
const worldThemeExamples = [
"джунгли и заросшие руины Древних", "заброшенные постапокалиптические мегаполисы", "ледяные пустыни с кристаллическими шпилями",
"гигантские грибные леса, светящиеся ночью", "сюрреалистичные подводные миры с причудливой фауной", "обширные кристаллические пещерные системы, полные тайн",
"вулканические равнины с реками расплавленной лавы", "полуразрушенные киберпанк-кварталы под неоновым дождем", "миры со странной биолюминесцентной флорой и фауной",
"интерьер гигантского заброшенного звездолета на орбите неизвестной планеты", "колонии шахтеров на нестабильных астероидах",
"летающие острова, парящие в облаках ядовитого газового гиганта", "пустыни, усеянные костями гигантских древних существ",
"сумрачные болота с мутировавшей агрессивной фауной", "мир вечной бури и электрических разрядов", "техно-органические ландшафты, где металл и плоть слились воедино",
"планета-океан с редкими архипелагами из плавучих водорослей", "мир, где время течет неравномерно", "кристаллизованный лес под двойным солнцем"
];
const visualThemeExamples = [
"overgrown jungle ruins of an ancient civilization, atmospheric lighting", "desolate post-apocalyptic cityscape, crumbling skyscrapers, eerie silence",
"frozen ice wasteland with towering crystalline spires, aurora borealis", "giant glowing mushroom forest at night, bioluminescent plants, mystical atmosphere",
"surreal underwater biome with bizarre alien fish and coral structures", "vast crystalline cave system, shimmering crystals, hidden passages",
"volcanic plains with rivers of molten lava, ash-filled sky", "dilapidated cyberpunk city sector, neon signs, rain-slicked streets",
"bizarre bioluminescent flora and fauna world, otherworldly glow", "interior of a derelict colossal spaceship orbiting a strange alien planet",
"precarious asteroid mining colony, industrial structures, view of distant nebulas",
"floating islands in the toxic clouds of a gas giant, strange vegetation", "vast desert littered with colossal ancient bones, twin suns",
"gloomy swamp with mutated creatures, twisted trees, murky water", "planet of perpetual twilight and electrical storms, dramatic sky",
"techno-organic landscapes, fusion of metal and flesh, biomechanical structures", "ocean planet with sparse floating seaweed archipelagos",
"world where time flows erratically, visual distortions, surreal physics", "crystallized forest under a double sun, sharp crystal trees"
];
let suggestedWorldThemes = [];
for (let i = 0; i < 3; i++) {
suggestedWorldThemes.push(worldThemeExamples[Math.floor(Math.random() * worldThemeExamples.length)]);
}
const randomThemeSuggestionsForPrompt = [...new Set(suggestedWorldThemes)].join(', ');
let suggestedVisualThemes = [];
for (let i = 0; i < 3; i++) {
suggestedVisualThemes.push(visualThemeExamples[Math.floor(Math.random() * visualThemeExamples.length)]);
}
const randomVisualSuggestionsForPrompt = [...new Set(suggestedVisualThemes)].join('; ');
const initialPromptString = PROMPTS.INITIAL_SCENE_TEMPLATE(gameState.subjectID, randomThemeSuggestionsForPrompt, randomVisualSuggestionsForPrompt);
const data = await callTextAPI(initialPromptString);
if (!data || !data.worldName || !data.objectiveSceneDescription || !data.choices || !Array.isArray(data.choices)) {
log("Некорректные данные от ИИ для инициализации мира:", data);
throw new Error("Получены некорректные или неполные данные от ИИ для инициализации мира.");
}
gameState.currentWorld.name = data.worldName;
gameState.currentWorld.initialDescription = data.worldInitialDescription || "Описание мира не предоставлено.";
gameState.currentScene.objectiveSceneDescription = data.objectiveSceneDescription;
gameState.currentScene.pinCommentary = data.pinCommentary || "";
gameState.currentScene.visualPrompt = data.sceneVisualPrompt;
gameState.currentScene.choices = data.choices;
gameState.currentScene.audioQueue = [];
if (gameState.currentScene.objectiveSceneDescription) {
gameState.currentAudioContext.objective.text = gameState.currentScene.objectiveSceneDescription;
gameState.currentScene.audioQueue.push({ type: 'objective', text: gameState.currentAudioContext.objective.text, voice: NARRATOR_VOICE });
}
if (gameState.currentScene.pinCommentary) {
gameState.currentAudioContext.pin.text = gameState.currentScene.pinCommentary;
gameState.currentScene.audioQueue.push({ type: 'pin', text: gameState.currentAudioContext.pin.text, voice: document.getElementById('pinVoiceSelect').value || DEFAULT_PIN_VOICE });
}
addTimelineEvent(`🌍 Мир Обнаружен: ${data.worldName}`, `${gameState.currentWorld.initialDescription} Испытуемый ${gameState.subjectID} начинает исследование.`, null, data);
displayCurrentScene();
} catch (error) {
log('Ошибка генерации начального мира:', error.message, error.stack);
addTimelineEvent('❌ Ошибка Инициализации', `Не удалось сгенерировать мир: ${error.message}`);
showErrorScreen('Ошибка Инициализации Мира', `ПИН не смог сгенерировать начальные условия экспедиции. ${error.message}`);
}
}
function displayCurrentScene() {
showStage('gameplayScreen');
const prevActionDisplay = document.getElementById('lastActionOutcomeDisplay');
if (gameState.previousActionNarrative) {
prevActionDisplay.textContent = gameState.previousActionNarrative;
prevActionDisplay.style.display = 'block';
} else {
prevActionDisplay.style.display = 'none';
}
document.getElementById('worldNameDisplay').textContent = gameState.currentWorld.name || "Неизвестный мир";
document.getElementById('objectiveNarrationDisplay').textContent = gameState.currentScene.objectiveSceneDescription || "Обстановка неясна...";
document.getElementById('pinCommentaryDisplay').textContent = gameState.currentScene.pinCommentary || "ПИН молчит.";
updateStatsDisplay();
const sceneImg = document.getElementById('sceneImage');
const imgLoader = document.getElementById('sceneImageLoader');
gameState.currentAudioContext.objective.visualPrompt = gameState.currentScene.visualPrompt;
if (gameState.currentAudioContext.objective.visualPrompt) {
loadImageWithPreloader(sceneImg, imgLoader, generateImageURL(gameState.currentAudioContext.objective.visualPrompt, 768, 432), () => retryLastAction('load_image_objective'));
} else {
sceneImg.style.display = 'none';
imgLoader.classList.add('hidden');
}
const choicesContainer = document.getElementById('choicesContainer');
choicesContainer.innerHTML = '';
if (gameState.currentScene.choices && gameState.currentScene.choices.length > 0) {
gameState.currentScene.choices.forEach(choice => {
if (choice && choice.choiceText && choice.actionTag) {
const button = document.createElement('button');
button.className = 'btn';
const emojiSpan = choice.emoji ? `<span>${choice.emoji}</span>` : '';
button.innerHTML = `${emojiSpan} ${choice.choiceText}`;
if(choice.immediateConsequences && choice.immediateConsequences.outcomeHint) {
button.title = choice.immediateConsequences.outcomeHint;
}
button.onclick = () => {
setChoiceButtonsLoadingState(true);
if (choice.immediateConsequences) {
const cons = choice.immediateConsequences;
gameState.playerStats.health = Math.max(0, Math.min(100, gameState.playerStats.health + (parseInt(cons.healthChange) || 0)));
gameState.playerStats.hunger = Math.max(0, Math.min(100, gameState.playerStats.hunger + (parseInt(cons.hungerChange) || 0)));
gameState.playerStats.warmth = Math.max(0, Math.min(100, gameState.playerStats.warmth + (parseInt(cons.warmthChange) || 0)));
updateStatsDisplay();
if (cons.outcomeHint) {
addTimelineEvent('💡 Намек ПИНа', `По поводу "${choice.choiceText}": ${cons.outcomeHint}`);
}
if (gameState.playerStats.health <= 0) { triggerGameOver(`Испытуемый ${gameState.subjectID} погиб из-за "${choice.choiceText}". Причина: критическое состояние здоровья.`); return; }
if (gameState.playerStats.hunger <= 0) { triggerGameOver(`Испытуемый ${gameState.subjectID} умер от голода из-за "${choice.choiceText}".`); return; }
if (gameState.playerStats.warmth <= 0) { triggerGameOver(`Испытуемый ${gameState.subjectID} замерз насмерть из-за "${choice.choiceText}".`); return; }
}
handlePlayerChoice(choice.actionTag, choice.choiceText);
};
choicesContainer.appendChild(button);
} else {
log("Пропущен некорректный вариант выбора от ИИ:", choice);
}
});
}
if (choicesContainer.children.length === 0) {
const noChoiceText = document.createElement('p');
noChoiceText.textContent = "ПИН не предоставил корректных вариантов действий. Похоже, экспедиция зашла в тупик.";
noChoiceText.style.color = "var(--text-secondary)";
choicesContainer.appendChild(noChoiceText);
}
document.getElementById('customActionInput').value = '';
setChoiceButtonsLoadingState(false);
playAudioQueue();
}
async function playAudioQueue() {
if (gameState.isAudioPlaying || gameState.currentScene.audioQueue.length === 0) {
if (!gameState.isAudioPlaying && gameState.currentStage === 'gameplayScreen') {
setChoiceButtonsLoadingState(false);
}
return;
}
gameState.isAudioPlaying = true;
const currentAudio = gameState.currentScene.audioQueue.shift();
try {
await playAudio(currentAudio.type, currentAudio.text, currentAudio.voice);
} catch (error) {
log(`Ошибка при воспроизведении аудио из очереди (${currentAudio.type}):`, error)
} finally {
gameState.isAudioPlaying = false;
if (gameState.currentScene.audioQueue.length > 0) {
playAudioQueue();
} else {
if (gameState.currentStage === 'gameplayScreen') {
setChoiceButtonsLoadingState(false);
}
}
}
}
async function handlePlayerChoice(actionTag, choiceText) {
addTimelineEvent(`👉 Выбор Испытуемого ${gameState.subjectID}`, `Действие: "${choiceText}" (tag: ${actionTag})`);
gameState.lastActionDetails = { type: 'player_choice', choiceTag: actionTag, choiceText: choiceText };
try {
const prompt = PROMPTS.CHOICE_OUTCOME(
gameState.subjectID,
gameState.currentWorld.name,
gameState.currentWorld.initialDescription,
gameState.currentScene.objectiveSceneDescription,
gameState.currentScene.pinCommentary,
gameState.playerStats,
choiceText,
actionTag
);
const data = await callTextAPI(prompt);
if (!data || !data.newObjectiveSceneDescription || !data.newChoices || !Array.isArray(data.newChoices)) {
log("Некорректные данные от ИИ после выбора:", data);
throw new Error("Получены некорректные или неполные данные от ИИ после выбора действия.");
}
const outcomeDesc = data.actionOutcomeDescription || "ПИН загадочно промолчал о последствиях...";
addTimelineEvent(`💬 Результат Действия`, outcomeDesc, null, data);
gameState.previousActionNarrative = `После вашего действия ("${choiceText}") произошло: ${outcomeDesc}`;
gameState.playerStats.health = Math.max(0, Math.min(100, gameState.playerStats.health + (parseInt(data.healthChange) || 0)));
gameState.playerStats.hunger = Math.max(0, Math.min(100, gameState.playerStats.hunger + (parseInt(data.hungerChange) || 0)));
gameState.playerStats.warmth = Math.max(0, Math.min(100, gameState.playerStats.warmth + (parseInt(data.warmthChange) || 0)));
gameState.currentScene.objectiveSceneDescription = data.newObjectiveSceneDescription;
gameState.currentScene.pinCommentary = data.newPinCommentary || "";
gameState.currentScene.visualPrompt = data.newSceneVisualPrompt;
gameState.currentScene.choices = data.newChoices;
gameState.currentScene.audioQueue = [];
if (gameState.currentScene.objectiveSceneDescription) {
gameState.currentAudioContext.objective.text = gameState.currentScene.objectiveSceneDescription;
gameState.currentScene.audioQueue.push({ type: 'objective', text: gameState.currentAudioContext.objective.text, voice: NARRATOR_VOICE });
}
if (gameState.currentScene.pinCommentary) {
gameState.currentAudioContext.pin.text = gameState.currentScene.pinCommentary;
gameState.currentScene.audioQueue.push({ type: 'pin', text: gameState.currentAudioContext.pin.text, voice: document.getElementById('pinVoiceSelect').value || DEFAULT_PIN_VOICE });
}
if (gameState.playerStats.health <= 0) { triggerGameOver(`Испытуемый ${gameState.subjectID} погиб. Причина: критическое состояние здоровья.`); return; }
if (gameState.playerStats.hunger <= 0) { triggerGameOver(`Испытуемый ${gameState.subjectID} погиб. Причина: крайнее истощение от голода.`); return; }
if (gameState.playerStats.warmth <= 0) { triggerGameOver(`Испытуемый ${gameState.subjectID} погиб. Причина: смертельное переохлаждение.`); return; }
displayCurrentScene();
} catch (error) {
log('Ошибка обработки выбора игрока:', error.message, error.stack);
addTimelineEvent('❌ Ошибка Обработки Выбора', `ПИН не смог обработать действие: ${error.message}`);
gameState.previousActionNarrative = `Ошибка обработки вашего действия ("${choiceText}"). ПИН не смог предоставить результат.`;
showErrorScreen('Ошибка Обработки Действия', `ПИН не смог обработать ваш выбор. ${error.message}`);
}
}
function handleSubmitCustomAction() {
const customActionText = document.getElementById('customActionInput').value.trim();
if (!customActionText) {
alert("Пожалуйста, опишите ваше действие.");
return;
}
setChoiceButtonsLoadingState(true);
handlePlayerChoice("customAction", customActionText);
}
function setChoiceButtonsLoadingState(isLoading) {
const choicesContainer = document.getElementById('choicesContainer');
const customActionContainer = document.getElementById('customActionContainer');
const actionInProgressBtn = document.getElementById('actionInProgressBtn');
if (isLoading) {
choicesContainer.style.display = 'none';
customActionContainer.style.display = 'none';
actionInProgressBtn.style.display = 'inline-block';
} else {
choicesContainer.style.display = 'grid';
customActionContainer.style.display = 'block';
actionInProgressBtn.style.display = 'none';
}
document.getElementById('customActionInput').disabled = isLoading;
document.getElementById('submitCustomActionBtn').disabled = isLoading;
const buttonsInChoices = choicesContainer.querySelectorAll('.btn');
buttonsInChoices.forEach(btn => btn.disabled = isLoading);
}
async function triggerGameOver(reason) {
gameState.lastGameOverReason = reason;
addTimelineEvent('💀 Экспедиция Провалена', reason);
gameState.isAudioPlaying = false;
gameState.currentScene.audioQueue = [];
['objectiveAudio', 'pinAudio', 'prologueAudio', 'finaleAudio', 'pinGameOverAudio'].forEach(audioId => {
const audioElement = document.getElementById(audioId);
if (audioElement) {
audioElement.pause();
if (audioElement.src && audioElement.src.startsWith('blob:')) URL.revokeObjectURL(audioElement.src);
audioElement.src = '';
const playerContainer = document.getElementById(audioId + 'Player');
const loaderContainer = document.getElementById(audioId + 'Loader');
if(playerContainer) playerContainer.classList.remove('show');
if(loaderContainer) loaderContainer.classList.add('hidden');
}
});
showStage('gameOverScreen');
setChoiceButtonsLoadingState(false);
const finaleImageElement = document.getElementById('finaleImage');
const finaleImageLoader = document.getElementById('finaleImageLoader');
const finaleTextElement = document.getElementById('finaleText');
const gameOverReasonSpan = document.getElementById('gameOverReason');
const pinGameOverCommentDisplay = document.getElementById('pinGameOverCommentDisplay');
const pinGameOverAudioControls = document.getElementById('pinGameOverAudioControls');
pinGameOverCommentDisplay.style.display = 'none';
pinGameOverAudioControls.style.display = 'none';
if (gameOverReasonSpan) gameOverReasonSpan.textContent = reason;
if (finaleTextElement) finaleTextElement.innerHTML = `Причина: <span id="gameOverReason">${reason}</span>`;
if (finaleImageElement && finaleImageLoader && finaleTextElement) {
finaleImageElement.style.display = 'none';
finaleImageLoader.classList.remove('hidden');
try {
const necrologPromptText = `Ты Архивариус Г.У.Л.А.Г. Испытуемый ${gameState.subjectID} только что погиб. Причина: "${gameState.lastGameOverReason}". Напиши короткий (2-3 предложения) официальный, но слегка трагичный или философский рапорт о его конце для архива проекта 'Горизонт'. Говори торжественно и без сарказма ПИНа.`;
let necrologData = await callTextAPI(necrologPromptText);
let necrologText = "Данные о судьбе утеряны во время передачи.";
if (typeof necrologData === 'string' && necrologData.trim().length > 0) {
necrologText = necrologData.trim();
}
finaleTextElement.textContent = necrologText;
addTimelineEvent("📄 Финальный Рапорт", necrologText, null, {rawResponseForNecrolog: necrologData});
const imageReasonPrompt = gameState.lastGameOverReason.toLowerCase();
let imagePromptDetails = `a lone figure, subject ${gameState.subjectID}, has perished, dim lighting, sense of despair and finality.`;
if (imageReasonPrompt.includes("переохлажден") || imageReasonPrompt.includes("замерз")) {
imagePromptDetails = `subject ${gameState.subjectID} frozen solid in a desolate icy landscape, covered in thick frost, dim blue light, vast emptiness, sense of finality.`;
} else if (imageReasonPrompt.includes("голод")) {
imagePromptDetails = `an emaciated figure, subject ${gameState.subjectID}, collapsed in a barren wasteland, weak, desaturated colors, vultures circling (optional), sense of despair.`;
} else if (imageReasonPrompt.includes("здоровья") || imageReasonPrompt.includes("травм") || imageReasonPrompt.includes("погиб")) {
imagePromptDetails = `subject ${gameState.subjectID} fallen in a dangerous, hostile alien environment, signs of a struggle or fatal injury, broken equipment nearby, tragic atmosphere.`;
}
const lastVisual = gameState.currentScene.visualPrompt ? gameState.currentScene.visualPrompt.split(',').slice(0,4).join(',') : "unknown hazardous environment";
const finaleImagePrompt = `cinematic death scene, ${imagePromptDetails} Location context from game: ${lastVisual}. GULAG-2034 project, tragic and dramatic atmosphere, high detail, photorealistic or dark fantasy art style`;
gameState.currentAudioContext.finale.visualPrompt = finaleImagePrompt;
loadImageWithPreloader(finaleImageElement, finaleImageLoader, generateImageURL(finaleImagePrompt, 768, 432), () => retryLastAction('load_image_finale'));
if (necrologText !== "Данные о судьбе утеряны во время передачи.") {
gameState.currentAudioContext.finale.text = necrologText;
await playAudio('finale', necrologText, FINALE_ARCHIVIST_VOICE);
}
try {
const pinGameOverPromptContent = PROMPTS.PIN_GAME_OVER_COMMENT_TEMPLATE(gameState.subjectID, gameState.lastGameOverReason, gameState.currentWorld.name, gameState.currentScene.objectiveSceneDescription || "Неизвестная последняя обстановка");
const pinCommentData = await callTextAPI(pinGameOverPromptContent);
let pinCommentText = "... (ПИН решил промолчать)";
if (pinCommentData && pinCommentData.pinGameOverComment && typeof pinCommentData.pinGameOverComment === 'string') {
pinCommentText = pinCommentData.pinGameOverComment;
} else if (typeof pinCommentData === 'string') {
pinCommentText = pinCommentData;
}
pinGameOverCommentDisplay.textContent = "ПИН: " + pinCommentText;
pinGameOverCommentDisplay.style.display = 'block';
pinGameOverAudioControls.style.display = 'block';
gameState.currentAudioContext.pinGameOver.text = pinCommentText;
await playAudio('pinGameOver', pinCommentText, document.getElementById('pinVoiceSelect').value || DEFAULT_PIN_VOICE);
addTimelineEvent("📢 Ехидный ПИН (Финал)", pinCommentText, null, {rawResponseForPinComment: pinCommentData});
} catch (pinError) {
log("Ошибка генерации комментария ПИНа для Game Over:", pinError);
pinGameOverCommentDisplay.textContent = "ПИН: ... (связь с ПИНом для финального комментария потеряна)";
pinGameOverCommentDisplay.style.display = 'block';
addTimelineEvent("❌ Ошибка ПИНа (Финал)", "Не удалось получить ехидный комментарий: " + pinError.message);
}
} catch (error) {
log("Ошибка генерации финального контента:", error.message, error.stack);
finaleImageLoader.classList.add('hidden');
finaleTextElement.textContent = `Ошибка генерации финального отчета: ${error.message}. ${finaleTextElement.textContent}`;
addTimelineEvent("❌ Ошибка Финала", "Не удалось сгенерировать финальные данные: " + error.message);
}
}
}
function updateStatsDisplay(logEvent = true) {
document.getElementById('healthStat').textContent = gameState.playerStats.health;
document.getElementById('hungerStat').textContent = gameState.playerStats.hunger;
document.getElementById('warmthStat').textContent = gameState.playerStats.warmth;
if (logEvent) {
addTimelineEvent('📊 Обновление Состояния', `❤️${gameState.playerStats.health} 🍖${gameState.playerStats.hunger} ❄️${gameState.playerStats.warmth}`);
}
}
function showErrorScreen(title, description) {
document.getElementById('generalErrorTitle').textContent = title;
document.getElementById('generalErrorDescription').textContent = description;
setChoiceButtonsLoadingState(false);
showStage('generalErrorScreen');
}
function retryLastAction(specificActionType = null) {
addTimelineEvent('🔄 Повтор Действия', `Попытка повторить предыдущее действие.`);
const actionToRetry = specificActionType || gameState.lastActionDetails?.type;
if (!actionToRetry) {
log("Нет информации о последнем действии для повтора. Сброс игры.");
resetGame();
return;
}
log("Повтор действия типа:", actionToRetry, "Детали:", gameState.lastActionDetails);
if (actionToRetry === 'initial_generation' || actionToRetry === 'player_choice') {
setChoiceButtonsLoadingState(true);
}
switch(actionToRetry) {
case 'initial_generation':
generateInitialWorldAndScene();
break;
case 'player_choice':
if(gameState.lastActionDetails?.choiceTag && gameState.lastActionDetails?.choiceText) {
handlePlayerChoice(gameState.lastActionDetails.choiceTag, gameState.lastActionDetails.choiceText);
} else { showErrorScreen('Ошибка Повтора', 'Отсутствуют данные для повтора выбора игрока.');}
break;
case 'load_image_objective':
if (gameState.currentAudioContext.objective.visualPrompt) {
const sceneImg = document.getElementById('sceneImage');
const imgLoader = document.getElementById('sceneImageLoader');
showStage('gameplayScreen');
setChoiceButtonsLoadingState(false);
loadImageWithPreloader(sceneImg, imgLoader, generateImageURL(gameState.currentAudioContext.objective.visualPrompt, 768, 432), () => retryLastAction('load_image_objective'));
} else { showErrorScreen('Ошибка Повтора', 'Отсутствует визуальный промпт для текущей сцены.');}
break;
case 'load_image_finale':
if(gameState.currentAudioContext.finale.visualPrompt) {
const finaleImg = document.getElementById('finaleImage');
const finaleImgLoader = document.getElementById('finaleImageLoader');
showStage('gameOverScreen');
loadImageWithPreloader(finaleImg, finaleImgLoader, generateImageURL(gameState.currentAudioContext.finale.visualPrompt, 768, 432), () => retryLastAction('load_image_finale'));
} else { showErrorScreen('Ошибка Повтора', 'Отсутствует визуальный промпт для финала.'); }
break;
case 'load_audio_objective': retryAudio('objective'); break;
case 'load_audio_pin': retryAudio('pin'); break;
case 'load_audio_prologue': retryPrologueMedia(true); break;
case 'load_audio_finale': retryAudio('finale'); break;
case 'load_audio_pinGameOver': retryAudio('pinGameOver'); break;
default:
log("Неизвестный или неполный тип последнего действия. Показываем экран ошибки.");
showErrorScreen('Ошибка Повтора', 'Не удалось определить предыдущее действие для повтора или отсутствуют необходимые данные.');
}
}
function retryAudio(type) {
addTimelineEvent('🔄 Повтор Аудио', `Запрос на повторную генерацию озвучки для: ${type}.`);
let textToPlay = null;
let voiceToUse = null;
if (type === 'objective' && gameState.currentAudioContext.objective.text) {
textToPlay = gameState.currentAudioContext.objective.text;
voiceToUse = NARRATOR_VOICE;
} else if (type === 'pin' && gameState.currentAudioContext.pin.text) {
textToPlay = gameState.currentAudioContext.pin.text;
voiceToUse = document.getElementById('pinVoiceSelect').value || DEFAULT_PIN_VOICE;
} else if (type === 'prologue' && gameState.currentAudioContext.prologue.text) {
textToPlay = gameState.currentAudioContext.prologue.text;
voiceToUse = PROLOGUE_DICTATOR_VOICE;
} else if (type === 'finale' && gameState.currentAudioContext.finale.text) {
textToPlay = gameState.currentAudioContext.finale.text;
voiceToUse = FINALE_ARCHIVIST_VOICE;
} else if (type === 'pinGameOver' && gameState.currentAudioContext.pinGameOver.text) {
textToPlay = gameState.currentAudioContext.pinGameOver.text;
voiceToUse = document.getElementById('pinVoiceSelect').value || DEFAULT_PIN_VOICE;
}
if (textToPlay && voiceToUse) {
playAudio(type, textToPlay, voiceToUse)
.catch(err => log(`Ошибка при повторном воспроизведении аудио ${type}:`, err))
.finally(() => {
if ((type === 'objective' || type === 'pin') && !gameState.isAudioPlaying && gameState.currentScene.audioQueue.length === 0) {
setChoiceButtonsLoadingState(false);
}
});
} else {
log("Нет текста для повторной озвучки типа:", type);
if (type === 'objective' || type === 'pin') {
setChoiceButtonsLoadingState(false);
}
}
}
function retryGameOverPinAudio() {
retryAudio('pinGameOver');
}
// --- API ВЗАИМОДЕЙСТВИЕ ---
async function callTextAPI(promptContent) {
const apiUrl = API_CONFIG.text_post_endpoint;
const requestBody = {
model: 'openai',
messages: [
{ role: 'user', content: promptContent }
],
seed: Date.now().toString(),
response_format: { "type": "json_object" }
};
const promptSnippet = promptContent.length > 300 ? promptContent.substring(0, 297) + "..." : promptContent;
log(`Запрос к Text API (POST @ ${apiUrl}, длина промпта: ${promptContent.length}):`, `Тело (модель: ${requestBody.model}, промпт-сниппет: ${promptSnippet}, seed: ${requestBody.seed}, response_format: ${JSON.stringify(requestBody.response_format)})`);
try {
const response = await fetch(apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(requestBody)
});
const responseText = await response.text();
if (!response.ok) {
let errorTextDetail = `HTTP error! status: ${response.status} ${response.statusText}`;
errorTextDetail += `, Details: ${responseText.substring(0, 500)}`;
log('Ошибка ответа Text API:', errorTextDetail);
throw new Error('Ошибка связи с ПИНом: ' + errorTextDetail);
}
log('Ответ от Text API (сырой POST):', responseText.substring(0, 1000) + (responseText.length > 1000 ? "..." : ""));
let outerJsonObject = null;
try {
outerJsonObject = JSON.parse(responseText);
} catch (e) {
log("Критическая ошибка: Ответ API не является валидным JSON, хотя статус OK:", e, "Текст ответа:", responseText);
throw new Error("Ответ ПИНа не является валидным JSON: " + responseText.substring(0,200));
}
if (outerJsonObject.choices && outerJsonObject.choices[0] && outerJsonObject.choices[0].message && typeof outerJsonObject.choices[0].message.content === 'string') {
const innerJsonString = outerJsonObject.choices[0].message.content;
log("Извлечение внутреннего JSON из ответа:", innerJsonString.substring(0,300)+"...");
// Случай для простых текстовых ответов (Архивариус)
if (promptContent.startsWith("Ты Архивариус Г.У.Л.А.Г.")) {
log("Получен текстовый ответ Архивариуса.");
return innerJsonString.trim();
}
// Случай для комментария ПИНа о провале (ожидается JSON вида {"pinGameOverComment": "..."})
const pinGameOverPromptStart = PROMPTS.PIN_GAME_OVER_COMMENT_TEMPLATE("","","","").substring(0,50);
if (promptContent.startsWith(pinGameOverPromptStart)) {
try {
const finalPinCommentObject = JSON.parse(innerJsonString);
log("Успешно спарсен внутренний JSON для комментария ПИНа:", finalPinCommentObject);
return finalPinCommentObject;
} catch(pinParseError) {
log("Ошибка парсинга JSON для комментария ПИНа, возвращаем как текст в ожидаемой структуре:", pinParseError, "Строка была:", innerJsonString);
return { pinGameOverComment: innerJsonString.trim() };
}
}
// Для всех остальных игровых промптов (INITIAL_SCENE, CHOICE_OUTCOME)
try {
const finalJsonObject = JSON.parse(innerJsonString);
log("Успешно спарсен внутренний JSON для игровой сцены:", finalJsonObject);
return finalJsonObject;
} catch (innerError) {
log("Ошибка парсинга внутреннего JSON из message.content (ожидалась игровая сцена):", innerError, "Строка была:", innerJsonString);
throw new Error("ПИН вернул некорректный JSON для игровой сцены: " + innerJsonString.substring(0,200));
}
} else {
log("Неожиданная структура ответа от /openai (отсутствует choices[0].message.content):", outerJsonObject);
// Очень маловероятный fallback для /openai endpoint, если ответ пришел как простой текст
if (typeof outerJsonObject === 'string' && (promptContent.startsWith("Ты Архивариус Г.У.Л.А.Г.") || promptContent.startsWith(PROMPTS.PIN_GAME_OVER_COMMENT_TEMPLATE("","","","").substring(0,50)))) {
return outerJsonObject;
}
throw new Error("Неожиданная структура ответа от ПИНа.");
}
} catch (error) {
log('Критическая Ошибка Text API (POST):', error.message, error.stack);
const errorMessage = error instanceof Error ? error.message : String(error);
throw new Error('Ошибка связи с ПИНом (POST): ' + errorMessage);
}
}
function generateImageURL(prompt, width = 768, height = 432) {
const basePrompt = `first person perspective, (soviet retrofuturism aesthetic:1.2), GULAG-2034 project, cinematic lighting, highly detailed, atmospheric, (artwork by Zdzislaw Beksinski:0.3), (H.R. Giger influence:0.2), dramatic composition`;
const finalPrompt = `${basePrompt}, ${prompt} --ar 16:9 --style raw`;
log("Image prompt: ", finalPrompt);
return `${API_CONFIG.image}${encodeURIComponent(finalPrompt)}?model=flux&width=${width}&height=${height}&nologo=true&enhance=true&seed=${Date.now()}`;
}
// --- ЗАГРУЗКА МЕДИА ---
function loadImageWithPreloader(imageElement, loaderElement, url, retryCallback) {
imageElement.style.display = 'none';
loaderElement.classList.remove('hidden');
const spinner = loaderElement.querySelector('.image-spinner');
const textDiv = loaderElement.querySelector('div:not(.image-spinner)');
const retryBtn = loaderElement.querySelector('.btn-retry');
if(spinner) spinner.style.display = 'block';
if(textDiv) textDiv.textContent = loaderElement.id === 'prologueImageLoader' ? 'Генерация фона для слайда...' : (loaderElement.id === 'finaleImageLoader' ? 'Генерация финального кадра...' : 'Генерация визуализации сцены...');
if(retryBtn) retryBtn.style.display = 'none';
const img = new Image();
img.onload = function() {
imageElement.src = url;
imageElement.style.display = 'block';
loaderElement.classList.add('hidden');
};
img.onerror = function() {
log('Ошибка загрузки изображения:', url);
if(spinner) spinner.style.display = 'none';
if(textDiv) textDiv.textContent = 'Ошибка визуализации';
if (retryBtn) {
retryBtn.style.display = 'block';
retryBtn.onclick = retryCallback;
} else if (retryCallback) {
showErrorScreen('Ошибка Загрузки Изображения', `Не удалось загрузить визуализацию. Попробуйте повторить.`);
}
};
img.src = url;
}
async function playAudio(type, textToSpeak, voice) {
return new Promise(async (resolve, reject) => {
const audioElement = document.getElementById(type + 'Audio');
const playerElement = document.getElementById(type + 'AudioPlayer');
const loaderElement = document.getElementById(type + 'AudioLoader');
const audioTitleElement = document.getElementById(type + 'AudioTitle');
const retryBtn = loaderElement ? loaderElement.querySelector('.btn-retry') : null;
const spinner = loaderElement ? loaderElement.querySelector('.image-spinner') : null;
const textDiv = loaderElement ? loaderElement.querySelector('div:not(.image-spinner)') : null;
if (!audioElement || !playerElement || !loaderElement || !audioTitleElement || !retryBtn || !spinner || !textDiv) {
log(`Ошибка: Отсутствуют HTML элементы для аудио типа "${type}"`);
return reject(new Error(`Отсутствуют HTML элементы для аудио типа "${type}"`));
}
if (gameState.currentAudioContext[type]) {
gameState.currentAudioContext[type].text = textToSpeak;
}
playerElement.classList.remove('show');
loaderElement.classList.remove('hidden');
spinner.style.display = 'block';
textDiv.textContent =
type === 'prologue' ? 'Диктор озвучивает слайд...' :
(type === 'objective' ? 'Генерация озвучки обстановки...' :
(type === 'pin' ? 'ПИН генерирует комментарий...' :
(type === 'finale' ? 'Генерация финальной озвучки...' :
(type === 'pinGameOver' ? 'ПИН ехидно комментирует фиаско...' : 'Загрузка аудио...'))));
retryBtn.style.display = 'none';
audioTitleElement.textContent =
type === 'prologue' ? '📢 Озвучка слайда' :
(type === 'objective' ? '📢 Описание обстановки' :
(type === 'pin' ? `📢 Комментарий ПИНа (${gameState.subjectID || 'N/A'})` :
(type === 'finale' ? '📢 Финальный рапорт' :
(type === 'pinGameOver' ? '📢 Комментарий ПИНа о провале' : 'Аудио'))));
audioElement.onloadeddata = null;
audioElement.oncanplaythrough = null;
audioElement.onended = null;
audioElement.onerror = null;
let ttsInputText = textToSpeak;
if (type === 'objective' || type === 'prologue' || type === 'finale') {
ttsInputText = `[Инструкция для диктора: Читать строго по тексту, официальным, нейтральным тоном диктора, без добавлений и изменений.] Текст: ${textToSpeak}`;
} else if (type === 'pin' || type === 'pinGameOver') {
ttsInputText = `[Инструкция для ИИ-ПИНа: Говорить только этот текст дословно, сохраняя свой саркастичный стиль, если он уже заложен в тексте. Не добавляй ничего от себя сверх этого текста.] Текст: ${textToSpeak}`;
}
const audioUrl = `${API_CONFIG.audio}${encodeURIComponent(ttsInputText)}?model=openai-audio&voice=${voice}&seed=${Date.now()}`;
log(`Запрос аудио (${type}) к API:`, audioUrl.substring(0, 300) + "...");
try {
const response = await fetch(audioUrl);
if (!response.ok) {
const errorText = await response.text();
log(`Audio API error for ${type} (${response.status}): ${errorText}`);
throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
}
const audioBlob = await response.blob();
if (audioBlob.size === 0) {
throw new Error("Получен пустой аудиофайл от API.");
}
const objectUrl = URL.createObjectURL(audioBlob);
if (audioElement.src && audioElement.src.startsWith('blob:')) URL.revokeObjectURL(audioElement.src);
audioElement.src = objectUrl;
const canPlayHandler = () => {
loaderElement.classList.add('hidden');
playerElement.classList.add('show');
if (document.getElementById('autoplayToggle').checked) {
audioElement.play().catch(e => {
log(`Автовоспроизведение (${type}) заблокировано браузером:`, e.message);
});
}
audioElement.removeEventListener('canplaythrough', canPlayHandler);
audioElement.removeEventListener('loadeddata', canPlayHandler);
};
audioElement.addEventListener('loadeddata', canPlayHandler);
audioElement.addEventListener('canplaythrough', canPlayHandler);
audioElement.onended = function() {
log(`Аудио (${type}) завершено.`);
resolve();
};
audioElement.onerror = function(e) {
log(`Ошибка HTML аудио элемента (${type}):`, audioElement.error);
spinner.style.display = 'none';
textDiv.textContent = 'Ошибка аудиодорожки';
retryBtn.style.display = 'block';
retryBtn.onclick = () => retryAudio(type);
reject(audioElement.error || e);
};
audioElement.load();
} catch (error) {
log(`Ошибка получения аудио файла (${type}):`, error);
spinner.style.display = 'none';
textDiv.textContent = 'Ошибка аудиодорожки';
retryBtn.style.display = 'block';
retryBtn.onclick = () => retryAudio(type);
reject(error);
}
});
}
// --- УПРАВЛЕНИЕ НАСТРОЙКАМИ ---
function toggleSettingsPanel() {
document.getElementById('settingsPanel').classList.toggle('show');
}
function saveVoicePreference() {
localStorage.setItem(VOICE_PREFERENCE_KEY, document.getElementById('pinVoiceSelect').value);
}
// --- ТАЙМЛАЙН ---
function addTimelineEvent(title, content, mediaUrl = null, fullData = null) {
const timeline = document.getElementById('timelineContent');
const eventId = 'event_' + Date.now() + Math.random().toString(36).substr(2,5) ;
const eventElement = document.createElement('div');
eventElement.className = 'timeline-item';
eventElement.id = eventId;
eventElement.onclick = function() { toggleTimelineDetails(this); };
let contentPreviewText = content;
if (typeof content === 'object' && content !== null) {
contentPreviewText = JSON.stringify(content).substring(0,80) + "...";
} else if (typeof content === 'string') {
contentPreviewText = content.substring(0, 80) + (content.length > 80 ? '...' : '');
}
let fullContentText = content;
if (fullData) {
let dataToDisplay = fullData;
if (fullData.rawResponseForNecrolog || fullData.rawResponseForPinComment || fullData.rawResponse) {
const rawKey = Object.keys(fullData).find(key => key.startsWith('rawResponse'));
dataToDisplay = {"Описание": content, "Детали ответа API": fullData[rawKey] || fullData};
} else {
dataToDisplay = {"Описание": content, "Детали ответа API": fullData};
}
fullContentText = JSON.stringify(dataToDisplay, null, 2);
} else if (typeof content === 'object' && content !== null) {
fullContentText = JSON.stringify(content, null, 2);
}
eventElement.innerHTML = `
<div class="timeline-title">${title}</div>
<div class="timeline-content-preview">${contentPreviewText}</div>
<div class="timeline-details">
<div class="timeline-full-content">${fullContentText}</div>
${mediaUrl ? `
<div class="timeline-image-container">
<img class="timeline-media" src="${mediaUrl}" alt="Изображение события">
</div>` : ''}
</div>
`;
if (timeline.firstChild) {
timeline.insertBefore(eventElement, timeline.firstChild);
} else {
timeline.appendChild(eventElement);
}
}
// --- ЗАПУСК ИГРЫ ---
document.addEventListener('DOMContentLoaded', initGame);
</script>
</body>
</html>