Полнофункциональная система для создания современных веб-приложений, мобильных игр, AI-ассистентов с интеграцией DeepSeek API. Все инструменты в одном месте!
Профессиональная разработка и экспорт проектов на хостинг
Создайте собственного интеллектуального помощника
Разработка игр для iOS и Android
Умные боты с нейросетями
Интеграция всех популярных платежек
Бизнес-проекты под ключ
Введите ваш API ключ DeepSeek выше и начните использовать AI-функции прямо сейчас!
// Быстрая интеграция DeepSeek API const deepseek = new DeepSeekClient({ apiKey: 'ваш-ключ-здесь', // Используйте форму выше model: 'deepseek-chat' }); // Простой запрос к AI const response = await deepseek.chat('Помоги создать веб-приложение'); console.log(response);
Полное руководство по созданию интеллектуального ассистента с использованием DeepSeek API
// ai-assistant.js - Ядро AI ассистента class AIAssistant { constructor(config = {}) { this.name = config.name || 'Assistant'; this.apiKey = config.apiKey || localStorage.getItem('deepseek_api_key'); this.personality = config.personality || 'professional'; this.language = config.language || 'ru'; this.memory = new ConversationMemory(); this.skills = new Map(); this.plugins = []; this.initializeCore(); } initializeCore() { // Инициализация DeepSeek this.ai = new DeepSeekClient({ apiKey: this.apiKey, model: 'deepseek-chat' }); // Загрузка базовых навыков this.loadBaseSkills(); // Инициализация голосового интерфейса this.voice = new VoiceInterface(); // Загрузка плагинов this.loadPlugins(); } // Основной метод обработки запросов async process(input, context = {}) { try { // Анализ намерения пользователя const intent = await this.analyzeIntent(input); // Извлечение сущностей const entities = await this.extractEntities(input); // Получение контекста из памяти const memoryContext = this.memory.getRelevantContext(input); // Выбор подходящего навыка const skill = this.selectSkill(intent); if (skill) { // Выполнение специализированного навыка const result = await skill.execute(input, { intent, entities, memory: memoryContext, ...context }); // Сохранение в память this.memory.save(input, result); return result; } // Fallback на общий AI return await this.generalResponse(input, memoryContext); } catch (error) { console.error('Processing error:', error); return this.handleError(error); } } // Анализ намерения async analyzeIntent(input) { const prompt = ` Определи намерение пользователя из следующих категорий: - question: вопрос, требующий ответа - task: задача для выполнения - conversation: обычный разговор - code: запрос на написание кода - analysis: анализ данных - creative: творческая задача Текст: "${input}" Ответь только одним словом - категорией намерения. `; const response = await this.ai.complete(prompt, { temperature: 0.3, max_tokens: 10 }); return response.trim().toLowerCase(); } // Извлечение сущностей async extractEntities(input) { const prompt = ` Извлеки ключевые сущности из текста. Верни в формате JSON: { "people": [], "locations": [], "dates": [], "numbers": [], "keywords": [] } Текст: "${input}" `; const response = await this.ai.complete(prompt, { temperature: 0.3, response_format: { type: "json_object" } }); return JSON.parse(response); } // Загрузка базовых навыков loadBaseSkills() { // Навык: Написание кода this.skills.set('code', new CodeGenerationSkill(this.ai)); // Навык: Анализ данных this.skills.set('analysis', new DataAnalysisSkill(this.ai)); // Навык: Творческие задачи this.skills.set('creative', new CreativeWritingSkill(this.ai)); // Навык: Техническая поддержка this.skills.set('support', new TechnicalSupportSkill(this.ai)); // Навык: Обучение this.skills.set('education', new EducationSkill(this.ai)); } // Выбор навыка на основе намерения selectSkill(intent) { return this.skills.get(intent); } // Общий ответ через AI async generalResponse(input, context) { const systemPrompt = this.getSystemPrompt(); const messages = [ { role: 'system', content: systemPrompt }, ...context.messages || [], { role: 'user', content: input } ]; const response = await this.ai.chat(messages, { temperature: 0.7, max_tokens: 2000 }); return { text: response, type: 'general', confidence: 0.8 }; } // Системный промпт на основе личности getSystemPrompt() { const personalities = { professional: `Ты - профессиональный ассистент по имени ${this.name}. Отвечай четко, информативно и вежливо. Используй структурированные ответы.`, friendly: `Ты - дружелюбный помощник ${this.name}. Будь позитивным и поддерживающим. Используй эмодзи для улучшения общения.`, technical: `Ты - технический эксперт ${this.name}. Давай подробные технические объяснения. Приводи примеры кода и документацию.`, creative: `Ты - творческий ассистент ${this.name}. Будь изобретательным и оригинальным. Предлагай нестандартные решения.` }; return personalities[this.personality] || personalities.professional; } // Загрузка плагинов loadPlugins() { // Плагин: Интеграция с календарем this.plugins.push(new CalendarPlugin()); // Плагин: Работа с файлами this.plugins.push(new FileManagerPlugin()); // Плагин: Web поиск this.plugins.push(new WebSearchPlugin()); // Плагин: База знаний this.plugins.push(new KnowledgeBasePlugin()); } // Обработка ошибок handleError(error) { return { text: 'Извините, произошла ошибка при обработке запроса. Попробуйте переформулировать.', type: 'error', error: error.message }; } } // Класс для управления памятью разговора class ConversationMemory { constructor(maxSize = 100) { this.shortTerm = []; // Последние сообщения this.longTerm = new Map(); // Важная информация this.maxSize = maxSize; this.embeddings = new EmbeddingStore(); } save(input, response) { // Сохранение в краткосрочную память this.shortTerm.push({ input, response, timestamp: Date.now() }); // Ограничение размера if (this.shortTerm.length > this.maxSize) { this.shortTerm.shift(); } // Извлечение важной информации для долгосрочной памяти this.extractImportantInfo(input, response); } getRelevantContext(input) { // Поиск релевантного контекста через embeddings const relevant = this.embeddings.search(input, 5); // Последние сообщения const recent = this.shortTerm.slice(-5); return { messages: [...relevant, ...recent].map(item => ({ role: 'user', content: item.input })), facts: Array.from(this.longTerm.values()) }; } extractImportantInfo(input, response) { // Анализ на важную информацию const patterns = { name: /меня зовут (\w+)/i, preference: /я (люблю|предпочитаю|хочу) (.+)/i, fact: /важно: (.+)/i }; for (const [key, pattern] of Object.entries(patterns)) { const match = input.match(pattern); if (match) { this.longTerm.set(key + '_' + Date.now(), { type: key, value: match[1], context: input, timestamp: Date.now() }); } } } } // Голосовой интерфейс class VoiceInterface { constructor() { this.recognition = null; this.synthesis = window.speechSynthesis; this.initRecognition(); } initRecognition() { if ('webkitSpeechRecognition' in window) { this.recognition = new webkitSpeechRecognition(); this.recognition.continuous = false; this.recognition.interimResults = false; this.recognition.lang = 'ru-RU'; } } async listen() { return new Promise((resolve, reject) => { if (!this.recognition) { reject(new Error('Speech recognition not supported')); return; } this.recognition.onresult = (event) => { const transcript = event.results[0][0].transcript; resolve(transcript); }; this.recognition.onerror = reject; this.recognition.start(); }); } speak(text) { const utterance = new SpeechSynthesisUtterance(text); utterance.lang = 'ru-RU'; utterance.rate = 1.0; utterance.pitch = 1.0; this.synthesis.speak(utterance); } } // Использование ассистента const assistant = new AIAssistant({ name: 'Jarvis', apiKey: localStorage.getItem('deepseek_api_key'), personality: 'professional' }); // Пример взаимодействия async function interact() { const response = await assistant.process( 'Помоги мне создать веб-приложение для управления задачами' ); console.log(response); // Голосовой ответ if (response.text) { assistant.voice.speak(response.text); } }
# train_assistant.py - Обучение персонализированного ассистента import json import numpy as np from typing import List, Dict, Tuple import torch from transformers import AutoTokenizer, AutoModelForCausalLM from datasets import Dataset import deepseek_sdk class AssistantTrainer: def __init__(self, base_model="deepseek-ai/deepseek-chat"): self.base_model = base_model self.tokenizer = AutoTokenizer.from_pretrained(base_model) self.model = AutoModelForCausalLM.from_pretrained(base_model) self.training_data = [] def prepare_training_data(self, conversations: List[Dict]): """Подготовка данных для обучения""" formatted_data = [] for conv in conversations: # Форматирование в instruction-following формат instruction = conv.get('instruction', '') input_text = conv.get('input', '') output = conv.get('output', '') if instruction and output: formatted_data.append({ 'text': f"### Instruction:\n{instruction}\n\n### Input:\n{input_text}\n\n### Response:\n{output}" }) return Dataset.from_list(formatted_data) def create_custom_personality(self, personality_traits: Dict): """Создание кастомной личности ассистента""" system_prompts = { 'professional': """You are a professional AI assistant focused on accuracy and efficiency.""", 'creative': """You are a creative AI that thinks outside the box.""", 'empathetic': """You are an empathetic AI that understands emotions.""", 'technical': """You are a technical expert with deep knowledge.""" } # Комбинирование черт личности combined_prompt = "" for trait, weight in personality_traits.items(): if trait in system_prompts: combined_prompt += f"{system_prompts[trait]} (Weight: {weight})\n" return combined_prompt def train_on_domain_data(self, domain_data: List[str], domain_name: str): """Обучение на специфичных для домена данных""" # Создание эмбеддингов для domain-specific знаний embeddings = [] for text in domain_data: # Токенизация и создание эмбеддингов inputs = self.tokenizer(text, return_tensors="pt", truncation=True) with torch.no_grad(): outputs = self.model(**inputs) embeddings.append(outputs.last_hidden_state.mean(dim=1)) # Сохранение эмбеддингов для retrieval torch.save({ 'domain': domain_name, 'embeddings': embeddings, 'texts': domain_data }, f'domain_{domain_name}_embeddings.pt') return embeddings def create_skill_module(self, skill_name: str, examples: List[Tuple[str, str]]): """Создание специализированного модуля навыка""" skill_data = { 'name': skill_name, 'examples': examples, 'patterns': self.extract_patterns(examples), 'responses': self.generate_response_templates(examples) } # Сохранение модуля навыка with open(f'skill_{skill_name}.json', 'w', encoding='utf-8') as f: json.dump(skill_data, f, ensure_ascii=False, indent=2) return skill_data def extract_patterns(self, examples: List[Tuple[str, str]]): """Извлечение паттернов из примеров""" patterns = [] for input_text, output_text in examples: # Простое извлечение паттернов words = input_text.lower().split() patterns.append({ 'keywords': list(set(words)), 'length': len(words), 'question_type': self.detect_question_type(input_text) }) return patterns def detect_question_type(self, text: str): """Определение типа вопроса""" question_words = { 'what': 'definition', 'how': 'procedure', 'why': 'explanation', 'when': 'temporal', 'where': 'location', 'who': 'person' } text_lower = text.lower() for word, q_type in question_words.items(): if word in text_lower: return q_type return 'general' def generate_response_templates(self, examples: List[Tuple[str, str]]): """Генерация шаблонов ответов""" templates = [] for _, output in examples: # Анализ структуры ответа template = { 'has_list': '•' in output or '1.' in output, 'has_code': '```' in output, 'avg_length': len(output.split()), 'style': self.detect_style(output) } templates.append(template) return templates def detect_style(self, text: str): """Определение стиля текста""" if '!' in text: return 'enthusiastic' elif '?' in text: return 'questioning' elif len(text.split('.')) > 5: return 'detailed' else: return 'concise' # Пример использования trainer = AssistantTrainer() # Подготовка данных для обучения conversations = [ { 'instruction': 'Создай план разработки мобильного приложения', 'input': 'Приложение для отслеживания привычек', 'output': '''План разработки приложения для отслеживания привычек: 1. Исследование и планирование (1-2 недели) • Анализ конкурентов • Определение ключевых функций • Создание user stories 2. Дизайн (2-3 недели) • Wireframes и прототипы • UI/UX дизайн • Создание дизайн-системы 3. Разработка MVP (4-6 недель) • Настройка проекта • Основные экраны • База данных • Уведомления 4. Тестирование (1-2 недели) • Unit тесты • Интеграционные тесты • Бета-тестирование 5. Запуск (1 неделя) • Подготовка к релизу • Публикация в сторах • Мониторинг''' } ] # Обучение на данных dataset = trainer.prepare_training_data(conversations) # Создание кастомной личности personality = trainer.create_custom_personality({ 'professional': 0.4, 'creative': 0.3, 'technical': 0.3 }) # Создание специализированного навыка coding_skill = trainer.create_skill_module( 'coding', [ ('Напиши функцию сортировки', 'def bubble_sort(arr):...'), ('Создай React компонент', 'const Component = () => {...}') ] )
Создание игр для iOS и Android с монетизацией и публикацией в сторах
// GameController.cs - Основной контроллер игры using UnityEngine; using UnityEngine.UI; using System.Collections; using System.Collections.Generic; using UnityEngine.Advertisements; using Unity.Services.Core; using Unity.Services.Analytics; public class GameController : MonoBehaviour { // Singleton паттерн public static GameController Instance { get; private set; } // Игровые состояния public enum GameState { Menu, Playing, Paused, GameOver, Victory } [Header("Game Settings")] public GameState currentState = GameState.Menu; public int playerScore = 0; public int highScore = 0; public float gameTime = 0f; [Header("UI Elements")] public GameObject menuPanel; public GameObject gamePanel; public GameObject pausePanel; public GameObject gameOverPanel; public Text scoreText; public Text highScoreText; public Text coinsText; [Header("Player")] public GameObject playerPrefab; private GameObject currentPlayer; public Transform spawnPoint; [Header("Enemies")] public GameObject[] enemyPrefabs; public float spawnRate = 2f; private float nextSpawnTime = 0f; [Header("Power-ups")] public GameObject[] powerUpPrefabs; public float powerUpSpawnRate = 10f; [Header("Audio")] public AudioSource musicSource; public AudioSource sfxSource; public AudioClip[] soundEffects; [Header("Monetization")] public string gameId = "YOUR_GAME_ID"; public bool testMode = true; private string rewardedVideoId = "Rewarded_Android"; private string interstitialId = "Interstitial_Android"; // Игровые данные private int coins = 0; private int lives = 3; private bool isDoubleScore = false; private ListactiveEnemies = new List (); async void Awake() { // Singleton setup if (Instance == null) { Instance = this; DontDestroyOnLoad(gameObject); } else { Destroy(gameObject); return; } // Инициализация Unity Services await UnityServices.InitializeAsync(); // Инициализация рекламы Advertisement.Initialize(gameId, testMode); // Загрузка сохраненных данных LoadGameData(); } void Start() { ShowMenu(); } void Update() { if (currentState == GameState.Playing) { gameTime += Time.deltaTime; // Спавн врагов if (Time.time > nextSpawnTime) { SpawnEnemy(); nextSpawnTime = Time.time + spawnRate; // Увеличиваем сложность со временем if (spawnRate > 0.5f) { spawnRate -= 0.01f; } } // Обновление UI UpdateUI(); // Проверка на паузу if (Input.GetKeyDown(KeyCode.Escape) || Input.GetKeyDown(KeyCode.P)) { PauseGame(); } } } public void StartGame() { currentState = GameState.Playing; // Скрываем меню menuPanel.SetActive(false); gamePanel.SetActive(true); // Сброс игровых параметров playerScore = 0; gameTime = 0f; lives = 3; spawnRate = 2f; // Спавн игрока SpawnPlayer(); // Запуск игровой музыки PlayMusic(0); // Аналитика SendAnalyticsEvent("game_started"); } void SpawnPlayer() { if (currentPlayer != null) { Destroy(currentPlayer); } currentPlayer = Instantiate(playerPrefab, spawnPoint.position, Quaternion.identity); // Добавляем компонент управления PlayerController controller = currentPlayer.GetComponent (); if (controller != null) { controller.OnPlayerDeath += HandlePlayerDeath; controller.OnCoinCollected += HandleCoinCollected; } } void SpawnEnemy() { // Случайный выбор врага int enemyIndex = Random.Range(0, enemyPrefabs.Length); // Случайная позиция спавна float randomX = Random.Range(-8f, 8f); Vector3 spawnPos = new Vector3(randomX, 6f, 0f); GameObject enemy = Instantiate(enemyPrefabs[enemyIndex], spawnPos, Quaternion.identity); activeEnemies.Add(enemy); // Настройка врага EnemyController enemyController = enemy.GetComponent (); if (enemyController != null) { enemyController.moveSpeed = Random.Range(2f, 5f); enemyController.scoreValue = 10 * (enemyIndex + 1); } } public void AddScore(int points) { if (isDoubleScore) { points *= 2; } playerScore += points; // Проверка рекорда if (playerScore > highScore) { highScore = playerScore; SaveHighScore(); } // Бонус за каждые 1000 очков if (playerScore % 1000 == 0) { GiveExtraLife(); } } public void AddCoins(int amount) { coins += amount; SaveGameData(); UpdateUI(); } void HandleCoinCollected(int value) { AddCoins(value); PlaySound(1); // Звук подбора монеты } void HandlePlayerDeath() { lives--; if (lives <= 0) { GameOver(); } else { StartCoroutine(RespawnPlayer()); } } IEnumerator RespawnPlayer() { // Эффект мигания yield return new WaitForSeconds(1f); SpawnPlayer(); // Неуязвимость на 2 секунды if (currentPlayer != null) { PlayerController controller = currentPlayer.GetComponent (); controller.SetInvulnerable(2f); } } void GiveExtraLife() { lives++; PlaySound(3); // Звук бонуса ShowFloatingText("+1 Life!", Color.green); } public void PauseGame() { if (currentState == GameState.Playing) { currentState = GameState.Paused; Time.timeScale = 0f; pausePanel.SetActive(true); } } public void ResumeGame() { currentState = GameState.Playing; Time.timeScale = 1f; pausePanel.SetActive(false); } void GameOver() { currentState = GameState.GameOver; // Останавливаем игру Time.timeScale = 0f; // Показываем панель Game Over gameOverPanel.SetActive(true); // Сохраняем результаты SaveGameData(); // Аналитика SendAnalyticsEvent("game_over", new Dictionary { {"score", playerScore}, {"time", gameTime}, {"coins_earned", coins} }); // Показываем рекламу (каждый 3-й раз) if (PlayerPrefs.GetInt("GamesPlayed", 0) % 3 == 0) { ShowInterstitialAd(); } } public void RestartGame() { Time.timeScale = 1f; UnityEngine.SceneManagement.SceneManager.LoadScene( UnityEngine.SceneManagement.SceneManager.GetActiveScene().name ); } public void ShowMenu() { currentState = GameState.Menu; menuPanel.SetActive(true); gamePanel.SetActive(false); pausePanel.SetActive(false); gameOverPanel.SetActive(false); } // Монетизация - Показ рекламы public void ShowRewardedVideo() { if (Advertisement.IsReady(rewardedVideoId)) { Advertisement.Show(rewardedVideoId, new ShowOptions { resultCallback = HandleRewardedVideoResult }); } } void HandleRewardedVideoResult(ShowResult result) { switch (result) { case ShowResult.Finished: // Награда за просмотр AddCoins(100); ShowFloatingText("+100 Coins!", Color.yellow); break; case ShowResult.Skipped: Debug.Log("Ad skipped"); break; case ShowResult.Failed: Debug.LogError("Ad failed to show"); break; } } void ShowInterstitialAd() { if (Advertisement.IsReady(interstitialId)) { Advertisement.Show(interstitialId); } } // Внутриигровые покупки public void PurchaseRemoveAds() { // Интеграция с Unity IAP // IAPManager.Instance.BuyProduct("remove_ads"); } public void PurchaseCoins(int amount) { // Интеграция с Unity IAP // IAPManager.Instance.BuyProduct($"coins_{amount}"); } // Сохранение и загрузка void SaveGameData() { PlayerPrefs.SetInt("HighScore", highScore); PlayerPrefs.SetInt("Coins", coins); PlayerPrefs.SetInt("GamesPlayed", PlayerPrefs.GetInt("GamesPlayed", 0) + 1); PlayerPrefs.Save(); } void LoadGameData() { highScore = PlayerPrefs.GetInt("HighScore", 0); coins = PlayerPrefs.GetInt("Coins", 0); } void SaveHighScore() { PlayerPrefs.SetInt("HighScore", highScore); // Отправка в лидерборд // PlayGamesPlatform.Instance.ReportScore(highScore, "LEADERBOARD_ID", null); } // UI Updates void UpdateUI() { scoreText.text = $"Score: {playerScore}"; highScoreText.text = $"Best: {highScore}"; coinsText.text = coins.ToString(); } void ShowFloatingText(string text, Color color) { // Создание всплывающего текста GameObject floatingText = new GameObject("FloatingText"); Text textComponent = floatingText.AddComponent (); textComponent.text = text; textComponent.color = color; textComponent.fontSize = 32; // Анимация StartCoroutine(AnimateFloatingText(floatingText)); } IEnumerator AnimateFloatingText(GameObject textObject) { float duration = 1.5f; float elapsed = 0f; Vector3 startPos = textObject.transform.position; while (elapsed < duration) { elapsed += Time.deltaTime; float progress = elapsed / duration; textObject.transform.position = startPos + Vector3.up * progress * 2f; Color color = textObject.GetComponent ().color; color.a = 1f - progress; textObject.GetComponent ().color = color; yield return null; } Destroy(textObject); } // Звуки void PlaySound(int index) { if (index < soundEffects.Length) { sfxSource.PlayOneShot(soundEffects[index]); } } void PlayMusic(int trackIndex) { // Воспроизведение фоновой музыки musicSource.Play(); } // Аналитика void SendAnalyticsEvent(string eventName, Dictionary parameters = null) { // Unity Analytics AnalyticsService.Instance.CustomData(eventName, parameters ?? new Dictionary ()); } }
// MobileGame.js - React Native игра import React, { useState, useEffect, useRef } from 'react'; import { View, Text, StyleSheet, TouchableOpacity, Animated, Dimensions, PanResponder, Alert, Vibration, AsyncStorage } from 'react-native'; import Sound from 'react-native-sound'; import { accelerometer, gyroscope } from 'react-native-sensors'; import * as Animatable from 'react-native-animatable'; import { AdMobBanner, AdMobInterstitial, AdMobRewarded } from 'react-native-admob'; const { width: screenWidth, height: screenHeight } = Dimensions.get('window'); const MobileGame = () => { // Игровые состояния const [gameState, setGameState] = useState('menu'); // menu, playing, paused, gameOver const [score, setScore] = useState(0); const [highScore, setHighScore] = useState(0); const [lives, setLives] = useState(3); const [level, setLevel] = useState(1); const [coins, setCoins] = useState(0); // Позиции игровых объектов const [playerPos, setPlayerPos] = useState({ x: screenWidth / 2, y: screenHeight - 100 }); const [enemies, setEnemies] = useState([]); const [powerUps, setPowerUps] = useState([]); const [projectiles, setProjectiles] = useState([]); // Анимации const playerAnim = useRef(new Animated.ValueXY(playerPos)).current; const enemyAnims = useRef([]).current; // Игровые настройки const [gameSpeed, setGameSpeed] = useState(1); const [isPowerUpActive, setIsPowerUpActive] = useState(false); const [powerUpType, setPowerUpType] = useState(null); // Звуки const shootSound = useRef(null); const explosionSound = useRef(null); const powerUpSound = useRef(null); const backgroundMusic = useRef(null); // Таймеры const gameLoopRef = useRef(null); const enemySpawnRef = useRef(null); useEffect(() => { // Загрузка сохраненных данных loadGameData(); // Инициализация звуков initSounds(); // Инициализация рекламы AdMobRewarded.setAdUnitID('ca-app-pub-xxx/xxx'); AdMobInterstitial.setAdUnitID('ca-app-pub-xxx/xxx'); return () => { // Очистка if (gameLoopRef.current) clearInterval(gameLoopRef.current); if (enemySpawnRef.current) clearInterval(enemySpawnRef.current); }; }, []); // Инициализация звуков const initSounds = () => { Sound.setCategory('Playback'); shootSound.current = new Sound('shoot.mp3', Sound.MAIN_BUNDLE); explosionSound.current = new Sound('explosion.mp3', Sound.MAIN_BUNDLE); powerUpSound.current = new Sound('powerup.mp3', Sound.MAIN_BUNDLE); backgroundMusic.current = new Sound('background.mp3', Sound.MAIN_BUNDLE, (error) => { if (!error) { backgroundMusic.current.setNumberOfLoops(-1); backgroundMusic.current.setVolume(0.3); } }); }; // Загрузка сохраненных данных const loadGameData = async () => { try { const savedHighScore = await AsyncStorage.getItem('highScore'); const savedCoins = await AsyncStorage.getItem('coins'); if (savedHighScore) setHighScore(parseInt(savedHighScore)); if (savedCoins) setCoins(parseInt(savedCoins)); } catch (error) { console.error('Error loading game data:', error); } }; // Сохранение данных const saveGameData = async () => { try { await AsyncStorage.setItem('highScore', highScore.toString()); await AsyncStorage.setItem('coins', coins.toString()); } catch (error) { console.error('Error saving game data:', error); } }; // Управление игроком через жесты const panResponder = useRef( PanResponder.create({ onStartShouldSetPanResponder: () => true, onMoveShouldSetPanResponder: () => true, onPanResponderMove: (evt, gestureState) => { if (gameState === 'playing') { const newX = Math.max(0, Math.min(screenWidth - 50, playerPos.x + gestureState.dx)); const newY = Math.max(screenHeight / 2, Math.min(screenHeight - 50, playerPos.y + gestureState.dy)); setPlayerPos({ x: newX, y: newY }); playerAnim.setValue({ x: newX, y: newY }); } }, onPanResponderRelease: () => { if (gameState === 'playing') { shoot(); } } }) ).current; // Начало игры const startGame = () => { setGameState('playing'); setScore(0); setLives(3); setLevel(1); setEnemies([]); setPowerUps([]); setProjectiles([]); // Запуск фоновой музыки backgroundMusic.current?.play(); // Запуск игрового цикла gameLoopRef.current = setInterval(gameLoop, 16); // 60 FPS // Запуск спавна врагов enemySpawnRef.current = setInterval(spawnEnemy, 2000); }; // Основной игровой цикл const gameLoop = () => { // Обновление врагов setEnemies(prevEnemies => { return prevEnemies.map(enemy => ({ ...enemy, y: enemy.y + enemy.speed * gameSpeed, x: enemy.x + Math.sin(enemy.y / 50) * 2 // Волнообразное движение })).filter(enemy => { // Удаление врагов за пределами экрана if (enemy.y > screenHeight) { loseLife(); return false; } return true; }); }); // Обновление снарядов setProjectiles(prevProjectiles => { return prevProjectiles.map(proj => ({ ...proj, y: proj.y - proj.speed })).filter(proj => proj.y > 0); }); // Проверка столкновений checkCollisions(); // Обновление уровня if (score > 0 && score % 1000 === 0) { levelUp(); } }; // Спавн врагов const spawnEnemy = () => { const enemyTypes = [ { type: 'basic', health: 1, speed: 2, points: 10, color: '#FF6B6B' }, { type: 'fast', health: 1, speed: 4, points: 20, color: '#4ECDC4' }, { type: 'tank', health: 3, speed: 1, points: 50, color: '#95E77E' } ]; const enemyType = enemyTypes[Math.floor(Math.random() * enemyTypes.length)]; const newEnemy = { id: Date.now() + Math.random(), x: Math.random() * (screenWidth - 50), y: -50, width: 40, height: 40, ...enemyType }; setEnemies(prev => [...prev, newEnemy]); }; // Стрельба const shoot = () => { if (gameState !== 'playing') return; shootSound.current?.play(); Vibration.vibrate(10); const projectile = { id: Date.now(), x: playerPos.x + 20, y: playerPos.y, speed: 10, damage: isPowerUpActive && powerUpType === 'doubleDamage' ? 2 : 1 }; setProjectiles(prev => [...prev, projectile]); // Двойной выстрел при power-up if (isPowerUpActive && powerUpType === 'doubleShot') { setTimeout(() => { const secondProjectile = { ...projectile, id: Date.now() + 1, x: playerPos.x + 30 }; setProjectiles(prev => [...prev, secondProjectile]); }, 100); } }; // Проверка столкновений const checkCollisions = () => { setProjectiles(prevProjectiles => { return prevProjectiles.filter(projectile => { let hit = false; setEnemies(prevEnemies => { return prevEnemies.map(enemy => { // Проверка попадания if ( Math.abs(projectile.x - enemy.x) < 30 && Math.abs(projectile.y - enemy.y) < 30 ) { hit = true; enemy.health -= projectile.damage; if (enemy.health <= 0) { // Враг уничтожен explosionSound.current?.play(); addScore(enemy.points); // Шанс выпадения power-up if (Math.random() < 0.1) { spawnPowerUp(enemy.x, enemy.y); } return null; } } return enemy; }).filter(Boolean); }); return !hit; }); }); // Проверка столкновения игрока с врагами enemies.forEach(enemy => { if ( Math.abs(playerPos.x - enemy.x) < 40 && Math.abs(playerPos.y - enemy.y) < 40 ) { if (!isPowerUpActive || powerUpType !== 'shield') { loseLife(); Vibration.vibrate(500); } } }); // Проверка подбора power-up setPowerUps(prevPowerUps => { return prevPowerUps.filter(powerUp => { if ( Math.abs(playerPos.x - powerUp.x) < 30 && Math.abs(playerPos.y - powerUp.y) < 30 ) { activatePowerUp(powerUp.type); return false; } return true; }); }); }; // Спавн power-up const spawnPowerUp = (x, y) => { const types = ['shield', 'doubleShot', 'doubleDamage', 'extraLife', 'coins']; const type = types[Math.floor(Math.random() * types.length)]; setPowerUps(prev => [...prev, { id: Date.now(), x, y, type, icon: getPowerUpIcon(type) }]); }; // Активация power-up const activatePowerUp = (type) => { powerUpSound.current?.play(); switch (type) { case 'shield': case 'doubleShot': case 'doubleDamage': setIsPowerUpActive(true); setPowerUpType(type); setTimeout(() => { setIsPowerUpActive(false); setPowerUpType(null); }, 10000); break; case 'extraLife': setLives(prev => prev + 1); break; case 'coins': setCoins(prev => prev + 100); break; } }; const getPowerUpIcon = (type) => { const icons = { shield: '????️', doubleShot: '⚡', doubleDamage: '????', extraLife: '❤️', coins: '????' }; return icons[type]; }; // Потеря жизни const loseLife = () => { setLives(prev => { const newLives = prev - 1; if (newLives <= 0) { gameOver(); } return newLives; }); }; // Добавление очков const addScore = (points) => { setScore(prev => { const newScore = prev + points * (isPowerUpActive && powerUpType === 'doubleScore' ? 2 : 1); if (newScore > highScore) { setHighScore(newScore); } return newScore; }); }; // Повышение уровня const levelUp = () => { setLevel(prev => prev + 1); setGameSpeed(prev => prev + 0.2); Alert.alert('Level Up!', `You reached level ${level + 1}!`); }; // Конец игры const gameOver = () => { setGameState('gameOver'); // Остановка игрового цикла if (gameLoopRef.current) clearInterval(gameLoopRef.current); if (enemySpawnRef.current) clearInterval(enemySpawnRef.current); // Остановка музыки backgroundMusic.current?.stop(); // Сохранение результатов saveGameData(); // Показ рекламы if (Math.random() < 0.3) { AdMobInterstitial.showAd(); } }; // Пауза const pauseGame = () => { setGameState('paused'); if (gameLoopRef.current) clearInterval(gameLoopRef.current); if (enemySpawnRef.current) clearInterval(enemySpawnRef.current); backgroundMusic.current?.pause(); }; // Продолжение игры const resumeGame = () => { setGameState('playing'); gameLoopRef.current = setInterval(gameLoop, 16); enemySpawnRef.current = setInterval(spawnEnemy, 2000); backgroundMusic.current?.play(); }; // Просмотр рекламы за награду const watchRewardedAd = () => { AdMobRewarded.showAd() .then(() => { setCoins(prev => prev + 500); Alert.alert('Reward', 'You earned 500 coins!'); }) .catch(error => console.error('Ad failed:', error)); }; return ({/* Игровое поле */} {gameState === 'playing' && ( ); }; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#0a0a0a' }, gameArea: { flex: 1, position: 'relative' }, player: { position: 'absolute', width: 50, height: 50, alignItems: 'center', justifyContent: 'center' }, playerIcon: { fontSize: 40 }, enemy: { position: 'absolute', width: 40, height: 40, borderRadius: 20 }, projectile: { position: 'absolute', width: 4, height: 20, backgroundColor: '#00ff88' }, powerUp: { position: 'absolute', fontSize: 30 }, hud: { position: 'absolute', top: 40, left: 20, right: 20, flexDirection: 'row', justifyContent: 'space-between' }, hudText: { color: 'white', fontSize: 16, fontWeight: 'bold' }, pauseButton: { position: 'absolute', top: 40, right: 20, padding: 10 }, pauseText: { fontSize: 30 }, menu: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#1a1a1a' }, title: { fontSize: 40, color: '#00ff88', fontWeight: 'bold', marginBottom: 20 }, subtitle: { fontSize: 20, color: 'white', marginBottom: 10 }, menuButton: { backgroundColor: '#00ff88', paddingHorizontal: 40, paddingVertical: 15, borderRadius: 25, marginVertical: 10 }, buttonText: { color: '#0a0a0a', fontSize: 18, fontWeight: 'bold' } }); export default MobileGame;{/* Враги */} {enemies.map(enemy => ( )} {/* Меню */} {gameState === 'menu' && ())} {/* Снаряды */} {projectiles.map(projectile => ( ))} {/* Power-ups */} {powerUps.map(powerUp => ( {powerUp.icon} ))} {/* Игрок */}{/* HUD */} ???? {/* Кнопка паузы */} Score: {score} Lives: {'❤️'.repeat(lives)} Level: {level} ???? {coins} ⏸️ )} {/* Пауза */} {gameState === 'paused' && ( ???? Space Shooter High Score: {highScore} Coins: {coins} Play Free Coins (Ad) console.error(error)} /> )} {/* Game Over */} {gameState === 'gameOver' && ( Paused Resume setGameState('menu')} > Main Menu )} Game Over Score: {score} High Score: {highScore} Play Again setGameState('menu')} > Main Menu
Профессиональные шаблоны и полноценные проекты для быстрого старта
Здесь будет полное руководство по работе с Tilda...
Здесь будет руководство по работе с базами данных...
Здесь будет руководство по созданию Telegram ботов...
Здесь будет руководство по интеграции платежей...
Здесь будет руководство по созданию личного кабинета...
Здесь будет руководство по работе с DeepSeek API...
Здесь будет руководство по настройке Docker...