Click here to Skip to main content
15,900,518 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am a beginner programmer working on a program in c++ visual studio 2015 that takes an instance of a class titled rect and passes it to a function within rect that sets a rectangle of random size and position somewhere on a imaginary board in a console window. At the bottom of the code there are full instructions on what the code needs to do. The problem I am having is when the program prints the rectangles, the rectangle of "0's" is not printing but the rectangle of "1's" is. The rectangle rect0 is being passed by reference and the rect1 is being passed by pointer.

C++
/*
iLab2: rectangles
*/

#define NOMINMAX // prevent Windows API from conflicting with "min" and "max"

#include <stdio.h>   // C-style output. printf(char*,...), putchar(int)
#include <windows.h> // SetConsoleCursorPosition(HANDLE,COORD)
#include <conio.h>   // _getch()
#include <time.h>

/**
* moves the console cursor to the given x/y coordinate
* 0, 0 is the upper-left hand coordinate. Standard consoles are 80x24.
* @param x
* @param y
*/
void moveCursor(int x, int y)
{
	COORD c = { x,y };
	SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), c);
}

struct Vec2
{
	short x, y;		// variables x and y for storing rectangle coordinates
	Vec2() : x(0), y(0) { }		// default constructor for vect2 if no parameters are specified
	Vec2(int x, int y) : x(x), y(y) { } // default constructor for vect2 if parameters are given
	void operator+=(Vec2 v)		// function for adding or subtracting (if v is negative) to move the rectangle
	{
		x += v.x;
		y += v.y;
	}
};

class Rect
{
	Vec2 min, max;
public:
	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);
				}
			}
		}
	}

	void setMax(int maxx, int maxy)
	{
		this->max.x = maxx;
		this->max.y = maxy;
	}

	void setMin(int minx, int miny)
	{
		this->min.x = minx;
		this->min.y = miny;
	}
	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);
	}
	void setRandom(Rect & r);
	void setRandom(Rect* r);
};


void Rect::setRandom(Rect & r)
{
	srand(time(NULL));		// added to make the random placement and size of the rect different each time program runs
	int pos_x, pos_y, height, width;
	pos_x = rand() % 51;
	pos_y = rand() % 21;

	height = 2 + rand() % 11;
	width = 2 + rand() % 11;

	height = height / 2;
	width = width / 2;

	r.min.x = pos_x - width;
	r.min.y = pos_y - height;
	r.max.x = pos_x + width;
	r.max.y = pos_y + height;
}
void Rect::setRandom(Rect * r)
{
	srand(time(NULL));		// added to make the random placement and size of the rect different each time program runs
	int posX, posY, heightPoint, widthPoint;
	posX = rand() % 51;
	posY = rand() % 21;

	heightPoint = 2 + rand() % 11;
	widthPoint = 2 + rand() % 11;

	heightPoint = heightPoint / 2;
	widthPoint = widthPoint / 2;

	this->min.x = posX - widthPoint;
	this->min.y = posY - heightPoint;
	this->max.x = posX + widthPoint;
	this->max.y = posY + heightPoint;
}

int main()
{
	// initialization
	//Rect userRect(7, 5, 10, 9);		// (x-min, y-min, x-max, y-max) x-min how far left the rectange can be
	//Rect rect0(10, 2, 14, 4);		// (x-min, y-min, x-max, y-max)
	//Rect rect1(1, 6, 5, 15);		// (x-min, y-min, x-max, y-max)
	//Rect userRect;
	Rect * userRect;
	Rect rect0;
	Rect rect1;
	const int rectSize = 5;
	Rect rect[rectSize];


	userRect = new Rect();
	// set
	rect[0].setRandom(rect0);
	rect[1].setRandom(& rect1);
	userRect->setMin(7, 5);
	userRect->setMax(10, 9);
	//rect0.setMin(10, 2);
	//rect0.setMax(14, 4);
	//rect1.setMin(1, 6);
	//rect1.setMax(5, 15);
	int userInput;

	do
	{
		// draw
		rect[0].draw('0');	
		//rect[1].draw('1');	
		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;		// Moves the user Rectangle -y or up on the screen
		case 'a':	move = Vec2(-1, 0);	break;		// Moves the user Rectangle -x or left on the screen
		case 's':	move = Vec2(0, +1);	break;		// Moves the user Rectangle +y or down on the screen
		case 'd':	move = Vec2(+1, 0);	break;		// Moves the user Rectangle +x or right on the screen
		}
		userRect->draw(' ');	// un-draw before moving
		userRect->translate(move);		// moves the user rectangle to the new location
	} while (userInput != 27); // escape key
	delete userRect;	// delete dynamic object to release memory
	return 0;
}

// INSTRUCTIONS
// ------------
// 3) Random rectangles, by reference and by pointer
//   a) create a method with the method signature "void setRandom(Rect & r)".
//      This function will give the passed-in Rect object a random location.
//      The random x should be between 0 and 50 x. The random y should be  
//      between 0 and 20. Limit the possible width and height to a minimum of 2
//      and a maximum of 10.
//   b) test "void setRandom(Rect & r)" on the local Rect object "rect0".
//   c) create a method with the method signature
//      "void setRandomByPointer(Rect * r)", which functions the same as
//      "void setRandom(Rect & r)", except that the argument is
//      passed-by-pointer.
//   d) test "void setRandomByPointer(Rect * r)" on the local Rect object
//      "rect1".
// 4) Test and show overlap
//   a) Using the existing function "isOverlapping(Rect const &)", test to see
//      if userRect collides with any other Rect objects. If userRect is
//      overlapping, draw it with '+' instead '#'.
//   b) Create a Rect * pointer that points to the address if the Rect object
//      that userRect collides with. It should point at NULL if userRect is
//      colliding with no other Rect objects.
//   c) Print to the screen the width and height of a Rect object that userRect
//      collides with. If no collision is happening, print "no collision"
//      instead.
// 5) Array of objects
//   a) Replace the Rect objects rect0 and rect1 with an array of 2 Rect
//      objects, "rect[2]".
//   b) Make sure you replace every remaining "rect0" with "rect[0]", and every
//      "rect1" with "rect[1]".
//   c) Increase the size of the "rect" array to 5. Make sure all 5 Rect
//      objects are randomized, drawn to the screen, and tested for collision.
//   d) If you have not already done so, replace
//      duplicate-code-using-array-elements with a for-loop. For example:
//      If you have:
//          rect[0].draw('0');
//          rect[1].draw('1');
//          rect[2].draw('2');
//          rect[3].draw('3');
//          rect[4].draw('4');
//      Replace it with:
//          for(int i = 0; i < NUMBER_OF_RECTS; i++)
//          {
//              rect[i].draw('0'+i);
//          }
//      Do this where objects are randomized, drawn, and tested for collision


What I have tried:

I have tried adding a & to the rect0 in parenthesis
rect[0].setRandom(rect0);

but this only made the code use the pointer function instead of the reference function.
Posted
Updated 5-Nov-16 4:36am
Comments
Richard MacCutchan 5-Nov-16 5:15am    
You need to point us to the actual code that is failing, and explain what is supposed to happen.

First of all, in the instruction it is said that the function working with pointers should be called setRandomByPointer. By doing so, it might help you know which function is called.

But as mentioned in solution 1, it would be possible to have both functions having the same name and the compiler would be able to figure out which one to call.

Then it seems that you have not properly done some steps or not doing them in order... It also seems to depends on a previous homework. And some stuff seems to come from nowhere...

As a side note, normally a non static member function would operate on its own rectangle.

And by the way, if we compare your 2 functions, we can see that the first one operate on the argument (r):
C++
r.min.x = pos_x - width;
...

while the second one operate on the object itself (this) :
C++
this->min.x = posX - widthPoint;
...


In your homework, you need to work on the argument as specified in the instruction. In real world, no one would do that as it is the most confusing way to do that (you call the function on one instance but update the one passed in argument).
 
Share this answer
 
You must learn two important concepts of the c++ language: overloading and class concept.

It means that this is always the object on which the method is called. Here is some tutorial.

If you overload an function what means that function have the same name but different call parameters the compiler desides on the parameter which it uses. It makes code unclear and tricky, so sometimes it is better to rename one function. Some tutorial is here.

I do overloading only with a different count of parameters like:
C++
int DoStuff(char* p);
int DoStuff(char* p, int count);
 
Share this answer
 
Comments
Philippe Mori 5-Nov-16 10:17am    
According to the assignment, the function working with a pointer is expected to be called setRandomByPointer. Thus, although you are right that understanding overloading is important, it is not necessary for that project.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900