|
<!DOCTYPE html>
|
|
<html lang="ru">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<title>GPT Arena - Эпические битвы ИИ</title>
|
|
<style>
|
|
* {
|
|
margin: 0;
|
|
padding: 0;
|
|
box-sizing: border-box;
|
|
}
|
|
|
|
|
|
:root {
|
|
--bg-primary: #0f0f23;
|
|
--bg-secondary: #1a1a3a;
|
|
--bg-tertiary: #252551;
|
|
--text-primary: #ffffff;
|
|
--text-secondary: #a0a0c0;
|
|
--accent-primary: #667eea;
|
|
--accent-secondary: #764ba2;
|
|
--success: #10b981;
|
|
--warning: #f59e0b;
|
|
--error: #ef4444;
|
|
--border: #3a3a5c;
|
|
}
|
|
|
|
|
|
body.theme-brutal {
|
|
--bg-primary: #1a0508;
|
|
--bg-secondary: #26070b;
|
|
--bg-tertiary: #30090e;
|
|
--text-primary: #f8f8f8;
|
|
--text-secondary: #d0b0b0;
|
|
--accent-primary: #9e1b32;
|
|
--accent-secondary: #6e1323;
|
|
--success: #66bb6a;
|
|
--error: #ff0000;
|
|
--border: #5c2626;
|
|
}
|
|
|
|
|
|
body.theme-realistic {
|
|
--bg-primary: #212529;
|
|
--bg-secondary: #343a40;
|
|
--bg-tertiary: #495057;
|
|
--text-primary: #e0e0e0;
|
|
--text-secondary: #b0b0b0;
|
|
--accent-primary: #6c757d;
|
|
--accent-secondary: #495057;
|
|
--success: #81c784;
|
|
--error: #e57373;
|
|
--border: #757575;
|
|
}
|
|
|
|
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: transform 0.1s ease-out, 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;
|
|
}
|
|
|
|
.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-item.current {
|
|
border-color: var(--accent-primary);
|
|
box-shadow: 0 0 10px rgba(102, 126, 234, 0.3);
|
|
}
|
|
|
|
.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: 500px;
|
|
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);
|
|
}
|
|
|
|
.timeline-media img {
|
|
width: 100%;
|
|
border-radius: 4px;
|
|
max-height: 80px;
|
|
object-fit: cover;
|
|
margin-top: 0.5rem;
|
|
}
|
|
|
|
.timeline-image-container, .timeline-audio-container {
|
|
position: relative;
|
|
margin-top: 1rem;
|
|
}
|
|
|
|
.timeline-audio-container button {
|
|
background: var(--accent-primary);
|
|
color: white;
|
|
border: none;
|
|
padding: 0.5rem 1rem;
|
|
border-radius: 8px;
|
|
cursor: pointer;
|
|
font-size: 0.85rem;
|
|
margin-top: 0.5rem;
|
|
transition: all 0.2s ease;
|
|
}
|
|
.timeline-audio-container button:hover {
|
|
background: var(--accent-secondary);
|
|
transform: translateY(-1px);
|
|
}
|
|
.timeline-audio-container audio {
|
|
width: 100%;
|
|
margin-top: 0.5rem;
|
|
}
|
|
|
|
|
|
.audio-controls {
|
|
text-align: center;
|
|
margin: 1rem 0;
|
|
position: relative;
|
|
}
|
|
|
|
.audio-player {
|
|
background: var(--bg-tertiary);
|
|
border: 2px solid var(--border);
|
|
border-radius: 12px;
|
|
padding: 1rem;
|
|
margin: 1rem auto;
|
|
max-width: 400px;
|
|
display: none;
|
|
}
|
|
|
|
.audio-player.show {
|
|
display: block;
|
|
}
|
|
|
|
.audio-loader {
|
|
background: var(--bg-tertiary);
|
|
border: 2px solid var(--border);
|
|
border-radius: 12px;
|
|
padding: 1.5rem;
|
|
margin: 1rem auto;
|
|
max-width: 400px;
|
|
display: flex;
|
|
align-items: center;
|
|
justify-content: center;
|
|
flex-direction: column;
|
|
gap: 1rem;
|
|
color: var(--text-secondary);
|
|
}
|
|
|
|
.audio-loader.hidden {
|
|
display: none;
|
|
}
|
|
|
|
.audio-loader .image-spinner {
|
|
width: 24px;
|
|
height: 24px;
|
|
border-width: 2px;
|
|
}
|
|
|
|
.audio-title {
|
|
color: var(--accent-primary);
|
|
font-weight: 600;
|
|
margin-bottom: 0.5rem;
|
|
font-size: 0.9rem;
|
|
}
|
|
|
|
|
|
|
|
.container {
|
|
max-width: 1200px;
|
|
margin: 0 auto;
|
|
}
|
|
|
|
.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%;
|
|
}
|
|
|
|
.mode-display {
|
|
color: var(--text-secondary);
|
|
font-size: 0.9rem;
|
|
margin-top: -0.5rem;
|
|
margin-bottom: 0.5rem;
|
|
width: 100%;
|
|
text-align: center;
|
|
}
|
|
|
|
.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;
|
|
}
|
|
|
|
.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;
|
|
}
|
|
.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 {
|
|
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;
|
|
appearance: none;
|
|
-webkit-appearance: none;
|
|
cursor: pointer;
|
|
min-width: 100px;
|
|
}
|
|
.settings-panel select:focus {
|
|
outline: none;
|
|
border-color: var(--accent-primary);
|
|
box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
|
|
}
|
|
.settings-panel input[type="checkbox"] {
|
|
width: 18px;
|
|
height: 18px;
|
|
cursor: pointer;
|
|
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;
|
|
}
|
|
|
|
.game-stage.active {
|
|
display: block;
|
|
}
|
|
|
|
@keyframes fadeInUp {
|
|
from { opacity: 0; transform: translateY(30px); }
|
|
to { opacity: 1; transform: translateY(0); }
|
|
}
|
|
|
|
@keyframes pulse {
|
|
0%, 100% { transform: scale(1); }
|
|
50% { transform: scale(1.05); }
|
|
}
|
|
|
|
|
|
@keyframes shake-effect {
|
|
0%, 100% { transform: translateX(0); }
|
|
10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
|
|
20%, 40%, 60%, 80% { transform: translateX(5px); }
|
|
}
|
|
body.shake-effect {
|
|
animation: shake-effect 0.5s ease-out;
|
|
}
|
|
|
|
|
|
.flash-overlay {
|
|
position: fixed;
|
|
top: 0;
|
|
left: 0;
|
|
width: 100%;
|
|
height: 100%;
|
|
background-color: rgba(255, 0, 0, 0.4);
|
|
opacity: 0;
|
|
z-index: 999;
|
|
pointer-events: none;
|
|
}
|
|
@keyframes flash-effect {
|
|
0% { opacity: 0; }
|
|
50% { opacity: 1; }
|
|
100% { opacity: 0; }
|
|
}
|
|
.flash-overlay.active {
|
|
animation: flash-effect 0.2s ease-out forwards;
|
|
}
|
|
|
|
@keyframes spin {
|
|
0% { transform: rotate(0deg); }
|
|
100% { transform: rotate(360deg); }
|
|
}
|
|
|
|
@keyframes dice {
|
|
0%, 100% { transform: rotate(0deg); }
|
|
25% { transform: rotate(90deg); }
|
|
50% { transform: rotate(180deg); }
|
|
75% { transform: rotate(270deg); }
|
|
}
|
|
|
|
.form-container {
|
|
background: var(--bg-secondary);
|
|
padding: 2rem;
|
|
border-radius: 16px;
|
|
border: 1px solid var(--border);
|
|
max-width: 600px;
|
|
margin: 0 auto;
|
|
}
|
|
|
|
.form-group {
|
|
margin-bottom: 1.5rem;
|
|
}
|
|
|
|
.form-group label {
|
|
display: block;
|
|
font-weight: 600;
|
|
margin-bottom: 0.5rem;
|
|
color: var(--text-primary);
|
|
}
|
|
|
|
.form-group textarea {
|
|
width: 100%;
|
|
padding: 0.75rem;
|
|
border: 2px solid var(--border);
|
|
border-radius: 8px;
|
|
background: var(--bg-tertiary);
|
|
color: var(--text-primary);
|
|
font-size: 1rem;
|
|
resize: vertical;
|
|
min-height: 100px;
|
|
}
|
|
|
|
.form-group textarea:focus {
|
|
outline: none;
|
|
border-color: var(--accent-primary);
|
|
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2);
|
|
}
|
|
|
|
.input-with-button {
|
|
display: flex;
|
|
gap: 0.5rem;
|
|
align-items: flex-end;
|
|
}
|
|
|
|
.input-with-button textarea {
|
|
flex: 1;
|
|
}
|
|
|
|
.dice-btn {
|
|
background: var(--warning);
|
|
color: white;
|
|
border: none;
|
|
padding: 0.75rem;
|
|
border-radius: 8px;
|
|
cursor: pointer;
|
|
font-size: 1.2rem;
|
|
min-width: 50px;
|
|
height: 50px;
|
|
display: flex;
|
|
align-items: center;
|
|
justify-content: center;
|
|
transition: all 0.3s ease;
|
|
}
|
|
|
|
.dice-btn:hover {
|
|
transform: scale(1.1);
|
|
box-shadow: 0 4px 12px rgba(245, 158, 11, 0.3);
|
|
}
|
|
|
|
.dice-btn.rolling {
|
|
animation: dice 0.5s ease infinite;
|
|
}
|
|
|
|
.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: block;
|
|
margin: 0 auto;
|
|
}
|
|
|
|
.btn:hover:not(:disabled) {
|
|
transform: translateY(-2px);
|
|
box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
|
|
}
|
|
|
|
.btn:disabled {
|
|
opacity: 0.7;
|
|
cursor: not-allowed;
|
|
transform: none;
|
|
}
|
|
|
|
.btn-group {
|
|
display: flex;
|
|
gap: 1rem;
|
|
justify-content: center;
|
|
flex-wrap: wrap;
|
|
}
|
|
|
|
.btn-secondary {
|
|
background: var(--bg-tertiary);
|
|
border: 2px solid var(--border);
|
|
}
|
|
|
|
.btn-retry {
|
|
background: var(--warning);
|
|
padding: 0.5rem 1rem;
|
|
font-size: 0.9rem;
|
|
margin-top: 1rem;
|
|
}
|
|
|
|
.loading-stage {
|
|
text-align: center;
|
|
padding: 3rem 0;
|
|
}
|
|
|
|
.spinner {
|
|
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: 3rem 0;
|
|
}
|
|
|
|
.error-icon {
|
|
font-size: 4rem;
|
|
color: var(--error);
|
|
margin-bottom: 1rem;
|
|
}
|
|
|
|
.error-title {
|
|
font-size: 1.5rem;
|
|
color: var(--error);
|
|
margin-bottom: 1rem;
|
|
}
|
|
|
|
.error-description {
|
|
color: var(--text-secondary);
|
|
margin-bottom: 2rem;
|
|
}
|
|
|
|
.character-card {
|
|
background: var(--bg-secondary);
|
|
border: 2px solid var(--border);
|
|
border-radius: 16px;
|
|
padding: 1.5rem;
|
|
margin: 1rem 0;
|
|
transition: all 0.3s ease;
|
|
}
|
|
|
|
.character-card:hover {
|
|
border-color: var(--accent-primary);
|
|
box-shadow: 0 8px 30px rgba(102, 126, 234, 0.2);
|
|
}
|
|
|
|
.character-info {
|
|
display: grid;
|
|
grid-template-columns: 200px 1fr;
|
|
gap: 1.5rem;
|
|
align-items: start;
|
|
}
|
|
|
|
.character-avatar-container {
|
|
position: relative;
|
|
width: 200px;
|
|
height: 333px;
|
|
border-radius: 12px;
|
|
overflow: hidden;
|
|
}
|
|
|
|
.character-avatar {
|
|
width: 100%;
|
|
height: 100%;
|
|
object-fit: cover;
|
|
object-position: top;
|
|
border: 3px solid transparent;
|
|
border-radius: 12px;
|
|
transition: all 0.3s ease, border-color 0.5s ease;
|
|
}
|
|
|
|
.image-loader {
|
|
position: absolute;
|
|
top: 0;
|
|
left: 0;
|
|
width: 100%;
|
|
height: 100%;
|
|
background: var(--bg-tertiary);
|
|
border-radius: 12px;
|
|
display: flex;
|
|
align-items: center;
|
|
justify-content: center;
|
|
flex-direction: column;
|
|
gap: 1rem;
|
|
}
|
|
|
|
.image-loader.hidden {
|
|
display: none;
|
|
}
|
|
|
|
.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;
|
|
}
|
|
|
|
.retry-btn {
|
|
background: var(--warning);
|
|
color: white;
|
|
border: none;
|
|
padding: 0.5rem 1rem;
|
|
border-radius: 6px;
|
|
cursor: pointer;
|
|
font-size: 0.8rem;
|
|
}
|
|
|
|
.character-details h3 {
|
|
font-size: 1.5rem;
|
|
margin-bottom: 0.5rem;
|
|
color: var(--accent-primary);
|
|
}
|
|
|
|
.character-description {
|
|
color: var(--text-secondary);
|
|
line-height: 1.6;
|
|
margin-bottom: 1rem;
|
|
}
|
|
|
|
.stats-grid {
|
|
display: grid;
|
|
grid-template-columns: repeat(3, 1fr);
|
|
gap: 0.5rem;
|
|
}
|
|
|
|
.stat-item {
|
|
background: var(--bg-tertiary);
|
|
padding: 0.5rem;
|
|
border-radius: 6px;
|
|
text-align: center;
|
|
}
|
|
|
|
.stat-name {
|
|
font-size: 0.8rem;
|
|
color: var(--text-secondary);
|
|
margin-bottom: 0.25rem;
|
|
}
|
|
|
|
.stat-value {
|
|
font-size: 1.2rem;
|
|
font-weight: 700;
|
|
color: var(--accent-primary);
|
|
}
|
|
|
|
.abilities {
|
|
margin-top: 1rem;
|
|
padding-top: 1rem;
|
|
border-top: 1px solid var(--border);
|
|
}
|
|
|
|
.abilities h4 {
|
|
margin-bottom: 0.5rem;
|
|
color: var(--text-primary);
|
|
}
|
|
|
|
.ability {
|
|
background: var(--bg-tertiary);
|
|
padding: 0.5rem;
|
|
border-radius: 6px;
|
|
margin-bottom: 0.5rem;
|
|
font-size: 0.9rem;
|
|
color: var(--text-secondary);
|
|
}
|
|
|
|
.battle-arena {
|
|
background: var(--bg-secondary);
|
|
border-radius: 16px;
|
|
padding: 2rem;
|
|
margin: 1rem 0;
|
|
border: 2px solid var(--border);
|
|
}
|
|
|
|
.fighters-display {
|
|
display: grid;
|
|
grid-template-columns: 1fr auto 1fr;
|
|
gap: 2rem;
|
|
align-items: center;
|
|
margin-bottom: 2rem;
|
|
}
|
|
|
|
.fighter {
|
|
text-align: center;
|
|
position: relative;
|
|
}
|
|
|
|
.fighter-avatar {
|
|
width: 150px;
|
|
height: 150px;
|
|
border-radius: 12px;
|
|
object-fit: cover;
|
|
object-position: top;
|
|
border: 3px solid transparent;
|
|
margin: 0 auto 1rem;
|
|
transition: all 0.3s ease, border-color 0.5s ease;
|
|
}
|
|
|
|
@keyframes subtle-pulse {
|
|
0% { transform: scale(1); }
|
|
50% { transform: scale(1.02); }
|
|
100% { transform: scale(1); }
|
|
}
|
|
.fighter-avatar.pulsing {
|
|
animation: subtle-pulse 1.5s infinite ease-in-out;
|
|
}
|
|
|
|
@keyframes pulse-attack {
|
|
0% { transform: scale(1); filter: brightness(1); }
|
|
50% { transform: scale(1.05); filter: brightness(1.2); }
|
|
100% { transform: scale(1); filter: brightness(1); }
|
|
}
|
|
.fighter-avatar.damaged {
|
|
animation: pulse-attack 0.3s ease-out;
|
|
}
|
|
|
|
.vs-icon {
|
|
font-size: 3rem;
|
|
color: var(--accent-primary);
|
|
animation: pulse 2s infinite;
|
|
}
|
|
|
|
.hp-bar {
|
|
width: 100%;
|
|
height: 20px;
|
|
background: var(--bg-tertiary);
|
|
border-radius: 10px;
|
|
overflow: hidden;
|
|
margin: 0.5rem 0;
|
|
border: 1px solid var(--border);
|
|
position: relative;
|
|
}
|
|
|
|
.hp-fill {
|
|
height: 100%;
|
|
transition: width 0.5s ease, background-color 0.5s ease;
|
|
|
|
}
|
|
|
|
.hp-text {
|
|
position: absolute;
|
|
width: 100%;
|
|
text-align: center;
|
|
top: 50%;
|
|
left: 0;
|
|
transform: translateY(-50%);
|
|
color: var(--text-primary);
|
|
font-size: 0.85rem;
|
|
font-weight: 600;
|
|
text-shadow: 1px 1px 2px rgba(0,0,0,0.7);
|
|
pointer-events: none;
|
|
}
|
|
|
|
.round-info {
|
|
text-align: center;
|
|
margin: 2rem 0;
|
|
}
|
|
|
|
.round-title {
|
|
font-size: 2rem;
|
|
font-weight: 700;
|
|
color: var(--accent-primary);
|
|
margin-bottom: 0.5rem;
|
|
}
|
|
|
|
.arena-name {
|
|
color: var(--text-secondary);
|
|
font-size: 1.1rem;
|
|
margin-bottom: 1rem;
|
|
}
|
|
|
|
.battle-scene {
|
|
background: var(--bg-tertiary);
|
|
border-radius: 12px;
|
|
padding: 1.5rem;
|
|
margin: 1rem 0;
|
|
border: 1px solid var(--border);
|
|
text-align: center;
|
|
position: relative;
|
|
}
|
|
|
|
.battle-image-container {
|
|
position: relative;
|
|
margin: 1rem 0;
|
|
min-height: 200px;
|
|
overflow: hidden;
|
|
border-radius: 8px;
|
|
}
|
|
|
|
@keyframes panImage {
|
|
0% { transform: translateX(0); }
|
|
50% { transform: translateX(-5%); }
|
|
100% { transform: translateX(0); }
|
|
}
|
|
.battle-image {
|
|
max-width: 110%;
|
|
max-height: 400px;
|
|
border-radius: 8px;
|
|
display: block;
|
|
margin: 0 auto;
|
|
animation: panImage 15s infinite alternate ease-in-out;
|
|
}
|
|
|
|
.battle-image-loader {
|
|
position: absolute;
|
|
top: 0;
|
|
left: 50%;
|
|
transform: translateX(-50%);
|
|
background: var(--bg-secondary);
|
|
border: 2px solid var(--border);
|
|
border-radius: 12px;
|
|
padding: 2rem;
|
|
display: flex;
|
|
align-items: center;
|
|
justify-content: center;
|
|
flex-direction: column;
|
|
gap: 1rem;
|
|
min-width: 300px;
|
|
z-index: 2;
|
|
}
|
|
|
|
.battle-image-loader.hidden {
|
|
display: none;
|
|
}
|
|
|
|
.battle-description {
|
|
font-size: 1.1rem;
|
|
line-height: 1.6;
|
|
color: var(--text-primary);
|
|
margin-top: 1rem;
|
|
}
|
|
|
|
.finale-stage {
|
|
text-align: center;
|
|
padding: 3rem 0;
|
|
}
|
|
|
|
.finale-title {
|
|
font-size: 3rem;
|
|
font-weight: 800;
|
|
margin-bottom: 2rem;
|
|
background: linear-gradient(135deg, var(--accent-primary), var(--accent-secondary));
|
|
-webkit-background-clip: text;
|
|
-webkit-text-fill-color: transparent;
|
|
}
|
|
|
|
|
|
@keyframes floatAndFade {
|
|
0% { transform: translate(-50%, 0); opacity: 1; }
|
|
100% { transform: translate(-50%, -50px); opacity: 0; }
|
|
}
|
|
.damage-number {
|
|
position: absolute;
|
|
top: 50%;
|
|
left: 50%;
|
|
transform: translate(-50%, 0);
|
|
font-size: 1.8rem;
|
|
font-weight: bold;
|
|
color: var(--error);
|
|
text-shadow:
|
|
-1px -1px 0 #000,
|
|
1px -1px 0 #000,
|
|
-1px 1px 0 #000,
|
|
1px 1px 0 #000;
|
|
animation: floatAndFade 1.5s ease-out forwards;
|
|
pointer-events: none;
|
|
z-index: 10;
|
|
white-space: nowrap;
|
|
}
|
|
|
|
|
|
|
|
.battle-actions {
|
|
display: flex;
|
|
gap: 1rem;
|
|
justify-content: center;
|
|
margin-top: 2rem;
|
|
flex-wrap: wrap;
|
|
}
|
|
|
|
.battle-actions .btn {
|
|
margin: 0;
|
|
padding: 0.8rem 1.5rem;
|
|
font-size: 1rem;
|
|
}
|
|
|
|
@media (max-width: 1024px) {
|
|
.main-container {
|
|
grid-template-columns: 1fr;
|
|
grid-template-rows: 1fr auto;
|
|
}
|
|
|
|
.timeline {
|
|
max-height: 300px;
|
|
border-left: none;
|
|
border-top: 2px solid var(--border);
|
|
}
|
|
|
|
.settings-panel {
|
|
position: static;
|
|
margin: 1rem auto;
|
|
width: fit-content;
|
|
transform: translateY(0);
|
|
}
|
|
.settings-panel > div {
|
|
width: 100%;
|
|
}
|
|
.settings-btn {
|
|
position: static;
|
|
margin: 1rem auto;
|
|
}
|
|
}
|
|
|
|
@media (max-width: 768px) {
|
|
.character-info {
|
|
grid-template-columns: 1fr;
|
|
text-align: center;
|
|
}
|
|
|
|
.fighters-display {
|
|
grid-template-columns: 1fr;
|
|
gap: 1rem;
|
|
}
|
|
|
|
.vs-icon {
|
|
order: 2;
|
|
}
|
|
|
|
.stats-grid {
|
|
grid-template-columns: repeat(2, 1fr);
|
|
}
|
|
|
|
.btn-group {
|
|
flex-direction: column;
|
|
}
|
|
|
|
.input-with-button {
|
|
flex-direction: column;
|
|
}
|
|
|
|
.input-with-button textarea {
|
|
margin-bottom: 0.5rem;
|
|
}
|
|
.battle-actions {
|
|
flex-direction: column;
|
|
}
|
|
}
|
|
</style>
|
|
</head>
|
|
<body class="theme-fantasy">
|
|
|
|
<div id="flashOverlay" class="flash-overlay"></div>
|
|
|
|
<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="voiceSelect">Голос диктора:</label>
|
|
<select id="voiceSelect" onchange="saveVoicePreference()">
|
|
<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="coral">Coral</option>
|
|
<option value="verse">Verse</option>
|
|
<option value="ballad">Ballad</option>
|
|
<option value="ash">Ash</option>
|
|
<option value="sage">Sage</option>
|
|
<option value="amuch">Amuch</option>
|
|
<option value="dan">Dan</option>
|
|
</select>
|
|
</div>
|
|
<div>
|
|
<input type="checkbox" id="autoplayToggle" checked>
|
|
<label for="autoplayToggle">Автоматически воспроизводить озвучку</label>
|
|
</div>
|
|
<div class="info-block">
|
|
<p>Создал:<br><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>Все генерации происходят в реальном времени.</p>
|
|
</div>
|
|
</div>
|
|
|
|
<h1>⚔️ GPT Arena</h1>
|
|
<p id="currentModeDisplay" class="mode-display"></p>
|
|
<p>Эпические битвы с искусственным интеллектом</p>
|
|
</div>
|
|
|
|
|
|
<div id="modeSelection" class="game-stage active">
|
|
<div class="form-container">
|
|
<h2 style="text-align: center; margin-bottom: 2rem; color: var(--accent-primary);">Выберите режим Арены</h2>
|
|
<div class="btn-group">
|
|
<button class="btn" onclick="selectMode('fantasy')">✨ Эпическое фэнтези</button>
|
|
<button class="btn" onclick="selectMode('brutal')">🩸 Кровавый файтинг</button>
|
|
<button class="btn" onclick="selectMode('realistic')">🚶 Скучная реальность</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<div id="start" class="game-stage">
|
|
<div class="form-container">
|
|
<h2 style="text-align: center; margin-bottom: 2rem; color: var(--accent-primary);">Создайте своего героя</h2>
|
|
<div class="form-group">
|
|
<label for="heroInput">Опишите вашего бойца:</label>
|
|
<div class="input-with-button">
|
|
<textarea id="heroInput" placeholder="Например: Эльфийка-ассасин в черном плаще, владеет кинжалами и магией теней. Её глаза светятся в темноте..."></textarea>
|
|
<button class="dice-btn" onclick="generateRandomHero()" title="Случайный герой">🎲</button>
|
|
</div>
|
|
</div>
|
|
<button class="btn" onclick="createHero()">🎨 Создать героя</button>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<div id="heroLoading" class="game-stage">
|
|
<div class="loading-stage">
|
|
<div class="spinner"></div>
|
|
<div class="loading-text">Создаем вашего героя...</div>
|
|
<div class="loading-text" style="font-size: 1rem; color: var(--text-secondary);">Генерируем характеристики и способности</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<div id="heroError" class="game-stage">
|
|
<div class="error-stage">
|
|
<div class="error-icon">❌</div>
|
|
<div class="error-title">Ошибка создания героя</div>
|
|
<div class="error-description">Не удалось создать вашего героя. Попробуйте еще раз.</div>
|
|
<button class="btn btn-retry" onclick="retryCreateHero()">🔄 Попробовать снова</button>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<div id="heroPresentation" class="game-stage">
|
|
<div id="heroCard" class="character-card"></div>
|
|
<div class="audio-controls">
|
|
<div class="audio-loader" id="heroAudioLoader">
|
|
<div class="image-spinner"></div>
|
|
<div>Создаем голосовое описание героя...</div>
|
|
<button class="retry-btn" onclick="retryHeroAudio()" style="display: none;">Повторить</button>
|
|
</div>
|
|
<div class="audio-player" id="heroAudioPlayer">
|
|
<div class="audio-title">🎵 Описание героя</div>
|
|
<audio id="heroAudio" controls></audio>
|
|
</div>
|
|
</div>
|
|
<div style="text-align: center; margin-top: 2rem;">
|
|
<button class="btn" onclick="chooseOpponent()">⚔️ Найти противника</button>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<div id="opponentChoice" class="game-stage">
|
|
<div class="form-container">
|
|
<h2 style="text-align: center; margin-bottom: 2rem; color: var(--accent-primary);">Выберите противника</h2>
|
|
<div class="btn-group">
|
|
<button class="btn" onclick="createAutoOpponent()">🎲 Автоматический противник</button>
|
|
<button class="btn btn-secondary" onclick="createCustomOpponent()">✍️ Создать своего</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<div id="customOpponent" class="game-stage">
|
|
<div class="form-container">
|
|
<h2 style="text-align: center; margin-bottom: 2rem; color: var(--accent-primary);">Создайте противника</h2>
|
|
<div class="form-group">
|
|
<label for="opponentInput">Опишите противника:</label>
|
|
<div class="input-with-button">
|
|
<textarea id="opponentInput" placeholder="Например: Огромный орк-берсерк в железной броне, сражается двуручным топором..."></textarea>
|
|
<button class="dice-btn" onclick="generateRandomOpponent()" title="Случайный противник">🎲</button>
|
|
</div>
|
|
</div>
|
|
<button class="btn" onclick="createOpponent()">👹 Создать противника</button>
|
|
</div>
|
|
<div style="text-align: center; margin-top: 1rem;">
|
|
<button class="btn btn-secondary" onclick="showStage('opponentChoice')">⬅️ Назад</button>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<div id="opponentLoading" class="game-stage">
|
|
<div class="loading-stage">
|
|
<div class="spinner"></div>
|
|
<div class="loading-text">Создаем достойного противника...</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<div id="opponentError" class="game-stage">
|
|
<div class="error-stage">
|
|
<div class="error-icon">❌</div>
|
|
<div class="error-title">Ошибка создания противника</div>
|
|
<div class="error-description">Не удалось создать противника. Попробуйте еще раз.</div>
|
|
<button class="btn btn-retry" onclick="retryCreateOpponent()">🔄 Попробовать снова</button>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<div id="opponentPresentation" class="game-stage">
|
|
<div id="opponentCard" class="character-card"></div>
|
|
<div class="audio-controls">
|
|
<div class="audio-loader" id="opponentAudioLoader">
|
|
<div class="image-spinner"></div>
|
|
<div>Создаем голосовое описание противника...</div>
|
|
<button class="retry-btn" onclick="retryOpponentAudio()" style="display: none;">Повторить</button>
|
|
</div>
|
|
<div class="audio-player" id="opponentAudioPlayer">
|
|
<div class="audio-title">🎵 Описание противника</div>
|
|
<audio id="opponentAudio" controls></audio>
|
|
</div>
|
|
</div>
|
|
|
|
<div style="text-align: center; margin-top: 2rem;">
|
|
<button class="btn" onclick="chooseLocation()">🗺️ Выбрать локацию</button>
|
|
<button class="btn btn-secondary" onclick="showStage('opponentChoice')" style="margin-left: 1rem;">⬅️ Назад</button>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<div id="locationChoice" class="game-stage">
|
|
<div class="form-container">
|
|
<h2 style="text-align: center; margin-bottom: 2rem; color: var(--accent-primary);">Выберите место битвы</h2>
|
|
<div class="btn-group">
|
|
<button class="btn" onclick="createAutoLocation()">🎲 Автоматическая локация</button>
|
|
<button class="btn btn-secondary" onclick="createCustomLocation()">✍️ Создать свою</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<div id="customLocation" class="game-stage">
|
|
<div class="form-container">
|
|
<h2 style="text-align: center; margin-bottom: 2rem; color: var(--accent-primary);">Опишите место битвы</h2>
|
|
<div class="form-group">
|
|
<label for="locationInput">Опишите локацию:</label>
|
|
<div class="input-with-button">
|
|
<textarea id="locationInput" placeholder="Например: Древний заброшенный храм на вершине горы, окруженный густым туманом и развалинами..."></textarea>
|
|
<button class="dice-btn" onclick="generateRandomLocation()" title="Случайная локация">🎲</button>
|
|
</div>
|
|
</div>
|
|
<button class="btn" onclick="createLocation()">🏞️ Создать локацию</button>
|
|
</div>
|
|
<div style="text-align: center; margin-top: 1rem;">
|
|
<button class="btn btn-secondary" onclick="showStage('locationChoice')">⬅️ Назад</button>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<div id="locationLoading" class="game-stage">
|
|
<div class="loading-stage">
|
|
<div class="spinner"></div>
|
|
<div class="loading-text">Создаем место битвы...</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<div id="locationError" class="game-stage">
|
|
<div class="error-stage">
|
|
<div class="error-icon">❌</div>
|
|
<div class="error-title">Ошибка создания локации</div>
|
|
<div class="error-description">Не удалось создать локацию. Попробуйте еще раз.</div>
|
|
<button class="btn btn-retry" onclick="retryCreateLocation()">🔄 Попробовать снова</button>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<div id="battle" class="game-stage">
|
|
<div class="battle-arena">
|
|
<div class="fighters-display">
|
|
<div class="fighter hero">
|
|
<img id="heroAvatar" class="fighter-avatar" src="" alt="Герой">
|
|
<div class="hp-bar">
|
|
<div id="heroHP" class="hp-fill" style="width: 100%;"></div>
|
|
<span id="heroHPText" class="hp-text">HP: 100/100</span>
|
|
</div>
|
|
<div id="heroName" style="font-weight: 600; color: var(--text-primary);"></div>
|
|
</div>
|
|
|
|
<div class="vs-icon">⚔️</div>
|
|
|
|
<div class="fighter opponent">
|
|
<img id="opponentAvatar" class="fighter-avatar" src="" alt="Противник">
|
|
<div class="hp-bar">
|
|
<div id="opponentHP" class="hp-fill" style="width: 100%;"></div>
|
|
<span id="opponentHPText" class="hp-text">HP: 100/100</span>
|
|
</div>
|
|
<div id="opponentName" style="font-weight: 600; color: var(--text-primary);"></div>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="round-info">
|
|
<div id="roundTitle" class="round-title">Раунд 1</div>
|
|
<div id="arenaName" class="arena-name"></div>
|
|
</div>
|
|
|
|
<div class="battle-scene">
|
|
<div class="battle-image-container">
|
|
<div class="battle-image-loader" id="battleImageLoader">
|
|
<div class="image-spinner"></div>
|
|
<div style="color: var(--text-secondary); font-size: 0.9rem;">Создаем сцену битвы...</div>
|
|
<button class="retry-btn" onclick="retryBattleImage()" style="display: none;">Повторить</button>
|
|
</div>
|
|
<img id="battleImage" class="battle-image" style="display: none;" alt="Сцена битвы">
|
|
</div>
|
|
<div id="battleDescription" class="battle-description"></div>
|
|
</div>
|
|
|
|
<div class="audio-controls">
|
|
<div class="audio-loader" id="battleAudioLoader">
|
|
<div class="image-spinner"></div>
|
|
<div>Создаем озвучку раунда, еще секундочку...</div>
|
|
<button class="retry-btn" onclick="retryBattleAudio()" style="display: none;">Повторить</button>
|
|
</div>
|
|
<div class="audio-player" id="battleAudioPlayer">
|
|
<div class="audio-title" id="battleAudioTitle">🎵 Комментарий раунда</div>
|
|
<audio id="battleAudio" controls></audio>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<div id="battleActions" class="battle-actions" style="display: none;">
|
|
<button class="btn" onclick="performAction('attack')">👊 Атаковать</button>
|
|
<button class="btn btn-secondary" id="abilityBtn" onclick="performAction('ability1')" style="display: none;">✨ Использовать способность</button>
|
|
<button class="btn btn-secondary" onclick="performAction('defend')">🛡️ Защититься</button>
|
|
|
|
|
|
<div class="form-group" style="width: 100%; margin-top: 1rem; margin-bottom: 0;">
|
|
<label for="customActionInput" style="font-size: 0.9rem;">Или опишите своё действие:</label>
|
|
<div class="input-with-button">
|
|
<textarea id="customActionInput" placeholder="Например: Прыгнуть в воздух и обрушить огненный удар"></textarea>
|
|
<button class="btn" style="min-width: unset; height: 50px; font-size: 1rem; padding: 0.75rem 1rem;" onclick="performCustomAction()">🚀 Действие</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div style="text-align: center; margin-top: 2rem;">
|
|
<button id="nextRoundBtn" class="btn" onclick="nextRound()" style="display: none;">➡️ Следующий раунд</button>
|
|
<button id="finaleBtn" class="btn" onclick="showFinale()" style="display: none;">🏆 Финал</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<div id="roundLoading" class="game-stage">
|
|
<div class="loading-stage">
|
|
<div class="spinner"></div>
|
|
<div class="loading-text" id="roundLoadingText">Симулируем раунд...</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<div id="roundError" class="game-stage">
|
|
<div class="error-stage">
|
|
<div class="error-icon">❌</div>
|
|
<div class="error-title">Ошибка симуляции раунда</div>
|
|
<div class="error-description">Не удалось провести раунд битвы. Попробуйте еще раз.</div>
|
|
<button class="btn btn-retry" onclick="retryRound()">🔄 Попробовать снова</button>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<div id="finale" class="game-stage">
|
|
<div class="finale-stage">
|
|
<div id="finaleTitle" class="finale-title"></div>
|
|
<div class="battle-scene">
|
|
<div class="battle-image-container">
|
|
<div class="battle-image-loader" id="finaleImageLoader">
|
|
<div class="image-spinner"></div>
|
|
<div style="color: var(--text-secondary); font-size: 0.9rem;">Создаем финальную сцену...</div>
|
|
<button class="retry-btn" onclick="retryFinaleImage()" style="display: none;">Повторить</button>
|
|
</div>
|
|
<img id="finaleImage" class="battle-image" style="display: none;" alt="Финальная сцена">
|
|
</div>
|
|
<div id="finaleDescription" class="battle-description"></div>
|
|
</div>
|
|
<div class="audio-controls">
|
|
<div class="audio-loader" id="finaleAudioLoader">
|
|
<div class="image-spinner"></div>
|
|
<div>Создаем финальную озвучку, еще секундочку...</div>
|
|
<button class="retry-btn" onclick="retryFinaleAudio()" style="display: none;">Повторить</button>
|
|
</div>
|
|
<div class="audio-player" id="finaleAudioPlayer">
|
|
<div class="audio-title">🎵 Эпический финал</div>
|
|
<audio id="finaleAudio" controls></audio>
|
|
</div>
|
|
</div>
|
|
<div style="text-align: center; margin-top: 3rem;">
|
|
<button class="btn" onclick="resetGame()">🎮 Новая игра</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<div id="finaleError" class="game-stage">
|
|
<div class="error-stage">
|
|
<div class="error-icon">❌</div>
|
|
<div class="error-title">Ошибка создания финала</div>
|
|
<div class="error-description">Не удалось создать финальную сцену. Попробуйте еще раз.</div>
|
|
<button class="btn btn-retry" onclick="retryFinale()">🔄 Попробовать снова</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
|
|
<div class="timeline">
|
|
<h3>📜 Лог событий</h3>
|
|
<div id="timelineContent"></div>
|
|
</div>
|
|
</div>
|
|
|
|
<script>
|
|
// Глобальное состояние игры
|
|
let gameState = {
|
|
gameId: null,
|
|
stage: 'modeSelection', // Start on mode selection screen
|
|
hero: null,
|
|
opponent: null,
|
|
location: null,
|
|
heroAction: null,
|
|
battleLog: [],
|
|
currentHP: { hero: 100, opponent: 100 },
|
|
currentRound: 1,
|
|
lastAction: null,
|
|
currentMode: null, // Stores the selected game mode (e.g., MODES.fantasy)
|
|
locationAnnounced: false // NEW: Flag to ensure location description is announced only once
|
|
};
|
|
|
|
// API конфигурация
|
|
const API_CONFIG = {
|
|
text: 'https://text.pollinations.ai/',
|
|
image: 'https://image.pollinations.ai/prompt/',
|
|
audio: 'https://text.pollinations.ai/'
|
|
};
|
|
|
|
// --- PROMPT TEMPLATES AND MODE CONFIGURATION ---
|
|
const PROMPTS = {
|
|
// General instruction for LLM to respect user input length
|
|
PROMPT_INSTRUCTION: `Если описание пользователя подробное, используй его максимально точно, не искажая внешний вид и характер. Если описание краткое, расширь его, добавив уместные детали.`,
|
|
|
|
// Character prompt (common structure, different details per mode)
|
|
CHARACTER_PROMPT_TEMPLATE: (additionalInstruction = "") => `Ты создатель персонажей для GPT Arena. Отвечай СТРОГО в JSON формате.
|
|
Создай уникального персонажа для динамичной арены на основе предоставленного описания. ${PROMPTS.PROMPT_INSTRUCTION} Персонаж должен точно соответствовать заданному сеттингу, внешности и характеру, без добавления посторонних юмористических или абсурдных элементов, если они явно не запрошены. Сеттинг может быть любым: фэнтези, научная фантатика, постапокалипсис, современность, комиксы или гибридный. ${additionalInstruction}
|
|
|
|
{
|
|
"name": "Имя персонажа (креативное, но уместное, на русском языке)",
|
|
"description": "Подробное и интригующее описание с бэкграундом персонажа (3-5 предложений), строго по заданному пользователем стилю и сеттингу, без привнесения постороннего юмора или сарказма. (на русском языке)",
|
|
"visualPrompt": "highly detailed character portrait, [внешность], [одежда], [оружие], [поза], with a consistent and clear core visual identity. The art style and setting should strictly match the user's description (e.g., fantasy, cyberpunk, realistic, anime, comic book). Emphasize a unique, recognizable, and visually striking look. Cinematic lighting, high quality, unique style. This visualPrompt string MUST be in English.",
|
|
"stats": {
|
|
"strength": число_1_10,
|
|
"agility": число_1_10,
|
|
"intelligence": число_1_10,
|
|
"endurance": число_1_10,
|
|
"magic": число_1_10,
|
|
"luck": число_1_10
|
|
},
|
|
"abilities": ["способность 1 (точно соответствует описанию персонажа и его стилю, на русском языке)", "способность 2 (точно соответствует описанию персонажа и его стилю, на русском языке)"]
|
|
}`,
|
|
|
|
// Location prompt (common structure, different details per mode)
|
|
LOCATION_PROMPT_TEMPLATE: (additionalInstruction = "") => `Ты генератор локаций для GPT Arena. Отвечай СТРОГО в JSON формате.
|
|
Создай описание и визуальный промпт для эпической арены, подходящей для битвы. ${PROMPTS.PROMPT_INSTRUCTION} Локация должна быть интригующей и атмосферной, но без специфических элементов, которые могли бы дать преимущество одному из бойцов. ${additionalInstruction}
|
|
|
|
{
|
|
"name": "Название локации (на русском языке)",
|
|
"description": "Краткое, атмосферное описание локации (2-3 предложения, на русском языке).",
|
|
"visualPrompt": "highly detailed wide shot of a battle arena, [описание локации], dramatic lighting, epic atmosphere, high quality, unique style. This visualPrompt string MUST be in English."
|
|
}`,
|
|
|
|
// Battle prompt (common structure, different details per mode)
|
|
BATTLE_PROMPT_TEMPLATE: (heroActionDescription, locationPrompt, heroName, opponentName, currentHeroHP, currentOpponentHP, additionalInstruction = "") => `Ты симулятор битв для GPT Arena. Отвечай СТРОГО в JSON формате.
|
|
Симулируй раунд битвы. ${additionalInstruction}
|
|
|
|
Контекст:
|
|
Герой: ${heroName} (HP: ${currentHeroHP})
|
|
Противник: ${opponentName} (HP: ${currentOpponentHP})
|
|
Действие героя в этом раунде: ${heroActionDescription}
|
|
|
|
{
|
|
"round": номер_раунда,
|
|
"description": "Опиши ход раунда, учитывая, что герой ${heroName} ${heroActionDescription}. Максимум 300 символов. (на русском языке)",
|
|
"visualPrompt": "intense, dynamic battle scene within ${locationPrompt}, ${heroName} fiercely engaging ${opponentName}. This visualPrompt string MUST be in English.",
|
|
"winner": "hero" или "opponent" или "draw",
|
|
"damage": {"hero": урон_15_40, "opponent": урон_15_40}
|
|
}`,
|
|
|
|
// Finale prompt (common structure, different details per mode)
|
|
FINALE_PROMPT_TEMPLATE: (winnerName, loserName, locationPrompt, additionalInstruction = "") => `Ты финалист битв для GPT Arena. Отвечай СТРОГО в JSON формате.
|
|
Создай завершение битвы. ${additionalInstruction}
|
|
|
|
{
|
|
"description": "Кульминационное и драматичное завершение битвы в ${locationPrompt}, где описывается решающий удар или момент окончательной победы. Максимум 300 символов. (на русском языке)",
|
|
"winner": "hero" или "opponent",
|
|
"visualPrompt": "victorious ${winnerName} standing triumphantly over defeated ${loserName} in ${locationPrompt}. This visualPrompt string MUST be in English.",
|
|
"finalMessage": "Торжественное объявление победителя, его 'достижений' и что ждет Арену дальше. Максимум 200 символов. (на русском языке)"
|
|
}`,
|
|
|
|
// Commentator prompt (base, will be prepended)
|
|
COMMENTATOR_PROMPT_BASE: (modeDescription) => `Ты Мастер Турнира - комментатор арены. Говори от лица опытного распорядителя боев, который видел тысячи сражений. Используй ${modeDescription} тон, драматизм и профессиональные комментарии как настоящий спортивный комментатор. Начинай фразы разнообразно, например: "Леди и джентльмены!", "Что за зрелище!", "Невероятно!", "Зрители замерли!", "Это просто нечто!", "Добро пожаловать на Арену!", "Только посмотрите на это!", "Исторический момент!", "Этого никто не ожидал!". Все комментарии должны быть на русском языке.`,
|
|
};
|
|
|
|
const MODES = {
|
|
fantasy: {
|
|
id: 'fantasy',
|
|
name: 'Эпическое фэнтези',
|
|
class: 'theme-fantasy',
|
|
defaultVoice: 'ash',
|
|
characterPrompt: PROMPTS.CHARACTER_PROMPT_TEMPLATE("Персонаж должен быть типичным для фэнтези мира: эльф, маг, рыцарь, дракон, минотавр и т.д."),
|
|
locationPrompt: PROMPTS.LOCATION_PROMPT_TEMPLATE("Локация должна быть из фэнтези мира: древний замок, волшебный лес, подземелье, горы, руины и т.д."),
|
|
battlePrompt: (action, loc, hN, oN, hHP, oHP) => PROMPTS.BATTLE_PROMPT_TEMPLATE(action, loc, hN, oN, hHP, oHP, `Симулируй раунд битвы в стиле "Эпическое фэнтези", сфокусируясь на динамичных, драматичных и зрелищных моментах. Допускаются элементы героического пафоса.`),
|
|
finalePrompt: (wN, lN, loc) => PROMPTS.FINALE_PROMPT_TEMPLATE(wN, lN, loc, `Создай эпическое завершение битвы в стиле "Эпическое фэнтези". Победа может быть результатом решающего удара, но с торжественным подтекстом в описании.`),
|
|
commentatorPrompt: PROMPTS.COMMENTATOR_PROMPT_BASE("эпический"),
|
|
imageStyle: "cinematic fantasy illustration, high quality, unique style, vibrant colors",
|
|
damageRange: [15, 40]
|
|
},
|
|
brutal: {
|
|
id: 'brutal',
|
|
name: 'Кровавый файтинг',
|
|
class: 'theme-brutal',
|
|
defaultVoice: 'ballad',
|
|
characterPrompt: PROMPTS.CHARACTER_PROMPT_TEMPLATE("Персонаж должен быть брутальным бойцом, киборгом, ниндзя, монстром, без лишнего юмора. Подумай о персонажах вроде Скорпиона, Саб-Зиро, Рэйдена из Mortal Kombat."),
|
|
locationPrompt: PROMPTS.LOCATION_PROMPT_TEMPLATE("Локация должна быть темной, мрачной ареной, местом жестоких боев, без лишнего юмора."),
|
|
battlePrompt: (action, loc, hN, oN, hHP, oHP) => PROMPTS.BATTLE_PROMPT_TEMPLATE(action, loc, hN, oN, hHP, oHP, `Симулируй раунд битвы в стиле "Mortal Kombat", сфокусируйся на динамичных, брутальных и драматичных моментах. Каждый удар - сокрушительный. Допускаются элементы черного юмора или иронии в повествовании, но не в ущерб интенсивности самих боевых действий. Без лишнего юмора или сарказма в действиях, только брутальность.`),
|
|
finalePrompt: (wN, lN, loc) => PROMPTS.FINALE_PROMPT_TEMPLATE(wN, lN, loc, `Создай эпическое, но с элементами черного юмора или иронии, завершение битвы в стиле "Mortal Kombat". Победа может быть результатом решающего удара, но с ироничным или саркастическим подтекстом в описании. Без лишнего юмора или сарказма в действиях, только брутальность.`),
|
|
commentatorPrompt: PROMPTS.COMMENTATOR_PROMPT_BASE("интенсивный, брутальный"),
|
|
imageStyle: "brutal 3D fighting game render, dark atmosphere, gore details, high quality, realistic textures",
|
|
damageRange: [25, 60]
|
|
},
|
|
realistic: {
|
|
id: 'realistic',
|
|
name: 'Скучная реальность',
|
|
class: 'theme-realistic',
|
|
defaultVoice: 'shimmer',
|
|
characterPrompt: PROMPTS.CHARACTER_PROMPT_TEMPLATE("Персонаж должен быть обычным человеком, без каких-либо сверхспособностей или эпических качеств. Например: офисный работник, продавец, студент, пенсионер, дворник."),
|
|
locationPrompt: PROMPTS.LOCATION_PROMPT_TEMPLATE("Локация должна быть обычным, ничем не примечательным местом из реального мира, например: общественное место, жилая зона, рабочее пространство, или место для отдыха."),
|
|
battlePrompt: (action, loc, hN, oN, hHP, oHP) => PROMPTS.BATTLE_PROMPT_TEMPLATE(action, loc, hN, oN, hHP, oHP, `Симулируй раунд нелепой, скучной драки в реалистичном стиле. Сосредоточься на неуклюжих движениях, случайных тычках и бытовой ругани. Добавь элементы абсурдного, бытового юмора в описание. Урон должен быть минимальным.`),
|
|
finalePrompt: (wN, lN, loc) => PROMPTS.FINALE_PROMPT_TEMPLATE(wN, lN, loc, `Создай нелепое и скучное завершение драки в реалистичном стиле. Победа может быть по случайности или из-за усталости, а не мастерства. Добавь элементы абсурдного, бытового юмора.`),
|
|
commentatorPrompt: PROMPTS.COMMENTATOR_PROMPT_BASE("скучный, саркастический"),
|
|
imageStyle: "photorealistic, everyday scene, natural lighting, mundane details, high quality, realistic textures",
|
|
damageRange: [1, 10]
|
|
}
|
|
};
|
|
// --- END PROMPT TEMPLATES AND MODE CONFIGURATION ---
|
|
|
|
// Global state variables
|
|
let lastFinaleData = null;
|
|
let lastRoundData = null;
|
|
const VOICE_PREFERENCE_KEY = 'gptArenaVoicePreference';
|
|
|
|
// --- UTILITY FUNCTIONS ---
|
|
function generateId() {
|
|
return 'game_' + Math.random().toString(36).substr(2, 9);
|
|
}
|
|
|
|
function log(...args) {
|
|
console.log('[GPT Arena]', ...args);
|
|
}
|
|
|
|
function showStage(stageId) {
|
|
document.querySelectorAll('.game-stage').forEach(stage => {
|
|
stage.classList.remove('active');
|
|
});
|
|
document.getElementById(stageId).classList.add('active');
|
|
gameState.stage = stageId;
|
|
log('Переход на стадию:', stageId);
|
|
}
|
|
|
|
function triggerVisualEffects() {
|
|
const body = document.body;
|
|
const flashOverlay = document.getElementById('flashOverlay');
|
|
|
|
body.classList.add('shake-effect');
|
|
setTimeout(() => {
|
|
body.classList.remove('shake-effect');
|
|
}, 500);
|
|
|
|
flashOverlay.classList.add('active');
|
|
setTimeout(() => {
|
|
flashOverlay.classList.remove('active');
|
|
}, 200);
|
|
}
|
|
|
|
function addTimelineEvent(title, content, media = null, audioData = null) {
|
|
const timeline = document.getElementById('timelineContent');
|
|
const eventId = 'event_' + Date.now();
|
|
|
|
const eventElement = document.createElement('div');
|
|
eventElement.className = 'timeline-item';
|
|
eventElement.id = eventId;
|
|
eventElement.onclick = function() { toggleTimelineDetails(this); };
|
|
|
|
const contentPreview = content.substring(0, 80) + (content.length > 80 ? '...' : '');
|
|
|
|
eventElement.innerHTML = `
|
|
<div class="timeline-title">${title}</div>
|
|
<div class="timeline-content-preview">${contentPreview}</div>
|
|
<div class="timeline-details">
|
|
<div class="timeline-full-content">${content}</div>
|
|
${media ? `
|
|
<div class="timeline-image-container">
|
|
<div class="image-loader" id="${eventId}_img_loader">
|
|
<div class="image-spinner"></div>
|
|
<div style="color: var(--text-secondary); font-size: 0.9rem;">Загрузка изображения...</div>
|
|
</div>
|
|
<img class="timeline-media" id="${eventId}_img" src="" alt="" style="display:none;">
|
|
</div>` : ''}
|
|
${audioData ? `
|
|
<div class="timeline-audio-container">
|
|
<button onclick="event.stopPropagation(); playTimelineAudio(this, '${audioData.text.replace(/'/g, "\\'")}', '${audioData.voice}', ${audioData.isCommentary});">Воспроизвести аудио</button>
|
|
<audio controls style="display:none;"></audio>
|
|
</div>` : ''}
|
|
</div>
|
|
`;
|
|
|
|
document.querySelectorAll('.timeline-item.current').forEach(item => {
|
|
if (item.id !== eventId) item.classList.remove('current');
|
|
});
|
|
|
|
timeline.appendChild(eventElement);
|
|
eventElement.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
|
|
|
|
if (media) {
|
|
const imageElement = document.getElementById(`${eventId}_img`);
|
|
const loaderElement = document.getElementById(`${eventId}_img_loader`);
|
|
loadImageWithPreloader(imageElement, loaderElement, media.url, null);
|
|
}
|
|
}
|
|
|
|
function toggleTimelineDetails(element) {
|
|
const details = element.querySelector('.timeline-details');
|
|
if (details) {
|
|
details.classList.toggle('expanded');
|
|
if (details.classList.contains('expanded')) {
|
|
const audioButton = details.querySelector('.timeline-audio-container button');
|
|
if (audioButton && !audioButton.dataset.loaded) {
|
|
audioButton.dataset.loaded = true;
|
|
}
|
|
}
|
|
}
|
|
element.classList.toggle('current');
|
|
}
|
|
|
|
async function playTimelineAudio(button, text, voice, isCommentary) {
|
|
const audioContainer = button.parentNode;
|
|
const audioElement = audioContainer.querySelector('audio');
|
|
|
|
button.style.display = 'none';
|
|
audioElement.style.display = 'block';
|
|
|
|
await loadAudioWithPreloader(
|
|
audioElement,
|
|
audioContainer,
|
|
null,
|
|
text,
|
|
'Комментарий события',
|
|
voice,
|
|
() => {
|
|
button.style.display = 'block';
|
|
audioElement.style.display = 'none';
|
|
playTimelineAudio(button, text, voice, isCommentary);
|
|
},
|
|
isCommentary,
|
|
false
|
|
);
|
|
}
|
|
|
|
async function callTextAPI(prompt, systemPrompt, apiParams = {}) {
|
|
const fullPrompt = `${systemPrompt}\n\nЗапрос: ${prompt}`;
|
|
let url = `${API_CONFIG.text}${encodeURIComponent(fullPrompt)}?model=openai`;
|
|
|
|
const queryParams = new URLSearchParams(apiParams);
|
|
if (queryParams.toString()) {
|
|
url += `&${queryParams.toString()}`;
|
|
}
|
|
|
|
log('Запрос к Text API:', url);
|
|
|
|
try {
|
|
const response = await fetch(url);
|
|
let text = await response.text();
|
|
log('Ответ от Text API:', text);
|
|
|
|
if (text.includes('```json')) {
|
|
const match = text.match(/```json\s*([\s\S]*?)\s*```/);
|
|
if (match) text = match[1].trim();
|
|
} else if (text.includes('```')) {
|
|
const match = text.match(/```\s*([\s\S]*?)\s*```/);
|
|
if (match) text = match[1].trim();
|
|
}
|
|
|
|
return JSON.parse(text);
|
|
} catch (error) {
|
|
log('Ошибка Text API:', error);
|
|
throw new Error('Ошибка связи с ИИ: ' + error.message);
|
|
}
|
|
}
|
|
|
|
function generateImageURL(prompt, width = 512, height = 512) {
|
|
const finalPrompt = `${gameState.currentMode.imageStyle}, ${prompt}`;
|
|
return `${API_CONFIG.image}${encodeURIComponent(finalPrompt)}?model=flux&width=${width}&height=${height}&nologo=true&enhance=true&seed=${Date.now()}`;
|
|
}
|
|
|
|
function generateAudioURL(text, voice, isCommentary = false) {
|
|
let finalPrompt = text;
|
|
if (isCommentary) {
|
|
finalPrompt = `${gameState.currentMode.commentatorPrompt} ${text}`;
|
|
}
|
|
const selectedVoice = document.getElementById('voiceSelect').value;
|
|
return `${API_CONFIG.audio}${encodeURIComponent(finalPrompt)}?model=openai-audio&voice=${selectedVoice}&seed=${Date.now()}`;
|
|
}
|
|
|
|
function loadImageWithPreloader(imageElement, loaderElement, url, retryCallback = null) {
|
|
imageElement.style.display = 'none';
|
|
if (loaderElement) {
|
|
loaderElement.classList.remove('hidden');
|
|
loaderElement.querySelector('.image-spinner').style.display = 'block';
|
|
const retryBtn = loaderElement.querySelector('.retry-btn');
|
|
if (retryBtn) retryBtn.style.display = 'none';
|
|
|
|
if (loaderElement.id === 'battleImageLoader') {
|
|
loaderElement.querySelector('div:nth-child(2)').textContent = 'Создаем сцену битвы...';
|
|
} else if (loaderElement.id === 'finaleImageLoader') {
|
|
loaderElement.querySelector('div:nth-child(2)').textContent = 'Создаем финальную сцену...';
|
|
} else if (loaderElement.id === 'locationImageLoader') {
|
|
loaderElement.querySelector('div:nth-child(2)').textContent = 'Создаем изображение локации...';
|
|
} else if (loaderElement.id === 'heroCardImageLoader' || loaderElement.id === 'opponentCardImageLoader') {
|
|
loaderElement.querySelector('div:nth-child(2)').textContent = 'Создаем портрет...';
|
|
} else {
|
|
loaderElement.querySelector('div:nth-child(2)').textContent = 'Загрузка изображения...';
|
|
}
|
|
}
|
|
|
|
const img = new Image();
|
|
img.onload = function() {
|
|
imageElement.src = url;
|
|
imageElement.style.display = 'block';
|
|
if (loaderElement) loaderElement.classList.add('hidden');
|
|
};
|
|
img.onerror = function() {
|
|
log('Ошибка загрузки изображения:', `Failed to load image from ${url}`);
|
|
if (loaderElement) {
|
|
loaderElement.querySelector('.image-spinner').style.display = 'none';
|
|
const retryBtn = loaderElement.querySelector('.retry-btn');
|
|
if (retryBtn) {
|
|
retryBtn.style.display = 'block';
|
|
retryBtn.onclick = retryCallback;
|
|
}
|
|
loaderElement.querySelector('div:nth-child(2)').textContent = 'Ошибка загрузки';
|
|
} else {
|
|
console.error('Failed to load image (no specific loader):', url);
|
|
imageElement.src = 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"><rect width="200" height="200" fill="%23333"/><text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" fill="%23aaa" font-size="20">Ошибка загрузки</text></svg>';
|
|
imageElement.style.display = 'block';
|
|
}
|
|
};
|
|
img.src = url;
|
|
}
|
|
|
|
async function loadAudioWithPreloader(audioElement, playerElement, loaderElement, textToSpeak, audioTitle, voice = 'alloy', retryCallback = null, isCommentary = false, manageVisibility = true) {
|
|
if (manageVisibility && loaderElement && playerElement) {
|
|
playerElement.classList.remove('show');
|
|
loaderElement.classList.remove('hidden');
|
|
loaderElement.querySelector('.image-spinner').style.display = 'block';
|
|
const retryBtn = loaderElement.querySelector('.retry-btn');
|
|
if (retryBtn) retryBtn.style.display = 'none';
|
|
loaderElement.querySelector('div:nth-child(2)').textContent = `Создаем озвучку: "${audioTitle.substring(0, 50)}${audioTitle.length > 50 ? '...' : ''}"...`;
|
|
} else {
|
|
audioElement.style.display = 'none';
|
|
}
|
|
|
|
const audioUrl = generateAudioURL(textToSpeak, voice, isCommentary);
|
|
log('Запрос аудио к API:', audioUrl);
|
|
|
|
try {
|
|
const response = await fetch(audioUrl);
|
|
if (!response.ok) {
|
|
const errorText = await response.text();
|
|
throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
|
|
}
|
|
const audioBlob = await response.blob();
|
|
const objectUrl = URL.createObjectURL(audioBlob);
|
|
|
|
if (audioElement.src && audioElement.src.startsWith('blob:')) {
|
|
URL.revokeObjectURL(audioElement.src);
|
|
}
|
|
|
|
audioElement.src = objectUrl;
|
|
audioElement.load();
|
|
|
|
audioElement.oncanplaythrough = function() {
|
|
if (manageVisibility && loaderElement && playerElement) {
|
|
loaderElement.classList.add('hidden');
|
|
playerElement.classList.add('show');
|
|
} else {
|
|
audioElement.style.display = 'block';
|
|
}
|
|
|
|
const autoplayToggle = document.getElementById('autoplayToggle');
|
|
if (autoplayToggle && autoplayToggle.checked && manageVisibility) {
|
|
audioElement.play().catch(e => log('Автовоспроизведение заблокировано:', e));
|
|
}
|
|
if (!manageVisibility) {
|
|
audioElement.play().catch(e => log('Автовоспроизведение аудио таймлайна заблокировано:', e));
|
|
}
|
|
};
|
|
|
|
audioElement.onerror = function(e) {
|
|
log('Ошибка загрузки аудио:', `Failed to load audio from ${audioUrl}`, e);
|
|
if (manageVisibility && loaderElement) {
|
|
loaderElement.querySelector('.image-spinner').style.display = 'none';
|
|
const retryBtn = loaderElement.querySelector('.retry-btn');
|
|
if (retryBtn) {
|
|
retryBtn.style.display = 'block';
|
|
retryBtn.onclick = retryCallback;
|
|
}
|
|
loaderElement.querySelector('div:nth-child(2)').textContent = 'Ошибка получения аудио';
|
|
} else {
|
|
if (retryCallback && e.target.parentNode.querySelector('button')) {
|
|
const btn = e.target.parentNode.querySelector('button');
|
|
btn.textContent = 'Ошибка аудио. Повторить?';
|
|
btn.style.backgroundColor = 'var(--error)';
|
|
btn.style.display = 'block';
|
|
audioElement.style.display = 'none';
|
|
}
|
|
}
|
|
};
|
|
|
|
} catch (error) {
|
|
log('Ошибка получения аудио (fetch failed):', error);
|
|
if (manageVisibility && loaderElement) {
|
|
loaderElement.querySelector('.image-spinner').style.display = 'none';
|
|
const retryBtn = loaderElement.querySelector('.retry-btn');
|
|
if (retryBtn) {
|
|
retryBtn.style.display = 'block';
|
|
retryBtn.onclick = retryCallback;
|
|
}
|
|
loaderElement.querySelector('div:nth-child(2)').textContent = 'Ошибка получения аудио';
|
|
} else {
|
|
if (retryCallback && button) {
|
|
button.textContent = 'Ошибка аудио. Повторить?';
|
|
button.style.backgroundColor = 'var(--error)';
|
|
button.style.display = 'block';
|
|
audioElement.style.display = 'none';
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// --- MODE SELECTION LOGIC ---
|
|
function selectMode(modeId) {
|
|
gameState.currentMode = MODES[modeId];
|
|
log(`Выбран режим: ${gameState.currentMode.name}`);
|
|
addTimelineEvent('✨ Выбран режим Арены', `Вы будете сражаться в режиме "${gameState.currentMode.name}"`);
|
|
|
|
document.body.classList.remove('theme-fantasy', 'theme-brutal', 'theme-realistic');
|
|
document.body.classList.add(gameState.currentMode.class);
|
|
|
|
document.getElementById('currentModeDisplay').textContent = `Режим: ${gameState.currentMode.name}`;
|
|
|
|
const userVoicePreference = localStorage.getItem(VOICE_PREFERENCE_KEY);
|
|
const voiceSelect = document.getElementById('voiceSelect');
|
|
if (!userVoicePreference) {
|
|
voiceSelect.value = gameState.currentMode.defaultVoice;
|
|
} else {
|
|
voiceSelect.value = userVoicePreference;
|
|
}
|
|
|
|
showStage('start');
|
|
}
|
|
|
|
function saveVoicePreference() {
|
|
const voiceSelect = document.getElementById('voiceSelect');
|
|
localStorage.setItem(VOICE_PREFERENCE_KEY, voiceSelect.value);
|
|
log('Настройки: голос сохранен:', voiceSelect.value);
|
|
}
|
|
|
|
async function generateRandomHero() {
|
|
const diceBtn = document.querySelector('#start .dice-btn');
|
|
diceBtn.classList.add('rolling');
|
|
|
|
try {
|
|
const randomPrompt = `Создай случайного героя для ${gameState.currentMode.name} битвы (Random: ${Date.now()})`;
|
|
const randomData = await callTextAPI(randomPrompt, gameState.currentMode.characterPrompt, {seed: Date.now()});
|
|
document.getElementById('heroInput').value = `${randomData.name} - ${randomData.description}`;
|
|
addTimelineEvent('🎲 Случайный герой', `Сгенерирован: ${randomData.name}`);
|
|
} catch (error) {
|
|
log('Ошибка генерации случайного героя:', error);
|
|
document.getElementById('heroInput').value = 'Загадочный рыцарь в черных доспехах с пылающим мечом';
|
|
} finally {
|
|
diceBtn.classList.remove('rolling');
|
|
}
|
|
}
|
|
|
|
async function generateRandomOpponent() {
|
|
const diceBtn = document.querySelector('#customOpponent .dice-btn');
|
|
diceBtn.classList.add('rolling');
|
|
|
|
try {
|
|
const randomPrompt = `Создай случайного противника для ${gameState.currentMode.name} битвы (Random: ${Date.now()})`;
|
|
const randomData = await callTextAPI(randomPrompt, gameState.currentMode.characterPrompt, {seed: Date.now()});
|
|
document.getElementById('opponentInput').value = `${randomData.name} - ${randomData.description}`;
|
|
addTimelineEvent('🎲 Случайный противник', `Сгенерирован: ${randomData.name}`);
|
|
} catch (error) {
|
|
log('Ошибка генерации случайного противника:', error);
|
|
document.getElementById('opponentInput').value = 'Древний демон с огненными крыльями и когтями тьмы';
|
|
} finally {
|
|
diceBtn.classList.remove('rolling');
|
|
}
|
|
}
|
|
|
|
async function generateRandomLocation() {
|
|
const diceBtn = document.querySelector('#customLocation .dice-btn');
|
|
diceBtn.classList.add('rolling');
|
|
|
|
try {
|
|
const uniquePrompt = `Создай случайную локацию для ${gameState.currentMode.name} битвы (Timestamp: ${Date.now()})`;
|
|
const randomData = await callTextAPI(uniquePrompt, gameState.currentMode.locationPrompt, {seed: Date.now()});
|
|
document.getElementById('locationInput').value = `${randomData.name} - ${randomData.description}`;
|
|
addTimelineEvent('🎲 Случайная локация', `Сгенерирована: ${randomData.name}`);
|
|
} catch (error) {
|
|
log('Ошибка генерации случайной локации:', error);
|
|
document.getElementById('locationInput').value = 'Колизей в руинах, где некогда сражались великие герои';
|
|
} finally {
|
|
diceBtn.classList.remove('rolling');
|
|
}
|
|
}
|
|
|
|
function createCharacterCard(character, cardId, imgWidth, imgHeight) {
|
|
const card = document.getElementById(cardId);
|
|
const avatarId = cardId + 'Avatar';
|
|
const imageLoaderId = cardId + 'ImageLoader';
|
|
|
|
card.innerHTML = `
|
|
<div class="character-info">
|
|
<div class="character-avatar-container">
|
|
<div class="image-loader" id="${imageLoaderId}">
|
|
<div class="image-spinner"></div>
|
|
<div style="color: var(--text-secondary); font-size: 0.9rem;">Создаем портрет...</div>
|
|
<button class="retry-btn" onclick="retryImage('${cardId}')" style="display: none;">Повторить</button>
|
|
</div>
|
|
<img class="character-avatar" id="${avatarId}" alt="${character.name}">
|
|
</div>
|
|
<div class="character-details">
|
|
<h3>${character.name}</h3>
|
|
<div class="character-description">${character.description}</div>
|
|
<div class="stats-grid">
|
|
<div class="stat-item">
|
|
<div class="stat-name">Сила</div>
|
|
<div class="stat-value">${character.stats.strength}</div>
|
|
</div>
|
|
<div class="stat-item">
|
|
<div class="stat-name">Ловкость</div>
|
|
<div class="stat-value">${character.stats.agility}</div>
|
|
</div>
|
|
<div class="stat-item">
|
|
<div class="stat-name">Интеллект</div>
|
|
<div class="stat-value">${character.stats.intelligence}</div>
|
|
</div>
|
|
<div class="stat-item">
|
|
<div class="stat-name">Выносливость</div>
|
|
<div class="stat-value">${character.stats.endurance}</div>
|
|
</div>
|
|
<div class="stat-item">
|
|
<div class="stat-name">Магия</div>
|
|
<div class="stat-value">${character.stats.magic}</div>
|
|
</div>
|
|
<div class="stat-item">
|
|
<div class="stat-name">Удача</div>
|
|
<div class="stat-value">${character.stats.luck}</div>
|
|
</div>
|
|
</div>
|
|
<div class="abilities">
|
|
<h4>Способности:</h4>
|
|
${character.abilities.map((ability, index) => `<div class="ability" data-ability-index="${index}">${ability}</div>`).join('')}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
`;
|
|
|
|
const imageElement = document.getElementById(avatarId);
|
|
const loaderElement = document.getElementById(imageLoaderId);
|
|
const imageUrl = generateImageURL(character.visualPrompt, imgWidth, imgHeight);
|
|
|
|
character.imageUrl = imageUrl;
|
|
character.imageWidth = imgWidth;
|
|
character.imageHeight = imgHeight;
|
|
|
|
loadImageWithPreloader(imageElement, loaderElement, imageUrl, () => retryImage(cardId));
|
|
}
|
|
|
|
function retryImage(cardId) {
|
|
let character;
|
|
let imageElementId;
|
|
let imageLoaderId;
|
|
|
|
if (cardId === 'heroCard') {
|
|
character = gameState.hero;
|
|
imageElementId = 'heroCardAvatar';
|
|
imageLoaderId = 'heroCardImageLoader';
|
|
} else if (cardId === 'opponentCard') {
|
|
character = gameState.opponent;
|
|
imageElementId = 'opponentCardAvatar';
|
|
imageLoaderId = 'opponentCardImageLoader';
|
|
} else {
|
|
return;
|
|
}
|
|
|
|
if (character) {
|
|
const imageElement = document.getElementById(imageElementId);
|
|
const loaderElement = document.getElementById(imageLoaderId);
|
|
loadImageWithPreloader(imageElement, loaderElement, generateImageURL(character.visualPrompt, character.imageWidth, character.imageHeight), () => retryImage(cardId));
|
|
}
|
|
}
|
|
|
|
async function createHero() {
|
|
const heroInput = document.getElementById('heroInput').value.trim();
|
|
if (!heroInput) {
|
|
alert('Пожалуйста, опишите вашего героя');
|
|
return;
|
|
}
|
|
|
|
gameState.lastAction = 'createHero';
|
|
showStage('heroLoading');
|
|
addTimelineEvent('⚔️ Создание героя', `Создаем героя: "${heroInput.substring(0, 50)}${heroInput.length > 50 ? '...' : ''}"`);
|
|
|
|
try {
|
|
const heroData = await callTextAPI(`Создай персонажа на основе описания: "${heroInput}"`, gameState.currentMode.characterPrompt);
|
|
|
|
gameState.hero = heroData;
|
|
gameState.gameId = generateId();
|
|
|
|
log('Герой создан:', heroData);
|
|
|
|
createCharacterCard(heroData, 'heroCard', 768, 1280);
|
|
|
|
showStage('heroPresentation');
|
|
|
|
const selectedVoice = document.getElementById('voiceSelect').value;
|
|
loadAudioWithPreloader(
|
|
document.getElementById('heroAudio'),
|
|
document.getElementById('heroAudioPlayer'),
|
|
document.getElementById('heroAudioLoader'),
|
|
`Встречайте героя ${heroData.name}! ${heroData.description}`,
|
|
'Описание героя',
|
|
selectedVoice,
|
|
retryHeroAudio,
|
|
false,
|
|
true
|
|
);
|
|
|
|
addTimelineEvent('✅ Герой создан', `${heroData.name} готов к бою!`, { type: 'image', url: heroData.imageUrl }, {
|
|
text: `Встречайте героя ${heroData.name}! ${heroData.description}`,
|
|
voice: selectedVoice,
|
|
isCommentary: false,
|
|
audioTitle: 'Описание героя'
|
|
});
|
|
|
|
} catch (error) {
|
|
log('Ошибка создания героя:', error);
|
|
addTimelineEvent('❌ Ошибка', 'Не удалось создать героя');
|
|
showStage('heroError');
|
|
}
|
|
}
|
|
|
|
function retryCreateHero() {
|
|
createHero();
|
|
}
|
|
|
|
function retryHeroAudio() {
|
|
if (gameState.hero) {
|
|
const selectedVoice = document.getElementById('voiceSelect').value;
|
|
loadAudioWithPreloader(
|
|
document.getElementById('heroAudio'),
|
|
document.getElementById('heroAudioPlayer'),
|
|
document.getElementById('heroAudioLoader'),
|
|
`Встречайте героя ${gameState.hero.name}! ${gameState.hero.description}`,
|
|
'Описание героя',
|
|
selectedVoice,
|
|
retryHeroAudio,
|
|
false,
|
|
true
|
|
);
|
|
}
|
|
}
|
|
|
|
function chooseOpponent() {
|
|
showStage('opponentChoice');
|
|
addTimelineEvent('🎯 Выбор противника', 'Выбираем достойного противника для битвы');
|
|
}
|
|
|
|
async function createAutoOpponent() {
|
|
gameState.lastAction = 'createAutoOpponent';
|
|
showStage('opponentLoading');
|
|
addTimelineEvent('🤖 Автоматический противник', 'Система подбирает противника автоматически');
|
|
|
|
try {
|
|
const opponentData = await callTextAPI(`Создай достойного противника для героя ${gameState.hero.name}. Противник должен быть контрастным но равным по силе. (Random: ${Date.now()})`, gameState.currentMode.characterPrompt);
|
|
|
|
const imageUrl = generateImageURL(opponentData.visualPrompt, 768, 1280);
|
|
opponentData.imageUrl = imageUrl;
|
|
|
|
gameState.opponent = opponentData;
|
|
|
|
log('Противник создан:', opponentData);
|
|
|
|
createCharacterCard(opponentData, 'opponentCard', 768, 1280);
|
|
|
|
showStage('opponentPresentation');
|
|
|
|
const selectedVoice = document.getElementById('voiceSelect').value;
|
|
loadAudioWithPreloader(
|
|
document.getElementById('opponentAudio'),
|
|
document.getElementById('opponentAudioPlayer'),
|
|
document.getElementById('opponentAudioLoader'),
|
|
`А вот и противник! ${opponentData.name}! ${opponentData.description}`,
|
|
'Описание противника',
|
|
selectedVoice,
|
|
retryOpponentAudio,
|
|
false,
|
|
true
|
|
);
|
|
|
|
addTimelineEvent('✅ Противник создан', `${opponentData.name} бросает вызов!`, { type: 'image', url: opponentData.imageUrl }, {
|
|
text: `А вот и противник! ${opponentData.name}! ${opponentData.description}`,
|
|
voice: selectedVoice,
|
|
isCommentary: false,
|
|
audioTitle: 'Описание противника'
|
|
});
|
|
|
|
} catch (error) {
|
|
log('Ошибка создания противника:', error);
|
|
addTimelineEvent('❌ Ошибка', 'Не удалось создать противника');
|
|
showStage('opponentError');
|
|
}
|
|
}
|
|
|
|
function createCustomOpponent() {
|
|
showStage('customOpponent');
|
|
addTimelineEvent('✍️ Кастомный противник', 'Создаем собственного противника');
|
|
}
|
|
|
|
async function createOpponent() {
|
|
const opponentInput = document.getElementById('opponentInput').value.trim();
|
|
if (!opponentInput) {
|
|
alert('Пожалуйста, опишите противника');
|
|
return;
|
|
}
|
|
|
|
gameState.lastAction = 'createOpponent';
|
|
showStage('opponentLoading');
|
|
addTimelineEvent('⚔️ Создание противника', `Создаем противника: "${opponentInput.substring(0, 50)}${opponentInput.length > 50 ? '...' : ''}"`);
|
|
|
|
try {
|
|
const opponentData = await callTextAPI(`Создай персонажа на основе описания: "${opponentInput}"`, gameState.currentMode.characterPrompt);
|
|
|
|
const imageUrl = generateImageURL(opponentData.visualPrompt, 768, 1280);
|
|
opponentData.imageUrl = imageUrl;
|
|
|
|
gameState.opponent = opponentData;
|
|
|
|
log('Кастомный противник создан:', opponentData);
|
|
|
|
createCharacterCard(opponentData, 'opponentCard', 768, 1280);
|
|
|
|
showStage('opponentPresentation');
|
|
|
|
const selectedVoice = document.getElementById('voiceSelect').value;
|
|
loadAudioWithPreloader(
|
|
document.getElementById('opponentAudio'),
|
|
document.getElementById('opponentAudioPlayer'),
|
|
document.getElementById('opponentAudioLoader'),
|
|
`А вот и противник! ${opponentData.name}! ${opponentData.description}`,
|
|
'Описание противника',
|
|
selectedVoice,
|
|
retryOpponentAudio,
|
|
false,
|
|
true
|
|
);
|
|
|
|
addTimelineEvent('✅ Противник создан', `${opponentData.name} готов к схватке!`, { type: 'image', url: opponentData.imageUrl }, {
|
|
text: `А вот и противник! ${opponentData.name}! ${opponentData.description}`,
|
|
voice: selectedVoice,
|
|
isCommentary: false,
|
|
audioTitle: 'Описание противника'
|
|
});
|
|
|
|
} catch (error) {
|
|
log('Ошибка создания противника:', error);
|
|
addTimelineEvent('❌ Ошибка', 'Не удалось создать противника');
|
|
showStage('opponentError');
|
|
}
|
|
}
|
|
|
|
function retryCreateOpponent() {
|
|
if (gameState.lastAction === 'createAutoOpponent') {
|
|
createAutoOpponent();
|
|
} else {
|
|
createOpponent();
|
|
}
|
|
}
|
|
|
|
function retryOpponentAudio() {
|
|
if (gameState.opponent) {
|
|
const selectedVoice = document.getElementById('voiceSelect').value;
|
|
loadAudioWithPreloader(
|
|
document.getElementById('opponentAudio'),
|
|
document.getElementById('opponentAudioPlayer'),
|
|
document.getElementById('opponentAudioLoader'),
|
|
`А вот и противник! ${gameState.opponent.name}! ${gameState.opponent.description}`,
|
|
'Описание противника',
|
|
selectedVoice,
|
|
retryOpponentAudio,
|
|
false,
|
|
true
|
|
);
|
|
}
|
|
}
|
|
|
|
// NEW: Location functions
|
|
function chooseLocation() {
|
|
showStage('locationChoice');
|
|
addTimelineEvent('🗺️ Выбор локации', 'Приготовьтесь выбрать место битвы');
|
|
}
|
|
|
|
async function createAutoLocation() {
|
|
gameState.lastAction = 'createAutoLocation';
|
|
showStage('locationLoading');
|
|
addTimelineEvent('🤖 Автоматическая локация', 'Система подбирает случайную локацию');
|
|
try {
|
|
const uniquePrompt = `Создай случайную локацию для ${gameState.currentMode.name} битвы (Timestamp: ${Date.now()})`;
|
|
const locationData = await callTextAPI(uniquePrompt, gameState.currentMode.locationPrompt, {seed: Date.now()});
|
|
gameState.location = locationData;
|
|
log('Локация создана:', locationData);
|
|
addTimelineEvent('✅ Локация выбрана', `${locationData.name} - место вашей следующей битвы!`, { type: 'image', url: generateImageURL(locationData.visualPrompt, 1280, 768) });
|
|
startBattleSetup();
|
|
} catch (error) {
|
|
log('Ошибка создания локации:', error);
|
|
addTimelineEvent('❌ Ошибка', 'Не удалось создать локацию');
|
|
showStage('locationError');
|
|
}
|
|
}
|
|
|
|
function createCustomLocation() {
|
|
showStage('customLocation');
|
|
addTimelineEvent('✍️ Кастомная локация', 'Введите описание места битвы');
|
|
}
|
|
|
|
async function createLocation() {
|
|
const locationInput = document.getElementById('locationInput').value.trim();
|
|
if (!locationInput) {
|
|
alert('Пожалуйста, опишите локацию');
|
|
return;
|
|
}
|
|
gameState.lastAction = 'createLocation';
|
|
showStage('locationLoading');
|
|
addTimelineEvent('🗺️ Создание локации', `Создаем локацию: "${locationInput.substring(0, 50)}${locationInput.length > 50 ? '...' : ''}"`);
|
|
try {
|
|
const locationData = await callTextAPI(`Создай локацию на основе описания: "${locationInput}"`, gameState.currentMode.locationPrompt);
|
|
gameState.location = locationData;
|
|
log('Кастомная локация создана:', locationData);
|
|
addTimelineEvent('✅ Локация выбрана', `${locationData.name} - место вашей следующей битвы!`, { type: 'image', url: generateImageURL(locationData.visualPrompt, 1280, 768) });
|
|
startBattleSetup();
|
|
} catch (error) {
|
|
log('Ошибка создания локации:', error);
|
|
addTimelineEvent('❌ Ошибка', 'Не удалось создать локацию');
|
|
showStage('locationError');
|
|
}
|
|
}
|
|
|
|
function retryCreateLocation() {
|
|
if (gameState.lastAction === 'createAutoLocation') {
|
|
createAutoLocation();
|
|
} else {
|
|
createLocation();
|
|
}
|
|
}
|
|
// END NEW Location functions
|
|
|
|
// HP Color Interpolation Logic
|
|
function getInterpolatedColor(percentage) {
|
|
const p = percentage / 100;
|
|
const hueGreen = 120;
|
|
const hueRed = 0;
|
|
const hue = hueGreen * p + hueRed * (1 - p);
|
|
const saturation = 70;
|
|
const lightness = 45;
|
|
return `hsl(${hue}, ${saturation}%, ${lightness}%)`;
|
|
}
|
|
|
|
function updateHPDisplay(heroHP, opponentHP) {
|
|
const heroHPFill = document.getElementById('heroHP');
|
|
const opponentHPFill = document.getElementById('opponentHP');
|
|
const heroAvatar = document.getElementById('heroAvatar');
|
|
const opponentAvatar = document.getElementById('opponentAvatar');
|
|
const heroHPText = document.getElementById('heroHPText');
|
|
const opponentHPText = document.getElementById('opponentHPText');
|
|
|
|
heroHPFill.style.width = `${heroHP}%`;
|
|
opponentHPFill.style.width = `${opponentHP}%`;
|
|
|
|
heroHPFill.style.backgroundColor = getInterpolatedColor(heroHP);
|
|
opponentHPFill.style.backgroundColor = getInterpolatedColor(opponentHP);
|
|
|
|
heroAvatar.style.borderColor = getInterpolatedColor(heroHP);
|
|
opponentAvatar.style.borderColor = getInterpolatedColor(opponentHP);
|
|
|
|
heroHPText.textContent = `HP: ${heroHP}/100`;
|
|
opponentHPText.textContent = `HP: ${opponentHP}/100`;
|
|
}
|
|
|
|
function setBattleActionsEnabled(enabled) {
|
|
const actionButtons = document.querySelectorAll('#battleActions .btn');
|
|
actionButtons.forEach(btn => btn.disabled = !enabled);
|
|
document.getElementById('customActionInput').disabled = !enabled;
|
|
document.querySelector('#battleActions .input-with-button button').disabled = !enabled;
|
|
}
|
|
|
|
function startBattleSetup() {
|
|
if (!gameState.hero || !gameState.opponent || !gameState.location || !gameState.currentMode) {
|
|
log('Ошибка: Отсутствуют данные для начала битвы.');
|
|
showStage('modeSelection');
|
|
return;
|
|
}
|
|
|
|
document.getElementById('heroAvatar').src = gameState.hero.imageUrl;
|
|
document.getElementById('heroName').textContent = gameState.hero.name;
|
|
document.getElementById('opponentAvatar').src = gameState.opponent.imageUrl;
|
|
document.getElementById('opponentName').textContent = gameState.opponent.name;
|
|
|
|
gameState.currentRound = 1;
|
|
gameState.currentHP = { hero: 100, opponent: 100 };
|
|
gameState.battleLog = [];
|
|
gameState.locationAnnounced = false; // Reset for new battle
|
|
|
|
updateHPDisplay(100, 100);
|
|
|
|
addTimelineEvent('🔥 Битва началась!', `${gameState.hero.name} vs ${gameState.opponent.name} на ${gameState.location.name}`);
|
|
|
|
showStage('battle');
|
|
document.querySelector('.fighter.hero .fighter-avatar').classList.add('pulsing');
|
|
document.querySelector('.fighter.opponent .fighter-avatar').classList.add('pulsing');
|
|
|
|
const battleImage = document.getElementById('battleImage');
|
|
const battleImageLoader = document.getElementById('battleImageLoader');
|
|
const locationImageUrl = generateImageURL(gameState.location.visualPrompt, 1280, 768);
|
|
|
|
battleImageLoader.classList.remove('hidden');
|
|
loadImageWithPreloader(battleImage, battleImageLoader, locationImageUrl, null);
|
|
|
|
prepareRound();
|
|
}
|
|
|
|
function performAction(action) {
|
|
gameState.heroAction = action;
|
|
setBattleActionsEnabled(false); // Disable actions while processing
|
|
document.getElementById('battleActions').style.display = 'none';
|
|
|
|
simulateRound();
|
|
}
|
|
|
|
function performCustomAction() {
|
|
const customActionText = document.getElementById('customActionInput').value.trim();
|
|
if (customActionText) {
|
|
performAction(`custom:${customActionText}`);
|
|
} else {
|
|
alert('Пожалуйста, опишите ваше кастомное действие.');
|
|
}
|
|
}
|
|
|
|
function prepareRound() {
|
|
document.getElementById('roundTitle').textContent = `Раунд ${gameState.currentRound}`;
|
|
document.getElementById('arenaName').textContent = `Арена: ${gameState.location.name}`;
|
|
|
|
// ALWAYS enable actions when preparing a round, regardless of audio state.
|
|
setBattleActionsEnabled(true);
|
|
document.getElementById('battleActions').style.display = 'flex'; // Show actions
|
|
|
|
// Handle initial location announcement
|
|
if (gameState.currentRound === 1 && !gameState.locationAnnounced) {
|
|
document.getElementById('battleDescription').textContent = gameState.location.description;
|
|
document.getElementById('battleAudioTitle').textContent = '🎵 Описание локации';
|
|
|
|
const selectedVoice = document.getElementById('voiceSelect').value;
|
|
const audioElement = document.getElementById('battleAudio');
|
|
const playerElement = document.getElementById('battleAudioPlayer');
|
|
const loaderElement = document.getElementById('battleAudioLoader');
|
|
|
|
// Load and play audio. Buttons remain enabled.
|
|
loadAudioWithPreloader(
|
|
audioElement,
|
|
playerElement,
|
|
loaderElement,
|
|
gameState.location.description,
|
|
'Описание локации',
|
|
selectedVoice,
|
|
retryBattleAudio,
|
|
true,
|
|
true
|
|
);
|
|
gameState.locationAnnounced = true; // Mark as announced
|
|
} else {
|
|
// For subsequent rounds or if already announced
|
|
document.getElementById('battleDescription').textContent = 'Выберите действие для вашего героя!';
|
|
document.getElementById('battleAudioTitle').textContent = '🎵 Комментарий раунда';
|
|
// Ensure audio loader is hidden for subsequent rounds if not needed
|
|
document.getElementById('battleAudioLoader').classList.add('hidden');
|
|
document.getElementById('battleAudioPlayer').classList.remove('show');
|
|
}
|
|
|
|
document.getElementById('nextRoundBtn').style.display = 'none';
|
|
document.getElementById('finaleBtn').style.display = 'none';
|
|
|
|
document.getElementById('customActionInput').value = '';
|
|
|
|
const abilityBtn = document.getElementById('abilityBtn');
|
|
if (gameState.hero.abilities && gameState.hero.abilities.length > 0) {
|
|
abilityBtn.style.display = 'block';
|
|
abilityBtn.textContent = `✨ Использовать способность (${gameState.hero.abilities[0].substring(0,20)}...)`;
|
|
} else {
|
|
abilityBtn.style.display = 'none';
|
|
}
|
|
}
|
|
|
|
function displayDamageNumber(fighterElement, damageValue) {
|
|
const numberElement = document.createElement('span');
|
|
numberElement.textContent = `-${damageValue}`;
|
|
numberElement.className = 'damage-number';
|
|
fighterElement.appendChild(numberElement);
|
|
|
|
numberElement.addEventListener('animationend', () => {
|
|
numberElement.remove();
|
|
});
|
|
}
|
|
|
|
async function simulateRound() {
|
|
gameState.lastAction = 'simulateRound';
|
|
showStage('roundLoading');
|
|
document.getElementById('roundLoadingText').textContent = `Симулируем раунд ${gameState.currentRound}...`;
|
|
|
|
addTimelineEvent(`⚔️ Раунд ${gameState.currentRound}`, `Симулируем ход битвы, герой выбрал: ${gameState.heroAction}`);
|
|
|
|
try {
|
|
const [minDamage, maxDamage] = gameState.currentMode.damageRange;
|
|
|
|
const battlePrompt = gameState.currentMode.battlePrompt(
|
|
getHeroActionDescriptionForPrompt(gameState.heroAction), // Helper function for detailed action description
|
|
gameState.location.visualPrompt,
|
|
gameState.hero.name,
|
|
gameState.opponent.name,
|
|
gameState.currentHP.hero,
|
|
gameState.currentHP.opponent
|
|
);
|
|
const roundData = await callTextAPI(`Проведи раунд ${gameState.currentRound} битвы`, battlePrompt);
|
|
|
|
let heroDamage = Math.max(minDamage, Math.min(maxDamage, parseInt(roundData.damage?.hero || 0)));
|
|
let opponentDamage = Math.max(minDamage, Math.min(maxDamage, parseInt(roundData.damage?.opponent || 0)));
|
|
|
|
if (gameState.heroAction === 'defend') {
|
|
heroDamage = Math.floor(heroDamage * 0.5);
|
|
}
|
|
|
|
gameState.currentHP.hero -= heroDamage;
|
|
gameState.currentHP.opponent -= opponentDamage;
|
|
|
|
gameState.currentHP.hero = Math.max(0, gameState.currentHP.hero);
|
|
gameState.currentHP.opponent = Math.max(0, gameState.currentHP.opponent);
|
|
|
|
log(`Раунд ${gameState.currentRound} завершен:`, roundData);
|
|
log(`HP: Hero ${gameState.currentHP.hero}, Opponent ${gameState.currentHP.opponent}`);
|
|
|
|
lastRoundData = roundData;
|
|
gameState.battleLog.push(roundData);
|
|
|
|
showRoundResult(roundData, heroDamage, opponentDamage);
|
|
|
|
} catch (error) {
|
|
log('Ошибка симуляции раунда:', error);
|
|
addTimelineEvent('❌ Ошибка', 'Ошибка симуляции раунда');
|
|
showStage('roundError');
|
|
}
|
|
}
|
|
|
|
function getHeroActionDescriptionForPrompt(action) {
|
|
if (action === 'attack') {
|
|
return 'провел мощную атаку, стремясь нанести максимальный урон';
|
|
} else if (action === 'defend') {
|
|
return 'ушел в глухую оборону, ожидая атаки противника и минимизируя входящий урон';
|
|
} else if (action.startsWith('ability')) {
|
|
const abilityIndex = parseInt(action.replace('ability', '')) - 1;
|
|
return `использовал свою особую способность "${gameState.hero.abilities[abilityIndex]}"`;
|
|
} else if (action.startsWith('custom:')) {
|
|
return `выполнил особое действие: "${action.substring(7)}"`;
|
|
}
|
|
return 'сражался как обычно, без специфических действий';
|
|
}
|
|
|
|
function retryRound() {
|
|
simulateRound();
|
|
}
|
|
|
|
function showRoundResult(roundData, heroDamage = 0, opponentDamage = 0) {
|
|
showStage('battle');
|
|
|
|
const roundTitleText = `Раунд ${gameState.currentRound}`;
|
|
document.getElementById('roundTitle').textContent = roundTitleText;
|
|
document.getElementById('arenaName').textContent = `Арена: ${gameState.location.name}`;
|
|
document.getElementById('battleDescription').textContent = roundData.description;
|
|
document.getElementById('battleAudioTitle').textContent = `🎵 Комментарий ${roundTitleText}`;
|
|
|
|
updateHPDisplay(gameState.currentHP.hero, gameState.currentHP.opponent);
|
|
|
|
const heroFighterElement = document.querySelector('.fighter.hero');
|
|
const opponentFighterElement = document.querySelector('.fighter.opponent');
|
|
|
|
if (heroDamage > 0) {
|
|
heroFighterElement.querySelector('.fighter-avatar').classList.add('damaged');
|
|
displayDamageNumber(heroFighterElement, heroDamage);
|
|
setTimeout(() => heroFighterElement.querySelector('.fighter-avatar').classList.remove('damaged'), 500);
|
|
}
|
|
if (opponentDamage > 0) {
|
|
opponentFighterElement.querySelector('.fighter-avatar').classList.add('damaged');
|
|
displayDamageNumber(opponentFighterElement, opponentDamage);
|
|
setTimeout(() => opponentFighterElement.querySelector('.fighter-avatar').classList.remove('damaged'), 500);
|
|
}
|
|
if (heroDamage > 0 || opponentDamage > 0) {
|
|
triggerVisualEffects();
|
|
}
|
|
|
|
if (roundData.visualPrompt) {
|
|
const battleImageUrl = generateImageURL(roundData.visualPrompt, 1280, 768);
|
|
const battleImage = document.getElementById('battleImage');
|
|
const battleLoader = document.getElementById('battleImageLoader');
|
|
|
|
loadImageWithPreloader(battleImage, battleLoader, battleImageUrl, retryBattleImage);
|
|
|
|
addTimelineEvent(`✅ ${roundTitleText} завершен`, roundData.description, { type: 'image', url: battleImageUrl }, {
|
|
text: `В ${roundTitleText}! ${roundData.description}`,
|
|
voice: document.getElementById('voiceSelect').value,
|
|
isCommentary: true,
|
|
audioTitle: `Комментарий раунда ${gameState.currentRound}`
|
|
});
|
|
|
|
}
|
|
|
|
const selectedVoice = document.getElementById('voiceSelect').value;
|
|
const audioElement = document.getElementById('battleAudio');
|
|
const playerElement = document.getElementById('battleAudioPlayer');
|
|
const loaderElement = document.getElementById('battleAudioLoader');
|
|
|
|
const textForCommentary = `В ${roundTitleText}! ${roundData.description}`;
|
|
|
|
loadAudioWithPreloader(
|
|
audioElement,
|
|
playerElement,
|
|
loaderElement,
|
|
textForCommentary,
|
|
`Комментарий раунда ${gameState.currentRound}`,
|
|
selectedVoice,
|
|
retryBattleAudio,
|
|
true,
|
|
true
|
|
);
|
|
|
|
if (gameState.currentHP.hero > 0 && gameState.currentHP.opponent > 0 && gameState.currentRound < 3) {
|
|
document.getElementById('nextRoundBtn').style.display = 'block';
|
|
document.getElementById('finaleBtn').style.display = 'none';
|
|
} else {
|
|
document.getElementById('nextRoundBtn').style.display = 'none';
|
|
document.getElementById('finaleBtn').style.display = 'block';
|
|
document.querySelector('.fighter.hero .fighter-avatar').classList.remove('pulsing');
|
|
document.querySelector('.fighter.opponent .fighter-avatar').classList.remove('pulsing');
|
|
}
|
|
}
|
|
|
|
function nextRound() {
|
|
gameState.currentRound++;
|
|
document.getElementById('nextRoundBtn').style.display = 'none';
|
|
prepareRound();
|
|
}
|
|
|
|
async function showFinale() {
|
|
gameState.lastAction = 'showFinale';
|
|
showStage('roundLoading');
|
|
document.getElementById('roundLoadingText').textContent = 'Генерируем эпический финал...';
|
|
|
|
addTimelineEvent('🏆 Финал', 'Определяем победителя эпической битвы!');
|
|
|
|
try {
|
|
let finalDeterminedWinner = "draw";
|
|
if (gameState.currentHP.hero <= 0 && gameState.currentHP.opponent <= 0) {
|
|
finalDeterminedWinner = "draw";
|
|
} else if (gameState.currentHP.hero <= 0) {
|
|
finalDeterminedWinner = "opponent";
|
|
} else if (gameState.currentHP.opponent <= 0) {
|
|
finalDeterminedWinner = "hero";
|
|
} else {
|
|
finalDeterminedWinner = (gameState.currentHP.hero >= gameState.currentHP.opponent) ? "hero" : "opponent";
|
|
}
|
|
const winnerName = finalDeterminedWinner === "hero" ? gameState.hero.name : gameState.opponent.name;
|
|
const loserName = finalDeterminedWinner === "hero" ? gameState.opponent.name : gameState.hero.name;
|
|
|
|
const finalePrompt = gameState.currentMode.finalePrompt(winnerName, loserName, gameState.location.visualPrompt);
|
|
const finaleData = await callTextAPI(`Создай эпическое завершение битвы между ${gameState.hero.name} и ${gameState.opponent.name}. Текущее HP героя: ${gameState.currentHP.hero}, HP противника: ${gameState.currentHP.opponent}. Объяви победителя: ${winnerName}.`, finalePrompt);
|
|
|
|
lastFinaleData = finaleData;
|
|
|
|
log('Финал сгенерирован:', finaleData);
|
|
|
|
showStage('finale');
|
|
|
|
const displayWinner = finalDeterminedWinner === 'hero' ? gameState.hero.name : gameState.opponent.name;
|
|
document.getElementById('finaleTitle').textContent = `🏆 ${displayWinner} побеждает!`;
|
|
document.getElementById('finaleDescription').textContent = finaleData.description;
|
|
|
|
if (finaleData.visualPrompt) {
|
|
const finaleImageUrl = generateImageURL(finaleData.visualPrompt, 1280, 768);
|
|
const finaleImage = document.getElementById('finaleImage');
|
|
const finaleLoader = document.getElementById('finaleImageLoader');
|
|
|
|
loadImageWithPreloader(finaleImage, finaleLoader, finaleImageUrl, retryFinaleImage);
|
|
|
|
addTimelineEvent('🎉 Победа!', `${displayWinner} одержал победу! ${finaleData.description}`, { type: 'image', url: finaleImageUrl }, {
|
|
text: finaleData.finalMessage || finaleData.description,
|
|
voice: document.getElementById('voiceSelect').value,
|
|
isCommentary: true,
|
|
audioTitle: 'Эпический финал'
|
|
});
|
|
}
|
|
|
|
const selectedVoice = document.getElementById('voiceSelect').value;
|
|
const audioElement = document.getElementById('finaleAudio');
|
|
const playerElement = document.getElementById('finaleAudioPlayer');
|
|
const loaderElement = document.getElementById('finaleAudioLoader');
|
|
|
|
const textForCommentary = finaleData.finalMessage || finaleData.description;
|
|
|
|
loadAudioWithPreloader(
|
|
audioElement,
|
|
playerElement,
|
|
loaderElement,
|
|
textForCommentary,
|
|
'Эпический финал',
|
|
selectedVoice,
|
|
retryFinaleAudio,
|
|
true,
|
|
true
|
|
);
|
|
|
|
} catch (error) {
|
|
log('Ошибка генерации финала:', error);
|
|
addTimelineEvent('❌ Ошибка', 'Ошибка генерации финала');
|
|
showStage('finaleError');
|
|
}
|
|
}
|
|
|
|
function retryFinale() {
|
|
showFinale();
|
|
}
|
|
|
|
function retryBattleImage() {
|
|
if (lastRoundData && lastRoundData.visualPrompt) {
|
|
const imageElement = document.getElementById('battleImage');
|
|
const loaderElement = document.getElementById('battleImageLoader');
|
|
loadImageWithPreloader(imageElement, loaderElement, generateImageURL(lastRoundData.visualPrompt, 1280, 768), retryBattleImage);
|
|
} else {
|
|
startBattleSetup();
|
|
}
|
|
}
|
|
|
|
function retryBattleAudio() {
|
|
if (lastRoundData) {
|
|
const selectedVoice = document.getElementById('voiceSelect').value;
|
|
const audioElement = document.getElementById('battleAudio');
|
|
const playerElement = document.getElementById('battleAudioPlayer');
|
|
const loaderElement = document.getElementById('battleAudioLoader');
|
|
const roundTitleText = `Раунд ${gameState.currentRound}`;
|
|
const textForCommentary = `В ${roundTitleText}! ${lastRoundData.description}`;
|
|
|
|
loadAudioWithPreloader(
|
|
audioElement,
|
|
playerElement,
|
|
loaderElement,
|
|
textForCommentary,
|
|
`Комментарий раунда ${gameState.currentRound}`,
|
|
selectedVoice,
|
|
retryBattleAudio,
|
|
true,
|
|
true
|
|
);
|
|
} else if (gameState.currentRound === 1 && gameState.locationAnnounced) {
|
|
// Special case: if it's the first round and location audio failed, retry it
|
|
const selectedVoice = document.getElementById('voiceSelect').value;
|
|
const audioElement = document.getElementById('battleAudio');
|
|
const playerElement = document.getElementById('battleAudioPlayer');
|
|
const loaderElement = document.getElementById('battleAudioLoader');
|
|
|
|
loadAudioWithPreloader(
|
|
audioElement,
|
|
playerElement,
|
|
loaderElement,
|
|
gameState.location.description,
|
|
'Описание локации',
|
|
selectedVoice,
|
|
retryBattleAudio,
|
|
true,
|
|
true
|
|
);
|
|
} else {
|
|
simulateRound();
|
|
}
|
|
}
|
|
|
|
function retryFinaleImage() {
|
|
if (lastFinaleData && lastFinaleData.visualPrompt) {
|
|
const finaleImage = document.getElementById('finaleImage');
|
|
const finaleLoader = document.getElementById('finaleImageLoader');
|
|
loadImageWithPreloader(finaleImage, finaleLoader, generateImageURL(lastFinaleData.visualPrompt, 1280, 768), retryFinaleImage);
|
|
} else {
|
|
showFinale();
|
|
}
|
|
}
|
|
|
|
function retryFinaleAudio() {
|
|
if (lastFinaleData) {
|
|
const selectedVoice = document.getElementById('voiceSelect').value;
|
|
const audioElement = document.getElementById('finaleAudio');
|
|
const playerElement = document.getElementById('finaleAudioPlayer');
|
|
const loaderElement = document.getElementById('finaleAudioLoader');
|
|
const textForCommentary = lastFinaleData.finalMessage || lastFinaleData.description;
|
|
|
|
loadAudioWithPreloader(
|
|
audioElement,
|
|
playerElement,
|
|
loaderElement,
|
|
textForCommentary,
|
|
'Эпический финал',
|
|
selectedVoice,
|
|
retryFinaleAudio,
|
|
true,
|
|
true
|
|
);
|
|
} else {
|
|
showFinale();
|
|
}
|
|
}
|
|
|
|
function toggleSettingsPanel() {
|
|
const settingsPanel = document.getElementById('settingsPanel');
|
|
settingsPanel.classList.toggle('show');
|
|
}
|
|
|
|
function resetGame() {
|
|
gameState = {
|
|
gameId: null,
|
|
stage: 'modeSelection', // Reset to mode selection screen
|
|
hero: null,
|
|
opponent: null,
|
|
location: null,
|
|
heroAction: null,
|
|
battleLog: [],
|
|
currentHP: { hero: 100, opponent: 100 },
|
|
currentRound: 1,
|
|
lastAction: null,
|
|
currentMode: null, // Clear selected mode
|
|
locationAnnounced: false // Reset flag
|
|
};
|
|
lastFinaleData = null;
|
|
lastRoundData = null;
|
|
|
|
document.getElementById('heroInput').value = '';
|
|
document.getElementById('opponentInput').value = '';
|
|
document.getElementById('locationInput').value = '';
|
|
document.getElementById('customActionInput').value = '';
|
|
|
|
document.getElementById('autoplayToggle').checked = true;
|
|
document.getElementById('settingsPanel').classList.remove('show');
|
|
|
|
document.getElementById('nextRoundBtn').style.display = 'none';
|
|
document.getElementById('finaleBtn').style.display = 'none';
|
|
document.getElementById('battleActions').style.display = 'none';
|
|
|
|
document.querySelectorAll('.audio-player').forEach(player => {
|
|
player.classList.remove('show');
|
|
const audio = player.querySelector('audio');
|
|
if (audio.src && audio.src.startsWith('blob:')) {
|
|
URL.revokeObjectURL(audio.src);
|
|
}
|
|
audio.src = '';
|
|
});
|
|
document.querySelectorAll('.audio-loader').forEach(loader => {
|
|
loader.classList.add('hidden');
|
|
loader.querySelector('.image-spinner').style.display = 'block';
|
|
const retryBtn = loader.querySelector('.retry-btn');
|
|
if (retryBtn) retryBtn.style.display = 'none';
|
|
});
|
|
|
|
document.querySelectorAll('.fighter-avatar.pulsing').forEach(avatar => {
|
|
avatar.classList.remove('pulsing');
|
|
});
|
|
document.querySelectorAll('.damage-number').forEach(el => el.remove());
|
|
|
|
const battleImage = document.getElementById('battleImage');
|
|
const battleImageLoader = document.getElementById('battleImageLoader');
|
|
if (battleImage) {
|
|
battleImage.style.display = 'none';
|
|
battleImage.src = '';
|
|
}
|
|
if (battleImageLoader) {
|
|
battleImageLoader.classList.add('hidden');
|
|
}
|
|
|
|
updateHPDisplay(100, 100);
|
|
|
|
document.getElementById('timelineContent').innerHTML = '';
|
|
document.getElementById('currentModeDisplay').textContent = '';
|
|
|
|
document.body.classList.remove('theme-fantasy', 'theme-brutal', 'theme-realistic');
|
|
document.body.classList.add('theme-fantasy'); // Re-apply default theme class (fantasy)
|
|
|
|
log('Игра сброшена');
|
|
addTimelineEvent('🎮 Инициализация', 'Выберите режим, чтобы начать!');
|
|
showStage('modeSelection');
|
|
}
|
|
|
|
// Initial setup on page load
|
|
document.addEventListener('DOMContentLoaded', () => {
|
|
const voiceSelect = document.getElementById('voiceSelect');
|
|
const savedVoice = localStorage.getItem(VOICE_PREFERENCE_KEY);
|
|
if (savedVoice) {
|
|
voiceSelect.value = savedVoice;
|
|
} else {
|
|
voiceSelect.value = MODES.fantasy.defaultVoice;
|
|
}
|
|
|
|
log('GPT Arena инициализирована');
|
|
addTimelineEvent('🎮 Инициализация', 'Выберите режим, чтобы начать!');
|
|
showStage('modeSelection');
|
|
document.getElementById('currentModeDisplay').textContent = '';
|
|
document.body.classList.add('theme-fantasy');
|
|
});
|
|
</script>
|
|
</body>
|
|
</html> |