This Java Swing application (a simple game ) with multiple levels called "Energy Quest." Let me provide an overview of the project:
JFrame and Panels: The main class initializes a JFrame named "Energy Quest" with a size of 450x450 pixels. It uses a mainPanel with a CardLayout to switch between different panels during the game.
Panels: There are four panels - titlePanel, namePanel, resultPanel, and gamePanel. The createTitlePanel, createNamePanel, and createResultPanel methods set up the initial panels. The createGamePanel method initializes the game panel.
The game starts with a title panel, and by clicking on "Click to continue," it transitions to the name panel where the player enters their name. After submitting the name, the result panel displays a welcome message, instructions, controls, and character ability details. Clicking "Start" transitions to the game panel.
The GameLogic class handles the game mechanics, including player movement, pet movement, energy management, and level transitions.
Timers: It uses timers for pet movement (petMoveTimer) and a countdown timer (countdownTimer) to create a time-based game. When time runs out, the game transitions to the next level.
Level Transitions: The levelUp method is triggered when the countdown timer reaches zero. It stops the pet movement timer, displays a message, and transitions to the next level by creating a new panel (gameLevelTwoPanel). A similar process is used for Level 3.
Level Two: The createGameLevelTwoPanel method sets up a new panel for Level 2. It includes a player label, an energy label, a destination label, and pot labels. The player needs to reach the destination while avoiding pots to win the level.
Level Three: The createGameLevelThreePanel method initializes a panel for Level 3. It currently displays a player label.
Randomized Movement: The pets move randomly on the screen, and the player can move using arrow keys.
Collision Detection: Collision detection is implemented for pets and pots. When the player collects a pet or collides with a pot, appropriate actions are taken (e.g., increase energy, decrease energy).
Transition Flow: The game transitions between panels using a CardLayout based on user interactions and timers.
Game Over: If the player's energy is depleted, a game over message is displayed.
Random Pet Types: Pets with different types (C, D, W, B) are randomly generated.
Random Positions: Pets and pots are placed at random positions on the screen.
package FinalGame;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
/*
*
* Energy Quest
Pet Collector Challenge
Level-Up Adventure: The Energy Race
Final Level Pursuit
Energetic Escapade
Pet Pot Dash
*/
public class FinalGame {
public static JFrame frame;
public static JPanel mainPanel;
public static JPanel titlePanel;
private static JPanel namePanel;
private static JPanel gamePanel;
private static JPanel resultPanel;
//private static JPanel mainPanel;
private static JLabel continueLabel;
private static JLabel howToPlayLabel;
private static JLabel characterAbilityLabel;
private static JLabel controlsLabel;
private static JLabel startLabel;
private static JLabel controlsDetailsLabel;
private static JLabel characterAbilityDetailsLabel;
private static JLabel instructionsLabel;
private static JTextField nameField;
private static JLabel playerLabel;
private static JLabel[] petLabels;
private static int playerEnergy = 50;
private static int petEnergy = 25;
private static int collectedPets = 0;
private static GameLogic gameLogic;
public static void main(String[] args) {
frame = new JFrame("Energy Quest");
frame.setSize(450, 450);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new JPanel(new CardLayout());
frame.add(mainPanel);
createTitlePanel();
createNamePanel();
createResultPanel();
createGamePanel();
frame.setVisible(true);
}
private static void createTitlePanel() {
titlePanel = new JPanel(null);
titlePanel.setBackground(Color.CYAN);
JLabel titleLabel = new JLabel("Energy Quest");
titleLabel.setBounds(150, 30, 100, 25);
titleLabel.setFont(new Font("Arial", Font.ITALIC, 16));
titlePanel.add(titleLabel);
continueLabel = new JLabel("Click to continue .");
continueLabel.setBounds(120, 80, 160, 25);
titlePanel.add(continueLabel);
mainPanel.add(titlePanel, "titlePanel");
continueLabel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent ev) {
CardLayout cardLayout = (CardLayout) mainPanel.getLayout();
cardLayout.show(mainPanel, "namePanel");
}
});
}
private static void createNamePanel() {
namePanel = new JPanel(null);
namePanel.setBackground(Color.GRAY);
JLabel enterNameLabel = new JLabel("Enter the name : ");
enterNameLabel.setBounds(150, 30, 200, 25);
namePanel.add(enterNameLabel);
nameField = new JTextField();
nameField.setBounds(120, 80, 160, 25);
namePanel.add(nameField);
JLabel submitLabel = new JLabel("Submit");
submitLabel.setBounds(120, 120, 160, 25);
namePanel.add(submitLabel);
mainPanel.add(namePanel, "namePanel");
submitLabel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent ev) {
CardLayout cardLayout = (CardLayout) mainPanel.getLayout();
cardLayout.show(mainPanel, "resultPanel");
displayResultPanel();
}
});
}
private static void createResultPanel() {
resultPanel = new JPanel(null);
resultPanel.setBackground(Color.LIGHT_GRAY);
JLabel resultLabel = new JLabel("Greetings!");
resultLabel.setBounds(150, 30, 500, 25);
resultPanel.add(resultLabel);
JLabel playerNameLabel = new JLabel();
playerNameLabel.setBounds(120, 80, 500, 25);
resultPanel.add(playerNameLabel);
JLabel gtTagLabel = new JLabel();
gtTagLabel.setBounds(120, 120, 500, 25);
resultPanel.add(gtTagLabel);
mainPanel.add(resultPanel, "resultPanel");
}
private static void displayResultPanel() {
String playerName = nameField.getText();
String gtTag = rearrangeString(playerName);
JLabel gtTagLabel = (JLabel) resultPanel.getComponent(2);
String gtTagText = "Your Gamer Tag is : " + gtTag;
gtTagLabel.setText(gtTagText);
JLabel playerNameLabel = (JLabel) resultPanel.getComponent(1);
String welcomeText = "Greetings, " + playerName;
playerNameLabel.setText(welcomeText);
howToPlayLabel = new JLabel("How to Play ");
howToPlayLabel.setBounds(50, 180, 120, 25);
resultPanel.add(howToPlayLabel);
controlsLabel = new JLabel("Controls");
controlsLabel.setBounds(50, 220, 140, 25);
resultPanel.add(controlsLabel);
characterAbilityLabel = new JLabel("Character Ability");
characterAbilityLabel.setBounds(50, 260, 140, 25);
resultPanel.add(characterAbilityLabel);
startLabel = new JLabel("Start");
startLabel.setBounds(50, 300, 120, 25);
resultPanel.add(startLabel);
instructionsLabel = new JLabel("<html>Instructions:<br>1. Use arrow keys to move.<br>2. Collect pets to increase energy.<br>3. Avoid obstacles.<br>4. Enjoy the game!</html>");
instructionsLabel.setBounds(200, 180, 300, 100);
resultPanel.add(instructionsLabel);
instructionsLabel.setVisible(false); // Initially, hide the instructions
howToPlayLabel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent ev) {
instructionsLabel.setVisible(!instructionsLabel.isVisible()); // Toggle visibility
}
});
controlsDetailsLabel = new JLabel("<html>Controls:<br>Use arrow keys to move your character.</html>");
controlsDetailsLabel.setBounds(200, 220, 300, 50);
resultPanel.add(controlsDetailsLabel);
controlsDetailsLabel.setVisible(false); // Initially, hide the controls details
controlsLabel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent ev) {
controlsDetailsLabel.setVisible(!controlsDetailsLabel.isVisible()); // Toggle visibility
}
});
characterAbilityDetailsLabel = new JLabel("<html>Character Ability:<br>Your character has the ability to collect pets.<br>Collecting pets increases your energy.<br>Use this ability wisely!</html>");
characterAbilityDetailsLabel.setBounds(200, 260, 300, 80);
resultPanel.add(characterAbilityDetailsLabel);
characterAbilityDetailsLabel.setVisible(false); // Initially, hide the character ability details
characterAbilityLabel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent ev) {
characterAbilityDetailsLabel.setVisible(!characterAbilityDetailsLabel.isVisible()); // Toggle visibility
}
});
startLabel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent ev) {
CardLayout cardLayout = (CardLayout) mainPanel.getLayout();
cardLayout.show(mainPanel, "gamePanel");
startGame();
}
});
}
private static void createGamePanel() {
gamePanel = new JPanel(null);
gamePanel.setBackground(Color.ORANGE);
playerLabel = new JLabel("P");
playerLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
playerLabel.setBounds(150, 30, 20, 25);
gamePanel.add(playerLabel);
petLabels = new JLabel[5];
for (int i = 0; i < 5; i++) {
char petType = getRandomPetType();
int x = getRandomPosition(50, 400);
int y = getRandomPosition(50, 300);
petLabels[i] = new JLabel(String.valueOf(petType));
petLabels[i].setBorder(BorderFactory.createLineBorder(Color.GREEN, 2));
petLabels[i].setBounds(x, y, 25, 25);
gamePanel.add(petLabels[i]);
}
mainPanel.add(gamePanel, "gamePanel");
gameLogic = new GameLogic(mainPanel, gamePanel, playerLabel, petLabels, 150, 30);
}
private static void startGame() {
gameLogic.startGame();
}
private static String rearrangeString(String input) {
if (input.length() < 4) {
System.out.println("Input string should have at least 4 characters");
return input;
}
String end = input.substring(input.length() - 2);
String start = input.substring(0, 2);
return end + input.substring(2, input.length() - 2) + start;
}
private static char getRandomPetType() {
char[] petTypes = {'C', 'D', 'W', 'B'};
int randomIndex = new Random().nextInt(petTypes.length);
return petTypes[randomIndex];
}
private static int getRandomPosition(int min, int max) {
return new Random().nextInt(max - min + 1) + min;
}
}
package FinalGame;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Random;
import java.util.ArrayList;
import java.util.List;
public class GameLogic {
private JPanel gamePanel;
private JPanel mainPanel;
private JPanel gameLevelTwoPanel;
private JPanel gameLevelThreePanel;
private JLabel playerLabelLevelThree;
private JLabel energyLabelLevelTwo;
private JLabel playerLabel;
private JLabel[] petLabels;
private JLabel energyLabel;
private JLabel countdownLabel;
private JLabel playerLabelLevelTwo;
private Timer petMoveTimer;
private int playerX;
private int playerY;
private int collectedPets;
private int playerEnergy = 50;
private int countdownTime = 15;
private Timer countdownTimer;
private static JLabel[] potLabels;
public GameLogic(JPanel mainPanel, JPanel gamePanel, JLabel playerLabel, JLabel[] petLabels, int initialPlayerX, int initialPlayerY) {
this.gamePanel = gamePanel;
//this.mainPanel = mainPanel;
this.playerLabel = playerLabel;
this.petLabels = petLabels;
this.playerX = initialPlayerX;
this.playerY = initialPlayerY;
this.collectedPets = 0;
this.mainPanel = mainPanel;
gamePanel.setFocusable(true);
gamePanel.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
handleKeyPress(e);
}
});
// adding countdownLabel to gamePanel
countdownLabel = new JLabel("Time Left: " + countdownTime + " seconds");
countdownLabel.setBounds(320, 60, 150, 25);
gamePanel.add(countdownLabel);
// creating and adding energy label
energyLabel = new JLabel("Energy : " + getFormattedEnergy());
energyLabel.setBounds(320, 30, 100, 25);
gamePanel.add(energyLabel);
}
private int getRandomPosition(int min, int max) {
if (min >= max) {
throw new IllegalArgumentException("Min must be less than max");
}
return new Random().nextInt((max - min) + 1) + min;
}
private void increasePlayerEnergy(int energyIncrease) {
playerEnergy += energyIncrease;
energyLabel.setText("Energy : " + getFormattedEnergy());
}
private String getFormattedEnergy() {
return String.valueOf(playerEnergy);
}
public void startGame() {
startPetMoveTimer();
startCountdownTimer();
gamePanel.requestFocusInWindow();
}
private void startCountdownTimer() {
countdownTimer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
countdownTime--;
countdownLabel.setText("Time Left : " + countdownTime + " seconds");
if (countdownTime == 0) {
stopCountdownTimer();
levelUp();
}
}
});
countdownTimer.start();
}
private void stopCountdownTimer() {
countdownTimer.stop();
}
private void levelUp() {
petMoveTimer.stop();
JOptionPane.showMessageDialog(null, "Time is up! Moving to Level 2");
System.out.println("Transitioning to Level 2");
// this.gameLevelTwoPanel = new JPanel();
// this.gameLevelTwoPanel.setBackground(Color.GREEN);
createGameLevelTwoPanel();
CardLayout cardLayout = (CardLayout) mainPanel.getLayout();
cardLayout.show(mainPanel, "gameLevelTwoPanel");
playerLabelLevelTwo.setLocation(playerX, playerY);
}
private void createGameLevelTwoPanel(){
gameLevelTwoPanel = new JPanel(null);
gameLevelTwoPanel.setBackground(Color.GREEN);
// dividing the screen into two halves
Border playerBorder = BorderFactory.createLineBorder(Color.BLACK, 2);
playerLabelLevelTwo = new JLabel("PX");
playerLabelLevelTwo.setBounds(playerX, playerY, 20, 20);
playerLabelLevelTwo.setBorder(playerBorder);
gameLevelTwoPanel.add(playerLabelLevelTwo);
energyLabelLevelTwo = new JLabel("Energy : " + getFormattedEnergy());
energyLabelLevelTwo.setBounds(10, 25, 100, 25);
gameLevelTwoPanel.add(energyLabelLevelTwo);
JLabel destinationLabel = new JLabel("Destination");
destinationLabel.setBounds(380, 260, 100, 25);
gameLevelTwoPanel.add(destinationLabel);
// Creating pot labels
potLabels = new JLabel[20];
System.out.println("Width of gameLevelTwoPanel " + gameLevelTwoPanel.getWidth());
for (int i = 0; i < 20; i++) {
//char petType = getRandomPetType();
// int x = getRandomPosition(50, 400);
// int y = getRandomPosition(50, 300);
int x, y;
do {
x = getRandomPosition(50, 400);
y = getRandomPosition(50, 300);
} while (checkPotIntersection(x,y));
System.out.println(x + " " + y);
String pot = "O";
potLabels[i] = new JLabel(pot);
potLabels[i].setBorder(BorderFactory.createLineBorder(Color.GREEN, 2));
potLabels[i].setBounds(x, y, 25, 25);
gameLevelTwoPanel.add(potLabels[i]);
}
mainPanel.add(gameLevelTwoPanel, "gameLevelTwoPanel");
gameLevelTwoPanel.setFocusable(true);
gameLevelTwoPanel.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
handleKeyPressLevelTwo(e);
}
});
}
private boolean checkPotIntersection(int x, int y){
Rectangle newPotBounds = new Rectangle(x,y,25,25);
for(int i=0; i < potLabels.length; i++){
if ( potLabels[i] != null && newPotBounds.intersects(potLabels[i].getBounds())){
return true;
}
}
return false;
}
private void updateEnergyLabelLevelTwo() {
energyLabelLevelTwo.setText("Energy : " + getFormattedEnergy());
}
private void handlePotCollision() {
decreasePlayerEnergy(10);
updateEnergyLabelLevelTwo();
// Additional logic if needed when the player collides with a pot
}
private void decreasePlayerEnergy(int energyDecrease) {
playerEnergy -= energyDecrease;
energyLabel.setText("Energy : " + getFormattedEnergy());
if (playerEnergy <= 0) {
// Player energy is depleted, handle game over logic
stopCountdownTimer();
JOptionPane.showMessageDialog(null, "Game Over! Your energy is depleted. You lost.");
// Additional game over logic if needed
}
}
private void createGameLevelThreePanel(){
gameLevelThreePanel = new JPanel();
gameLevelThreePanel.setBackground(Color.BLUE);
mainPanel.add(gameLevelThreePanel, "gameLevelThreePanel");
CardLayout cardLayout = (CardLayout) mainPanel.getLayout();
cardLayout.show(mainPanel, "gameLevelThreePanel");
// titleLabel = new JLabel("Final Level ");
// titleLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
// titleLabel.setBounds(150, 30, 100, 25);
// gameLevelThreePanel.add(titleLabel);
playerLabel = new JLabel("P");
playerLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
playerLabel.setBounds(100, 80, 20, 25);
gameLevelThreePanel.add(playerLabel);
}
private void startPetMoveTimer() {
petMoveTimer = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
movePets();
gamePanel.repaint();
checkCollisions();
}
});
petMoveTimer.start();
}
private void movePets() {
for (int i = 0; i < petLabels.length; i++) {
if (petLabels[i] != null) {
int movementX = getRandomMovement();
int movementY = getRandomMovement();
int currentX = petLabels[i].getX();
int currentY = petLabels[i].getY();
int newX = Math.max(50, Math.min(400, currentX + movementX * 10));
int newY = Math.max(50, Math.min(300, currentY + movementY * 10));
petLabels[i].setLocation(newX, newY);
}
}
}
private int getRandomMovement() {
return new Random().nextInt(6) - 3;
}
private void checkCollisions() {
Rectangle playerBounds = playerLabel.getBounds();
for (int i = 0; i < petLabels.length; i++) {
if (petLabels[i] != null && playerBounds.intersects(petLabels[i].getBounds())) {
collectPet(i);
break;
}
}
if (collectedPets == petLabels.length) {
// All pets collected, end the game or proceed to the next level
petMoveTimer.stop();
}
}
private void collectPet(int index) {
gamePanel.remove(petLabels[index]);
petLabels[index] = null;
collectedPets++;
increasePlayerEnergy(25);
}
public void handleKeyPressLevelTwo(KeyEvent e){
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_UP && playerY > 50) {
playerY -= 10;
} else if (keyCode == KeyEvent.VK_DOWN && playerY < 300) {
playerY += 10;
} else if (keyCode == KeyEvent.VK_LEFT && playerX > 50) {
playerX -= 10;
} else if (keyCode == KeyEvent.VK_RIGHT && playerX < 400) {
playerX += 10;
}
// Update the position of the player label in the gameLevelTwoPanel
playerLabelLevelTwo.setLocation(playerX, playerY);
checkPotCollisions();
// Check if the player reaches the bottom right edge with energy > 0
if (playerX >= 380 && playerY >= 260 && playerEnergy > 0) {
stopCountdownTimer();
JOptionPane.showMessageDialog(null, "Congratulations! You won!. Moving to level 3");
createGameLevelThreePanel();
}
else if (playerEnergy <=0){
JOptionPane.showMessageDialog(null, "Game Over! Your energy is depleted. You lost.");
System.exit(0);
}
updateEnergyLabelLevelTwo();
}
private void checkPotCollisions(){
Rectangle playerBounds = playerLabelLevelTwo.getBounds();
for (int i=0; i < potLabels.length; i++){
if(potLabels[i]!= null && playerBounds.intersects(potLabels[i].getBounds())){
handlePotCollision();
break;
}
}
}
// private void levelUpToLevelThree() {
// petMoveTimer.stop();
// JOptionPane.showMessageDialog(null, "Congratulations! Moving to Level 3");
// System.out.println("Transitioning to Level 3");
// // Add logic for Level 3 here if needed
// // For now, let's transition back to the main panel
// CardLayout cardLayout = (CardLayout) mainPanel.getLayout();
// cardLayout.show(mainPanel, "mainPanel"); // Change "mainPanel" to the panel for Level 3 if needed
// }
private void handleKeyPress(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_UP && playerY > 50) {
playerY -= 10;
} else if (keyCode == KeyEvent.VK_DOWN && playerY < 300) {
playerY += 10;
} else if (keyCode == KeyEvent.VK_LEFT && playerX > 50) {
playerX -= 10;
} else if (keyCode == KeyEvent.VK_RIGHT && playerX < 400) {
playerX += 10;
}
playerLabel.setLocation(playerX, playerY);
}
}