Cover Image for Pacman Game in C++
208 views

Pacman Game in C++

Creating a full-fledged Pac-Man game in C++ is a complex and time-consuming task that requires advanced game development skills and a deep understanding of graphics programming. However, I can provide you with a simplified text-based version of Pac-Man to help you get started. This version will use the console for input and output, and it won’t have advanced graphics or complex features.

C++
#include <iostream>
#include <vector>
#include <conio.h> // For _getch() function on Windows

using namespace std;

const int boardWidth = 20;
const int boardHeight = 10;

int pacManX, pacManY;
int ghostX, ghostY;
int score;

vector<vector<char>> board(boardHeight, vector<char>(boardWidth, ' '));

void InitializeGame() {
    pacManX = boardWidth / 2;
    pacManY = boardHeight / 2;
    ghostX = 0;
    ghostY = 0;
    score = 0;
    board[pacManY][pacManX] = 'P';
    board[ghostY][ghostX] = 'G';
}

void DrawBoard() {
    system("cls"); // Clear the console
    for (int y = 0; y < boardHeight; ++y) {
        for (int x = 0; x < boardWidth; ++x) {
            cout << board[y][x];
        }
        cout << endl;
    }
    cout << "Score: " << score << endl;
}

void MovePacMan(char direction) {
    board[pacManY][pacManX] = ' ';
    switch (direction) {
        case 'w':
            pacManY--;
            break;
        case 's':
            pacManY++;
            break;
        case 'a':
            pacManX--;
            break;
        case 'd':
            pacManX++;
            break;
    }
    if (pacManX == ghostX && pacManY == ghostY) {
        cout << "Game Over! You were caught by the ghost." << endl;
        exit(0);
    }
    board[pacManY][pacManX] = 'P';
}

void MoveGhost() {
    board[ghostY][ghostX] = ' ';
    // Implement ghost movement logic here
    // For simplicity, let's make the ghost move randomly
    ghostX = rand() % boardWidth;
    ghostY = rand() % boardHeight;
    board[ghostY][ghostX] = 'G';
}

int main() {
    InitializeGame();
    while (true) {
        DrawBoard();
        char input = _getch(); // Read a character from the console without pressing Enter
        if (input == 'q') {
            break; // Quit the game if 'q' is pressed
        }
        MovePacMan(input);
        MoveGhost();
        score++;
    }
    return 0;
}

This is a simple console-based Pac-Man game where Pac-Man (‘P’) can be moved using the ‘w’, ‘s’, ‘a’, and ‘d’ keys, and a ghost (‘G’) moves randomly. The game will continue until you press ‘q’ to quit. Note that this is just a basic example to get you started. Building a full-fledged Pac-Man game with advanced graphics and features would require a more extensive project and likely a game development framework or library.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS