I'll create a complete Pac-Man game in Java using Swing. Here's a standalone implementation:
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 PacManGame extends JPanel implements ActionListener, KeyListener {
private static final int BOARD_WIDTH = 600;
private static final int BOARD_HEIGHT = 600;
private static final int UNIT_SIZE = 25;
private static final int GAME_UNITS = (BOARD_WIDTH * BOARD_HEIGHT) / (UNIT_SIZE * UNIT_SIZE);
private static final int DELAY = 100;
private Timer timer;
private Random random;
private boolean running = false;
private int score = 0;
private int dotsEaten = 0;
private int totalDots = 0;
// Pac-Man
private int pacmanX = UNIT_SIZE;
private int pacmanY = UNIT_SIZE;
private char direction = 'R';
private char nextDirection = 'R';
// Ghosts
private List<Ghost> ghosts;
// Game board (1 = wall, 0 = dot, 2 = empty)
private int[][] board;
public PacManGame() {
random = new Random();
this.setPreferredSize(new Dimension(BOARD_WIDTH, BOARD_HEIGHT));
this.setBackground(Color.BLACK);
this.setFocusable(true);
this.addKeyListener(this);
initializeBoard();
startGame();
}
private void initializeBoard() {
board = new int[BOARD_HEIGHT / UNIT_SIZE][BOARD_WIDTH / UNIT_SIZE];
ghosts = new ArrayList<>();
// Create a simple maze layout
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
// Create walls around border and some internal walls
if (i == 0 || i == board.length - 1 || j == 0 || j == board[i].length - 1 ||
(i % 4 == 0 && j % 4 == 0 && i != 0 && j != 0)) {
board[i][j] = 1; // Wall
} else {
board[i][j] = 0; // Dot
totalDots++;
}
}
}
// Clear starting position for Pac-Man
board[1][1] = 2;
totalDots--;
// Add ghosts
ghosts.add(new Ghost(BOARD_WIDTH - 2 * UNIT_SIZE, UNIT_SIZE, Color.RED));
ghosts.add(new Ghost(BOARD_WIDTH - 2 * UNIT_SIZE, BOARD_HEIGHT - 2 * UNIT_SIZE, Color.PINK));
ghosts.add(new Ghost(UNIT_SIZE, BOARD_HEIGHT - 2 * UNIT_SIZE, Color.CYAN));
// Clear ghost starting positions
for (Ghost ghost : ghosts) {
int row = ghost.y / UNIT_SIZE;
int col = ghost.x / UNIT_SIZE;
if (board[row][col] == 0) {
board[row][col] = 2;
totalDots--;
}
}
}
public void startGame() {
running = true;
timer = new Timer(DELAY, this);
timer.start();
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
draw(g);
}
public void draw(Graphics g) {
if (running) {
// Draw board
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
if (board[i][j] == 1) {
// Wall
g.setColor(Color.BLUE);
g.fillRect(j * UNIT_SIZE, i * UNIT_SIZE, UNIT_SIZE, UNIT_SIZE);
} else if (board[i][j] == 0) {
// Dot
g.setColor(Color.WHITE);
g.fillOval(j * UNIT_SIZE + UNIT_SIZE/3, i * UNIT_SIZE + UNIT_SIZE/3,
UNIT_SIZE/3, UNIT_SIZE/3);
}
}
}
// Draw Pac-Man
g.setColor(Color.YELLOW);
g.fillOval(pacmanX, pacmanY, UNIT_SIZE, UNIT_SIZE);
// Draw Pac-Man mouth
g.setColor(Color.BLACK);
int mouthSize = UNIT_SIZE / 3;
switch (direction) {
case 'U':
g.fillPolygon(new int[]{pacmanX + UNIT_SIZE/2, pacmanX + UNIT_SIZE/4, pacmanX + 3*UNIT_SIZE/4},
new int[]{pacmanY + UNIT_SIZE/2, pacmanY, pacmanY}, 3);
break;
case 'D':
g.fillPolygon(new int[]{pacmanX + UNIT_SIZE/2, pacmanX + UNIT_SIZE/4, pacmanX + 3*UNIT_SIZE/4},
new int[]{pacmanY + UNIT_SIZE/2, pacmanY + UNIT_SIZE, pacmanY + UNIT_SIZE}, 3);
break;
case 'L':
g.fillPolygon(new int[]{pacmanX + UNIT_SIZE/2, pacmanX, pacmanX},
new int[]{pacmanY + UNIT_SIZE/2, pacmanY + UNIT_SIZE/4, pacmanY + 3*UNIT_SIZE/4}, 3);
break;
case 'R':
g.fillPolygon(new int[]{pacmanX + UNIT_SIZE/2, pacmanX + UNIT_SIZE, pacmanX + UNIT_SIZE},
new int[]{pacmanY + UNIT_SIZE/2, pacmanY + UNIT_SIZE/4, pacmanY + 3*UNIT_SIZE/4}, 3);
break;
}
// Draw ghosts
for (Ghost ghost : ghosts) {
g.setColor(ghost.color);
g.fillOval(ghost.x, ghost.y, UNIT_SIZE, UNIT_SIZE);
// Draw eyes
g.setColor(Color.WHITE);
g.fillOval(ghost.x + 5, ghost.y + 5, 5, 5);
g.fillOval(ghost.x + 15, ghost.y + 5, 5, 5);
g.setColor(Color.BLACK);
g.fillOval(ghost.x + 6, ghost.y + 6, 3, 3);
g.fillOval(ghost.x + 16, ghost.y + 6, 3, 3);
}
// Draw score
g.setColor(Color.WHITE);
g.setFont(new Font("Arial", Font.BOLD, 16));
FontMetrics metrics = getFontMetrics(g.getFont());
g.drawString("Score: " + score, (BOARD_WIDTH - metrics.stringWidth("Score: " + score)) / 2,
g.getFont().getSize());
} else {
gameOver(g);
}
}
public void move() {
// Update direction if valid
int nextX = pacmanX;
int nextY = pacmanY;
switch (nextDirection) {
case 'U':
nextY -= UNIT_SIZE;
break;
case 'D':
nextY += UNIT_SIZE;
break;
case 'L':
nextX -= UNIT_SIZE;
break;
case 'R':
nextX += UNIT_SIZE;
break;
}
if (isValidMove(nextX, nextY)) {
direction = nextDirection;
}
// Move Pac-Man in current direction
switch (direction) {
case 'U':
if (isValidMove(pacmanX, pacmanY - UNIT_SIZE)) {
pacmanY -= UNIT_SIZE;
}
break;
case 'D':
if (isValidMove(pacmanX, pacmanY + UNIT_SIZE)) {
pacmanY += UNIT_SIZE;
}
break;
case 'L':
if (isValidMove(pacmanX - UNIT_SIZE, pacmanY)) {
pacmanX -= UNIT_SIZE;
}
break;
case 'R':
if (isValidMove(pacmanX + UNIT_SIZE, pacmanY)) {
pacmanX += UNIT_SIZE;
}
break;
}
// Wrap around screen
if (pacmanX < 0) {
pacmanX = BOARD_WIDTH - UNIT_SIZE;
} else if (pacmanX >= BOARD_WIDTH) {
pacmanX = 0;
}
}
private boolean isValidMove(int x, int y) {
if (x < 0 || x >= BOARD_WIDTH || y < 0 || y >= BOARD_HEIGHT) {
return x < 0 || x >= BOARD_WIDTH; // Allow horizontal wrapping
}
int row = y / UNIT_SIZE;
int col = x / UNIT_SIZE;
return board[row][col] != 1; // Not a wall
}
public void checkFood() {
int row = pacmanY / UNIT_SIZE;
int col = pacmanX / UNIT_SIZE;
if (board[row][col] == 0) {
board[row][col] = 2; // Mark as eaten
score += 10;
dotsEaten++;
if (dotsEaten >= totalDots) {
// Win condition
running = false;
}
}
}
public void moveGhosts() {
for (Ghost ghost : ghosts) {
// Simple AI: move randomly, but prefer moving toward Pac-Man
int[] dx = {0, 0, -UNIT_SIZE, UNIT_SIZE};
int[] dy = {-UNIT_SIZE, UNIT_SIZE, 0, 0};
int bestMove = 0;
double minDistance = Double.MAX_VALUE;
for (int i = 0; i < 4; i++) {
int newX = ghost.x + dx[i];
int newY = ghost.y + dy[i];
if (isValidMove(newX, newY)) {
double distance = Math.sqrt(Math.pow(newX - pacmanX, 2) + Math.pow(newY - pacmanY, 2));
if (distance < minDistance && random.nextDouble() < 0.8) {
minDistance = distance;
bestMove = i;
}
}
}
ghost.x += dx[bestMove];
ghost.y += dy[bestMove];
// Wrap around screen
if (ghost.x < 0) {
ghost.x = BOARD_WIDTH - UNIT_SIZE;
} else if (ghost.x >= BOARD_WIDTH) {
ghost.x = 0;
}
}
}
public void checkCollisions() {
// Check ghost collisions
for (Ghost ghost : ghosts) {
if (Math.abs(pacmanX - ghost.x) < UNIT_SIZE && Math.abs(pacmanY - ghost.y) < UNIT_SIZE) {
running = false;
}
}
}
public void gameOver(Graphics g) {
// Score
g.setColor(Color.RED);
g.setFont(new Font("Arial", Font.BOLD, 40));
FontMetrics metrics1 = getFontMetrics(g.getFont());
g.drawString("Score: " + score, (BOARD_WIDTH - metrics1.stringWidth("Score: " + score)) / 2,
g.getFont().getSize());
// Game Over text
g.setColor(Color.RED);
g.setFont(new Font("Arial", Font.BOLD, 75));
FontMetrics metrics2 = getFontMetrics(g.getFont());
String message = (dotsEaten >= totalDots) ? "YOU WIN!" : "Game Over";
g.drawString(message, (BOARD_WIDTH - metrics2.stringWidth(message)) / 2, BOARD_HEIGHT / 2);
// Restart instruction
g.setColor(Color.WHITE);
g.setFont(new Font("Arial", Font.BOLD, 14));
FontMetrics metrics3 = getFontMetrics(g.getFont());
g.drawString("Press SPACE to restart", (BOARD_WIDTH - metrics3.stringWidth("Press SPACE to restart")) / 2,
BOARD_HEIGHT / 2 + 50);
}
@Override
public void actionPerformed(ActionEvent e) {
if (running) {
move();
checkFood();
moveGhosts();
checkCollisions();
}
repaint();
}
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT:
nextDirection = 'L';
break;
case KeyEvent.VK_RIGHT:
nextDirection = 'R';
break;
case KeyEvent.VK_UP:
nextDirection = 'U';
break;
case KeyEvent.VK_DOWN:
nextDirection = 'D';
break;
case KeyEvent.VK_SPACE:
if (!running) {
// Restart game
score = 0;
dotsEaten = 0;
pacmanX = UNIT_SIZE;
pacmanY = UNIT_SIZE;
direction = 'R';
nextDirection = 'R';
initializeBoard();
startGame();
}
break;
}
}
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyReleased(KeyEvent e) {}
// Ghost class
private class Ghost {
int x, y;
Color color;
public Ghost(int x, int y, Color color) {
this.x = x;
this.y = y;
this.color = color;
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Pac-Man Game");
PacManGame game = new PacManGame();
frame.add(game);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
}
This Pac-Man game includes:
Features:
- Complete maze with walls and dots to collect
- Pac-Man character that moves with arrow keys
- Three colorful ghosts with simple AI that chase Pac-Man
- Score system (10 points per dot)
- Collision detection between Pac-Man and ghosts
- Win condition when all dots are collected
- Game over screen with restart functionality (press SPACE)
- Screen wrapping (Pac-Man and ghosts can exit one side and appear on the other)
Controls:
- Arrow keys to move Pac-Man
- SPACE to restart after game over
To run:
- Save the code as
PacManGame.java
- Compile:
javac PacManGame.java
- Run:
java PacManGame
The game creates a simple but functional Pac-Man experience with a maze layout, dot collection mechanics, ghost enemies, and proper game state management. The ghosts use basic AI to chase Pac-Man, making the game challenging while remaining playable.