C++ simple game source code

If you’re a programming enthusiast looking to delve into game development, starting with a simple game in C++ is an excellent choice. This guide walks you through creating a basic Snake Game in C++ while explaining key concepts, offering tips for enhancement, and providing source code examples. The tutorial focuses on simplicity and clarity, making it perfect for beginners.

Why Choose C++ for Game Development?

C++ is widely used in the game development industry due to its performance and versatility. Here are some reasons to start with C++:

  1. High Performance: C++ enables direct memory manipulation, making it faster for rendering graphics and managing resources.
  2. Portability: It runs seamlessly across platforms.
  3. Libraries: You can integrate libraries like SDL or SFML for advanced features.
  4. Learning Opportunity: Developing games in C++ strengthens your understanding of algorithms, logic, and optimization.

Building a Simple Snake Game

Overview of the Game

The Snake Game is a classic arcade game where the player controls a snake to collect food while avoiding collisions with the snake’s tail or walls. The snake grows longer with each food item collected, and the goal is to score as high as possible.

Prerequisites

  1. Compiler: A C++ compiler like GCC or Visual Studio.
  2. Editor: Any code editor, such as VS Code or Notepad++.
  3. Basic Knowledge: Understanding of loops, arrays, and functions in C++.

Key Features of the Snake Game

  1. Game Logic:
    • Movement of the snake using keyboard inputs.
    • Random placement of food on the grid.
    • Collision detection for game over scenarios.
  2. Score Tracking: Tracks and displays the score as the snake eats food.
  3. Dynamic Difficulty: Offers modes like easy (slower snake) and hard (faster snake).

Example Source Code

Here’s a simplified version of the Snake Game in C++:

#include <iostream>
#include <conio.h>
#include <cstdlib>
using namespace std;

bool gameOver;
const int width = 20, height = 20;
int x, y, fruitX, fruitY, score;
int tailX[100], tailY[100];
int nTail;
enum Direction { STOP = 0, LEFT, RIGHT, UP, DOWN };
Direction dir;

void Setup() {
    gameOver = false;
    dir = STOP;
    x = width / 2;
    y = height / 2;
    fruitX = rand() % width;
    fruitY = rand() % height;
    score = 0;
    nTail = 0;
}

void Draw() {
    system("cls");
    for (int i = 0; i < width + 2; i++) cout << "#";
    cout << endl;

    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
            if (j == 0) cout << "#";
            if (i == y && j == x) cout << "O";
            else if (i == fruitY && j == fruitX) cout << "F";
            else {
                bool print = false;
                for (int k = 0; k < nTail; k++) {
                    if (tailX[k] == j && tailY[k] == i) {
                        cout << "o";
                        print = true;
                    }
                }
                if (!print) cout << " ";
            }
            if (j == width - 1) cout << "#";
        }
        cout << endl;
    }

    for (int i = 0; i < width + 2; i++) cout << "#";
    cout << "\nScore: " << score << endl;
}

void Input() {
    if (_kbhit()) {
        switch (_getch()) {
        case 'a': dir = LEFT; break;
        case 'd': dir = RIGHT; break;
        case 'w': dir = UP; break;
        case 's': dir = DOWN; break;
        case 'x': gameOver = true; break;
        }
    }
}

void Logic() {
    int prevX = tailX[0];
    int prevY = tailY[0];
    int prev2X, prev2Y;
    tailX[0] = x;
    tailY[0] = y;
    for (int i = 1; i < nTail; i++) {
        prev2X = tailX[i];
        prev2Y = tailY[i];
        tailX[i] = prevX;
        tailY[i] = prevY;
        prevX = prev2X;
        prevY = prev2Y;
    }
    switch (dir) {
    case LEFT: x--; break;
    case RIGHT: x++; break;
    case UP: y--; break;
    case DOWN: y++; break;
    }
    if (x >= width) x = 0; else if (x < 0) x = width - 1;
    if (y >= height) y = 0; else if (y < 0) y = height - 1;

    for (int i = 0; i < nTail; i++)
        if (tailX[i] == x && tailY[i] == y)
            gameOver = true;

    if (x == fruitX && y == fruitY) {
        score += 10;
        fruitX = rand() % width;
        fruitY = rand() % height;
        nTail++;
    }
}

int main() {
    Setup();
    while (!gameOver) {
        Draw();
        Input();
        Logic();
    }
    return 0;
}

Instructions to Run

  1. Copy and paste the code into a .cpp file.
  2. Compile using a C++ compiler (g++ game.cpp -o game).
  3. Run the compiled file and use W, A, S, D to control the snake.

Enhancements for Advanced Developers

  1. Graphics: Use libraries like SFML or SDL to replace console graphics.
  2. Levels: Add levels with increasing difficulty.
  3. Multiplayer: Allow multiple players to control different snakes.

FAQs

1. Can I use this code for advanced games?
Yes, this game introduces key programming concepts that can be scaled for more complex games.

2. How do I improve the graphics?
Implement libraries like SFML or SDL for advanced graphics rendering.

3. What if I encounter compilation errors?
Ensure your compiler supports modern C++ standards and that <conio.h> is available.

4. Can I create mobile or web games using C++?
Yes, but you’ll need frameworks like Unreal Engine or libraries like Emscripten.

5. How do I add sound effects?
You can use libraries like SDL2 or OpenAL for sound.

For more details on creating and modifying the Snake Game, check tutorials on GitHub and Instructables.

Also Read

How to Create a College Website Using HTML and CSS Code Free

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top