cpp

examples

examples.cpp⚙️
/**
 * Graphics - Examples (SFML)
 * 
 * Install: sudo apt install libsfml-dev
 * Compile: g++ -std=c++17 -Wall examples.cpp -lsfml-graphics -lsfml-window -lsfml-system -o examples
 * 
 * Note: Examples require SFML installed. Code shows concepts even without running.
 */

#include <iostream>
#include <vector>
#include <cmath>

// Uncomment if SFML is installed:
// #include <SFML/Graphics.hpp>

using namespace std;

// ============================================================
// SECTION 1: BASIC WINDOW (Pseudocode without SFML)
// ============================================================

void showWindowExample() {
    cout << "--- Basic Window Example ---" << endl;
    cout << R"(
#include <SFML/Graphics.hpp>

int main() {
    sf::RenderWindow window(sf::VideoMode(800, 600), "My Window");
    
    while (window.isOpen()) {
        sf::Event event;
        while (window.pollEvent(event)) {
            if (event.type == sf::Event::Closed)
                window.close();
        }
        
        window.clear(sf::Color::Black);
        window.display();
    }
    return 0;
}
)" << endl;
}

// ============================================================
// SECTION 2: DRAWING SHAPES
// ============================================================

void showShapesExample() {
    cout << "--- Drawing Shapes Example ---" << endl;
    cout << R"(
// Rectangle
sf::RectangleShape rect(sf::Vector2f(100, 50));
rect.setPosition(200, 150);
rect.setFillColor(sf::Color::Blue);
window.draw(rect);

// Circle
sf::CircleShape circle(30);
circle.setPosition(400, 300);
circle.setFillColor(sf::Color::Green);
window.draw(circle);

// Triangle
sf::ConvexShape triangle;
triangle.setPointCount(3);
triangle.setPoint(0, sf::Vector2f(50, 0));
triangle.setPoint(1, sf::Vector2f(0, 100));
triangle.setPoint(2, sf::Vector2f(100, 100));
triangle.setFillColor(sf::Color::Red);
window.draw(triangle);
)" << endl;
}

// ============================================================
// SECTION 3: SPRITE AND TEXTURE
// ============================================================

void showSpriteExample() {
    cout << "--- Sprite and Texture Example ---" << endl;
    cout << R"(
sf::Texture texture;
if (!texture.loadFromFile("player.png")) {
    return -1;  // Error
}

sf::Sprite sprite;
sprite.setTexture(texture);
sprite.setPosition(100, 100);
sprite.setScale(2.0f, 2.0f);

// Animation frame
sprite.setTextureRect(sf::IntRect(0, 0, 32, 32));

window.draw(sprite);
)" << endl;
}

// ============================================================
// SECTION 4: KEYBOARD INPUT
// ============================================================

void showInputExample() {
    cout << "--- Input Handling Example ---" << endl;
    cout << R"(
// Real-time input (for movement)
float speed = 200.0f;
float dt = clock.restart().asSeconds();

if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
    player.move(-speed * dt, 0);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
    player.move(speed * dt, 0);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
    player.move(0, -speed * dt);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
    player.move(0, speed * dt);

// Event-based input (for actions)
if (event.type == sf::Event::KeyPressed) {
    if (event.key.code == sf::Keyboard::Space) {
        jump();
    }
    if (event.key.code == sf::Keyboard::Escape) {
        window.close();
    }
}

// Mouse
sf::Vector2i mousePos = sf::Mouse::getPosition(window);
if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) {
    shoot();
}
)" << endl;
}

// ============================================================
// SECTION 5: GAME LOOP
// ============================================================

void showGameLoopExample() {
    cout << "--- Game Loop Example ---" << endl;
    cout << R"(
int main() {
    sf::RenderWindow window(sf::VideoMode(800, 600), "Game");
    window.setFramerateLimit(60);
    
    sf::Clock clock;
    
    // Game objects
    sf::RectangleShape player(sf::Vector2f(50, 50));
    player.setFillColor(sf::Color::Blue);
    player.setPosition(375, 275);
    
    float playerSpeed = 300.0f;
    
    while (window.isOpen()) {
        // Delta time
        float dt = clock.restart().asSeconds();
        
        // Events
        sf::Event event;
        while (window.pollEvent(event)) {
            if (event.type == sf::Event::Closed)
                window.close();
        }
        
        // Update
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
            player.move(0, -playerSpeed * dt);
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))
            player.move(0, playerSpeed * dt);
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
            player.move(-playerSpeed * dt, 0);
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
            player.move(playerSpeed * dt, 0);
        
        // Render
        window.clear();
        window.draw(player);
        window.display();
    }
    
    return 0;
}
)" << endl;
}

// ============================================================
// SECTION 6: ANIMATION CLASS
// ============================================================

void showAnimationExample() {
    cout << "--- Animation Example ---" << endl;
    cout << R"(
class Animation {
    sf::Sprite& sprite;
    int currentFrame = 0;
    int frameCount;
    float frameTime;
    float elapsedTime = 0;
    int frameWidth, frameHeight;
    
public:
    Animation(sf::Sprite& s, int frames, float duration, int fw, int fh)
        : sprite(s), frameCount(frames), frameTime(duration / frames),
          frameWidth(fw), frameHeight(fh) {
        sprite.setTextureRect(sf::IntRect(0, 0, fw, fh));
    }
    
    void update(float dt) {
        elapsedTime += dt;
        if (elapsedTime >= frameTime) {
            elapsedTime = 0;
            currentFrame = (currentFrame + 1) % frameCount;
            sprite.setTextureRect(
                sf::IntRect(currentFrame * frameWidth, 0, 
                           frameWidth, frameHeight)
            );
        }
    }
};

// Usage:
sf::Texture texture;
texture.loadFromFile("spritesheet.png");
sf::Sprite sprite(texture);
Animation walkAnim(sprite, 8, 1.0f, 32, 32);  // 8 frames, 1 second

// In game loop:
walkAnim.update(dt);
window.draw(sprite);
)" << endl;
}

// ============================================================
// SECTION 7: COLLISION DETECTION
// ============================================================

void showCollisionExample() {
    cout << "--- Collision Detection Example ---" << endl;
    cout << R"(
// AABB Collision (Axis-Aligned Bounding Box)
bool checkCollision(const sf::RectangleShape& a, 
                   const sf::RectangleShape& b) {
    return a.getGlobalBounds().intersects(b.getGlobalBounds());
}

// Circle collision
bool circleCollision(const sf::CircleShape& a, const sf::CircleShape& b) {
    sf::Vector2f posA = a.getPosition();
    sf::Vector2f posB = b.getPosition();
    
    float dx = posA.x - posB.x;
    float dy = posA.y - posB.y;
    float distance = std::sqrt(dx * dx + dy * dy);
    
    return distance < (a.getRadius() + b.getRadius());
}

// Point in rectangle
bool pointInRect(sf::Vector2f point, const sf::RectangleShape& rect) {
    return rect.getGlobalBounds().contains(point);
}

// Usage in game loop:
if (checkCollision(player, enemy)) {
    handleCollision();
}
)" << endl;
}

// ============================================================
// SECTION 8: COMPLETE MINI GAME
// ============================================================

void showMiniGameExample() {
    cout << "--- Mini Game Example (Catch the Falling Objects) ---" << endl;
    cout << R"(
#include <SFML/Graphics.hpp>
#include <vector>
#include <cstdlib>

class FallingObject {
public:
    sf::RectangleShape shape;
    float speed;
    
    FallingObject(float x) : speed(100 + rand() % 200) {
        shape.setSize(sf::Vector2f(30, 30));
        shape.setFillColor(sf::Color::Yellow);
        shape.setPosition(x, -30);
    }
    
    void update(float dt) {
        shape.move(0, speed * dt);
    }
    
    bool isOffScreen() {
        return shape.getPosition().y > 600;
    }
};

int main() {
    srand(time(nullptr));
    sf::RenderWindow window(sf::VideoMode(800, 600), "Catch Game");
    window.setFramerateLimit(60);
    
    // Player
    sf::RectangleShape player(sf::Vector2f(100, 20));
    player.setFillColor(sf::Color::Blue);
    player.setPosition(350, 550);
    
    vector<FallingObject> objects;
    float spawnTimer = 0;
    int score = 0;
    sf::Clock clock;
    
    while (window.isOpen()) {
        float dt = clock.restart().asSeconds();
        
        sf::Event event;
        while (window.pollEvent(event)) {
            if (event.type == sf::Event::Closed)
                window.close();
        }
        
        // Player movement
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
            player.move(-400 * dt, 0);
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
            player.move(400 * dt, 0);
        
        // Spawn objects
        spawnTimer += dt;
        if (spawnTimer > 1.0f) {
            spawnTimer = 0;
            objects.emplace_back(rand() % 770);
        }
        
        // Update objects
        for (auto& obj : objects) {
            obj.update(dt);
            if (obj.shape.getGlobalBounds().intersects(
                    player.getGlobalBounds())) {
                score++;
                obj.shape.setPosition(-100, -100);
            }
        }
        
        // Remove off-screen
        objects.erase(
            remove_if(objects.begin(), objects.end(),
                [](FallingObject& o) { return o.isOffScreen(); }),
            objects.end()
        );
        
        // Render
        window.clear();
        window.draw(player);
        for (auto& obj : objects)
            window.draw(obj.shape);
        window.display();
    }
    
    return 0;
}
)" << endl;
}

// ============================================================
// MAIN
// ============================================================

int main() {
    cout << "╔══════════════════════════════════════╗" << endl;
    cout << "║       GRAPHICS - EXAMPLES            ║" << endl;
    cout << "╚══════════════════════════════════════╝" << endl;
    cout << "\nNote: These examples require SFML library." << endl;
    cout << "Install: sudo apt install libsfml-dev" << endl;
    cout << "Compile: g++ -std=c++17 file.cpp -lsfml-graphics -lsfml-window -lsfml-system\n" << endl;
    
    showWindowExample();
    showShapesExample();
    showSpriteExample();
    showInputExample();
    showGameLoopExample();
    showAnimationExample();
    showCollisionExample();
    showMiniGameExample();
    
    cout << "\n=== Complete ===" << endl;
    return 0;
}
Examples - C++ Tutorial | DeepML