Think and write one simple Java program that lets us play the classic Pacman game. With score, multiple ghosts, powerup (invisibility and eating ghost), and all that. Controls is wasd ...
Assistant
Certainly! Creating a full-fledged Pacman game is a substantial task, but I can help you write a simplified version in Java that includes the core features:
Movement controls using WASD keys.
A score system.
Multiple ghosts.
Power-ups that allow invisibility and the ability to eat ghosts.
We'll use Java's Swing library for the GUI components.
Here's the complete code for a simple Pacman game:
java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Iterator;
public class SimplePacmanGame extends JPanel implements ActionListener, KeyListener {
private Timer timer;
private int cellSize = 20;
private int gridSize = 20;
private int pacmanX = gridSize / 2;
private int pacmanY = gridSize / 2;
private int score = 0;
private boolean powerUpActive = false;
private int powerUpTimer = 0;
private ArrayList<Point> ghosts;
private Point powerUp;
public SimplePacmanGame() {
setPreferredSize(new Dimension(gridSize * cellSize, gridSize * cellSize));
setBackground(Color.BLACK);
setFocusable(true);
addKeyListener(this);
// Initialize ghosts
ghosts = new ArrayList<>();
ghosts.add(new Point(0, 0));
ghosts.add(new Point(gridSize - 1, 0));
ghosts.add(new Point(0, gridSize - 1));
ghosts.add(new Point(gridSize - 1, gridSize - 1));
// Place a power-up
placePowerUp();
timer = new Timer(200, this);
timer.start();
}
private void placePowerUp() {
powerUp = new Point((int) (Math.random() * gridSize), (int) (Math.random() * gridSize));
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Draw power-up
if (powerUp != null) {
g.setColor(Color.GREEN);
g.fillOval(powerUp.x * cellSize, powerUp.y * cellSize, cellSize, cellSize);
}
// Draw ghosts
g.setColor(Color.RED);
for (Point ghost : ghosts) {
g.fillOval(ghost.x * cellSize, ghost.y * cellSize, cellSize, cellSize);
}
// Draw Pacman
g.setColor(Color.YELLOW);
g.fillOval(pacmanX * cellSize, pacmanY * cellSize, cellSize, cellSize);
// Draw score
g.setColor(Color.WHITE);
g.drawString("Score: " + score, 10, 10);
// Draw power-up timer
if (powerUpActive) {
g.drawString("Power-Up Active: " + powerUpTimer, 10, 25);
}
}
@Override
public void actionPerformed(ActionEvent e) {
moveGhosts();
checkCollisions();
if (powerUpActive) {
powerUpTimer--;
if (powerUpTimer <= 0) {
powerUpActive = false;
}
}
repaint();
}
private void moveGhosts() {
for (Point ghost : ghosts) {
int dx = pacmanX - ghost.x;
int dy = pacmanY - ghost.y;
if (Math.abs(dx) > Math.abs(dy)) {
ghost.x += dx > 0 ? 1 : -1;
} else {
ghost.y += dy > 0 ? 1 : -1;
}
ghost.x = Math.floorMod(ghost.x, gridSize);
ghost.y = Math.floorMod(ghost.y, gridSize);
}
}
private void checkCollisions() {
// Check for power-up collision
if (powerUp != null && pacmanX == powerUp.x && pacmanY == powerUp.y) {
powerUpActive = true;
powerUpTimer = 50;
powerUp = null;
}
// Check for ghost collisions
Iterator<Point> iterator = ghosts.iterator();
while (iterator.hasNext()) {
Point ghost = iterator.next();
if (pacmanX == ghost.x && pacmanY == ghost.y) {
if (powerUpActive) {
iterator.remove();
score += 100;
} else {
JOptionPane.showMessageDialog(this, "Game Over! Your score: " + score);
System.exit(0);
}
}
}
// If all ghosts are eaten
if (ghosts.isEmpty()) {
JOptionPane.showMessageDialog(this, "You Win! Your score: " + score);
System.exit(0);
}
}
// Movement controls
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
// WASD movement
switch (key) {
case KeyEvent.VK_W:
pacmanY = Math.floorMod(pacmanY - 1, gridSize);
break;
case KeyEvent.VK_S:
pacmanY = Math.floorMod(pacmanY + 1, gridSize);
break;
case KeyEvent.VK_A:
pacmanX = Math.floorMod(pacmanX - 1, gridSize);
break;
case KeyEvent.VK_D:
pacmanX = Math.floorMod(pacmanX + 1, gridSize);
break;
}
// Collect power-up if moved onto it
if (powerUp != null && pacmanX == powerUp.x && pacmanY == powerUp.y) {
powerUpActive = true;
powerUpTimer = 50;
powerUp = null;
}
checkCollisions();
repaint();
}
// Unused methods
@Override
public void keyReleased(KeyEvent e) {}
@Override
public void keyTyped(KeyEvent e) {}
// Main method to run the game
public static void main(String[] args) {
JFrame frame = new JFrame("Simple Pacman Game");
SimplePacmanGame game = new SimplePacmanGame();
frame.add(game);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Explanation:
Game Panel: The SimplePacmanGame class extends JPanel and implements ActionListener and KeyListener to handle game updates and user input.
Game State: Variables are used to keep track of Pacman's position, ghosts, power-up status, score, and more.
Rendering: The paintComponent method draws the game grid, Pacman, ghosts, power-ups, and displays the score and power-up timer.
Game Loop: A Timer triggers the actionPerformed method periodically to update the game state (e.g., moving ghosts, handling power-up duration).
Controls: The keyPressed method handles WASD inputs to move Pacman around the grid.
Ghost Movement: Ghosts move towards Pacman by comparing their positions and adjusting their coordinates accordingly.
Collision Detection: The game checks for collisions between Pacman and ghosts or power-ups to handle game over conditions or activate power-ups.
Power-Up: When Pacman collects a power-up, he becomes invincible for a short duration and can eat ghosts.
To Run the Game:
Copy the code into a file named SimplePacmanGame.java.
Compile the program using javac SimplePacmanGame.java.
Run the game using java SimplePacmanGame.
Notes:
This is a simplified version of Pacman and does not include walls or pellets.
The game uses a grid system where both Pacman and ghosts move from cell to cell.
The power-up makes Pacman invincible for a certain number of game ticks, allowing him to "eat" ghosts.
There is no maze; movement wraps around the edges of the grid.
Feel free to enhance the game by adding features like walls, pellets to collect, more sophisticated ghost AI, and better graphics!