This site requires JavaScript, please enable it in your browser!
Greenfoot back
JamesHughes244
JamesHughes244 wrote ...

2016/6/12

Edit the IceBurgs so that they move and turn randomly.

JamesHughes244 JamesHughes244

2016/6/12

#
Hey, I have a GCSE computer science exam coming up soon an I am doing a past paper. The paper says 'edit the iceburgs so that they turn and move randomly', but the world is a grid like the wombats scenario. How would I edit an object to turn and move randomly in an 8 by 8 grid world.
danpost danpost

2016/6/12

#
JamesHughes244 wrote...
How would I edit an object to turn and move randomly in an 8 by 8 grid world.
First, I would add fields for a pre-determined destination grid-square:
private int targetX, targetY;
The initial value of these fields should be the coordinate values of the location the actor was placed into the world at. The 'addedToWorld' method can be used for this (so you can use 'getX' and 'getY' to set the value of the fields with). Then, to make things a bit easier, we will alternate between moving horizontally and moving vertically. This will mean only one turn is necessary when changing target locations. Now, to set a new target location, we need a coordinate value between 0 and 7 that is not the current coordinate value of the actor (we want to choose one of the other 7 grid-squares along the current row or column to be the new target coordinate). You can point out each of the 7 squares by starting at the current location and counting the squares sequentially (in either direction; with wrapping), By doing so, you can relate that to what is needed to compute a new coordinate value along that axis. If 'targetX' is currently equal to the x-coordinate value of the actor, then:
targetX = (targetX+1+Greenfoot.getRandomNumber(7))%8;
will set 'targetX' to a different equally random value that is a valid target coordinate. Then depending on whether the new value is greater or smaller than the current coordinate value of the actor, you can turn appropriately.
You need to login to post a reply.