简体   繁体   中英

How can I fix this c++ console map problem?

I have a problem with my map because I want to place a lot of bots there. I should use other drawing idea or just make it work better. It looks like this(there are to many dots and i have no idea how to fix it):

...@...

@......

.@.....

.....

.....

but I want reach it:

...@..

@.....

.@....

.....

.....

#include <iostream>
#include <vector>
#include <string>
#include <ctime>
#include <cstdlib>
#include <Windows.h>
#include <iomanip>

class Bot
{
public:
    Bot(const int mapX, const int mapY)
    {
        x = rand() % mapX;
        y = rand() % mapY;
    }
    int getPosX()
    {
        return x;
    }
    int getPosY()
    {
        return y;
    }
private:
    int x;
    int y;
    const char sym = '@';
};
class Map
{
public:
    std::vector<Bot> bots;
    Map()
    {
        for (int i = 0; i < startingBotsNumber; i++)
        {
            bots.push_back(Bot(getMapSizeX(), getMapSizeY()));
        }
    }
    int getMapSizeX()
    {
        return x;
    }
    int getMapSizeY()
    {
        return y;
    }
    void draw()
    {
        for (int i = 0; i < y; i++)
        {
            for (int j = 0; j < x; j++)
            {
                for (int k = 0; k < startingBotsNumber; k++)
                {
                    if (bots[k].getPosX() == j && bots[k].getPosY() == i)
                        std::cout << '@';
                }
                std::cout << '.';
            }
            std::cout << std::endl;
        }
    }
private:
    const int x = 5;
    const int y = 5;
    const int startingBotsNumber = 3;
};
class Game
{
public:
    void run()
    {
        while (true)
        {
            m.draw();
            system("cls");
        }
    }
    Map m;
private:
};

I need a hint or smth bcs i have no idea how to fix it.

for (int k = 0; k < startingBotsNumber; k++)
{
    if (bots[k].getPosX() == j && bots[k].getPosY() == i)
        std::cout << '@';
}
std::cout << '.';

This codes prints another '.', even if there has been a '@' printed already for the location. That results in one extra '.' for each '@'.

Instead you could use something like this:

bool found = false;
for (int k = 0; k < startingBotsNumber; k++)
    if (bots[k].getPosX() == j && bots[k].getPosY() == i)
    {
        found = true;
        break;
    }
if (found)
    std::cout << '@';
else
    std::cout << '.';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM