0

Im writing a code to draw a square onto a screen but its not working for some reason. Its supposed to draw a square to the screen where the square is '#' but the non square area is '0'. When I run the program though it gives me a full screen of '0' but a single '^' in the top left of the terminal. Ive tried listing the values of the square but it says those are zero so I tried changing the way of initalizing the square but it still ended up with zeroes for all the values. I am currently looking into pointers and references to see if those could help but im not completely sure.

#include <unistd.h>
#include <ncurses.h>

int height, width;

class Square {
    public:
        float x;
        float y;
        int w; 
        int h;
        char c;
};

Square ball;
void initSquare(Square square, float x, float y, int w, int h, char c);
void Render();

int main(void) {
    initscr();
    getmaxyx(stdscr, height, width);

    initSquare(ball, width/2, height/2, 4, 4, '#');

    while(true) {
        Render();
        usleep(35000);
        refresh();
    }
    return 0; 
}

void initSquare(Square square, float x, float y, int w, int h, char c) {
    square.x = x;
    square.y = y;
    square.w = w;
    square.h = h;
    square.c = c;
}

void Render() {
    for(int i = 0; i < height; ++ i) {
        for (int j = 0; j < width; ++ j) {
            if(j >= ball.x && j <= ball.x+ball.w && i >= ball.y && i <= ball.y + ball.h) {
                mvaddch(i, j, ball.c); 
            } else {
                mvaddch(i, j, '0');
            }
        }
    }
}
Muffinz
  • 15
  • 3
  • You take `square` by value. Any changes you do to it inside `initSquare` are local to that function and won't be visible outside the function. Make the function take a pointer to a `Square` instead. – Ted Lyngmo Jun 04 '23 at 17:37
  • is there a way to make the changed i do inside `initSquare` visible outside of the function? – Muffinz Jun 04 '23 at 17:38
  • Yes, make it take a pointer to a `Square` instead. `void initSquare(Square *square, ...` - You then need to change the assignments to `square->x = x;` etc. and you need to call it with `initSquare(&ball, ...` – Ted Lyngmo Jun 04 '23 at 17:39
  • 2
    Oh sorry, I mistook this for a C question. Since it's C++, the only change you need to do is to take it by reference instead. `void initSquare(Square& square, ...` - nothing else. – Ted Lyngmo Jun 04 '23 at 17:41
  • 1
    Thanks that works, do you know of a website or youtube video that explains pointers and references well? im struggling to find something that explains it well. – Muffinz Jun 04 '23 at 17:43
  • 2
    You're welcome! No, unfortunately I don't know of such a website, but one of the beginner books on [The Definitive C++ Book Guide and List](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) should explain it well. – Ted Lyngmo Jun 04 '23 at 17:44

0 Answers0