To effectively separate the ReactionGame into two distinct modes—Free Mode and Level Mode—while maintaining shared functionalities, we'll adopt an object-oriented approach using inheritance. This will help in reducing code duplication and enhance maintainability.
Here's the plan:
- Create a Base Class (
BaseReactionGameActivity): This abstract class will contain all the shared logic and UI setup between both modes.
- Create Two Subclasses (
FreeModeActivity and LevelModeActivity): These classes will inherit from the base class and implement mode-specific behaviors.
- Adjust the Layout: Since both modes share most of the UI components, we'll use a single layout file with conditional logic based on the mode.
- Handle Mode-Specific Logic: Implement distinct behaviors for levels, success, failure, and progression in
LevelModeActivity.
Let's proceed with the detailed implementation.
1. BaseReactionGameActivity
This abstract class encapsulates the common functionalities shared between Free Mode and Level Mode.
// File: BaseReactionGameActivity.java
package com.example.memorygameone;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Color;
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 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 abstract class BaseReactionGameActivity extends Activity {
protected GridLayout gridLayout;
protected ArrayList<Button> squares;
protected TextView title, reactionTimeText, countdownText;
protected Button startButton, retryButton;
protected Handler handler;
protected Stopwatch stopwatch;
protected int reactionTime;
protected DB dbHelper;
protected SharedPreferences preferences;
protected String playerNickname;
protected int tileCount;
protected boolean gameStarted = false;
protected boolean countdownFinished = false;
protected boolean gameActive = false;
protected Button correctSquare;
protected Runnable showSquareRunnable;
protected SoundManager soundManager;
protected 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();
handler = new Handler();
soundManager = SoundManager.getInstance(this);
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", 4); // Default to 4 tiles
dbHelper = new DB(this);
preferences = getSharedPreferences("game_prefs", MODE_PRIVATE);
playerNickname = preferences.getString("nickname", "Player");
stopwatch = new Stopwatch();
setupGameGrid();
}
private void setupListeners() {
startButton.setOnClickListener(v -> {
soundManager.playButtonClickSound();
gameActive = true;
startCountdown();
startButton.setVisibility(View.GONE);
});
retryButton.setOnClickListener(v -> {
soundManager.playButtonClickSound();
retryButton.setVisibility(View.GONE);
resetGame();
startCountdown();
});
setAllSquaresClickable(true);
}
protected void setupGameGrid() {
squares = new ArrayList<>();
gridLayout.removeAllViews();
int columnCount = (int) Math.sqrt(tileCount);
gridLayout.setColumnCount(columnCount);
int screenWidth = getResources().getDisplayMetrics().widthPixels;
int tileSize = (screenWidth - 60) / columnCount; // 60 - total margin (30 on each side)
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);
}
}
protected void startCountdown() {
countdownText.setVisibility(View.VISIBLE);
gameStarted = false;
countdownFinished = false;
countdownText.setText("3");
handler.postDelayed(() -> countdownText.setText("2"), 1000);
handler.postDelayed(() -> countdownText.setText("1"), 2000);
handler.postDelayed(() -> {
countdownText.setText("");
countdownText.setVisibility(View.GONE);
countdownFinished = true;
startReactionGame();
}, 3000);
}
protected void startReactionGame() {
title.setText("Wait...");
int randomDelay = new Random().nextInt(4000) + 1000; // Between 1s and 5s
showSquareRunnable = () -> {
showRandomSquare();
stopwatch.start();
gameStarted = true;
};
handler.postDelayed(showSquareRunnable, randomDelay);
}
protected void showRandomSquare() {
Random random = new Random();
int randomIndex = random.nextInt(squares.size());
correctSquare = squares.get(randomIndex);
handler.post(() -> {
correctSquare.setBackgroundColor(Color.GREEN);
title.setText("Tap the green tile!");
});
}
protected void checkReaction(View view) {
if (!gameActive) {
return;
}
Button clickedButton = (Button) view;
if (!countdownFinished) {
title.setText("Wait for the countdown to finish!");
return;
}
if (!gameStarted) {
title.setText("Too soon! Wait for the green tile.");
resetGame();
onGameOver(false, "Tapped too early!");
return;
}
if (clickedButton != correctSquare) {
title.setText("Wrong tile tapped!");
resetGame();
onGameOver(false, "Tapped the wrong tile!");
return;
}
stopwatch.stop();
reactionTime = (int) stopwatch.getElapsedTimeMillis();
clickedButton.setBackgroundColor(Color.BLUE);
reactionTimeText.setText("Reaction Time: " + reactionTime + " ms");
handleSuccessfulTap();
saveBestTime();
resetGame();
}
protected void saveBestTime() {
boolean newRecord = dbHelper.updateReactionGameStats(playerNickname, reactionTime);
if (newRecord) {
soundManager.playNewRecordSound();
showConfetti();
title.setText(title.getText() + " New Record!");
}
}
protected void resetGame() {
handler.removeCallbacks(showSquareRunnable);
for (Button square : squares) {
square.setBackgroundColor(Color.WHITE);
}
gameStarted = false;
countdownFinished = false;
gameActive = false;
retryButton.setVisibility(View.VISIBLE);
if (stopwatch.isRunning()) {
stopwatch.stop();
}
}
protected void setAllSquaresClickable(boolean clickable) {
for (Button square : squares) {
square.setClickable(clickable);
square.setOnClickListener(clickable ? this::checkReaction : null);
}
}
protected 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);
}
// Abstract methods to be implemented by subclasses
protected abstract void handleSuccessfulTap();
protected abstract void onGameOver(boolean isLevelMode, String reason);
}
2. FreeModeActivity
This class handles the Free Mode where the player can practice their reaction without levels.
// File: FreeModeActivity.java
package com.example.memorygameone;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
public class FreeModeActivity extends BaseReactionGameActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
title.setText("Free Mode: Test Your Reaction!");
}
@Override
protected void handleSuccessfulTap() {
evaluateReactionTime(reactionTime);
}
@Override
protected void onGameOver(boolean isLevelMode, String reason) {
title.setText(reason);
retryButton.setVisibility(View.VISIBLE);
}
private void evaluateReactionTime(int reactionTime) {
if (reactionTime <= 200) {
title.setText("Excellent Reaction!");
} else if (reactionTime <= 300) {
title.setText("Good Reaction!");
} else if (reactionTime <= 500) {
title.setText("Average Reaction.");
} else {
title.setText("Can be Faster!");
}
}
}
3. LevelModeActivity
This class manages the Level Mode with progressive difficulty and level-based targets.
// File: LevelModeActivity.java
package com.example.memorygameone;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
public class LevelModeActivity extends BaseReactionGameActivity {
private int currentLevel = 1;
private final int[] levelTargets = {1000, 900, 800, 700, 600, 550, 500, 450, 400, 350}; // in ms
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
currentLevel = 1;
updateLevelTitle();
}
@Override
protected void handleSuccessfulTap() {
checkLevelCompletion(reactionTime);
}
@Override
protected void onGameOver(boolean isLevelMode, String reason) {
soundManager.playGameOverSound();
showConfetti(); // Optional: show confetti on game over
title.setText("Game Over: " + reason);
retryButton.setVisibility(View.VISIBLE);
retryButton.setText("Retry");
retryButton.setOnClickListener(v -> {
soundManager.playButtonClickSound();
currentLevel = 1;
updateLevelTitle();
resetGame();
startCountdown();
});
}
private void checkLevelCompletion(int reactionTime) {
if (reactionTime <= levelTargets[currentLevel - 1]) {
if (currentLevel >= levelTargets.length) {
gameCompleted();
} else {
levelCompleted();
}
} else {
onGameOver(true, "Reaction time exceeded the target!");
}
}
private void levelCompleted() {
soundManager.playLevelUpSound();
title.setText("Level " + currentLevel + " Passed!");
startButton.setText("Next Level");
startButton.setVisibility(View.VISIBLE);
startButton.setOnClickListener(v -> {
soundManager.playButtonClickSound();
currentLevel++;
updateLevelTitle();
resetGame();
startCountdown();
});
}
private void gameCompleted() {
soundManager.playVictorySound();
showConfetti();
title.setText("Congratulations! You completed all levels!");
startButton.setText("Play Again");
startButton.setVisibility(View.VISIBLE);
startButton.setOnClickListener(v -> {
soundManager.playButtonClickSound();
currentLevel = 1;
updateLevelTitle();
resetGame();
startCountdown();
});
}
private void updateLevelTitle() {
title.setText("Level " + currentLevel + ": React under " + levelTargets[currentLevel - 1] + " ms");
}
}
4. Updating the Layout
Assuming both modes share the same layout, ensure that all necessary UI components exist in activity_reaction_game.xml. Here's a simplified version:
<!-- File: res/layout/activity_reaction_game.xml -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/reactionGameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".BaseReactionGameActivity">
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Reaction Game"
android:textSize="24sp"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"/>
<TextView
android:id="@+id/countdownText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="3"
android:textSize="48sp"
android:layout_centerInParent="true"
android:visibility="gone"/>
<GridLayout
android:id="@+id/gridLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/title"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:columnCount="2"
android:rowCount="2">
<!-- Dynamic buttons will be added here -->
</GridLayout>
<TextView
android:id="@+id/reactionTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Reaction Time: --"
android:textSize="18sp"
android:layout_below="@id/gridLayout"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"/>
<Button
android:id="@+id/startBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start"
android:layout_below="@id/reactionTime"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"/>
<Button
android:id="@+id/retryBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Retry"
android:layout_below="@id/reactionTime"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:visibility="gone"/>
<nl.dionsegijn.konfetti.KonfettiView
android:id="@+id/konfettiView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"/>
</RelativeLayout>
Note: Ensure that the KonfettiView library is correctly integrated into your project. If not, add the dependency in your build.gradle:
dependencies {
implementation 'nl.dionsegijn:konfetti:2.0.2'
}
5. Handling Navigation Between Modes
Assuming you have a main menu where players can choose between Free Mode and Level Mode, here's a simple example of how to navigate to the respective activities.
// File: MainActivity.java
package com.example.memorygameone;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
private Button freeModeButton, levelModeButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
freeModeButton = findViewById(R.id.freeModeBtn);
levelModeButton = findViewById(R.id.levelModeBtn);
freeModeButton.setOnClickListener(v -> {
Intent intent = new Intent(MainActivity.this, FreeModeActivity.class);
intent.putExtra("tileCount", 4); // Example tile count
startActivity(intent);
});
levelModeButton.setOnClickListener(v -> {
Intent intent = new Intent(MainActivity.this, LevelModeActivity.class);
intent.putExtra("tileCount", 4); // Example tile count
startActivity(intent);
});
}
}
Main Menu Layout (activity_main_menu.xml):
<!-- File: res/layout/activity_main_menu.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:padding="20dp">
<Button
android:id="@+id/freeModeBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Free Mode"
android:layout_marginBottom="20dp"/>
<Button
android:id="@+id/levelModeBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Level Mode"/>
</LinearLayout>
6. Additional Classes (Assumed Implementations)
Ensure that the following classes are properly implemented in your project.
6.1. Stopwatch
A simple stopwatch to measure reaction time.
// File: Stopwatch.java
package com.example.memorygameone;
public class Stopwatch {
private long startTime = 0;
private long endTime = 0;
private boolean running = false;
public void start() {
startTime = System.currentTimeMillis();
running = true;
}
public void stop() {
if (running) {
endTime = System.currentTimeMillis();
running = false;
}
}
public long getElapsedTimeMillis() {
if (running) {
return System.currentTimeMillis() - startTime;
} else {
return endTime - startTime;
}
}
public boolean isRunning() {
return running;
}
}
6.2. SoundManager
Handles playing different sounds based on game events.
// File: SoundManager.java
package com.example.memorygameone;
import android.content.Context;
import android.media.MediaPlayer;
public class SoundManager {
private static SoundManager instance;
private MediaPlayer buttonClickPlayer, levelUpPlayer, victoryPlayer, gameOverPlayer, newRecordPlayer;
private SoundManager(Context context) {
buttonClickPlayer = MediaPlayer.create(context, R.raw.button_click); // Add appropriate sound files
levelUpPlayer = MediaPlayer.create(context, R.raw.level_up);
victoryPlayer = MediaPlayer.create(context, R.raw.victory);
gameOverPlayer = MediaPlayer.create(context, R.raw.game_over);
newRecordPlayer = MediaPlayer.create(context, R.raw.new_record);
}
public static synchronized SoundManager getInstance(Context context) {
if (instance == null) {
instance = new SoundManager(context.getApplicationContext());
}
return instance;
}
public void playButtonClickSound() {
if (buttonClickPlayer != null) {
buttonClickPlayer.start();
}
}
public void playLevelUpSound() {
if (levelUpPlayer != null) {
levelUpPlayer.start();
}
}
public void playVictorySound() {
if (victoryPlayer != null) {
victoryPlayer.start();
}
}
public void playGameOverSound() {
if (gameOverPlayer != null) {
gameOverPlayer.start();
}
}
public void playNewRecordSound() {
if (newRecordPlayer != null) {
newRecordPlayer.start();
}
}
public void release() {
if (buttonClickPlayer != null) {
buttonClickPlayer.release();
}
if (levelUpPlayer != null) {
levelUpPlayer.release();
}
if (victoryPlayer != null) {
victoryPlayer.release();
}
if (gameOverPlayer != null) {
gameOverPlayer.release();
}
if (newRecordPlayer != null) {
newRecordPlayer.release();
}
}
}
Note: Place appropriate sound files in the res/raw/ directory and reference them accordingly.
6.3. DB
A placeholder for the database helper class. Implement this based on your specific database needs (e.g., SQLite).
// File: DB.java
package com.example.memorygameone;
import android.content.Context;
import android.content.SharedPreferences;
public class DB {
private SharedPreferences sharedPreferences;
public DB(Context context) {
sharedPreferences = context.getSharedPreferences("reaction_game_stats", Context.MODE_PRIVATE);
}
/**
* Updates the reaction game stats for the player.
* Returns true if a new record is set.
*/
public boolean updateReactionGameStats(String nickname, int newTime) {
String key = nickname + "_best_time";
int currentBest = sharedPreferences.getInt(key, Integer.MAX_VALUE);
if (newTime < currentBest) {
sharedPreferences.edit().putInt(key, newTime).apply();
return true;
}
return false;
}
}
7. AndroidManifest Configuration
Ensure that all activities are declared in your AndroidManifest.xml.
<!-- File: AndroidManifest.xml -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.memorygameone">
<application
android:allowBackup="true"
android:label="Reaction Game"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MemoryGameOne">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".FreeModeActivity" />
<activity android:name=".LevelModeActivity" />
<activity android:name=".BaseReactionGameActivity" />
</application>
</manifest>
Note: Typically, you don't declare abstract activities like BaseReactionGameActivity in the manifest. Only include concrete activities (MainActivity, FreeModeActivity, LevelModeActivity).
8. Summary
By following this structure, you've effectively modularized the ReactionGame into Free Mode and Level Mode, allowing for better scalability and maintainability. The BaseReactionGameActivity contains all the shared logic, while the subclasses handle specific behaviors pertinent to each mode.
This approach ensures that:
- Free Mode allows players to test their reaction without the constraints of levels.
- Level Mode provides a progressive challenge, rewarding players with feedback, sounds, and visual effects upon successful completion, and gracefully handling game over scenarios.
Ensure to test each mode thoroughly to confirm that all functionalities work as expected.