0

Я программирую на c++ и использую графическую библиотеку SFML.

#include <SFML/Graphics.hpp>
using namespace sf;
using namespace std;

class Ball //Класс шара
{
public:
    Ball(double radius, Color color, double x, double y, double dx, double dy) //dy и dx - направления шара
    {
        this->radius = radius;
        this->color = color;
        this->x = x;
        this->y = y;
        this->dx = dx;
        this->dy = dy;
    }

    void draw(RenderWindow& window, CircleShape& shape) //Рисуем шар
    {
        shape.setFillColor(this->color);
        shape.setRadius(this->radius);
        shape.setOrigin(this->radius, this->radius);
        shape.setPosition(this->x, this->y);
        window.draw(shape);
    }

    void move(int winSize) //Двигаем шар
    {
        this->x += this->dx;
        this->y += this->dy;

        if (this->y < this->radius)
        {
            this->dy = -this->dy;
            this->y = this->radius;
        }
        else if (this->y > winSize - this->radius)
        {
            this->dy = -this->dy;
            this->y = winSize - this->radius;
        }

        if (this->x < this->radius)
        {
            this->dx = -this->dx;
            this->x = this->radius;
        }
        else if (this->x > winSize - this->radius)
        {
            this->dx = -this->dx;
            this->x = winSize - this->radius;
        }
    }

    void update(RenderWindow& window, CircleShape& shape, int winSize) //Сначала двигаем шар, а потом рисуем
    {
        this->move(winSize);
        this->draw(window, shape);
    }

private:
    double radius;
    Color color;
    double y;
    double x;
    double dy;
    double dx;
};

int main()
{
    const int winSize = 900;
    RenderWindow window(VideoMode(winSize, winSize), "Ball"); //Окно
    CircleShape shape(0);
    Ball ball(30, Color(255, 255, 0), 300, 450, 3, 2); //Шар

    while (window.isOpen())
    {
        Event event;
        while (window.pollEvent(event)) //Проверка событий
        {
            switch (event.type)
            {
                case Event::Closed:
                    window.close();
                    break;

                default:
                    break;
            }
        }

        window.clear();
        ball.update(window, shape, winSize); //Двигаем и рисуем шар
        window.display();
    }
}

В Ball ball(30, Color(255, 255, 0), 300, 450, 3, 2); создаётся шар и с помощью ball.update(window, shape, winSize); двигается и выводится на экран. Но что делать, если я хочу создать больше шаров, например 100? Можно создать массив balls, указать его размер в const int numberOfBalls и заполнить его шарами, а потом ball.update(window, shape, winSize); заменить на

for (int i = 0; i < numberOfBalls; i++)
    {
        balls[i].update(window, shape, winSize);
    }

вызывая у каждого шара функцию update(). Но у меня не получается заполнить массив шарами. Я попробовал создать и заполнить массив шарами так

const int numberOfBalls = 100;
Ball balls[numberOfBalls];
for (int i = 0; i < numberOfBalls; i++)
{
    balls[i] = ball(30, Color(255, 255, 0), 300, 450, 3, 2);
}

Но visual studio говорит, что есть 2 ошибки. Первая в Ball balls[numberOfBalls];, что нету конструктора по умолчанию, а вторая в balls[i] = ball(30, Color(255, 255, 0), 300, 450, 3, 2);, что идентификатор ball не определён.

2
  • Вторая ошибка - потому что название класса пишется с большой буквы.
    – CrazyElf
    27 мая 2021 в 5:39
  • А первая - определите в классе конструктор без параметров. 27 мая 2021 в 5:57

1 ответ 1

1

Если не принципиально использовать именно массив, советую std::vector. С его использованием можно преобразовать Ваш код так:

#include <vector>
//...
//...
//...
const int numberOfBalls = 100;
std::vector<Ball> balls;
for (int i = 0; i < numberOfBalls; i++)
{
    // Обратите внимание, как уже заметили в комментариях, имя класса с заглавной буквы
    balls.push_back(Ball(30, Color(255, 255, 0), 300, 450, 3, 2));
}

Дальше к элементам вектора можно обращаться так же, как к элементам обычного массива:

for (int i = 0; i < numberOfBalls; i++)
{
    balls[i].update(window, shape, winSize);
}

А можно и ещё удобнее, но здесь уже читайте про вектор

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.