🌿 Smart Garden Manager in C++ with Robotics, UI, Drones, and Sound "A Rainwater Conservation System for Tomorrow’s Farms"

Image
  🌿  Smart Garden Manager in C++ with Robotics, UI, Drones, and Sound "A Rainwater Conservation System for Tomorrow’s Farms" 🧭  1. Introduction: Farming in the Age of Climate Change In a world where clean water is more precious than gold, efficient  rainwater harvesting and plant care systems  are no longer optional — they’re essential. Smart farming doesn’t mean just automating irrigation. It means combining  robotic drones, environmental sensors, and intelligent scheduling  to build a garden that practically takes care of itself. In this guide, we build a  fully functional Garden Manager System  using  C++  that: Captures and conserves rainwater Uses  robotic drones and sensors  to monitor crop health Integrates a  real-time UI  with progress bars and alerts Includes  timers  for scheduling plant growth and drone tasks Plays  interactive sounds  based on crop state and events Whether you'r...

C++ Projects: Snake Game

C++ Projects: Snake Game

Hello everyone, welcome back to the blog. Today we will build the classic Snake Game using C++. This program offers a console-based version of the classic game where the snake moves around, eating food to grow in size. If the snake collides with itself or hits the walls, the game ends.

Skills Used

  • Arrays – Used for tracking the body of the snake.
  • Loops – Used for continuously running the game.
  • Conditional statements – Used for handling movements, collisions, and game-over logic.
  • Handling input – Detecting key presses for controlling the snake.

The Code to Build the Project

#include <iostream>
#include <conio.h> // For keyboard input
#include <windows.h> // For sleep function
using namespace std;

// Global variables
const int width = 20;
const int height = 20;
int x, y, foodX, foodY, score;
int tailX[100], tailY[100]; // Snake's tail coordinates
int nTail; // Current length of tail
bool gameOver;

enum Direction { STOP = 0, LEFT, RIGHT, UP, DOWN };
Direction dir;

// Function to initialize the game
void setup() {
    gameOver = false;
    dir = STOP;
    x = width / 2;
    y = height / 2;
    foodX = rand() % width;
    foodY = rand() % height;
    score = 0;
    nTail = 0;
}

// Function to draw the game area
void draw() {
    system("cls"); // Clear the console

    // Top wall
    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 << "#"; // Left wall
            if (i == y && j == x)
                cout << "O"; // Snake head
            else if (i == foodY && j == foodX)
                cout << "F"; // Food
            else {
                bool print = false;
                for (int k = 0; k < nTail; k++) {
                    if (tailX[k] == j && tailY[k] == i) {
                        cout << "o"; // Snake body
                        print = true;
                    }
                }
                if (!print)
                    cout << " ";
            }
            if (j == width - 1)
                cout << "#"; // Right wall
        }
        cout << endl;
    }

    // Bottom wall
    for (int i = 0; i < width + 2; i++)
        cout << "#";
    cout << endl;
    cout << "Score: " << score << endl;
}

// Function to handle user input
void input() {
    if (_kbhit()) {
        switch (_getch()) {
            case 'w': dir = UP; break;
            case 's': dir = DOWN; break;
            case 'a': dir = LEFT; break;
            case 'd': dir = RIGHT; break;
            case 'x': gameOver = true; break;
        }
    }
}

// Function to update game logic
void logic() {
    int prevX = tailX[0], prevY = tailY[0], prev2X, prev2Y;
    tailX[0] = x;
    tailY[0] = y;

    // Update tail
    for (int i = 1; i < nTail; i++) {
        prev2X = tailX[i];
        prev2Y = tailY[i];
        tailX[i] = prevX;
        tailY[i] = prevY;
        prevX = prev2X;
        prevY = prev2Y;
    }

    // Move the snake's head
    switch (dir) {
        case LEFT: x--; break;
        case RIGHT: x++; break;
        case UP: y--; break;
        case DOWN: y++; break;
        default: break;
    }

    // Check collision with the walls
    if (x >= width || x < 0 || y >= height || y < 0)
        gameOver = true;

    // Check if food is eaten
    if (x == foodX && y == foodY) {
        score += 10;
        foodX = rand() % width;
        foodY = rand() % height;
        nTail++;
    }
}

// Main function
int main() {
    setup();
    while (!gameOver) {
        draw();
        input();
        logic();
        Sleep(100); // Control game speed
    }
    cout << "Game Over! Your score: " << score << endl;
    return 0;
}

Explanation

  1. Setup – Initializes the snake's position, food location, score, and game state.
  2. Draw – Renders the game grid using symbols:
    • # represents the walls.
    • O is the snake's head, o is its body.
    • F represents food.
  3. Handling Input – Detects key presses (w, s, a, d for movement, x to exit the game).
  4. Game Logic
    • The snake's tail follows the head by shifting positions.
    • Eating food increases the score and lengthens the tail.
  5. Collision Detection – If the snake hits a wall or itself, the game ends.
  6. Speed ControlSleep(100) slows the game down to make it playable.

Real-World Applications

AI and Pathfinding

The logic behind the Snake Game is similar to pathfinding algorithms used in robotics and AI, such as in self-driving cars.

Game Development

Modern video games use similar movement and collision detection logic for character movement.

Data Structures

The use of arrays and queues to manage the snake's tail is a fundamental data structure concept applied in areas like cache memory management.

Embedded Systems

Handling real-time user input and rendering output is crucial for firmware development in industrial automation, microwaves, and other devices.

Problem-Solving Approaches

  • Handling Collisions – Instead of ending the game on wall collision, modify the code to allow the snake to pass through walls (e.g., portal effect).
  • Improved Controls – Implement a feature preventing immediate reversal of direction to avoid accidental self-collisions.
  • Game Optimization – Improve performance by optimizing how the game checks for collisions and updates the screen.

Thanks for reading! See you next time with another cool project!

Comments

Popular posts from this blog

C++ Projects: Basic Traffic Management System

C++ Projects: Book Shop Management System

C++ Projects: Password Manager