C ++矩形程序绘图在控制台窗口之外

时间:2018-01-13 17:21:30

标签: c++ windows windows-console conio

在以下代码的某处,我遗漏了一些东西。我的rects正在控制台窗口之外绘制,它们都需要在控制台内。这段代码是我的一个类的黑客工作,所以我为不必要或不正确的代码道歉。有时它可以工作,但大多数时候它只是在窗外画出东西。我该如何包含代码?

#include "stdafx.h"
#define NOMINMAX
#include <stdio.h>
#include <windows.h>
#include <conio.h>
#include <time.h>
void moveCursor(int x, int y)
{
COORD c = { x,y };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), c);

}



struct Vec2
{
short x, y;
int min, max;
Vec2() : x(rand()% 50), y(rand()%20 ){ }
Vec2(int x, int y) : x(x), y(y) { }
void operator+=(Vec2 v)
{
    x += v.x;
    y += v.y;
}

};

class Rect
{
Vec2 min, max;

public:
void setMin(Vec2 const & min)
{
    this->min = min;
}
void setMax(Vec2 const & max)
{
    this->max = max;
}
void setRandom(Rect & r)
{
    int x = rand() % 50;
    int y = rand() % 20;
    int x2 = rand() % 8+3;
    int y2 = rand() % 8+3;
    Vec2 min(x , y);
    r.setMin(min);
    Vec2 max(x + x2, y + y2);
    r.setMax(max);
}

Rect(int minx, int miny, int maxx, int maxy)
    :min(minx, miny), max(maxx, maxy)
{}
Rect() {}

void draw(const char letter) const
{
    for (int row = min.y; row < max.y; row++)
    {
        for (int col = min.x; col < max.x; col++)
        {
            if (row >= 0 && col >= 0)
            {
                moveCursor(col, row);
                putchar(letter);
            }
        }
    }
}

bool isOverlapping(Rect const & r) const
{
    return !(min.x >= r.max.x || max.x <= r.min.x
        || min.y >= r.max.y || max.y <= r.min.y);
}

void translate(Vec2 const & delta)
{

    min += (delta);
    max += (delta);
}

};

int main()
{
// initialization
srand(time (NULL));
const int Number_of_rects = 5;

Rect *userRect = new Rect(7, 5, 10, 9);
Rect rect[5]{};
int userInput;
do
{
    // draw

    for (int i = 0; i < Number_of_rects; i++)
      {
         rect[i].draw('0'+i);
    };

    moveCursor(0, 0);   // re-print instructions
    printf("move with 'w', 'a', 's', and 'd'");
    userRect->draw('#');
    // user input
    userInput = _getch();
    // update
    Vec2 move;
    switch (userInput)
    {
    case 'w':   move = Vec2(0, -1); break;
    case 'a':   move = Vec2(-1, 0); break;
    case 's':   move = Vec2(0, +1); break;
    case 'd':   move = Vec2(+1, 0); break;
    }
    userRect->draw(' ');    // un-draw before moving
    userRect->translate(move);

} while (userInput != 27); // escape key
delete userRect;
return 0;
}

enter image description here '#'总是在那里,1和0被绘制但是碰撞(不同的问题)和2,3和4被抽出屏幕

0 个答案:

没有答案