Random Movement

I need to make the bugs and ants move randomly throughout the grid. Will this allow for them to move randomly? Or am I simplifying the problem. Here is the code.

1
2

   }
Last edited on
So are you trying to generate random values? And what is the value of WORLDSIZE?
Looking at the snippet you provided, it looks like there is a 50% chance a bug or ant will move per call to World::one_step(). Now, that's given that your grid::move() function actually moves the bugs.
Well I need it to traverse the whole grid and have all organisms on the grid move for every time one_step is called. And move() function does work because I have a program that allows all the bugs to move, and then all the ants to move in one stimulation (i.e. calling one_step). Now I'm trying to edit so they move randomly in one stimulation
I don't see a direct problem with what you've posted. I'm assuming that you have called srand() once at the beginning of your program.
Does the move() member function reposition the critter to a random nearby open field?
I think this could certainly use some polishing and design changes, to be honest.

*EDIT* If you need every organism to move every time one_step() is called, then what's the deal with lines 16, 17, 18 and 30?
Last edited on
Yes, the move() function moves the critter to a random nearby field - either up, down, left, or right.

And with your edit, are you saying I wouldn't even need the random? I could just check to see if the spot isn't null and if it's a bug or ant, and move it if it is?
Last edited on
Basically, if you want every bug and ant to move, you don't need the random stuff. The way you have it set up now, every time the function is called, each bug and ant has a 50% chance to move.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
	 for(int j=0; j<WORLDSIZE; j++) {
		  //check to see if type doodlebug
		  if((grid[i][j]!=NULL) && (grid[i][j]->get_type()==DOODLEBUG)) {
			  //check to see if it hasn't moved
			  if(grid[i][j]->moved==false) {
				  //set moved to true
				  grid[i][j]->moved=true;
				  //call move function
				  grid[i][j]->move();
			  }
		  }
		   //check to see if type ant
		  if((grid[i][j]!=NULL) && (grid[i][j]->get_type()==ANT)) {
			  //check to see if it hasn't moved
			  if(grid[i][j]->moved==false) {
				  //set moved to true
				  grid[i][j]->moved=true;
				  //call move function
				  grid[i][j]->move();
			  }
		  }
	 }


Try that.
Last edited on
Okay, that makes sense. The way you just laid it out is so that if it runs across a bug or runs across an ant, its going to move? Correct?
Correct, it's the same exact way you had it before, except now, every time your code encounters a bug or ant it will move, before there was only a 50% chance the bug or ant the code encountered would move.
Thank you for your help!
Topic archived. No new replies allowed.