[ create a new paste ] login | about

Link: http://codepad.org/9iihYe3T    [ raw code | output | fork ]

C++, pasted on Aug 13:
#include <cmath>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <iostream>

struct Point
{
    int x;
    int y;
};

//Алгоритм Брезенхема
void line(char * screen, size_t xMax, Point p0, Point p1)
{
    bool steep = std::abs(p1.y - p0.y) > std::abs(p1.x - p0.x);
    if(steep)
    {
        std::swap(p0.x, p0.y);
        std::swap(p1.x, p1.y);
    }
    if(p0.x > p1.x)
    {
        std::swap(p0.x, p1.x);
        std::swap(p0.y, p1.y);
    }
    int dx = p1.x - p0.x;
    int dy = std::abs(p1.y - p0.y);
    int error = dx / 2;
    int ystep = (p0.y < p1.y) ? 1 : -1;
    int y = p0.y;
    for(int x = p0.x; x <= p1.x; ++x)
    {
        screen[steep ? y + x * xMax : x + y * xMax] = '*';
        error -= dy;
        if(error < 0)
        {
            y += ystep;
            error += dx;
        }
    }
}

template <size_t (*next)(size_t, size_t), size_t M>
void paintFigure(char (&screen)[M], size_t xMax, Point * points, size_t size)
{
    for(size_t idx = 0; idx < size; ++idx)
    {
        line(screen, xMax, points[idx], points[next(idx, size)]);
    }
    std::fwrite(screen, sizeof(char), M / sizeof(char), stdout);
}

size_t nextPoint(size_t idx, size_t limit)
{
    return (idx += 1) >= limit ? idx - limit : idx;
}

int main()
{
    enum
    {
        Chars = 20
      , Lines = 20
    };

    char screen[(Chars + 1) * Lines];
    std::memset(screen, ' ', sizeof(screen));

    for(size_t lines = 0; lines < Lines; ++lines)
    {
        screen[Chars + lines * (Chars + 1)] = '\n';
    }
    Point center = {Chars / 2, Lines / 2};

    int side;
    std::cout << "Enter side: 5";
    side = 5;
    //std::cin >> side;
    if(side <= Lines && side <= Chars && side > 0)
    {
        const size_t numPoints = 4;
        const bool a = side % 2 == 0;
        side /= 2;
        Point points[numPoints] =
        {
            {center.x + (side - a), center.y + (side - a)}
           ,{center.x - side, center.y + (side - a)}
           ,{center.x - side, center.y - side}
           ,{center.x + (side - a), center.y - side}
        };
        paintFigure<&nextPoint>(screen, Chars + 1, points, numPoints);
    }
    else
    {
        std::cerr << "Side is not in [1:20]\n";
    }
}


Output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Enter side: 5                    
                    
                    
                    
                    
                    
                    
                    
        *****       
        *   *       
        *   *       
        *   *       
        *****       
                    
                    
                    
                    
                    
                    
                    


Create a new paste based on this one


Comments: