MemoryGame.java: public class MemoryGame extends AppCompatActivity { private GridLayout…
- User
MemoryGame.java: public class MemoryGame extends AppCompatActivity {
private GridLayout gridLayout; private ArrayList<Button> squares; // Кнопки для плиток игры private TextView title, level, scoreText; private Button startButton, nextLevelButton; private ArrayList<Button> correctSeq; // Правильная последовательность плиток private int currentLevel; // Текущий уровень игры private int currentScore; // Текущий счет игрока private int userIndex; // Индекс текущего хода игрока private int tileCount; // Количество плиток в зависимости от сложности private String difficulty; // Сложность игры (легкая, средняя, сложная) private int attemptsLeft = 3; // Количество оставшихся попыток private int currentTilePoints = 50; // Очки за плитку private SoundManager soundManager; // Управление звуком в игре private Handler handler; private SharedPreferences preferences; private String playerUserId; // Идентификатор пользователя из Firebase @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_memory_game); // Инициализация компонентов игры soundManager = SoundManager.getInstance(this); gridLayout = findViewById(R.id.gridLayout); title = findViewById(R.id.title); level = findViewById(R.id.level); scoreText = findViewById(R.id.score); startButton = findViewById(R.id.startBtn); nextLevelButton = findViewById(R.id.nextLevelBtn); // Получаем настройки игры и идентификатор пользователя preferences = getSharedPreferences("game_prefs", MODE_PRIVATE); FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser(); if (currentUser != null) { playerUserId = currentUser.getUid(); } else { // Если пользователь не вошел в систему, перенаправляем его на экран входа Intent intent = new Intent(MemoryGame.this, LoginActivity.class); startActivity(intent); finish(); return; } // Инициализация уровня, очков и количества плиток currentLevel = 1; currentScore = 0; tileCount = getIntent().getIntExtra("tileCount", 9); // Количество плиток зависит от сложности difficulty = getDifficultyLabel(tileCount); // Получаем уровень сложности setupUI(); // Настройка пользовательского интерфейса setupGameGrid(); // Инициализация сетки плиток для игры // Запуск игры по нажатию на кнопку "Старт" startButton.setOnClickListener(v -> startGame()); nextLevelButton.setOnClickListener(v -> startGame()); nextLevelButton.setVisibility(View.GONE); // Кнопка следующего уровня скрыта до окончания текущего } // Метод для настройки UI элементов private void setupUI() { title.setTextColor(Color.ORANGE); level.setTextColor(Color.ORANGE); scoreText.setTextColor(Color.ORANGE); startButton.setBackgroundColor(Color.PURPLE); nextLevelButton.setBackgroundColor(Color.PURPLE); } // Метод для установки сетки игры в зависимости от количества плиток private void setupGameGrid() { squares = new ArrayList<>(); gridLayout.removeAllViews(); // Очищаем старую сетку int columnCount = (int) Math.sqrt(tileCount); // Определяем количество колонок в сетке gridLayout.setColumnCount(columnCount); // Рассчитываем размер плиток в зависимости от экрана int screenWidth = getResources().getDisplayMetrics().widthPixels; int availableWidth = screenWidth - 40; // Оставляем немного места для отступов int tileSize = availableWidth / columnCount; // Создаем кнопки для каждой плитки for (int i = 0; i < tileCount; i++) { Button button = new Button(this); GridLayout.LayoutParams params = new GridLayout.LayoutParams(); params.width = tileSize; params.height = tileSize; params.setMargins(5, 5, 5, 5); // Устанавливаем отступы button.setLayoutParams(params); button.setBackgroundColor(Color.WHITE); // Начальный цвет плитки button.setOnClickListener(this::checkSequence); // Обработка нажатия на плитку squares.add(button); // Добавляем плитку в список gridLayout.addView(button); // Добавляем плитку в сетку } } // Метод запуска игры private void startGame() { correctSeq.clear(); // Очищаем последовательность для нового уровня currentScore = 0; // Сбрасываем счет currentLevel = 1; // Сбрасываем уровень userIndex = 0; // Сбрасываем индекс пользователя // Отображаем подсказку для пользователя title.setText("Запоминай последовательность!"); nextLevelButton.setVisibility(View.GONE); // Скрываем кнопку следующего уровня showPattern(); // Показать правильную последовательность плиток } // Метод для показа правильной последовательности private void showPattern() { disableSquares(); // Отключаем нажатие на плитки, пока показывается последовательность for (int i = 0; i < currentLevel; i++) { int randomIndex = new Random().nextInt(squares.size()); Button randomSq = squares.get(randomIndex); correctSeq.add(randomSq); // Добавляем плитку в правильную последовательность // "Мигаем" правильной плиткой flashButton(randomSq, false); } } // Метод для проверки, правильно ли нажата плитка private void checkSequence(View view) { Button clickedButton = (Button) view; if (clickedButton == correctSeq.get(userIndex)) { // Правильное нажатие userIndex++; currentScore += currentTilePoints; // Начисляем очки updateUI(); // Обновляем интерфейс // Если последовательность полностью угадана, переходим на следующий уровень if (userIndex == currentLevel) { currentLevel++; nextLevelButton.setVisibility(View.VISIBLE); // Показываем кнопку следующего уровня } } else { // Ошибка attemptsLeft--; if (attemptsLeft == 0) { gameOver(); // Если попытки закончились, игра завершена } else { resetLevel(); // Перезапускаем уровень } } } // Метод для завершения игры private void gameOver() { // Показ сообщения об окончании игры и сброс игры showGameOverDialog(); } - Assistant