Почему не возникают кнопки следующий уровень в режиме на LevelMode а в режиме FreeMode…
- User
Почему не возникают кнопки следующий уровень в режиме на LevelMode а в режиме FreeMode не возникает кнопка еще раз для повтора
package com.example.memorygameone;
import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.widget.Button; import android.widget.GridLayout; import android.widget.TextView; import android.graphics.Color; import android.app.AlertDialog;
import java.util.ArrayList; import java.util.Random;
import nl.dionsegijn.konfetti.KonfettiView; import nl.dionsegijn.konfetti.models.Shape; import nl.dionsegijn.konfetti.models.Size;
public class ReactionGame extends Activity {
private GridLayout gridLayout; private ArrayList<Button> squares; private TextView title, reactionTimeText, countdownText; private Button startButton, retryButton; private Handler handler; private Stopwatch stopwatch; private int reactionTime; private DB dbHelper; private SharedPreferences preferences; private String playerNickname; private int tileCount; private boolean gameStarted = false; private boolean countdownFinished = false; private boolean gameActive = false; private Button correctSquare; private Runnable showSquareRunnable; private String gameMode; private int currentLevel = 1; private int[] levelTargets = {1000, 900, 800, 700, 600, 550, 500, 450, 400, 350}; private SoundManager soundManager; private KonfettiView konfettiView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_reaction_game); konfettiView = findViewById(R.id.konfettiView); gridLayout = findViewById(R.id.gridLayout); initializeViews(); initializeGame(); gameMode = getIntent().getStringExtra("gameMode"); if ("level".equals(gameMode)) { startLevelMode(); } else { startFreeMode(); } setupListeners(); } private void initializeViews() { title = findViewById(R.id.title); reactionTimeText = findViewById(R.id.reactionTime); countdownText = findViewById(R.id.countdownText); startButton = findViewById(R.id.startBtn); retryButton = findViewById(R.id.retryBtn); gridLayout = findViewById(R.id.gridLayout); } private void initializeGame() { tileCount = getIntent().getIntExtra("tileCount", 1); dbHelper = new DB(this); preferences = getSharedPreferences("game_prefs", MODE_PRIVATE); playerNickname = preferences.getString("nickname", "Player"); stopwatch = new Stopwatch(); handler = new Handler(); soundManager = SoundManager.getInstance(this); setupGameGrid(); } private void startLevelMode() { updateLevelTitle(); } private void startFreeMode() { title.setText("Свободный режим: Проверьте вашу реакцию"); } private void setupListeners() { startButton.setOnClickListener(v -> { soundManager.playButtonClickSound(); gameActive = true; startCountdown(); startButton.setVisibility(View.GONE); }); retryButton.setOnClickListener(v -> { soundManager.playButtonClickSound(); gameActive = true; retryButton.setVisibility(View.GONE); startCountdown(); }); setAllSquaresClickable(true); } private void setupGameGrid() { squares = new ArrayList<>(); gridLayout.removeAllViews(); int columnCount = tileCount == 2 ? 2 : (int) Math.sqrt(tileCount); gridLayout.setColumnCount(columnCount); int screenWidth = getResources().getDisplayMetrics().widthPixels; int tileSize = (screenWidth - 60) / 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::checkReaction); squares.add(button); gridLayout.addView(button); } } private void startCountdown() { countdownText.setVisibility(View.VISIBLE); gameStarted = false; countdownFinished = false; handler.postDelayed(() -> countdownText.setText("3"), 0); handler.postDelayed(() -> countdownText.setText("2"), 1000); handler.postDelayed(() -> countdownText.setText("1"), 2000); handler.postDelayed(() -> { countdownText.setText(""); countdownText.setVisibility(View.GONE); countdownFinished = true; startReactionGame(); }, 3000); } private void startReactionGame() { title.setText("Ждите..."); int randomDelay = new Random().nextInt(5000 - 1000) + 1000; showSquareRunnable = () -> { showRandomSquare(); stopwatch.start(); gameStarted = true; }; handler.postDelayed(showSquareRunnable, randomDelay); } private void showRandomSquare() { Random random = new Random(); int randomIndex = random.nextInt(squares.size()); correctSquare = squares.get(randomIndex); handler.post(() -> { correctSquare.setBackgroundColor(Color.GREEN); title.setText("Нажмите на зеленую плитку!"); }); } private void checkReaction(View view) { if (!gameActive) { return; } Button clickedButton = (Button) view; if (!countdownFinished) { title.setText("Подождите окончания отсчета!"); return; } if (!gameStarted) { title.setText("Слишком рано! Подождите зеленую плитку."); resetGame(); return; } if (clickedButton != correctSquare) { title.setText("Ошибка! Нажата неверная плитка."); resetGame(); return; } stopwatch.stop(); reactionTime = (int) stopwatch.getElapsedTimeMillis(); clickedButton.setBackgroundColor(Color.BLUE); reactionTimeText.setText("Время реакции: " + reactionTime + " мс"); if ("level".equals(gameMode)) { checkLevelCompletion(reactionTime); } else { evaluateReactionTime(reactionTime); retryButton.setVisibility(View.VISIBLE); gameActive = false; } saveBestTime(); gameActive = false; // Сброс игры после обработки реакции resetGame(); } private void levelCompleted() { soundManager.playLevelUpSound(); title.setText("Уровень " + currentLevel + " пройден!"); startButton.setText("Следующий уровень"); startButton.setVisibility(View.VISIBLE); retryButton.setVisibility(View.GONE); gameActive = false; startButton.setOnClickListener(v -> { soundManager.playButtonClickSound(); currentLevel++; updateLevelTitle(); startButton.setVisibility(View.GONE); gameActive = true; startCountdown(); }); } private void updateLevelTitle() { title.setText("Уровень " + currentLevel + ": Реагируйте быстрее чем " + levelTargets[currentLevel - 1] + " мс"); } private void gameCompleted() { soundManager.playVictorySound(); showConfetti(); title.setText("Поздравляем! Вы прошли все уровни!"); startButton.setText("Играть снова"); startButton.setVisibility(View.VISIBLE); retryButton.setVisibility(View.GONE); gameActive = false; startButton.setOnClickListener(v -> { soundManager.playButtonClickSound(); currentLevel = 1; updateLevelTitle(); startButton.setVisibility(View.GONE); gameActive = true; startCountdown(); }); } private void saveBestTime() { boolean newRecord = dbHelper.updateReactionGameStats(playerNickname, reactionTime); if (newRecord) { soundManager.playNewRecordSound(); showConfetti(); title.setText(title.getText() + " Новый рекорд!"); } } private void resetGame() { handler.removeCallbacks(showSquareRunnable); for (Button square : squares) { square.setBackgroundColor(Color.WHITE); } gameStarted = false; countdownFinished = false; gameActive = false; retryButton.setVisibility(View.GONE); // Скрываем кнопку "Еще раз" startButton.setVisibility(View.GONE); // Скрываем кнопку "Старт" if (stopwatch.isRunning()) { stopwatch.stop(); } setAllSquaresClickable(true); } private void evaluateReactionTime(int reactionTime) { if (reactionTime <= 200) { title.setText("Отличная реакция!"); } else if (reactionTime <= 300) { title.setText("Хорошая реакция!"); } else if (reactionTime <= 500) { title.setText("Средняя реакция."); } else { title.setText("Можно быстрее!"); } } private void checkLevelCompletion(int reactionTime) { if (reactionTime <= levelTargets[currentLevel - 1]) { if (currentLevel >= levelTargets.length) { gameCompleted(); } else { levelCompleted(); } } else { // Показываем диалоговое окно при провале уровня AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Уровень не пройден") .setMessage("Вы не уложились в " + levelTargets[currentLevel - 1] + " мс") .setCancelable(false) .setPositiveButton("Начать с первого уровня", (dialog, which) -> { soundManager.playButtonClickSound(); currentLevel = 1; updateLevelTitle(); gameActive = true; startCountdown(); }) .setNegativeButton("Главное меню", (dialog, which) -> { soundManager.playButtonClickSound(); finish(); // Возвращаемся в главное меню }); AlertDialog alert = builder.create(); alert.show(); gameActive = false; // Останавливаем игру до выбора действия } } private void setAllSquaresClickable(boolean clickable) { for (Button square : squares) { square.setClickable(clickable); if (clickable) { square.setOnClickListener(this::checkReaction); } else { square.setOnClickListener(null); } } } private void showConfetti() { konfettiView.build() .addColors(Color.YELLOW, Color.GREEN, Color.MAGENTA) .setDirection(0.0, 359.0) .setSpeed(1f, 5f) .setFadeOutEnabled(true) .setTimeToLive(2000L) .addShapes(Shape.Square.INSTANCE, Shape.Circle.INSTANCE) .addSizes(new Size(12, 5f)) .setPosition(-50f, konfettiView.getWidth() + 50f, -50f, -50f) .streamFor(300, 5000L); } - Assistant