Super turtles
Mouse Clicks
  Ex 1:
Remote Control
  Ex 2:
Enhancement
  Ex 3:
How to submit?
Policies
Back to labs

Lab 7 - Turtle-land, a magical turtle world created by you!

Welcome back from Spring break! In this lab you are going to build on your Java and Eclipse knowledge from Lab 3 and the Turtles package in creating event-based programs. First, we shall add mouse event handlers in the Java programs to catch couple of mouse events. Secondly, we'll write a program to change a turtle's name, followed by enchancement of our world where you would add a button and a picture of your liking, whether from your spring break or somewhere else, and fill out the world with many turtles.

Start Eclipse and create a new project called 'CS53-Spring10' (if you have not done it already for Lab 3). Next, create a new package and name it 'lab7_FirstName_LastName'. Then, for each exercise create a new class file and name it exercise1.java, exercise2.java, and exercise3.java respectively for each exercise and the supportive files.

The World class in the turtle's package has the mechanisms for keeping track of the turtles and displaying them on the screen. We are going to start working on GUI (Graphical User Interface) programs that would display our worlds and turtles on the screen.



User events

Most of the computer programs deal with some kind of user-events. We have worked on many types of events throughout the midterm project in Alice. This time, you will learn how to capture events in Java.

Rember the difference between user-events and program-events? Well, in this exercise, we are going to do just that. We will divide the user events into mouse events and keyboard events.

For starters, take a look at the World class and the Turtle class in the basic turtles package. Examine the code and understand what it does.

Exercise 1

User-story: Your turtle has wondered around the world and came across a hungry bear. Your task is to help your turtle change colors to save its life by getting the bear confused.

What you need to do is create a new turtle class that can change colors.

This means that you would need to create a new CamouflageTurtle class that inherits everything from the Turtle class by extending it. Your class declaration should look something like this:

public class CamouflageTurtle extends Turtle implements MouseListener {

By making your new turtle class implement MouseListener, automatically, it will ask you to add the unimplemented methods, i.e. Eclipse will add the mouse listener methods that you will need. We will use the MouseClicked method this time and here is the code for randomly changing colors:

public void mouseClicked(MouseEvent arg0) {
	Color newColor = new Color((int)(Math.random()*255),
				(int)(Math.random()*255),
				(int)(Math.random()*255),
				(int)(Math.random()*255));
	this.setColor(newColor);
	this.myWorld.repaint();
}

It is time to test our program. Create the main file Exercise1.java in which you will create a new world and a new turtle. Here is my example:

package lab7_Aleksandar_Stefanovski;

import basicTurtlePackage.World;

public class Example {

	public static void main(String[] args) {

		// Create our world
		World jungle = new World("Jungle world");
		
		// Create a new turtle and add it to our world
		CamouflageTurtle turtle = new CamouflageTurtle(jungle);
	}
}

Great, the program works (sort of). The turtle shows up in the world window, but it is not changing colors when I click on it. What may be wrong?

Did you forget to create a constructor method for your CamouflageTurtle in which you register your event handler with the world?

Here is my constructor method:

public CamouflageTurtle(World newWorld) {
	super(newWorld);
	newWorld.addMouseListener(this);
}

Alright, now it is changing colors when I click on the turtle, and when I click outside of it (anywhere in the world).

Fixing this "little" bug will be a piece of cake. All we have to do is think of our requirements: When we click on the turtle, it changes color, otherwise it does nothing. Well, we are changing the turtle's color only in our mouse clicked event handler method. Would it be it? Let go back in it and check if the event's coordinates are within the turtle's area or outside of it. Here is my modified event handler method:

public void mouseClicked(MouseEvent e) {
	// get the X,Y coordinate where the event happened
	int eX = e.getX();
	int eY = e.getY();
	// System.out.println("User clicked on the mouse at: " + eX + ","+ eY);
	// check if this is the turtle that was clicked on
	// note that the turtle's x,y coordinates are the center of the turtle
	if (eX > this.x - this.size/2 && eX < this.x + this.size/2) {
		if (eY > this.y - this.size/2 && eY < this.y + this.size/2) {
			//System.out.println("Clicked on the turtle!");
			changeColor();
		}
	}
}

Of course, I had also created a changeColor method which looks like this:

public void changeColor() {
	Color newColor = new Color((int)(Math.random()*255),
			(int)(Math.random()*255),
			(int)(Math.random()*255),
			(int)(Math.random()*255));
	this.setColor(newColor);
	this.myWorld.repaint();
}

If you are interested to learn about the different colors and how they are created take a look at the API for the Java Color.

For this exercise save the Exercise1.java and the CamouflageTurtle.java.

So far we have not only added event handling to our program, but we have also implemented the inheritance concept. We created a sub-class CamouflageTurtle of our parent Turtle class. All objects from the sub-class can do everything that objects from the parent class can do. Remember the SingingTurtle or the EducatedTurtle from the class examples? Well, that is exactly what we did with this exercise. We extended the existing class and create a new enhanced class that met our needs.





Remote Control

Now that we can click on our turtle and it will react by randomly changing its color, we would like to be able to remotely steer the turtle by pressing on the arrow keys. We are going to learn how to use key listeners.

Expand your previous CamouflageTurtle and create a new sub-class called RCTurtle (RC stands for Remove Control). Also, create a new Exercise2.java similar to Exercise1.java where you create a RCTurtle instead of a CamouflageTurtle, which you will use to run and test your program. Here is my RCTurtle constructor:

public RCTurtle(World newWorld) {
	super(newWorld);
	newWorld.addKeyListener(this);
}
As in Exercise1, Eclipse will automatically add the event handler methods for you. They are: KeyPressed, KeyReleased, and KeyTyped. I only used KeyPressed for my example:
public void keyPressed(KeyEvent k) {
	int dist = 20;		// move in increments of 20
	int code = k.getKeyCode();
	if(code == 40){		// arrow key down
		this.setHeading(180);
		this.forward(dist);	
	}
	else if(code == 38){	// arrow key up
		this.setHeading(0);
		this.forward(dist);	
	}
	else if(code == 37){ 	// arrow key left
		this.setHeading(270);
		this.forward(dist);
	}
	else if(code == 39){	// arrow key right
		this.setHeading(90);
		this.forward(dist);	
	}
	else {
		JOptionPane.showMessageDialog(null,"Invaild key! You can only press arrow keys.");
	}
}


Exercise 2

Your turn: refine and improve how your turtle moves around the world and add key "short-cuts" for the following turtle's methods:

  • P: penUp/penDown,
  • V: visible/invisible,
  • C: quick color change to green, red, blue, or any other color of your choice, but no more than five colors.




Enhancement

You have created the ultimate turtle. It is time to take your pet turtle with you on your world tour.

Exercise 3

Extend the current world by creating a new world whose background is an image/scenery of your liking from your spring break vacation. You may want to reuse the loadImage method from your Lab 3 solutions.








How to submit your homework

Create a folder on your computer and name it 'CS053-Spring10' (if you do not have it already). Create another folder and name it 'lab7'. In the newly created 'Lab7' folder copy your solutions to the exercises: Exercise1.java, Exercise2.java, Exercise3.java, and so on...

Next, go back up to your folder 'CS053-Spring10', right click on your folder 'lab7' and compress it either in a or file.

Your newly compressed file should be named:

  • FirstName_LastName_Lab_7.zip or
  • FirstName_LastName_Lab_7.rar

After you have compressed your homework, then proceed to submit it via Blackboard.

Got problems? If you have any problems make sure you clear them with your lab instructor because if you do not follow these requirements for submission your lab homework submissions will not be accepted and you will get zero points.