Это что-то типа готовой игры, но нужны картинки, кнопки, текстовое наполнение, проверки кода, добавление доп. контента и всяких достижений.
// Инициализация игровых переменных
let playerProfile = {
name: '',
age: '',
goals: '',
selfEsteem: 50,
communicationSkills: 50,
confidence: 50,
achievements: [],
currentLocation: 'roomOfHeritage'
};
const gameState = {
progress: 0,
stars: 0,
currentLevel: 1,
completedTasks: []
};
// Стили для интерфейса
const theme = {
primaryColor: '#FF69B4',
secondaryColor: '#4B0082',
tertiaryColor: '#32CD32',
font: 'Arial, sans-serif'
};
// Инициализация при загрузке
document.addEventListener('DOMContentLoaded', () => {
initGameProfile();
});
// Начальная настройка профиля
function initGameProfile() {
// Получение данных профиля
const profileData = getProfileData();
// Настройка интерфейса
setupInterface();
startGameLoop();
}
// Получение данных профиля
function getProfileData() {
try {
const data = JSON.parse(localStorage.getItem('playerProfile'));
playerProfile = {
...playerProfile,
...data
};
return data;
} catch(error) {
return {};
}
}
// Настройка пользовательского интерфейса
function setupInterface() {
const container = document.querySelector('.game-container');
container.style.cssText = `
font-family: ${theme.font};
color: ${theme.primaryColor};
background: linear-gradient(to bottom, ${theme.secondaryColor}, white);
`;
renderProfileUI();
renderCurrentLocation();
}
// Игровой цикл
let gameLoop;
function startGameLoop() {
gameLoop = setInterval(() => {
updateGameState();
renderUI();
}, 1000);
}
// Обновление состояния игры
function updateGameState() {
if (gameState.progress >= 100) {
completeGame();
return;
}
// Обновление показателей
updateMetrics();
checkAchievements();
}
// Метрики игрока
function updateMetrics() {
playerProfile.selfEsteem = Math.min(100, playerProfile.selfEsteem + 0.5);
playerProfile.confidence = Math.min(100, playerProfile.confidence + 0.3);
}
// Проверка достижений
function checkAchievements() {
if (playerProfile.selfEsteem >= 75) {
addAchievement('Уверенный игрок');
}
if (gameState.stars >= 10) {
addAchievement('Знаток себя');
}
}
// Добавление достижения
function addAchievement(name) {
if (!playerProfile.achievements.includes(name)) {
playerProfile.achievements.push(name);
gameState.stars += 5;
}
}
// Рендер интерфейса
function renderUI() {
renderProfileUI();
renderCurrentLocation();
renderMetrics();
}
// Профиль игрока
function renderProfileUI() {
const profileSection = document.querySelector('.profile');
profileSection.innerHTML = `
<div class="profile-info">
<h2>${playerProfile.name}</h2>
<p>Возраст: ${playerProfile.age}</p>
<p>Цель: ${playerProfile.goals}</p>
</div>
<div class="metrics">
<p>Самооценка: ${playerProfile.selfEsteem}%</p>
<p>Уверенность: ${playerProfile.confidence}%</p>
<p>Звёзд: ${gameState.stars}</p>
</div>
`;
}
// Текущая локация
function renderCurrentLocation() {
const location = document.querySelector('.location');
switch(playerProfile.currentLocation) {
case 'roomOfHeritage':
location.innerHTML = `
<h2>Комната Наследия</h2>
<p>Исследуйте своё прошлое</p>
<button onclick="startHeritageTest()">Начать тест
// Рендер текущей локации
function renderCurrentLocation() {
const location = document.querySelector('.location');
switch(playerProfile.currentLocation) {
case 'roomOfHeritage':
location.innerHTML = `
<h2>Комната Наследия</h2>
<p>Исследуйте своё прошлое</p>
<button onclick="startHeritageTest()">Начать тест</button>
<button onclick="showMirror()">Зеркало Правды</button>
`;
break;
case 'arenaOfEmotions':
location.innerHTML = `
<h2>Арена Эмоций</h2>
<p>Управляйте своими чувствами</p>
<button onclick="startEmotionChallenge()">Начать испытание</button>
`;
break;
case 'galleryOfDreams':
location.innerHTML = `
<h2>Галерея Мечтаний</h2>
<p>Создайте свой идеальный мир</p>
<button onclick="startDreamActivity()">Начать создание</button>
`;
break;
case 'labyrinthOfSelf':
location.innerHTML = `
<h2>Лабиринт Самооценки</h2>
<p>Найдите свою уникальность</p>
<button onclick="startSelfQuest()">Начать поиск</button>
`;
break;
case 'cityOfSocial':
location.innerHTML = `
<h2>Город Социальных Взаимодействий</h2>
<p>Развивайте навыки общения</p>
<button onclick="startSocialChallenge()">Начать тренировку</button>
`;
break;
}
}
// Тест семейных установок
function startHeritageTest() {
showDialog({
title: "Тест семейных установок",
content: "Ответьте на вопросы о вашем прошлом",
buttons: [
{text: "Начать", action: runHeritageQuestions},
{text: "Отмена", action: cancelTest}
]
});
}
// Вопросы теста
function runHeritageQuestions() {
// Здесь логика вопросов теста
// Можно использовать массив вопросов
const questions = [
{
text: "Как часто ваши родители...",
options: ['Часто', 'Редко', 'Никогда']
},
// Другие вопросы
];
renderQuestions(questions);
}
// Зеркало правды
function showMirror() {
const mirrorContent = getMirrorReflection();
showDialog({
title: "Зеркало Правды",
content: mirrorContent,
buttons: [
{text: "Принять", action: processReflection},
{text: "Повторить", action: showMirror}
]
});
}
// Система достижений
function updateAchievements() {
const achievementsSection = document.querySelector('.achievements');
achievementsSection.innerHTML = `
<h3>Ваши достижения</h3>
<ul>
${playerProfile.achievements.map(ach => `<li>${ach}</li>`).join('')}
</ul>
`;
}
// Система наград
function awardStars(amount) {
gameState.stars += amount;
updateUIStars();
if (gameState.stars >= 10) {
unlockNewLocation();
}
}
// Разблокировка новой локации
function unlockNewLocation() {
const nextLocation = getNextLocation();
playerProfile.currentLocation = nextLocation;
showNotification(`Открыта новая локация: ${nextLocation}`);
renderCurrentLocation();
}
// Обработка прогресса
function updateProgress() {
gameState.progress = calculateProgress();
if (gameState.progress >= 100) {
finishGame();
}
}
// Завершение игры
function finishGame() {
clearInterval(gameLoop);
showDialog({
title: "Поздравляем!",
content: "Вы завершили путешествие к себе",
buttons: [
{text: "Начать заново", action: restartGame},
{text: "В главное меню", action: goToMenu}
]
});
}
// Сохранение профиля игрока
function saveProfile() {
localStorage.setItem('playerProfile', JSON.stringify(playerProfile));
localStorage.setItem('gameState', JSON.stringify(gameState));
}
// Загрузка сохраненного профиля
function loadProfile() {
try {
playerProfile = JSON.parse(localStorage.getItem('playerProfile')) || playerProfile;
gameState = JSON.parse(localStorage.getItem('gameState')) || gameState;
} catch(e) {
console.error('Ошибка загрузки профиля', e);
}
}
// Система уведомлений
function showNotification(message) {
const notification = document.createElement('div');
notification.classList.add('notification');
notification.innerHTML = `<p>${message}</p>`;
document.body.appendChild(notification);
setTimeout(() => {
notification.remove();
}, 3000);
}
// Система диалогов
function showDialog(options) {
const dialog = document.createElement('div');
dialog.classList.add('dialog');
dialog.innerHTML = `
<div class="dialog-content">
<h3>${options.title}</h3>
<p>${options.content}</p>
<div class="buttons">
${options.buttons.map(btn =>
`<button onclick="${btn.action()}">${btn.text}</button>`
).join('')}
</div>
</div>
`;
document.body.appendChild(dialog);
}
// Расчет прогресса
function calculateProgress() {
let progress = 0;
progress += (playerProfile.selfEsteem / 100) * 25;
progress += (playerProfile.confidence / 100) * 25;
progress += (gameState.stars / 100) * 25;
progress += (gameState.completedTasks.length / totalTasks) * 25;
return Math.min(100, progress);
}
// Система достижений
function checkAchievements() {
const achievementConditions = [
{
name: 'Исследователь прошлого',
condition: () => playerProfile.currentLocation === 'roomOfHeritage'
},
{
name: 'Мастер эмоций',
condition: () => playerProfile.emotionSkills >= 75
},
{
name: 'Мечтатель',
condition: () => playerProfile.dreamsRealized > 0
}
];
achievementConditions.forEach(ach => {
if (ach.condition() && !playerProfile.achievements.includes(ach.name)) {
playerProfile.achievements.push(ach.name);
awardStars(5);
}
});
}
// Система наград
function awardStars(amount) {
gameState.stars = Math.min(100, gameState.stars + amount);
updateUIStars();
if (gameState.stars >= 10) {
unlockNewLocation();
}
}
// Разблокировка локаций
function unlockNewLocation() {
const nextLocations = [
'arenaOfEmotions',
'galleryOfDreams',
'labyrinthOfSelf',
'cityOfSocial'
];
const currentIndex = nextLocations.indexOf(playerProfile.currentLocation);
if (currentIndex < nextLocations.length - 1) {
playerProfile.currentLocation = nextLocations[currentIndex + 1];
showNotification(`Открыта новая локация: ${playerProfile.currentLocation}`);
renderCurrentLocation();
}
}
// Обработка ошибок
window.addEventListener('error', (event) => {
console.error('Произошла ошибка:', event.error);
showNotification('Произошла ошибка. Попробуйте перезагрузить страницу.');
});
// Инициализация при загрузке
document.addEventListener('DOMContentLoaded', () => {
loadProfile();
initGameProfile();
});
// Функция выхода в меню
function goToMenu() {
playerProfile.currentLocation = 'mainMenu';
renderCurrentLocation();
}
// Функция перезапуска игры
function restartGame() {
playerProfile = {
name: '',
age: '',
goals: '',
selfEsteem: 50,
communicationSkills: 50,
confidence: 50,
achievements: [],
currentLocation: 'roomOfHeritage'
};
gameState = {
progress: 0,
stars: 0,
currentLevel: 1,
completedTasks: []
};
saveProfile();
initGameProfile();
showNotification('Игра перезапущена!');
}
// Система дневника
function openJournal() {
showDialog({
title: "Дневник самоанализа",
content: `
<textarea placeholder="Запишите свои мысли..."></textarea>
<button onclick="saveEntry()">Сохранить</button>
`,
buttons: [
{text: "Закрыть", action: closeJournal}
]
});
}
// Сохранение записей
function saveEntry() {
const entry = document.querySelector('textarea').value;
playerProfile.journal = playerProfile.journal || [];
playerProfile.journal.push(entry);
saveProfile();
showNotification('Запись сохранена');
}
// Система подсказок
function showHints() {
const hints = [
"Попробуйте исследовать все локации",
"Не забывайте выполнять задания",
"Используйте зеркало для рефлексии",
"Ведите дневник регулярно"
];
const randomHint = hints[Math.floor(Math.random() * hints.length)];
showNotification(randomHint);
}
// Система мини-игр
function startMiniGame() {
showDialog({
title: "Мини-игра",
content: `
<button onclick="playMiniGame()">Начать игру</button>
`,
buttons: [
{text: "Пропустить", action: closeMiniGame}
]
});
}
// Обработка прогресса игрока
function updatePlayerMetrics() {
if (gameState.progress >= 25) {
playerProfile.selfEsteem += 5;
}
if (gameState.progress >= 50) {
playerProfile.confidence += 5;
}
if (gameState.progress >= 75) {
playerProfile.communicationSkills += 5;
}
saveProfile();
}
// Система достижений
function checkDailyAchievements() {
const today = new Date().toISOString().slice(0, 10);
if (!playerProfile.dailyCheck || playerProfile.dailyCheck !== today) {
playerProfile.stars += 3;
playerProfile.dailyCheck = today;
showNotification('Получено 3 звезды за ежедневный вход!');
}
}
// Обработка выхода
function closeGame() {
saveProfile();
showNotification('До встречи в следующем путешествии!');
}
// Инициализация всех компонентов
function initGameProfile() {
loadProfile();
setupInterface();
startGameLoop();
checkDailyAchievements();
updatePlayerMetrics();
}
// Оптимизация производительности
function optimizePerformance() {
const gameElements = document.querySelectorAll('.game-ui');
gameElements.forEach(element => {
element.style.willChange = 'transform, opacity';
});
}
// Адаптивность интерфейса
window.addEventListener('resize', () => {
const container = document.querySelector('.game-container');
container.style.padding = '20px';
container.style.boxSizing = 'border-box';
});
// Обработка ошибок
window.addEventListener('error', (event) => {
console.error('Произошла ошибка:', event.error);
showNotification('Произошла ошибка. Попробуйте перезагрузить страницу.');
});
// Начальная инициализация
document.addEventListener('DOMContentLoaded', () => {
initGameProfile();
setInterval(() => {
updatePlayerMetrics();
checkAchievements();
}, 60000); // Проверка достижений каждые 60 секунд
});