This is a simple Pet Collector Game implemented in Java using Swing. Let's break down the main components and functionalities:
PetCollectorGame: This class extends JFrame and implements the KeyListener interface. It represents the main frame of the game.
Attributes:
playerName: Stores the player's name.
playerEnergy: Represents the player's energy level.
pets: A list of Point objects representing the player and pets' positions on a grid.
Initializes the frame and sets up the initial state of the game.
Adds a timer to periodically move pets and repaint the game.
Overrides keyPressed to handle player movement based on arrow key input.
drawGame(Graphics g): Draws the player, pets, and energy level on the screen.
movePlayer(int keyCode): Updates the player's position based on arrow key input.
movePets(): Randomly moves pets (except the first one which follows the player).
showEndGameMessage(String message): Displays an endgame message dialog.
initPets(): Initializes the positions of the player and random pets.
paint(Graphics g): Overrides the paint method to draw the game components.
The player (blue rectangle) is moved using arrow keys.
Pets (green rectangles) move randomly.
The player collects a pet when their position overlaps with a pet, gaining energy.
The game ends when either all pets are collected or the player's energy reaches zero.
The main method initializes the game by prompting the user to enter their name using JOptionPane.
If a valid name is provided, it creates an instance of PetCollectorGame, sets it visible, and initializes pets.
User enters their name.
Game initializes with a player and random pets.
Timer triggers periodic pet movement.
User moves the player using arrow keys.
When a pet is collected, energy increases.
Game ends when all pets are collected or energy reaches zero.
The code uses a grid-based system where each cell is 40x40 pixels.
The player and pets' positions are represented as points (x, y) on the grid.
The code could benefit from comments to explain complex sections.
The game could be further enhanced with additional features, levels, or graphics.
This game is a basic example, and you can build upon it to create more complex and engaging games.
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
*/
package xx.petcollectorgame;
/**
*
* @author sagar_xbitlabs
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class PetCollectorGame extends JFrame implements KeyListener {
private String playerName;
private int playerEnergy;
private List<Point> pets;
public PetCollectorGame(String playerName) {
super("Pet Collector Game");
this.playerName = playerName;
this.playerEnergy = 100;
this.pets = new ArrayList<>();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setLocationRelativeTo(null);
addKeyListener(this);
setFocusable(true);
// Start a timer for pet movement
Timer timer = new Timer(2000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
movePets();
repaint();
}
});
timer.start();
}
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyPressed(KeyEvent e) {
movePlayer(e.getKeyCode());
}
@Override
public void keyReleased(KeyEvent e) {}
private void drawGame(Graphics g) {
// Draw pets
g.setColor(Color.GREEN);
for (Point pet : pets) {
g.fillRect(pet.x * 40, pet.y * 40, 40, 40);
}
// Draw player
g.setColor(Color.BLUE);
g.fillRect(pets.get(0).x * 40, pets.get(0).y * 40, 40, 40);
// Draw player energy
g.setColor(Color.BLACK);
g.drawString("Energy: " + playerEnergy, 10, 20);
}
private void movePlayer(int keyCode) {
// Update player position based on arrow keys
switch (keyCode) {
case KeyEvent.VK_LEFT:
pets.get(0).x = Math.max(0, pets.get(0).x - 1);
break;
case KeyEvent.VK_RIGHT:
pets.get(0).x = Math.min(6, pets.get(0).x + 1);
break;
case KeyEvent.VK_UP:
pets.get(0).y = Math.max(0, pets.get(0).y - 1);
break;
case KeyEvent.VK_DOWN:
pets.get(0).y = Math.min(4, pets.get(0).y + 1);
break;
}
// Check if player intersects with pets
for (int i = 1; i < pets.size(); i++) {
// Check if player collects a pet
if (pets.get(i).equals(pets.get(0))) {
pets.remove(i);
playerEnergy += 10; // Increase energy when collecting a pet
break; // Exit the loop after collecting one pet
}
}
// Update the game panel
repaint();
// Check game over conditions
if (pets.size() == 1) {
showEndGameMessage("Congratulations, " + playerName + "!\nYou collected all pets and completed the game!");
} else if (playerEnergy <= 0) {
showEndGameMessage("Game Over, " + playerName + "!\nYou ran out of energy.");
}
}
private void movePets() {
// Random movement for pets (except the first one which follows the player)
Random random = new Random();
for (int i = 1; i < pets.size(); i++) {
int movementX = random.nextInt(3) - 1; // Random movement between -1 and 1 for X-axis
int movementY = random.nextInt(3) - 1; // Random movement between -1 and 1 for Y-axis
pets.get(i).x = Math.max(0, Math.min(6, pets.get(i).x + movementX));
pets.get(i).y = Math.max(0, Math.min(4, pets.get(i).y + movementY));
}
}
/*
private void movePets() {
// Random movement for pets (except the first one which follows the player)
Random random = new Random();
for (int i = 1; i < pets.size(); i++) {
int movement = random.nextInt(3) - 1; // Random movement between -1 and 1
pets.get(i).x = Math.max(0, Math.min(6, pets.get(i).x + movement));
pets.get(i).y = Math.max(0, Math.min(4, pets.get(i).y + movement));
}
}
*/
private void showEndGameMessage(String message) {
JOptionPane.showMessageDialog(this, message, "Game Over", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
String playerName = JOptionPane.showInputDialog(null, "Enter your name", "Player Name", JOptionPane.PLAIN_MESSAGE);
if (playerName != null && !playerName.trim().isEmpty()) {
PetCollectorGame game = new PetCollectorGame(playerName);
game.setVisible(true);
game.initPets();
}
});
}
private void initPets() {
Random random = new Random();
pets.add(new Point(random.nextInt(7), random.nextInt(5))); // Player
for (int i = 0; i < 4; i++) {
pets.add(new Point(random.nextInt(7), random.nextInt(5))); // Random pets
}
repaint();
}
@Override
public void paint(Graphics g) {
super.paint(g);
drawGame(g);
}
}