package ai;
import controller.Game;
import java.util.Random;
/**
- The {@code Bot} class represents an automated player for the game.
- It is designed to simulate player actions in the game by making moves autonomously.
- The class contains logic to randomly decide between different actions such as moving
- left, moving right, or performing a long drop of the current game piece (MultiMino).
-
- It uses a {@code Random} object to generate random decisions, thereby introducing unpredictability
- in the bot's gameplay.
-
- to the left or right or perform a long drop to instantly bring the game piece to the lowest possible
- position. The actions are executed within the context of the provided {@code Game} instance.
-
- the changes on the game board.
- @version 0.1 - 2023-11-29, 16:05 PM
- @author Matthieu M
- TODO: bot
*/
public class Bot {
private Random random;
private int moveCount;
private int rotateCount;
public Bot() {
random = new Random();
moveCount = 0;
rotateCount = 0;
}
public void makeMove(Game game) {
// Step 1: Move left or right between 3 and 7 times
if (moveCount < 3 || (moveCount < 7 && random.nextBoolean())) {
boolean moveLeft = random.nextBoolean();
game.moveMultiMino(moveLeft ? -1 : 1, 0);
moveCount++;
}
// Step 2: Rotate between 1 and 4 times
else if (rotateCount < 1 || (rotateCount < 4 && random.nextBoolean())) {
game.rotateMultiMino(game.getCurrentMultiMino());
rotateCount++;
}
// Step 3: Long drop
else {
while (game.canMoveMultiMino(game.getCurrentMultiMino(), 0, 1)) {
game.moveMultiMino(0, 1);
}
resetCounts();
}
// Repaint the game window if it's not paused
if (!game.isPaused()) {
game.repaintWindow();
}
}
private void resetCounts() {
moveCount = 0;
rotateCount = 0;
}
}
package config;
import java.awt.*;
/**
- The {@code Config} class holds the configuration constants for the game.
- This includes settings for window size, board dimensions, color schemes, and game timings.
- This centralized configuration makes it easier to manage and modify the game's settings.
- @version 0.1 - last updated on 2023-11-18, 13:52 PM
- @author Matthieu M
*/
public class Config {
// Prevents instantiation
private Config() {}
// Window Settings
public static final String GAME_TITLE = "Basic Mino Game";
public static final int WINDOW_WIDTH = 1200;
public static final int WINDOW_HEIGHT = 900;
// Board Settings
public static final Color BACKGROUND_COLOR = new Color(0, 0, 60); // Dark blue
// Darker background color for the first five rows
public static final Color DARKER_BACKGROUND_COLOR = new Color(0, 0, 45);
public static final int CELL_SIZE = 30;
public static final int BOARD_WIDTH = 7;
public static final int BOARD_HEIGHT = 20;
// Game Timings
public static final int GAME_DELAY = 1000;
public static final int GAME_DELAY_DECREASE = 300;
public static final int GAME_DELAY_POINT_INCREMENTS = 3;
// Score Box Settings
public static final int SCORE_BOX_WIDTH = 250;
public static final int SCORE_BOX_HEIGHT = 250;
public static final int SCORE_BOX_PADDING = 50;
public static final Color SCORE_BOX_COLOR = Color.GRAY;
public static final Font SCORE_BOX_FONT = new Font("Arial", Font.BOLD, 16);
// Controls Box Settings
public static final int CONTROLS_BOX_PADDING = 50;
public static final int CONTROLS_BOX_RIGHT_PADDING = 10;
public static final Color CONTROLS_BOX_COLOR = Color.DARK_GRAY;
public static final Font CONTROLS_BOX_FONT = new Font("Arial", Font.BOLD, 16);
// Game Settings
public static final int POINTS_PER_ROW = 1;
// Game Controls
// TODO (MM): implement enums?
public static final String [] GAME_CONTROLS = {
"Keyboard Commands",
"",
"Controls:",
"Left Arrow - Move Left",
"Right Arrow - Move Right",
"Down Arrow - Move Down",
"Space Bar (Long Press) - Drop",
"P - Pause/Resume",
"ESC - Open Menu"
};
// AI
public static final int BOT_ACTION_DELAY = 200; // time between bot actions
}
package config;
import java.util.*;
/**
- The {@code MultiMinoTemplates} class contains the definitions of various Pentomino patterns used in the game.
- It provides a central repository of all the standard Pentomino shapes, represented as 2D arrays. Each array
- defines the structure of a Pentomino shape, where '1' represents a filled block and '0' represents an empty space.
-
- include new shapes. The patterns are used by the game engine to render the Pentominos on the game board.
-
- @since 0.1
- @version 0.2 - added getAllPatternVariations() and its helper methods (2023-11-22, 13:46 PM)
- @author Matthieu M
*/
public class MultiMinoTemplates {
// Representation of the empty Pentomino
public static final int[][] EMPTY_PATTERN = {
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
};
// Representation of the X Pentomino
public static final int[][] X_PATTERN = {
{0, 0, 0, 0, 0},
{0, 0, 1, 0, 0},
{0, 1, 1, 1, 0},
{0, 0, 1, 0, 0},
{0, 0, 0, 0, 0},
};
// Representation of the I Pentomino
public static final int[][] I_PATTERN = {
{0, 0, 1, 0, 0},
{0, 0, 1, 0, 0},
{0, 0, 1, 0, 0},
{0, 0, 1, 0, 0},
{0, 0, 1, 0, 0},
};
// Representation of the Z Pentomino
public static final int[][] Z_PATTERN = {
{0, 0, 0, 0, 0},
{0, 0, 1, 1, 0},
{0, 0, 1, 0, 0},
{0, 1, 1, 0, 0},
{0, 0, 0, 0, 0},
};
// Representation of the T Pentomino
public static final int[][] T_PATTERN = {
{0, 0, 0, 0, 0},
{0, 1, 1, 1, 0},
{0, 0, 1, 0, 0},
{0, 0, 1, 0, 0},
{0, 0, 0, 0, 0},
};
// Representation of the U Pentomino
public static final int[][] U_PATTERN = {
{0, 0, 0, 0, 0},
{0, 1, 0, 1, 0},
{0, 1, 1, 1, 0},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
};
// Representation of the V Pentomino
public static final int[][] V_PATTERN = {
{0, 0, 0, 0, 0},
{0, 1, 1, 1, 0},
{0, 1, 0, 0, 0},
{0, 1, 0, 0, 0},
{0, 0, 0, 0, 0},
};
// Representation of the W Pentomino
public static final int[][] W_PATTERN = {
{0, 0, 0, 0, 0},
{0, 0, 1, 1, 0},
{0, 0, 1, 0, 0},
{0, 1, 1, 0, 0},
{0, 0, 0, 0, 0},
};
// Representation of the Y Pentomino
public static final int[][] Y_PATTERN = {
{0, 1, 0, 0, 0},
{0, 1, 1, 0, 0},
{0, 1, 0, 0, 0},
{0, 1, 0, 0, 0},
{0, 0, 0, 0, 0},
};
// Representation of the L Pentomino
public static final int[][] L_PATTERN = {
{0, 1, 0, 0, 0},
{0, 1, 0, 0, 0},
{0, 1, 0, 0, 0},
{0, 1, 1, 0, 0},
{0, 0, 0, 0, 0},
};
// Representation of the P Pentomino
public static final int[][] P_PATTERN = {
{0, 0, 0, 0, 0},
{0, 1, 1, 0, 0},
{0, 1, 1, 0, 0},
{0, 1, 0, 0, 0},
{0, 0, 0, 0, 0},
};
// Representation of the N Pentomino
public static final int[][] N_PATTERN = {
{0, 0, 0, 0, 0},
{0, 1, 1, 0, 0},
{0, 0, 1, 1, 1},
{0, 0, 0, 0, 0},
{0, 0, 0, 0, 0},
};
// Representation of the N Pentomino
public static final int[][] F_PATTERN = {
{0, 0, 0, 0, 0},
{0, 0, 1, 1, 0},
{0, 1, 1, 0, 0},
{0, 0, 1, 0, 0},
{0, 0, 0, 0, 0},
};
/**
* Retrieves a specified pattern by its name.
*
* @param patternName The string name of the pattern to retrieve.
* @return A 2D integer array representing the requested pattern. Returns {@link #EMPTY_PATTERN} if the name does not match any known pattern.
*/
public static int[][] getPattern(String patternName) {
switch (patternName) {
case "X":
return X_PATTERN;
case "I":
return I_PATTERN;
case "Z":
return Z_PATTERN;
case "T":
return T_PATTERN;
case "U":
return U_PATTERN;
case "V":
return V_PATTERN;
case "W":
return W_PATTERN;
case "Y":
return Y_PATTERN;
case "L":
return L_PATTERN;
case "P":
return P_PATTERN;
case "N":
return N_PATTERN;
case "F":
return F_PATTERN;
default:
return EMPTY_PATTERN;
}
}
/**
* Retrieves a random pattern variation. This includes all possible rotations and flips of the patterns.
*
* @return A 2D integer array representing a randomly selected pattern variation.
*/
public static int[][] getRandomPatternVariation() {
List<int[][]> allVariations = getAllPatternVariations();
Random random = new Random();
return allVariations.get(random.nextInt(allVariations.size()));
}
/**
* Rotates a given pattern by 90 degrees clockwise.
*
* @param pattern The 2D integer array representing the pattern to rotate.
* @return A new 2D integer array representing the rotated pattern.
*/
private static int[][] rotate90(int[][] pattern) {
final int M = pattern.length;
final int N = pattern[0].length;
int[][] rotated = new int[N][M];
for (int r = 0; r < M; r++) {
for (int c = 0; c < N; c++) {
rotated[c][M - 1 - r] = pattern[r][c];
}
}
return rotated;
}
/**
* Flips a given pattern horizontally.
*
* @param pattern The 2D integer array representing the pattern to flip.
* @return A new 2D integer array representing the horizontally flipped pattern.
*/
private static int[][] flipHorizontal(int[][] pattern) {
int[][] flipped = new int[pattern.length][pattern[0].length];
for (int i = 0; i < pattern.length; i++) {
for (int j = 0; j < pattern[i].length; j++) {
flipped[i][pattern[i].length - 1 - j] = pattern[i][j];
}
}
return flipped;
}
/**
* Generates all unique variations of a given pattern, including its rotations and horizontal flips.
*
* @param pattern The 2D integer array representing the base pattern.
* @return A list of 2D integer arrays, each representing a unique variation of the pattern.
*/
public static List<int[][]> generateAllVariations(int[][] pattern) {
Set<String> seen = new HashSet<>();
List<int[][]> variations = new ArrayList<>();
int[][] current = pattern;
for (int i = 0; i < 4; i++) { // 4 rotations
current = rotate90(current);
if (seen.add(Arrays.deepToString(current))) {
variations.add(current);
}
int[][] flippedH = flipHorizontal(current);
if (seen.add(Arrays.deepToString(flippedH))) {
variations.add(flippedH);
}
}
return variations;
}
/**
* Compiles all variations of each predefined pattern into a single list. This includes rotations and horizontal flips of each pattern.
*
* @return A list of 2D integer arrays, each representing a unique pattern variation from the set of predefined patterns.
*/
public static List<int[][]> getAllPatternVariations() {
List<int[][]> allVariations = new ArrayList<>();
int[][][] patterns = {X_PATTERN, I_PATTERN, Z_PATTERN, T_PATTERN, U_PATTERN, V_PATTERN, W_PATTERN, Y_PATTERN, L_PATTERN, P_PATTERN, N_PATTERN, F_PATTERN};
for (int[][] pattern : patterns) {
allVariations.addAll(generateAllVariations(pattern));
}
return allVariations;
}
// Place additional patterns and methods here
}
package controller;
import ai.Bot;
import config.MultiMinoTemplates;
import model.*;
import view.GameWindow;
import config.Config;
import view.SoundManager;
import view.UserInterfaceManager;
import javax.swing.*;
import java.awt.Color;
import java.util.Random;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
- The {@code Game} class serves as the controller in the Model-View-Controller (MVC) pattern of this game application.
- It manages the game logic, processes user input, updates the game state, and interacts with the {@link GameWindow}
- to refresh the user interface.
- This class is responsible for moving the game pieces (Mino), handling pause/resume functionality, and managing the
- game's timing mechanism.
-
- {@code moveMino} for moving game pieces, and {@code togglePause} for pausing and resuming the game.
- @version 0.4 - 2023-11-22, 14:53 PM - Fixed the double game timer issue
- @version 0.5 - 2023-11-29, 16:24 PM - Added method isColorDifferenceSufficient to prevent Mino colors that are too
- close to the board grid
- @version 0.6 - 2023-11-29, 23:56 PM - Added rotational safeguards so the MultiMinos don't rotate outside of the grid
- @version 0.7 - 2023-11-29, 01:15 PM - Fixed bug where in bot mode, the multimino would go down 2 rows per game loop
- @version 0.8 - 2023-11-30, 09:31 AM - Added another timer to allow bot to play at a different speed than game speed
- @version 0.9 - 2023-11-30, 11:50 AM - Fixed the game over issue where the game didn't pause and kept looping
- @author Matthieu M
- TODO MM: move most methods that aren't "controller" natured out of the Game class
*/
public class Game {
// TODO MM: what is the name for these things?
// --------------------------------------------------------------------------------------------------------------------
// TODO MM: classify these variables below
private Mino nextMino;
private Mino mino;
private MultiMino nextMultiMino;
private MultiMino activeMultiMino;
// UI components
private GameWindow gameWindow;
private GameGrid boardGameGrid;
private SoundManager soundManager;
private UserInterfaceManager uiManager;
// Game logic components
private KeyboardController keyboardController;
private boolean isClearingRows = false;
private boolean isPaused = false;
// Utility objects
private Random random;
private Timer gameLoopTimer;
private ScoreManager scoreManager;
private int gameLevel = 1;
private boolean isGameOver = false;
// Gameplay components
public int score;
private String playerName;
private int lastSpeedIncreaseScore = 0; // Track the score at the last speed increase
// Developer components
// flag for static mode
// TODO MM: delete once it works
private boolean isStaticMode = false;
// AI components
private boolean isBotModeActivated;
private Bot botPlayer;
private Timer botActionTimer;
// Constructors
// --------------------------------------------------------------------------------------------------------------------
/**
* Constructor for Game class. Initializes the game state by prompting for player name,
* initializing game components, and starting the game loop.
*/
public Game() {
soundManager = new SoundManager();
uiManager = new UserInterfaceManager(soundManager);
uiManager.setGame(this);
// Prompt for player's name
playerName = uiManager.promptForPlayerName();
// Initialize game components
initializeGameComponents();
initializeBotActionTimer();
// Start the game loop
gameLoop();
}
// Main Functional Methods
// --------------------------------------------------------------------------------------------------------------------
/**
* Starts the game loop of the application.
* This method initializes and starts a timer that triggers events at regular intervals
* defined in the Config.GAME_DELAY. Each tick of the timer calls the moveMinoDown method,
* which is responsible for updating the game state and refreshing the UI. This setup
* centralizes the control of the game's timing mechanism, making it easier to manage
* the game's progression and frame updates.
*/
private void gameLoop() {
// Initialize the game loop timer with a delay specified in Config
gameLoopTimer = new Timer(Config.GAME_DELAY, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (isGameOver) {
return; // Stop the game loop updates if the game is over
}
if (isBotModeActivated) {
// If not already running, start the bot action timer
if (!botActionTimer.isRunning()) {
botActionTimer.start();
}
} else {
// If bot mode is not activated, stop the bot action timer
if (botActionTimer.isRunning()) {
botActionTimer.stop();
}
}
if (!isStaticMode) {
moveActiveMultiMinoDown();
}
printGridState(); // TODO delete
updateGameSpeed(); // Call this method to check and update game speed
}
});
// Start the timer to begin the game loop
gameLoopTimer.start();
}
/**
* Initializes all necessary components of the game, including the game grid, window,
* keyboard controller, and other utilities.
*/
private void initializeGameComponents() {
botPlayer = new Bot();
// Initialize the game grid with specified width and height from Config
boardGameGrid = new GameGrid(Config.BOARD_WIDTH, Config.BOARD_HEIGHT);
// Initialize the game window and set it visible
gameWindow = new GameWindow(boardGameGrid, this);
gameWindow.setVisible(true);
// Initialize the keyboard controller
keyboardController = new KeyboardController();
// Initialize the random object for random color generation
random = new Random();
// Set this game's score to 0
score = 0;
// Start a new Score Manager
scoreManager = new ScoreManager();
//gameLoopTimer.start();
// Generate the first multiMino
generateNewMultiMino();
}
/**
* Resets the current game state. This method halts the ongoing game loop, closes the existing game window,
* and initiates the creation of a new game instance. It ensures that all game components are reinitialized,
* effectively starting the game from the beginning. This method is particularly useful for providing
* players with the option to restart the game without needing to exit or re-launch the application.
*/
public void resetGame() {
// Stop the game loop timer
if (gameLoopTimer != null) {
gameLoopTimer.stop();
}
// Close the current game window
if (gameWindow != null) {
gameWindow.dispose();
}
// Create a new instance of Game
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Game();
}
});
}
public void toggleBotMode() {
isBotModeActivated = !isBotModeActivated;
// Start or stop the bot actions based on the new state of isBotModeActivated
if (isBotModeActivated && !botActionTimer.isRunning()) {
botActionTimer.start();
} else if (!isBotModeActivated && botActionTimer.isRunning()) {
botActionTimer.stop();
}
}
private void updateGameSpeed() {
if (score / Config.GAME_DELAY_POINT_INCREMENTS > lastSpeedIncreaseScore) {
lastSpeedIncreaseScore = score / Config.GAME_DELAY_POINT_INCREMENTS;
gameLevel++; // Increase game level
int newDelay = Math.max(gameLoopTimer.getDelay() - Config.GAME_DELAY_DECREASE, 100); // Adjust game speed
gameLoopTimer.setDelay(newDelay);
}
}
// Utility Methods
// --------------------------------------------------------------------------------------------------------------------
/**
* Handles key press events by delegating to the keyboard controller.
*
* @param keyCode The integer code of the key pressed.
*/
public void handleKeyPress(int keyCode) {
keyboardController.handleKeyPress(this, keyCode);
}
/**
* Toggles the pause state of the game. Pauses the game if running, resumes if paused.
*/
public void togglePause() {
if (gameLoopTimer != null) {
isPaused = !isPaused;
if (isPaused) {
gameLoopTimer.stop();
System.out.println("Game paused");
} else {
gameLoopTimer.start();
System.out.println("Game resumed");
}
}
}
/**
* Moves the active multiMino down one space, updating the game state and UI.
*/
private void moveActiveMultiMinoDown() {
if (!isClearingRows) {
if (activeMultiMino != null) {
moveMultiMino(0, 1); // Move the active MultiMino down by 1
if (!activeMultiMino.isMultiMinoActive()) {
// If the MultiMino is no longer active after the move, generate a new MultiMino
generateNewMultiMino();
}
}
}
gameWindow.repaintWindow();
}
/**
* Generates a new Mino piece and handles the transition of the next Mino to become the current Mino.
* The next Mino is generated but remains inactive until it becomes the current Mino.
*/
private void generateNewMino() {
if (nextMino == null) {
// This is for the first Mino
nextMino = createRandomMino();
nextMino.setMinoStatus(false); // The next Mino starts as inactive
}
// Transfer nextMino to be the current mino
mino = nextMino;
mino.setMinoStatus(true); // Activate the current Mino
// Check if the starting position is already occupied
if (isPositionOccupied(mino.getX(), mino.getY())) {
togglePause();
uiManager.gameOver(); // Call game over method if the position is occupied
} else {
boardGameGrid.placeMino(mino); // Place the mino if the position is not occupied
}
nextMino = createRandomMino();
nextMino.setMinoStatus(false);
}
/**
* TODO MM: write header
*/
private Mino createRandomMino() {
Color randomColor;
do {
randomColor = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
} while (!isColorDifferenceSufficient(randomColor, Config.BACKGROUND_COLOR));
return new Mino(2, 0, randomColor); // Modify as per your mino generation logic
}
/**
*
* Makes sure Mino color isn't too close to the GameGrid's color
*
* @param color1
* @param color2
* @return
*/
private boolean isColorDifferenceSufficient(Color color1, Color color2) {
int redDiff = Math.abs(color1.getRed() - color2.getRed());
int greenDiff = Math.abs(color1.getGreen() - color2.getGreen());
int blueDiff = Math.abs(color1.getBlue() - color2.getBlue());
int threshold = 30; // You can adjust this threshold value
return (redDiff > threshold || greenDiff > threshold || blueDiff > threshold);
}
/**
* Moves the mino in the specified direction if the new position is within the bounds of the board.
*
* @param dx The change in the x-direction.
* @param dy The change in the y-direction.
*
* TODO clean this method up
*/
public void moveMino(int dx, int dy) {
int newX = mino.getX() + dx;
int newY = mino.getY() + dy;
// Check if new position is within grid bounds
if (isWithinBoardBounds(newX, newY)) {
// Check if the position is either occupied or at the bottom of the grid
if (isAtBoardHeight(newY) || isPositionOccupied(newX, newY)) {
mino.setMinoStatus(false);
generateNewMino(); // Generate a new mino at the top
if (!isClearingRows) {
startClearFullRowsTimer(); // Start the timer to clear full rows after a delay
}
} else {
// Proceed to move mino to the new position
boardGameGrid.clearMino(mino.getX(), mino.getY()); // Clear old position
mino.setX(newX);
mino.setY(Math.min(newY, Config.BOARD_HEIGHT - 1)); // Ensure newY is within the grid boundary
boardGameGrid.placeMino(mino); // Place mino at new position
gameWindow.repaintWindow(); // Repaint the window
}
}
}
/**
* Checks whether the x and y coordinates are within board bounds.
*/
private boolean isWithinBoardBounds(int x, int y) {
return x >= 0 && x < Config.BOARD_WIDTH && y <= Config.BOARD_HEIGHT;
}
/**
* Checks whether the y coordinate is at the end of the board (board height)
*/
private boolean isAtBoardHeight(int y) {
return y == Config.BOARD_HEIGHT;
}
/**
* Checks whether the position at x, y on the board is occupied by a non-active Mino.
*/
private boolean isPositionOccupied(int x, int y) {
if (y < Config.BOARD_HEIGHT) {
Mino minoAtPosition = boardGameGrid.getMinoAt(y, x);
if (minoAtPosition != null && !minoAtPosition.isActive()) {
return true; // The position is occupied by a non-active Mino
}
}
return false; // The position is not occupied or occupied by an active Mino
}
/**
* Initiates a short delay before clearing full rows in the game grid. This method temporarily pauses the
* main game loop to process the clearing of full rows. It creates a one-second timer that, upon completion,
* checks and clears any full rows in the grid, updates the player's score based on the number of rows cleared,
* and then resumes the main game loop. This delay allows for a brief pause in gameplay, giving players a moment
* to visually recognize the row clearing action. Additionally, it updates the leaderboard and refreshes the game
* window to reflect these changes in the game state.
*/
private void startClearFullRowsTimer() {
// Stop the game loop timer
gameLoopTimer.stop();
isClearingRows = true;
// TODO MM: move values to Config
new Timer(100, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int rowsCleared = boardGameGrid.clearFullRows();
score += Config.POINTS_PER_ROW * rowsCleared; // Increment score based on rows cleared
updateGameSpeed();
scoreManager.updateLeaderboard(playerName, score);
gameWindow.repaintWindow(); // Repaint after rows are cleared
// Resume the game loop timer
gameLoopTimer.start();
isClearingRows = false;
((Timer) e.getSource()).stop(); // Stop the timer to avoid repeating the action
}
}).start();
}
/**
* Checks if the game is paused
*/
public boolean isPaused() {
return isPaused;
}
/**
* calls the repaintWindow method in gameWindow
*/
public void repaintWindow() {
gameWindow.repaintWindow();
}
private void initializeBotActionTimer() {
botActionTimer = new Timer(Config.BOT_ACTION_DELAY, e -> {
if (isBotModeActivated) {
botPlayer.makeMove(this);
}
});
}
// Accessor and Mutator Methods (Getters and Setters)
// --------------------------------------------------------------------------------------------------------------------
// These methods provide controlled access to the class's fields.
// Getters return the current values, and setters allow modification of the values
/**
* Getter for playerName.
* @return The current value of playerName.
*/
public String getPlayerName() {
return playerName;
}
/**
* Setter for playerName.
* @param playerName The new value to set for playerName.
*/
public void setPlayerName(String playerName) {
this.playerName = playerName;
}
/**
* Gets the current score manager.
*
* @return The instance of the ScoreManager.
*/
public ScoreManager getScoreManager() {
return scoreManager;
}
// Getter for nextMino
public Mino getNextMino() {
return nextMino;
}
public int getGameLevel() {
return gameLevel; // gameLevel is the variable tracking the game level
}
/**
* Getter for isBotModeActivated.
* @return The current value of isBotModeActivated.
*/
public boolean isBotModeActivated() {
return isBotModeActivated;
}
/**
* Setter for isBotModeActivated.
* @param isBotModeActivated The new value to set for isBotModeActivated.
*/
public void setBotModeActivated(boolean isBotModeActivated) {
this.isBotModeActivated = isBotModeActivated;
}
public void setGameOver(boolean isGameOver) {
this.isGameOver = isGameOver;
}
// Temporary Method Holding
// --------------------------------------------------------------------------------------------------------------------
/**
* Handles the ESC key press to open the in-game menu.
* This method pauses the game and displays a menu dialog with options to quit, resume, or reset the game.
* Depending on the player's choice, it either exits the game, resumes play, or resets the game state.
* The game's state is paused upon invoking this method and is resumed based on player interaction
* with the menu. This method ensures the game's responsiveness to player input and provides essential
* game control functionalities.
*/
// TODO MM: migrate this method to view.UserInterfaceManager
public void handleESCMenu() {
// Pause the game when the escape key is pressed
togglePause(); // This will pause the game if it's not already paused
// Use SwingUtilities.invokeLater to ensure the dialog is displayed after the game is paused
SwingUtilities.invokeLater(() -> {
String[] options = {"Yes, Quit", "No, Return to Game", "Reset Game"};
int choice = JOptionPane.showOptionDialog(
gameWindow,
"Quit game?\nYes - Quit\nNo - Return to Game\nReset - Restart the Game",
"Menu",
JOptionPane.DEFAULT_OPTION,
JOptionPane.INFORMATION_MESSAGE,
null,
options,
options[1]
);
if (choice == 0) { // "Yes, Quit"
System.exit(0);
} else if (choice == 2) { // "Reset Game"
resetGame();
togglePause(); // Unpause after resetting the game
} else {
// If "No, Return to Game" is selected or the dialog is closed,
// the pause state will toggle, unpausing the game
togglePause();
}
});
}
// MultiMino Code
// --------------------------------------------------------------------------------------------------------------------
/**
* TODO
*/
private void generateNewMultiMino() {
if (isGameOver) {
return; // Do not generate a new MultiMino if the game is over
}
if (nextMultiMino == null) {
nextMultiMino = new MultiMino(MultiMinoTemplates.getRandomPatternVariation());
nextMultiMino.setMultiMinoStatus(false); // The next MultiMino starts as inactive
}
// Calculate the starting position for the MultiMino
int patternWidth = 5; // Assuming a 5x5 pattern
int startX = (Config.BOARD_WIDTH - patternWidth) / 2; // Centered horizontally
// Update positions of each Mino in the MultiMino
for (Mino[] row : nextMultiMino.getMinos()) {
for (Mino mino : row) {
if (mino != null) {
mino.setX(mino.getX() + startX);
// If needed, adjust Y position
}
}
}
// Transfer nextMultiMino to be the current multiMino
activeMultiMino = nextMultiMino;
activeMultiMino.setMultiMinoStatus(true); // Activate the current multiMino
// Check if the starting position is already occupied
if (!checkMultiMinoPositions(activeMultiMino)) {
togglePause();
uiManager.gameOver(); // Call game over method if the position is occupied
} else {
boardGameGrid.placeMultiMino(activeMultiMino);
}
// Prepare the next MultiMino
nextMultiMino = new MultiMino(MultiMinoTemplates.getRandomPatternVariation());
nextMultiMino.setMultiMinoStatus(false);
}
/**
* Checks if all positions of a given MultiMino are unoccupied on the game grid.
*
* @param multiMino The MultiMino to check.
* @return True if all positions are unoccupied, false otherwise.
*/
private boolean checkMultiMinoPositions(MultiMino multiMino) {
for (Mino[] row : multiMino.getMinos()) {
for (Mino mino : row) {
if (mino != null) {
// Check if position is occupied
if (isPositionOccupied(mino.getX(), mino.getY())) {
System.out.println("MultiMino placement not possible, one of the positions is occupied.");
return false;
}
// Check if position is within the left and right bounds of the game grid
if (!isWithinBoardBounds(mino.getX(), mino.getY())) {
System.out.println("MultiMino placement not possible, one of the positions is out of bounds.");
return false;
}
}
}
}
return true; // All positions are unoccupied and within bounds
}
public void moveMultiMino(int dx, int dy) {
if (activeMultiMino != null && canMoveMultiMino(activeMultiMino, dx, dy)) {
// Move and place MultiMino to new positions
updateMultiMinoPosition(activeMultiMino, dx, dy);
boardGameGrid.placeMultiMino(activeMultiMino);
} else if (dy > 0) { // If the move was downward and it can't move
// Make the MultiMino inactive and generate a new one
activeMultiMino.setMultiMinoStatus(false);
generateNewMultiMino();
if (!isClearingRows) {
startClearFullRowsTimer();
}
}
// No else for sideways movement, as the MultiMino stays in place but active
}
/**
* Prints the current state of the game grid as a 2D matrix.
* Cells with static Minos are represented by 1, and empty cells by 0.
*/
public void printGridState() {
int[][] gridState = boardGameGrid.returnGridState();
for (int i = 0; i < gridState.length; i++) {
for (int j = 0; j < gridState[i].length; j++) {
System.out.print(gridState[i][j] + " ");
}
System.out.println(); // New line at the end of each row
}
}
public MultiMino getNextMultiMino() {
return nextMultiMino;
}
public boolean canMoveMultiMino(MultiMino multiMino, int dx, int dy) {
for (Mino[] row : multiMino.getMinos()) {
for (Mino mino : row) {
if (mino != null) {
int newX = mino.getX() + dx;
int newY = mino.getY() + dy;
// Check if the new position is within board bounds and not occupied
if (!isWithinBoardBounds(newX, newY) || isPositionOccupied(newX, newY)) {
return false; // Can't move if any part of the MultiMino can't be moved
}
// Check for the bottom of the grid specifically for downward movement
if (dy > 0 && newY >= Config.BOARD_HEIGHT) {
return false; // Can't move down beyond the bottom of the grid
}
}
}
}
return true; // All parts of the MultiMino can be moved
}
private void updateMultiMinoPosition(MultiMino multiMino, int dx, int dy) {
// Clear current positions of the MultiMino
for (Mino[] row : multiMino.getMinos()) {
for (Mino mino : row) {
if (mino != null) {
boardGameGrid.clearMino(mino.getX(), mino.getY());
}
}
}
// Update positions
for (Mino[] row : multiMino.getMinos()) {
for (Mino mino : row) {
if (mino != null) {
mino.setX(mino.getX() + dx);
mino.setY(mino.getY() + dy);
}
}
}
}
/**
* Rotates the specified MultiMino clockwise.
* If the rotation results in an invalid position, it reverts to the previous state.
*
* @param multiMino The MultiMino to rotate.
*/
public void rotateMultiMino(MultiMino multiMino) {
if (multiMino != null) {
// Save the current state of the MultiMino
Mino[][] originalMinos = deepCopyMinos(multiMino.getMinos());
// Clear current positions of the MultiMino
for (Mino[] row : multiMino.getMinos()) {
for (Mino mino : row) {
if (mino != null) {
boardGameGrid.clearMino(mino.getX(), mino.getY());
}
}
}
// Rotate the MultiMino
multiMino.rotateMultiMinoClockwise();
// Check if the rotated position is valid
if (checkMultiMinoPositions(multiMino)) {
boardGameGrid.placeMultiMino(multiMino);
} else {
soundManager.playSound("error_sound.wav");
multiMino.setMinos(originalMinos);
multiMino.setMultiMinoStatus(true); // Set the status back to active
boardGameGrid.placeMultiMino(multiMino);
}
System.out.println("check");
// Refresh the game window to show the updated positions
gameWindow.repaintWindow();
}
}
/**
* Creates a deep copy of a 2D array of Minos.
*
* @param original The original 2D array of Minos.
* @return A new 2D array of Minos that is a deep copy of the original.
*/
private Mino[][] deepCopyMinos(Mino[][] original) {
if (original == null) {
return null;
}
Mino[][] copy = new Mino[original.length][];
for (int i = 0; i < original.length; i++) {
copy[i] = new Mino[original[i].length];
for (int j = 0; j < original[i].length; j++) {
Mino originalMino = original[i][j];
if (originalMino != null) {
copy[i][j] = new Mino(originalMino.getX(), originalMino.getY(), originalMino.getColor());
}
}
}
return copy;
}
public MultiMino getCurrentMultiMino() {
return activeMultiMino;
}
}package controller;
import java.awt.event.KeyEvent;
/**
-
The {@code KeyboardController} class is responsible for interpreting keyboard inputs and translating them into
-
actions within the game in a Model-View-Controller (MVC) architecture. It listens for key events and, based on the
-
input, triggers corresponding actions in the {@link Game} class, such as moving pieces (Mino), toggling pause,
-
or handling game quit requests.
-
-
delegates actions to the {@code Game} class. This includes moving the game pieces in response to arrow keys,
-
pausing the game with the 'P' key, and handling the quit request with the ESCAPE key.
-
@version 0.1 - last updated on 2023-11-18, 14:05 PM
-
@author Matthieu M
*/
public class KeyboardController {
/**
-
Handles key press events and triggers corresponding actions in the game.
-
@param game The instance of the game where the actions will be applied.
-
@param keyCode The integer code of the key that was pressed.
*/
public void handleKeyPress(Game game, int keyCode) {
// Handle quit request when ESCAPE key is pressed
if (keyCode == KeyEvent.VK_ESCAPE) {
game.handleESCMenu(); // Call the method to handle quit request
return; // Return early so no other key processing happens
}
// If the game is paused, ignore all keys except 'P'
if (game.isPaused() && keyCode != KeyEvent.VK_P) {
return;
}
// Handling arrow keys and spacebar for game controls
switch (keyCode) {
case KeyEvent.VK_LEFT:
game.moveMultiMino(-1, 0); // Move the mino left
break;
case KeyEvent.VK_RIGHT:
game.moveMultiMino(1, 0); // Move the mino right
break;
case KeyEvent.VK_UP:
game.rotateMultiMino(game.getCurrentMultiMino()); // Rotate the current MultiMino
break;
case KeyEvent.VK_DOWN:
game.moveMultiMino(0, 1); // Move the mino down
break;
case KeyEvent.VK_SPACE:
while (game.canMoveMultiMino(game.getCurrentMultiMino(),0, 1)) {
game.moveMultiMino(0, 1); // Move the mino down
}
break;
case KeyEvent.VK_P:
game.togglePause(); // Toggle the game pause
break;
case KeyEvent.VK_B:
game.setBotModeActivated(!game.isBotModeActivated()); // Toggle bot mode
System.out.println("Bot mode is now " + (game.isBotModeActivated() ? "activated" : "deactivated"));
break;
}
// Repaint the game window if it's not paused
if (!game.isPaused()) {
game.repaintWindow();
}
}
}package model;
import view.SoundManager;
import java.util.ArrayList;
import java.util.List;
/**
-
The {@code GameGrid} class represents the grid structure of the game.
-
It handles the placement and removal of Minos, checks for full rows, and manages row shifts.
-
This class is integral for the game logic, dealing with the spatial arrangement of game elements.
-
@version 0.2 - last updated on 2023-11-20, 15:01 PM
-
@author Matthieu M
*/
public class GameGrid {
private SoundManager soundManager;
private Mino[][] grid;
private int width, height;
/**
-
Constructs a GameGrid with specified width and height.
-
The grid is initialized with null values, representing empty cells.
-
@param width The width of the grid.
-
@param height The height of the grid.
*/
public GameGrid(int width, int height) {
soundManager = new SoundManager();
System.out.println("New GameGrid created with width = " + width + " and height = " + height);
this.width = width;
this.height = height;
// Initialize the grid with null values.
// This is done implicitly, but this code makes it explicit for transparency
initializeGrid();
}
// Sets all values of the grid to null
private void initializeGrid() {
grid = new Mino[height][width];
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
grid[i][j] = null;
}
}
}
/**
- Places a Mino on the grid if the position is valid.
- @param mino The Mino to be placed.
*/
public void placeMino(Mino mino) {
if (mino != null && isValidPosition(mino.getX(), mino.getY())) {
grid[mino.getY()][mino.getX()] = mino;
}
}
/**
- Places a MultiMino on the grid.
- Each Mino within the MultiMino is placed individually if its position is valid.
- @param multiMino The MultiMino to be placed.
*/
public void placeMultiMino(MultiMino multiMino) {
if (multiMino != null) {
for (Mino[] row : multiMino.getMinos()) {
for (Mino mino : row) {
if (mino != null) {
placeMino(mino);
}
}
}
}
}
/**
- Clears a Mino from a specified position on the grid.
- @param x The x-coordinate of the position.
- @param y The y-coordinate of the position.
*/
public void clearMino(int x, int y) {
if (isValidPosition(x, y)) {
grid[y][x] = null;
}
}
/**
- Retrieves a Mino from a specified position on the grid.
- @param row The row of the position.
- @param col The column of the position.
- @return The Mino at the specified position, or null if empty.
*/
public Mino getMinoAt(int row, int col) {
if (row >= 0 && row < height && col >= 0 && col < width) {
return grid[row][col];
}
return null;
}
import java.awt.Color;
/**
-
The {@code Mino} represents a Mino, a basic unit in the game grid.
-
A Mino has a position (x, y), a color, and an active state.
-
@version 0.1 - last updated on 2023-11-18, 13:51 PM
-
@author Matthieu M
*/
public class Mino {
private int x; // X position
private int y; // Y position
private Color color; // Color of the Mino
private boolean isActive; // Indicates whether the Mino is active
/**
- Constructor for creating a Mino.
- @param x The X position of the Mino.
- @param y The Y position of the Mino.
- @param color The color of the Mino.
*/
public Mino(int x, int y, Color color) {
this.x = x;
this.y = y;
this.color = color;
this.isActive = false; // Initially, Mino is not active
}
// Getters and setters
/**
- Gets the X position of the Mino.
- @return The X position.
*/
public int getX() {
return x;
}
/**
- Sets the X position of the Mino.
- @param x The X position to set.
*/
public void setX(int x) {
this.x = x;
}
/**
- Gets the Y position of the Mino.
- @return The Y position.
*/
public int getY() {
return y;
}
/**
- Sets the Y position of the Mino.
- @param y The Y position to set.
*/
public void setY(int y) {
this.y = y;
}
/**
- Gets the color of the Mino.
- @return The color of the Mino.
*/
public Color getColor() {
return color;
}
/**
- Sets the color of the Mino.
- @param color The color to set.
*/
public void setColor(Color color) {
this.color = color;
}
/**
- Checks if the Mino is active.
- @return True if active, false otherwise.
*/
public boolean isActive() {
return isActive;
}
/**
- Sets the active state of the Mino.
- @param status The state to set (true or false).
*/
// TODO MM: streamline this, it's not best practice
public void setMinoStatus(boolean status) {
isActive = status;
}
}
package model;
import java.awt.Color;
import java.util.Random;
/**
-
The {@code MultiMino} class represents a composite structure of Minos, which are individual blocks of a Pentomino.
-
It creates a cohesive group of Minos based on a specified 2D pattern, where each Mino in the pattern is assigned a
-
random color. This class is essential for representing complex shapes composed of multiple Minos in the game.
-
-
generation of random colors for each Mino. The 2D array of Minos allows for easy manipulation and representation
-
of the shape within the game grid.
-
-
colors for each Mino block.
-
@version 0.1 - last updated on 2023-11-20, 14:10 PM
-
@author Matthieu M
*/
public class MultiMino {
private Mino[][] minos; // 2D array to store Mino objects
private int[][] pattern;
/**
-
Constructor for creating a MultiMino.
-
@param pattern The 2D integer array pattern to create the MultiMino.
*/
public MultiMino(int[][] pattern) {
System.out.println("Attempting to generate New MultiMino");
this.pattern = pattern;
displayPattern();
// Initialize the 2D Mino array based on the pattern dimensions
minos = new Mino[pattern.length][pattern[0].length];
// Generate a random color for this MultiMino
Color randomColor = generateRandomColor();
// Fill the 2D array with Minos or nulls based on the pattern
for (int i = 0; i < pattern.length; i++) {
for (int j = 0; j < pattern[i].length; j++) {
if (pattern[i][j] == 1) {
minos[i][j] = new Mino(i, j, randomColor);
} else {
minos[i][j] = null;
}
}
}
}
/**
- Generates a random color.
- @return A random Color object.
*/
private Color generateRandomColor() {
Random rand = new Random();
// Generate random RGB values
float r = rand.nextFloat();
float g = rand.nextFloat();
float b = rand.nextFloat();
return new Color(r, g, b);
}
/**
- Sets the active status of all Minos within the MultiMino.
- This method iterates through each Mino in the MultiMino and sets its active status
- to the provided value, affecting only non-null Minos.
- @param status The active status to set (true or false).
*/
public void setMultiMinoStatus(boolean status) {
for (Mino[] row : minos) {
for (Mino mino : row) {
if (mino != null) {
mino.setMinoStatus(status);
}
}
}
}
/**
- Gets the 2D array of Minos in this MultiMino.
- This method allows access to the individual Minos that make up the MultiMino.
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.LinkedHashMap;
/**
-
The {@code ScoreManager} class is responsible for managing the game's leaderboard.
-
It handles the loading, updating, and retrieving of player scores. This class
-
uses a file-based approach to persist the scores between game sessions.
-
@version @version 0.1 - last updated on 2023-11-18, 20:31 PM
-
@author Matthieu M
*/
public class ScoreManager {
//TODO: MM move to Config
private static final String LEADERBOARD_FILE = "Leaderboard.txt";
private Map<String, Integer> scores;
/**
- Constructs a new ScoreManager instance.
- Initializes the score map and loads existing scores from the leaderboard file.
*/
public ScoreManager() {
scores = new HashMap<>();
loadScores();
}
/**
- Loads scores from the leaderboard file into the scores map.
- The method reads the file line by line and extracts player names and their scores.
*/
private void loadScores() {
try (BufferedReader br = new BufferedReader(new FileReader(LEADERBOARD_FILE))) {
String line;
while ((line = br.readLine()) != null) {
String[] parts = line.split("] ");
if (parts.length == 2) {
String name = parts[0].substring(1); // Remove '[' from the start
int score = Integer.parseInt(parts[1]);
scores.put(name, score);
}
}
} catch (IOException e) {
System.err.println("Error reading leaderboard file: " + e.getMessage());
}
}
/**
- Updates the leaderboard with a new or existing player's score.
- It adds or replaces the player's score in the map and writes the updated scores to the file.
- @param playerName The name of the player.
- @param score The score to be updated for the player.
*/
public void updateLeaderboard(String playerName, int score) {
scores.put(playerName, score);
writeScores();
}
/**
- Retrieves the current leaderboard as a sorted map.
- The map is sorted by scores in descending order and limited to the top 5 entries.
- @return A map representing the leaderboard, sorted by scores.
*/
public Map<String, Integer> getLeaderboard() {
return scores.entrySet().stream()
.sorted((entry1, entry2) -> entry2.getValue().compareTo(entry1.getValue()))
.limit(5)
.collect(Collectors.toMap(
entry -> entry.getKey(),
entry -> entry.getValue(),
(e1, e2) -> e1, // In case of a key collision, keep the existing key
LinkedHashMap::new // Use a LinkedHashMap to maintain order
));
}
/**
- Writes the current scores map to the leaderboard file.
- This method is used to persist the scores across game sessions.
*/
private void writeScores() {
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(LEADERBOARD_FILE)))) {
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
out.println("[" + entry.getKey() + "] " + entry.getValue());
}
} catch (IOException e) {
System.err.println("Error writing to leaderboard file: " + e.getMessage());
}
}
}
package view;
import java.awt.*;
import model.GameGrid;
import model.Mino;
import config.Config;
/**
-
RenderGameGrid is responsible for rendering the game grid on the screen.
-
It draws each cell of the grid, filled with a Mino if present.
-
@version 0.1 - 2023-11-18, 13:51 PM
-
@version 0.2 - 2023-11-30, 00:16 AM - Added first five rows in different color (multimino "waiting room")
-
@author Matthieu M
*/
public class GameGridRenderer {
private GameGrid grid;
private int startX, startY; // starting coordinates for drawing the board
/**
- Constructor to initialize the RenderGameGrid object.
- @param boardGameGrid The GameGrid object to be rendered.
- @param startX The starting X coordinate for rendering.
- @param startY The starting Y coordinate for rendering.
*/
public GameGridRenderer(GameGrid boardGameGrid, int startX, int startY) {
this.grid = boardGameGrid;
this.startX = startX;
this.startY = startY;
}
/**
-
Renders the GameGrid object.
-
@param g The Graphics context used for drawing.
*/
public void render(Graphics g) {
// Draw the board grid
for (int row = 0; row < grid.getHeight(); row++) {
for (int col = 0; col < grid.getWidth(); col++) {
int x = startX + col * Config.CELL_SIZE;
int y = startY + row * Config.CELL_SIZE;
Mino mino = grid.getMinoAt(row, col);
if (mino != null) {
// Draw the Mino
g.setColor(mino.getColor());
g.fillRect(x, y, Config.CELL_SIZE, Config.CELL_SIZE);
} else {
// Draw cell border for all cells
g.setColor(Color.GRAY);
g.drawRect(x, y, Config.CELL_SIZE, Config.CELL_SIZE);
// Apply darker background color for the first five rows
if (row < 5) {
g.setColor(Config.DARKER_BACKGROUND_COLOR);
g.fillRect(x + 1, y + 1, Config.CELL_SIZE - 1, Config.CELL_SIZE - 1);
}
}
}
}
}
// Additional methods for updating the board state, if needed
}
package view;
import javax.swing.JFrame;
import java.awt.;
import java.awt.event.;
import java.sql.SQLOutput;
import java.util.Map;
import controller.Game;
import model.Mino;
import config.Config;
import model.GameGrid;
import model.MultiMino;
/**
- The {@code GameWindow} class represents the main window of the game.
- It extends {@link JFrame} and is responsible for setting up the game's graphical user interface.
- This includes creating and positioning the game board, handling user input, and refreshing the display.
- The class interacts with the {@link Game} controller to respond to user actions
- and with the {@link GameGridRenderer} class to render the game's grid.
- @version 0.2 - last updated on 2023-11-18, 18:00 PM
- @author Matthieu M
*/
public class GameWindow extends JFrame {
private Canvas canvas;
private GameGridRenderer board;
private Game gameController;
private int startX;
private int startY;
public GameWindow(GameGrid boardGameGrid, Game gameController) {
// Set the title of the window to the GAME_TITLE from the Config class
this.setTitle(Config.GAME_TITLE);
// Configure the window
this.setSize(Config.WINDOW_WIDTH, Config.WINDOW_HEIGHT); // Set size from config
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Set default close operation
this.setLocationRelativeTo(null); // Center the window
// Calculate center position for the game board
int centerX = (Config.WINDOW_WIDTH - (Config.BOARD_WIDTH * Config.CELL_SIZE)) / 2;
int centerY = (Config.WINDOW_HEIGHT - (Config.BOARD_HEIGHT * Config.CELL_SIZE)) / 2;
board = new GameGridRenderer(boardGameGrid, centerX, centerY); // Use the passed boardGameGrid
canvas = new Canvas() {
@Override
public void paint(Graphics g) {
super.paint(g);
board.render(g); // Existing call to render the game board
// Calculate positions for controls box and score box
startX = centerX;
startY = centerY;
int controlsBoxX = startX + (Config.BOARD_WIDTH * Config.CELL_SIZE) + Config.CONTROLS_BOX_PADDING;
int controlsBoxY = startY;
int controlsBoxWidth = Config.WINDOW_WIDTH - controlsBoxX - Config.CONTROLS_BOX_RIGHT_PADDING;
int controlsBoxHeight = Config.BOARD_HEIGHT * Config.CELL_SIZE;
// Draw the Controls Box
g.setColor(Config.CONTROLS_BOX_COLOR);
g.fillRect(controlsBoxX, controlsBoxY, controlsBoxWidth, controlsBoxHeight);
g.setColor(Color.WHITE);
g.setFont(Config.CONTROLS_BOX_FONT);
String[] controlsText = Config.GAME_CONTROLS;
int lineHeight = g.getFontMetrics().getHeight();
for (int i = 0; i < controlsText.length; i++) {
g.drawString(controlsText[i], controlsBoxX + 10, controlsBoxY + 10 + (i + 1) * lineHeight);
}
// Rendering next MultiMino
renderNextMultiMino(g);
// Draw the Score Box
int scoreBoxX = startX - Config.SCORE_BOX_WIDTH - Config.SCORE_BOX_PADDING;
int scoreBoxY = startY + 240;
g.setColor(Config.SCORE_BOX_COLOR);
g.fillRect(scoreBoxX, scoreBoxY, Config.SCORE_BOX_WIDTH, Config.SCORE_BOX_HEIGHT);
g.setColor(Color.WHITE);
g.setFont(Config.SCORE_BOX_FONT);
// Display player name
g.drawString("Player: " + gameController.getPlayerName(),scoreBoxX + 10, scoreBoxY + 40);
// Display the current score
g.drawString("SCORE", scoreBoxX + 10, scoreBoxY + 70);
int currentScore = gameController.score; // Fetching the score from the game controller
g.drawString(String.valueOf(currentScore), scoreBoxX + 10, scoreBoxY + 100); // Display the score
// Display the game level below the score
g.drawString("LEVEL", scoreBoxX + 10, scoreBoxY + 130); // Adjust position as needed
int currentLevel = gameController.getGameLevel(); // Fetching the game level from the game controller
g.drawString(String.valueOf(currentLevel), scoreBoxX + 10, scoreBoxY + 160); // Display the game level
// Display the bot mode status
g.drawString("Bot Mode: " + (gameController.isBotModeActivated() ? "Activated" : "Deactivated"),
scoreBoxX + 10,
scoreBoxY + 190); // Position this below the level display
// Draw the Leaderboard
int leaderboardX = scoreBoxX; // Adjust as needed
int leaderboardY = scoreBoxY + Config.SCORE_BOX_HEIGHT + 20 ; // Adjust as needed
g.setColor(Color.WHITE);
g.drawString("Leaderboard", leaderboardX, leaderboardY);
Map<String, Integer> leaderboard = gameController.getScoreManager().getLeaderboard(); // Fetch leaderboard data
int i = 1;
for (Map.Entry<String, Integer> entry : leaderboard.entrySet()) {
String text = i + ". " + entry.getKey() + ": " + entry.getValue();
g.drawString(text, leaderboardX, leaderboardY + i * 20); // Adjust 20 to change line spacing
i++;
}
}
};
// Set the background color
canvas.setBackground(Config.BACKGROUND_COLOR);
// Make canvas focusable and request focus
canvas.setFocusable(true);
canvas.requestFocusInWindow();
this.add(canvas); // Add canvas to the JFrame
this.gameController = gameController;
// Set up KeyListener
setupKeyListener();
}
private void renderNextMultiMino(Graphics g) {
MultiMino nextMultiMino = gameController.getNextMultiMino();
if (nextMultiMino != null) {
int previewBoxSize = 5 * Config.CELL_SIZE; // 5x5 square preview box
int previewBoxX = startX - previewBoxSize - Config.SCORE_BOX_PADDING; // Adjust X-position
int previewBoxY = startY; // Align the top of the preview box with the game grid
// Draw the frame of the preview box
g.setColor(Color.GRAY); // Color for the box frame
g.drawRect(previewBoxX, previewBoxY, previewBoxSize, previewBoxSize);
// Render the MultiMino inside the preview box
for (Mino[] row : nextMultiMino.getMinos()) {
for (Mino mino : row) {
if (mino != null) {
int x = previewBoxX + (mino.getX() * Config.CELL_SIZE);
int y = previewBoxY + (mino.getY() * Config.CELL_SIZE);
g.setColor(mino.getColor());
g.fillRect(x, y, Config.CELL_SIZE, Config.CELL_SIZE);
}
}
}
}
}
private void setupKeyListener() {
canvas.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
gameController.handleKeyPress(e.getKeyCode());
}
@Override
public void keyReleased(KeyEvent e) {
// Optionally handle key release
}
@Override
public void keyTyped(KeyEvent e) {
// Optionally handle key typing
}
});
canvas.setFocusable(true);
canvas.setFocusTraversalKeysEnabled(false);
}
public void repaintWindow() {
canvas.repaint();
}
}
package view;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.File;
import java.io.IOException;
/**
-
SoundManager is responsible for managing the playback of sound files in an application.
-
It provides functionality to play a sound file either once or in a continuous loop,
-
as well as stopping the sound playback and releasing resources.
-
@version 0.1 - last updated on 2023-11-18, 13:51 PM
-
@author Matthieu M
*/
public class SoundManager {
private Clip clip;
/**
- Plays the specified sound file once (without looping)
- @param soundFileName The name of the sound file to be played.
*/
public void playSound(String soundFileName) {
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(soundFileName).getAbsoluteFile());
clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start(); // Play once
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) {
e.printStackTrace();
}
}
/**
- Plays the specified sound file in a continuous loop.
- @param soundFileName The name of the sound file to be played in a loop.
*/
public void playSoundLoop(String soundFileName) {
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(soundFileName).getAbsoluteFile());
clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.loop(Clip.LOOP_CONTINUOUSLY); // Loop continuously
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) {
e.printStackTrace();
}
}
/**
- Stops the currently playing sound and releases the resources.
*/
public void stopSound() {
if (clip != null && clip.isRunning()) {
clip.stop();
clip.close(); // Close the clip to release resources
}
}
}
package view;
import controller.Game;
import javax.imageio.ImageIO;
import javax.swing.;
import java.awt.;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/**
-
Prompts the user to enter their name using a graphical input dialog. This method also attempts to display
-
an optional image alongside the input dialog for a more engaging user interface.
-
The method handles the loading of an image file and plays a looping sound during the input process.
-
If the image file is not found or an error occurs during its loading, the method falls back to displaying
-
the input dialog without the image. The sound is stopped once the dialog is closed.
-
In cases where the user enters a blank name or cancels the dialog, a default name "Player" is used.
-
@return The name entered by the user. Returns a default name "Player" if the input is blank or canceled.
-
@version 0.1 - last updated on 2023-11-20, 21:25 PM
-
@author Matthieu M
*/
public class UserInterfaceManager {
private SoundManager soundManager;
private String playerName;
private Game game;
public void setGame(Game game) {
this.game = game;
}
public UserInterfaceManager(SoundManager soundManager) {
this.soundManager = soundManager;
}
/**
-
Prompts the player for their name with an input dialog, also displaying an optional image.
-
@return
*/
public String promptForPlayerName() {
try {
// Load the original image
//TODO: move constants to Config class
BufferedImage originalImage = ImageIO.read(new File("Video_Game_Cover.png")); // Load image
// TODO: move constants to Config class
soundManager.playSoundLoop("pentomino_pirates_theme.wav");
// Calculate the new height to maintain the aspect ratio
int originalWidth = originalImage.getWidth();
int originalHeight = originalImage.getHeight();
int newWidth = Math.min(originalWidth, 600);
int newHeight = (newWidth * originalHeight) / originalWidth;
// Resize the image
Image resizedImage = originalImage.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
ImageIcon imageIcon = new ImageIcon(resizedImage); // Convert to ImageIcon for JOptionPane
// Show input dialog with the resized image
playerName = (String)JOptionPane.showInputDialog(
null,
"Enter your name:",
"Player Name",
JOptionPane.PLAIN_MESSAGE,
imageIcon,
null,
"Player" // Default name
);
// Handle case where playerName is null or empty
if (playerName == null || playerName.trim().isEmpty()) {
playerName = "Player"; // Default name if none entered
}
} catch (IOException e) {
e.printStackTrace();
// Handle the case where the image file is not found or another IO error occurs
// For example, you might just want to show the dialog without an image in this case
playerName = JOptionPane.showInputDialog("Enter your name:");
} finally {
soundManager.stopSound(); // Stop the sound when the dialog is closed
}
return playerName;
}
}
import controller.Game;
/**
- The {@code Run} class serves as the entry point for the game.
- It initializes and starts the game by creating an instance of the {@link Game} class.
- @version @version 0.1 - last updated on 2023-11-18, 13:51 PM
- @author Matthieu M
/
public class
Run {
/*
* The main method that serves as the entry point of the application.
*
* @param args Command line arguments (not used in this application).
*/
public static void main(String[] args) {
new Game(); // Start the game
}
}
So with all this data i want you to modify the bot as much as you want, I want you to create bot that can previsualize the where the piece is going to fall as soons as the piece spawns, i also want the bot to be intelligent and to clear the lines so i want you to creat an algorithm into the new bot that can do the best choice and be a perfect bot, you have all the potential you want and you can create as many classes and many methods and algorithms you want