• Log in or sign up for an account here: https://www.sythe.org/login

GridWorld Help (Exam Pre-Test)

Glyder

Forum Addict
Joined
Sep 6, 2009
Sythe Gold
0
Messages
527
Location
Georgia
For my Pre-Test in my CPU Prog class, we had to make a ZigZagBug Class.

I used a line from a person that I know in the class, but for a comment with
that line, I don't know how to explain it.

Here is the code.

Code:
import info.gridworld.actor.Bug;

public class ZigZagBug extends Bug {
    int counter = 1;
    
    public ZigZagBug(){
        turn();
    }
    
    public void act(){
        if(canMove()){
            //This gets the adjacent location, of the direction that the bug is facing.
            //IE - Faces Right-North, the next location is the location directly in front of what the bug faces.
            moveTo(getLocation().getAdjacentLocation(getDirection()));
            setDirection(getDirection() + 90 + ((counter++)%2 * 180));
        }else{
            //If the bug cannot move, it turns 180 degrees and then moves again.
            setDirection(getDirection() + 180);
        }
    }
}

Now, what is..

This for?
Code:
int counter = 1;

And this for?
Code:
setDirection(getDirection() + 90 + ((counter++)%2 * 180));
 
Based on what the name suggests a "ZigZagBug" would be moving in a ZigZag shape.

If you are using a counter and using the %2 (mod or modulo) operator it would basically give you whether the number was odd or even.

So the counter determines the "step" of the zigzag that it is at - 0 being even 1 being odd.

The setDirection uses the counter to draw this change in direction - basically saying in pseudo code - use the current direction, add 90 degrees, then add another 0 or 180 degrees based on which step it is currently at.


As Quadro states - it would be necessary to see the full implementation of the class to be sure, but this sounds about right. good luck - take a look at my java help link (in sig) if you need more help.
 
duelarena.gg
Back
Top