Code not working

Okay. So I am experimenting with some things that I have learned and wanted to make one of my cubes on the screen go from left to right until it reaches x 600, and when it reaches x 600 I want it to go back to x 100, one pixel at a time. I've tried to get it to work through several different methods and different code but when the cube reaches x 600 it always flickers, like it is trying to go to the left but it goes to the right at the same time. I have tried doing it with if statements as well, but from my point of view I don't see why the code below shouldn't work. Thank you!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  int Game::Automatic(int x)
{
	bool isActive = true;

	while (x < 600 && isActive)
	{
		x++;
		return x;
	}

	isActive = false;
	while (x > 100 && !isActive)
	{
		x--;
		return x;
	}
	return x;
}
Last edited on
Think about you snippet a bit. What happens when it reaches 600? It keeps doing 600->599->600->599...

What if you give your cube direction instead of your current code and define bounds so when it reaches to end of current direction and then swap it?
Lines 3-9: isActive is true and does not change. Thus it has no effect on the condition.

IF the x<600, THEN the function ends during first iteration of the loop by returning x+1.
In other words, there is no reason to have a loop at all, is there?


Lines 11-16: Again, !false is always true and loop is not beneficial.


Line 17 ... you never get here. The x is always less than 600 or more than 100.


On the other hand, you do know that x<=600.
If it is <600, then it moves right, and if it is exactly 600, then it moves left.
If it did move left, then it is <600 again on the next round and must go right.

It is not enough to remember where the cube is, you have to keep the direction too.
How about void Game::Automatic( std::pair<int,bool> & x )
Thanks for your responses.
But I do not understand why it goes 600->599->600->599 as the second loop should be looping until it reaches 100 and then the first loop starts again?
Last edited on
if you call it with 600, it will decrement and return.
if you call it with 599, it will increment and return.

isactive is effectively doing nothing as you set it to a hard-coded value, then check that exact value to make sure it was the same thing you set it to. It does not do anything at all.

because of the return statements in the loop, with no conditions on them, it exits right away!

return() tells the c++ code to exit the current routine and assign the value given into the name of the function. Everything in the function stops executing, the loop, everything. Its done! If you want it to sit in those loops a while, the return statements need to go away.
Last edited on
Topic archived. No new replies allowed.