Blog

Great advice from '09/'10 AP CS!

Ms. Martin : June 9, 2010 5:31 pm : 2009 AP CS A

The Five Tenets of Programming
1. If you feel like you’re falling behind, ask for help, if not from Ms. Martin, then from other students.  You’ll save yourself hours of frustration.
2. Don’t be afraid to try your own thing if you get the chance, even if you think it’s beyond your level.  You’ll learn faster if you’re interested in the project.
3. Temp variables are awesome.  So are ArrayLists.
4. Don’t let the sometimes snooty programming club people argue with you — by the end of the year, you’ll probably know more.
5. And NEVER tell yourself you’re bad at coding.  EVER.  This just leads to failure.  See tenet 1.

Don’t trust the GridWorld.  Never code a method unless necessary.

BE PATIENT! It’s frustrating, yes, but when you think about it calmly and figure out what needs to be done and what you need to do that, end results will be exhilarating!  Side story: I refused, eventually, to help my friend on his work for another programming class because instead of thinking everything out, he gets angry and rants about how much CS sucks.  Honestly, being patient and drawing things out will be more helpful than sitting around and crying.

PAY ATTENTION DURING GRIDWORLD INTRO.  If you don’t you’ll be mighty confused.

Take loads of notes, pay attention and GO TO GOOGLE.

I didn’t sign up for AP CS, so I was surprised when it became my favorite class and Ms. Martin my favorite teacher.  Appreciate that your teacher is passionate and knowledgeable about her subject.  Don’t be afraid to ask for help, don’t give up when you get frustrated, always make your code as pretty as possible, and celebrate when you complete a task.

Use Ms. Martin — she’s a great resource.  Don’t be afraid to look at what other coders have done before you.  Stay ahead of deadlines if you can.  Enjoy yourself, work hard, this class can be a blast.

Learn to speak in code.  It helps on history papers when you write an essay in Java.  Also become a fan of curly braces and other lingo that can make or break your program.  Also love Ms. Martin.  She’s an awesome teacher and is driving herself broke by teaching.

Use Eclipse and come in after school.  The teacher actually teaches and helps — whoa!


for(int days = 1; days <=  365; days++) {
    haveFun();
}

Stay on top of things and don’t get behind!  Stay after school to get extra help.  Work with others and form connections for help later in the class.

Work hard, listen to Ms. Martin.  This IS the best class at Garfield, so be sure to make the most of it.

Do all work early and finish as soon as possible.  Ask Ms. Martin for help when needed and use patience.

AP computer science is one of the funnest and most interesting classes I have ever taken.  Remember to always compile your code so that it saves and so that you can fix your errors as you go rather than having a giant amount of errors by the time you finish.  Participate in programming competitions — they’re fun and you learn a lot by working with others.

GOOD LUCK!  Don’t get frustrated because the concepts become easier as a person codes more and learns more.  Also, take advantage of class time!

Be good at pinball.  Be committed if you are going to take this class and study hard and often.  Make sure to stay on top of your projects and don’t get behind.

Don’t jump in second semester!  Or I guess you can if you really wanna!

Pay attention in class, don’t let yourself get behind or it will suck.  Hard work doesn’t guarantee success so be patient.  Ms. Martin is hella scary so don’t ask her for anything. ;)

Don’t slack off! Listen to the lecture because… IT ACTUALLY HELPS!! When in doubt, ask for help or look back on slides.

Eclipse is your best friend.  Neglect your other classes because this one is better.

It is a fascinating logic-based environment with simply the best and most competent teacher at Garfield.

1 Comment »

Guest Speaker: Ben Slivka

Ms. Martin : May 25, 2010 5:21 pm : 2009 AP CS A, 2010 Spring Exploring CS, Programming Club

We were lucky to have Ben Slivka join us in Exploring Computer Science and AP Computer Science.  Mr. Slivka is a computer scientist who worked at Microsoft from 1985 to 1999 and was involved in several exciting projects there, including starting Internet Explorer.  Since, he has worked at Amazon, started and recently sold Dreambox Learning, and has worked with several non-profits.

Mr. Slivka shared his ideas on the current state of computing technology as well as some of what is to come.  I took some notes as students asked questions and have done my best to recreate some of what was discussed.

Which of the companies you worked in was the most fun?
Mr. Slivka told us that he had the most fun at Microsoft.  Starting Internet Explorer was a creative and innovative endeavor involving great people.  It was a lot of work, too — he told us that 80-100 hour weeks were not uncommon for him!  Mr. Slivka first saw a web browser in 1994 (Mosaic) and knew that it was an exciting development.  In fact, in 1995, he wrote an internal memo on how important the web would become titled “The Web is the Next Platform.”  At the time, there were only a few thousand websites as opposed to today’s tens of millions.

Mr. Slivka worked with Internet Explorer through its third release and grew the team from 7 to 69 engineers.  He shared with us that during his time at Microsoft, a person in the USA was more likely to become a Microsoft millionaire than an NBA player!

Why did you leave Microsoft?
Young Microsoft took lots of risks to become successful but as it has grown, it has become more concerned with protecting its primary products (Windows and Office) rather than innovating.  Around 1999, Mr. Slivka wanted to pursue Internet-related innovations but that was not the direction the company was taking.  The book Breaking Windows covers the time when he was leaving Microsoft and the prologue is online.

Is it scary to talk to company founders like Bill Gates (Microsoft) or Jeff Bezos (Amazon)?
No!  According to Mr. Slivka, companies are a lot less hierarchical now than they were maybe 50 years ago so it’s natural for CEOs to have relatively frequent contact with their employees.  When he was at Microsoft, it was not unusual for him to trade e-mails and have face-to-face meetings with Bill Gates.

What is one of the most exciting ideas in computer science?
Mr. Slivka told us about computational complexity, the study of the difficulty of programming tasks.

Was it difficult to see OS/2 fail after 5 and a half years of work?
Only doing things that will succeed is boring, says Mr. Slivka!  There is a lot more to learn from mistakes than from successes.  It was difficult to see such a big time and energy investment be lost but going through the process of creating the product was valuable.  OS/2 was a joint venture between Microsoft and IBM and their goals were different.

What was the hardest project you were involved in?
The human factor in projects is often the most difficult.  In 1998, Mr. Slivka was asked to take part in designing a new interface for Windows.  He and two others were in charge of the project and there was conflict among the leadership which made it difficult.

What do you think of the iPad?
It’s somewhere between a phone and a laptop and it’s hard to know where it fits in.  It still requires a PC since when turned on it wants to be synced to iTunes.  The device is too heavy but it does have a gorgeous screen.  The brushed aluminum is beautiful but very slippery.  Mr. Slivka sees it mostly as an expensive toy.  He reminded us that computing technology is like grocery store produce in that it has a limited shelf life.  This first version of the iPad is not likely to be popular for long.  The lack of multitasking and virtual memory are real limitations.

Can you comment on the Apple vs. Adobe war?
Apple is playing defense right now by trying to protect their control over all aspects of their products.  The Flash battle is not about security or stability, it’s about market control and — ultimately — dollars.

Which web browser do you use?
IE7 was too slow and Mr. Slivka switched to Firefox.  He does not use Bing.

What do you think about cloud computing?
Offline computing still has a role since there is no pervasive connectivity yet.  If cloud computing means data is never lost, actions can be infinitely undone, groups can collaborate well, no need to worry about installations of software then it’s a great idea but in practice, there is no great implementation yet.  Google Docs doesn’t work well but it’s definitely possible to create a fully-functioning word editor in the cloud some day.

What are the main privacy issues on the Internet?
Mr. Slivka shared his policy: he doesn’t put anything up online that he wouldn’t be ok with being on the New York Times front page.  People should be thoughtful about what they share and market forces will work to punish companies that don’t respect privacy well enough.  In his opinion, the government is getting involved because it’s currently on people’s mind and will help politicians win elections.

What will Google look like in the next few years?
Google is now suffering from the same problem as Microsoft: Microsoft has revenue from Windows and Office and wants to protect those while Google has Search and AdWords and wants to protect those revenue streams.  Google’s challenge will be innovating beyond search and ads while making sure they can maintain their dominance as products like Bing get significant investment.  Their current strategy is to be everywhere (Android, Chrome, etc) and make Google the preferred platform so they can protect their search and ad dominance.

Leave a response »

Final Project Ideas

Ms. Martin : May 16, 2010 5:32 pm : 2009 AP CS A

You will spend the remaining month of AP Computer Science creating a project of your own design.  I realize that there’s a lot of pressure involved in coming up with a good project idea so I’m providing starting points below.  I’ve organized the ideas by category.  Note that the research-only (no coding) options can get you up to a 90% (if you do a stellar job) — after all, this is a programming class and I want to encourage you to choose an option that will result in a software product.  That being said, this could be a great option for those of you who have found that programming is not quite for you and need a grade boost.

You are welcome to work in groups of up to three.  I reserve the right to veto groups.

Grading

Your grade will depend on:

- Remaining on task — very little off-topic chitchat, demonstration of good problem solving skills, etc.

- The project itself (paper, software, series of exercises demonstrating new skill, etc)

- A ~5min presentation showing off what you’ve done

- A 2-3 page writeup with the following sections:

• Project goal: What is the general problem addressed by your project?  Are you learning a new skill?  Are you designing a game for a particular niche?
• Motivation: Why is what you’re doing valuable to you or others?
• Design and architecture: Describe how the parts of your system fit together. What software tools did you choose to use and why?  What classes are you implementing and why?
• Implementation challenges: What were the tricky problems you had to overcome, and how did you solve them?
• Conclusion: How well did you achieve your goals?  Were you on task for the majority of the allotted time?  Are you proud of your product?

Some ideas I’ve thought of, in no particular order, and in no way meant to restrict your options.

Games in Java

Games are a great source of interesting computer science problems.

- Focus on AI: write a command-line driven game for a popular board game such as Checkers or Othello.  You could even start with Tic-Tac-Toe.  Other games to write interesting AI for can be found here.

- Focus on visuals: Learn to use Swing for graphics.  Here is a pretty good tutorial on Java game programming.

- Set game: I have good starter code for getting you going with a graphical version of the game.

- Gridworld game: Check out ideas and starter code at http://www.themrmiller.com/ap/projects/ap11.shtml

Animation or visualization in Processing.js

- Use information from the New York Times API and display it in some interesting way.  You’ll need to figure out some standard Javascript and JSON which can be mixed with the Processing.js Java-like language.

Game in Processing.js

- Side scroller: for inspiration, check out Pianoman, complete with source.

- Strategy game: for inspiration, check out Sheep Herding, complete with source or the Plumber Game (in Flash, but an interesting idea).

Learn a new skill

Now that you know the basics of Java, you’re ready to expand your CS knowledge very rapidly.

- Learn Python: Python is a modern, object-oriented scripting language.  It’s go lots of great libraries.  Teach yourself some Python and implement a relatively complex project in it — something like Baby Names.

- Learn JavaScript: JavaScript is a client-side web scripting language interpreted by browsers.  It allows for all kinds of cool interactivity in websites.  The patterns in JavaScript are different than those in Java so it will take some getting used to.  Learn the basics and then implement something like a hangman game or fifteen puzzle game that runs in browser.

- Learn Swing: get to know Java’s graphics library.

Research paper

Note that the highest possible grade you can get on this is 90% if you do an amazing job.

Research an area of computing that interests you and write a paper and presentation about it.  You should use several trusted sources and use sources like Wikipedia just as starting points.  I would expect at least 5 pages of quality text accompanied by an engaging presentation.  Possible topics:

- Privacy.  For example, you could explore the history of the Facebook privacy settings and write a summary of how they currently stand and why they’re so controversial.  Alternately, you could look into the US’ privacy laws and how they’re enforced.

- Artificial Intelligence.  What is?  What breakthroughs have there been?  What are useful applications?  Alternately, you could focus on one AI researcher or the evolution of a single project such as the ASIMO robot.

- Future of wireless technologies.  WIMAX, 4G, etc.  What impact they’ll have on businesses, why they’re not implemented yet, who will control them, etc.

- Open source software.  What is it?  What are examples of open source projects?  What open source licenses exist?  What controversies are there surrounding open source software?

Leave a response »

Processing.js

Ms. Martin : May 13, 2010 9:21 pm : 2009 AP CS A

You will need to download this zip file and extract its contents to a convenient folder.  We will be working with Processing.js, which uses a language very similar to Java that later gets converted to JavaScript.  The advantages here are that you’ll be working with a familiar language and be able to create browser-ready projects.  Today I just want you playing around with a provided example (gogo.html in the zip file) and hopefully looking at the API.  Processing.js is an extremely powerful framework — check out a Tower Defense game to convince yourself of this.  Here’s another cool example which visualizes tweets about JavaScript.

Today can be a fairly free-form exploration day, but if you’re unable to stay on task that way, here’s what I recommend you do to tweak gogo.html and get familiar with Processing.js:

- Change the canvas background to green when the animation starts.
- Make the circle twice as big
- Change the frame rate and see what happens
- Change the delay and see what happens
- Make the animation twice as big (800 x 800)
- Make the white ring around the circle flash green when the circle is clicked
- Make the circle follow your cursor as you click (like in this example)

More complex things you may want to try:

- Write a Snake game!

Leave a response »

Networks

Ms. Martin : May 10, 2010 5:58 pm : 2009 AP CS A

Find out what your IP address is.  Note that any service with access to your IP address also knows where you are.

Use a ping tool to find out how long it takes to get to a particular server.  Try google, garfieldcs.com?  Note that this tool sends the ping from the network-tools.com server, NOT from your machine.  Compare with a ping from the command line.

Use a visual traceroute tool to find out the physical path information takes to get to you from a particular website.  Interesting searches might include bbc.co.uk gicp.org.gh gcaa.com.gh (the last two sites are Ghanaian sites.  Where are they hosted?  Why?)

Do a whois lookup to find out who, if anyone, owns a particular address.  Try your name?

Take a look at what information websites have about you — they definitely know where you are and may be able to infer your age, gender, etc.

1 Comment »

Critter notes

Ms. Martin : April 5, 2010 7:07 am : 2009 AP CS A

Adapted from Cay Horstmann — thanks!

Critters are included in GridWorld to emphasize design. The act method calls five methods, and subclasses override some or all of them to achieve some desired behavior. (For those of you interested in digging deeper into programming and software engineering, the act method is an example of the “template method” design pattern. Design patterns are a powerful way of expressing common best-practices about code structure. Google it!)

When to use Critter

Not every actor can or should be represented as a
Critter. In the context of GridWorld, a Critter is not a warm and fuzzy
creature, but an actor that first processes actors and then makes a move. Trying to make Actors that don’t follow this pattern into Critters will generally result in overly-complicated logic.

Critter rules

Here are a few simple rules to remember when working with Critters (these don’t apply to bugs or other Actors!). They will be discussed in a little more detail below.

  • Don’t override act
  • A critter can change its state only in processActors or
    makeMove
  • A critter can change the state of other actors in processActors

Critter methods

Each of the five methods called from act has postconditions that restrict what it can do. The following table shows the postconditions as they are stated in the GridWorld documentation.

Here, the state of an actor includes

  • the location
  • the direction
  • the contents of any other instance variables
getActors The state of all actors is unchanged.
processActors (1) The state of all actors in the grid other than this critter and
the elements of actors is unchanged. (2) The location of
this critter is unchanged.
getMoveLocations The state of all actors is unchanged.
selectMoveLocation (1) The returned location is an element of locs (the parameter of type ArrayList<Location>), this
critter’s current location, or null. (2) The state of
all actors is unchanged.
makeMove (1) getLocation() == loc. (2) The state of all actors
other than those at the old and new locations is unchanged.

If a critter wants to change its own state, it can only do so in processActors and makeMove. If it wants to change
its location (or remove itself), it can only do so in makeMove (Removing an actor changes its state: its location becomes null).

If a critter wants to change the state of another critter, it can only do so in processActors. (There is a teensy exception: makeMove removes the critter at the target location, and it may add a new critter to the old location.)

Note that getActors, getMoveLocations, and selectMoveLocation can’t change the state of any actor.

Also note that processActors can only mutate actors that were handed to it, and selectMoveLocations can only select from the locations that were handed to it. The makeMove method has even less choice—it must move to the location given in the
parameter.

These conditions significantly restrict what a critter can do, and how it can do it. When you design a particular critter, you need to distribute
responsibilities among the five methods that are called by act.

Leave a response »

Ant Farm Gridworld Project

Ms. Martin : April 5, 2010 6:39 am : 2009 AP CS A

Thanks to Robert Glen Martin for the project idea and writeup. Any errors are my own!

You will need to turn in whatever you have by 11:30pm on Monday April 11th. No late work will be accepted — not turning anything in will result in a 0.

Introduction

This assignment is designed to get you thinking about the design of larger systems, to get a small introduction to artificial intelligence and to deepen your familiarity with GridWorld. Hopefully you’ll find it pretty cool — by the end, your ants should be acting in a coordinated fashion to collect food and bring it back to their queen. I think it’s a great illustration of the power of object-oriented design.

This document does a lot more “hand holding” than the previous assignment descriptions have and I’m giving you a lot more starter code. In a way, that’s more of a realistic programming situation than those we’ve experienced so far — many more people work on modifying and adapting systems than start them from scratch! I also think this is a pretty good way of illustrating some core concepts without having you spin your wheels too much. As you work through this project, you will complete an interface and both concrete and abstract classes. Your solution will demonstrate inheritance, encapsulation, and polymorphism.

Begin by downloading AntFarmStudent, a zip file containing all the starter code. Make sure you take a look at each class briefly to get a big-picture view of what the system should be doing and how the various pieces are connected together.

Overview

The project utilizes four new types of objects (see Figure 1), two kinds of food (ACookie and BCake) and two kinds of ants (CWorkerAnt and DQueenAnt). Initially, the worker ants walk around in search of food. When they find food, they take a bite. Ants with food turn red. Then the worker ants go in search of a queen ant to give food. Once they give their food to a queen, they turn black and go back to get more food.

Figure 1 – Ant Farm (Initial Sate) – Worker ants hunt for food.

Food and queens remain stationary. Worker ants remember the locations of the food and
queen. Additionally, they share those locations with other worker ants they meet.

When the Ant Farm program starts, the worker ants are spread around the grid in random
locations. Initially, they are disorganized as they search for food. As the worker
ants start to find food and the queen, they get more organized (see Figure 2 below).
After all the ants learn the locations, they exhibit an emergent behavior that is
very organized (see Figure 3 below).

Figure 2 – Intermediate State – worker ants start learning locations of food & queen.
Figure 3 – Final State – worker ants know locations of food & queen.

Program Organization

Figure 4 shows the organization of the Ant Farm classes and interface.

Figure 4 – Ant Farm Classes

Recall that GridWorld has a “built-in” Actor class for objects that “live” in the grid. Actors that have minimal interaction with other objects in the grid normally inherit from Actor. This is appropriate for QueenAnt and Food. Cake and Cookie inherit indirectly from Actor through their immediate parent, the abstract class Food.

Also recall that Critter is a GridWorld type derived from Actor. Critters have a particular pattern for their act useful for interacting with other Actors. WorkerAnts need to “communicate” with the QueenAnt, Cake, Cookie, and other WorkerAnt objects so inheriting from Critter is appropriate for them.

Ant Farm also requires a Processable interface. This interface has a single process method that is the key to communication between worker ants and the other Actors. By implementing a common interface, QueenAnt, Cake, Cookie, and WorkerAnt objects will be able to be used interchangeably when they need to communicate.

Starter Code

AntFarmRunner (the application) is complete and requires no changes. The needed imports, class headings, method headings, block comments, and image (gif) files are provided for the remaining classes. Place the gif files in the same directory as your .class files are stored. The interface heading and comments are provided for Processable.

Compiling early and often is a good programming practice. It helps identify errors when they are easiest to fix. Compile and execute the project. You should see all the Actors on the screen. All the Actors are blue at this point. Why? (Hint: think about which parent classes are involved)

Note: Clicking the Step or Run button at this point will cause a NullPointerException since many of the method bodies just return null for the time being. This is another great design tactic: writing headers for all methods before implementation really helps catch problems with a project’s design early on. Of course, a header that includes a return type will keep the method from compiling unless something really is returned. It’s typical to return “” as a placeholder for a method that must return a String or 0 for int or double methods. The corresponding value for objects is null. Unsurprisingly this practice is likely to cause run-time NullPointerExceptions. At this point, that’s totally fine — we’re just interested in making sure there are no compile-time errors.

Processable Interface

The Processable interface is a key component of the Ant Farm design and a great opportunity for you to better understand the value of interfaces as well as some of the details of polymorphism. Examine the Processable.java file. You should see that the interface contains a single method: process. The process method is used to communicate with the WorkerAnt object passed in as a parameter. This allows for communication between your Ant Farm’s objects. Since QueenAnt, Food, and WorkerAnt all implement the Processable interface, they must all implement the process method. The beauty of this is that all classes which implement the Processable interface can be initialized as or cast into Processable objects. Here are examples of how this works:

	WorkerAnt andy = new WorkerAnt();
	Processable c = new Cake();
	c.process(andy); // no problem since Processable requires process method
	c.act(); // error because the reference type (Processable) does not implement an act method.
	// It doesn't matter that Cake actually implements act!  The variable c can only use methods declared in the Processable interface.

	((Processable)andy).process(new WorkerAnt()); // an example of casting to Processable 

	ArrayList l = new ArrayList();
	l.add(new Cake());
	l.add(new WorkerAnt());
	l.add(new QueenAnt());
	for(Processable p : l) {
		p.process(andy);
	}

Notice that the process method can be called polymorphically on any object which implements Processable. Sweet!!

As described, the Processable interface should contain a single void process method which takes one parameter of type WorkerAnt. Add the abstract process method in the Processable interface.

Compile the project and correct any errors.

You will later implement the process method in each class which implements the interface. The individual process methods in each class will do the following (repeated later):

  • QueenAnt
    • Get food from the worker ant.
    • Give the queen’s location to the worker ant.
  • Food
    • Give food to the worker ant.
    • Give the food’s location to the worker ant.
  • WorkerAnt
    • Give the saved food location to the other worker ant.
    • Give the saved queen location to the other worker ant.

QueenAnt Class

Figure 5 shows the QueenAnt class. Queen ants are the simplest of the new Ant Farm objects.

Figure 5 QueenAnt Class.

Start updating QueenAnt by adding the new foodQuantity instance field. It is used to contain the total amount of food that has been given to the queen by the worker ants. You will make all instance fields private to preserve encapsulation.

Write the constructor body. It needs to initialize foodQuantity to 0 and use the inherited setColor method to set the queen’s color to Color.MAGENTA.

Since QueenAnt implements Processable, you need to write the process method. process needs to get food from the passed worker ant using the WorkerAnt giveFood method. This method, which is shown in Figure 7 below, returns an int amount which should be added to foodQuantity. process also needs to provide the worker ant with queen’s location by calling the WorkerAnt shareQueenLocation method. Write the process method.

The Actor act method needs to be overridden with an empty “do nothing” method (QueenAnts don’t act). Look at QueenAnt to see how this was accomplished.  Note the use of the @Override annotation (on the line preceding the act method heading).  You don’t need to remember this, but @Override is very helpful.  If you accidentally misspell the method name, @Override will cause a compile error telling you about this mistake. This error can be very difficult to find otherwise. Compiler errors may cause you irritation, but they’re much, much better than silent mistakes!! Many of you experienced problems that didn’t cause errors but just made your program fail with ShoppingCart.

The Actor toString method also needs to be overridden to add additional information to the string returned by Actor‘s toString. Notice that the Actor toString() already provides useful information: the Actor type, its location, its direction and its color. We’d like to retain this behavior so this provides a good example of using super to call a superclass method. Here is the code you will need:

	return super.toString() + ", FQty=" + foodQuantity;

Compile and execute your project. The queen ant at location (15, 9) should now be magenta. Hover your mouse over the queen — you should get “QueenAnt[location=(9, 15),direction=0,color=java.awt.Color[r=255,g=0,b=255]], FQty=0″.

Foods – Food, Cake, and Cookie Classes

Figure 6 shows the Food, Cake, and Cookie classes. Foods act like queens, but they give food instead of getting it.

Figure 6 – Food, Cake, and Cookie Classes.

Different kinds of food are very similar. They differ only by the size of a bite and the displayed image (note that the image displayed is simply the name of the class with .gif at the end). To take advantage of this similarity, the common instance fields and methods are placed in a Food super class. This class contains no abstract methods,
but it is declared abstract so that it can not be instantiated. The use of abstract classes is important for you to understand! It doesn’t make sense to have a thing which is a ‘food’ — that’s not specific enough. So in this case, we’re deliberately blocking instantiation of Foods even though the class contains complete code.

All foods have both bite sizes and keep track of the total amount that has been eaten. So, instead of repeating
this information in both Cake and Cookie, it is stored in Food instance fields:

  • BITE_SIZE – a constant that determines how much food is given to a worker ant when it gets food.
  • foodEaten – keeps track of the total amount of food “given” to worker ants.

The constructor initializes BITE_SIZE to the bite value passed in the parameter, initializes foodEaten to 0, and calls setColor(null) so that the Cake.gif and Cookie.gif images display with their original coloring.

Update Food to include the two new instance fields and complete the constructor as discussed above. You will need to uncomment the constructor heading and brackets. Note that Java allows constant (final) instance fields to be initialized in a constructor but not to be modified anywhere else.

Compile your Ant Farm project again. Food should have no errors, but Cake and Cookie now have compile errors. Why? What change caused these errors? Recall that subclasses do not inherit their superclass’ constructors. We will fix these errors later.

All foods implement the process method (from Processable) to give food to the passed worker ant and to provide it the food’s location. Foods need to override the Actor act method with an empty “do nothing” method (foods don’t act). Foods also need to override the toString method to include the BITE_SIZE and foodEaten information. Since all three of these methods are the same for all foods, they are placed in Food. Otherwise they would have to be written in both Cake and Cookie.

Write the process method (use WorkerAnt‘s takeFood and shareFoodLocation methods). Also replace the body of the toString method as discussed above. Don’t forget to include the Actor super class toString information like you did with QueenAnt. Make sure that Food compiles without error.

Because of the Food class, the Cake and Cookie classes are very simple. They contain a single class constant BITE which contains the size of a bite. They each have a one statement constructor which passes the value of BITE to the Food constructor.

Complete the Cake and Cookie classes by adding the BITE class constants (see Figure 6 for the appropriate values).

Complete the Cake and Cookie constructors by adding a single statement – super(BITE); This causes the one parameter Food constructor to be used when a Cake or Cookie is created.

Compile and execute the project. The cake and cookie should now display properly. They should not be tinted. Hover your mouse above the cake and cookie images to make sure that the toString methods are working properly. For example, the cookie should display “(2, 2) contains Cookie[location=(2, 2),direction=0,color=null], BSize=1, FEaten=0″

WorkerAnt Class

WorkerAnt (Figure 7) is the most complex Ant Farm class. This is to be expected,
since Critters interact with other Actors in the grid.

Figure 7 – WorkerAnt Class.

Worker ants have instance fields to keep track of the amount of food they currently have as well as known locations of the food and the queen.

The constructor initializes these instance fields (to 0, null, and null), makes the ant black, and uses Math.random to randomly point the ant in one of the eight valid compass directions.

Add the WorkerAnt instance fields and complete the constructor as discussed above and in Figure 7. Use the Location constants HALF_RIGHT and FULL_CIRCLE when writing your constructor. Do not “hard code” constants like 45 and 8. Compile and execute the project to check your code.

WorkerAnt implements the process method to share queen and food locations with other worker ants. WorkerAnt has four methods that do the actual “processing.” They are takeFood , giveFood , shareFoodLocation, and shareQueenLocation. These methods are called from the process methods of the QueenAnt, Food, and WorkerAnt classes.

Complete the five processing methods as follows. Make sure that the project compiles after every change.

  1. process – call the passed worker ant’s shareFoodLocation and shareQueenLocation methods to
    share the food and queen locations with the other ant.
  2. takeFood – add the amount of food passed in fQty to the food quantity instance field.
  3. giveFood – replace the method body to return the current food quantity to the caller
    (queen). Before giveFood exits, the food quantity needs to be reset to zero (all the food is
    being given to the queen).
  4. shareFoodLocation – Foods and worker ants call shareFoodLocation to share the food location.
    If the current saved food location is null, then set it to the value of fLoc.
  5. shareQueenLocation – Queens and worker ants call shareQueenLocation to share the queen
    location. If the current saved queen location is null, then set it to the value of qLoc.

You are about ready to override several of the Critter act methods, but first you will need to complete the useful getDesiredDirecton private helper method. This method returns the general direction that the ant wants to go.

Replace the getDesiredDirecton body to return one of three directions:

  1. If the queen location is not null and the food quantity is not zero, then return the direction from this
    ant toward the known location of the queen (use Location ‘s getDirectionToward method).
  2. Otherwise, if the food location is not null and the food quantity is zero, then return the direction from
    this ant toward the known location of the food.
  3. Otherwise, return the current direction of this ant.

The Critter act method calls the following methods in this order:

  1. getActors – gets a list of Actors for interaction.
  2. processActors – interacts with each of the Actors in the list from getActors.
  3. getMoveLocations – gets a list of possible locations for moving this critter.
  4. selectMoveLocation – chooses one of the possible move locations for this critter.
  5. makeMove – moves this critter.

WorkerAnt inherits the Critter act method which does the following:

  1. Uses the inherited getActors to get all the adjacent neighboring Actors.
  2. processActors processes each of the neighboring ant farm actors. This method should be very short.
    It needs a loop to traverse (loop through) the actors ArrayList. An enhanced for loop works well for this.
    Each actor in actors needs to call its process method. The parameter for each call will be this, the
    reference to the worker ant executing the processActors method.An Actor could be a QueenAnt, a Cake, a Cookie, or a WorkerAnt. Without the Processable interface,
    processActors would need to determine the type of actor and then downcast the actor reference
    before making the call to process. But, since each of these classes implements Processable,
    processActors only needs to cast the actor to Processable before the call. This polymorphic
    processing is allowed because Processable contains the process abstract method. The Java Run
    Time Environment (JRE) determines the actual type of object at runtime and calls the appropriate process method.

    Complete the processActors method as discussed in the preceding paragraphs.

  3. getMoveLocations does the following:
    1. Calls the private getDesiredDirecton method to get the general direction the ant wants to move.
    2. Creates a list with up to three adjacent locations that are in the general direction of the one returned
      by getDesiredDirection. Locations are included if they meet all of the following criteria. They must be:

      1. Adjacent to the current location.
      2. In the desired direction, or 45 degrees to the left of the desired direction, or 45 degrees to the right
        of the desired direction.
      3. Valid (in the grid).
      4. Empty.
    3. Returns the list of locations.Replace the getMoveLocations body as discussed above. For part b, use Location ‘s HALF_LEFT and HALF_RIGHT
      constants. You may also want to use the getAdjacentLocation method, Grid‘s isValid to see if a given location
      is valid (is in the grid) and get to help see if the location is empty (get returns null). There are other possible implementations, though.
  4. Uses the inherited selectMoveLocation to randomly select one of the possible locations. If the list of
    possible locations is empty, it returns the current location.
  5. If the selected move location is different from the current location, makeMove moves to the selected
    location and changes its direction to match the direction it moved. Otherwise it stays put and changes its
    direction by randomly choosing between the two directions 45 degrees to the left or right (use Location.HALF_LEFT
    and Location.HALF_RIGHT ). Then, in either case, it sets its color based on if it has food (red) or not (black).Write the body of the makeMove method as discussed above.

    Complete the toString body to include Critter‘s toString result as well as the values of the WorkerAnt instance
    fields.

    Compile and thoroughly test your project. Make sure that your actors behave properly as described in the
    Overview section at the beginning of this assignment. You can learn a lot about the the state of your actors
    by viewing their toString information (hover over the object). Make sure this information changes appropriately
    as your Actors interact with each other.

Congratulations, your Ant Farm should now be exhibiting intelligent behavior! You have completed what you need to do for this assignment. If you’re done, I expect you to complete the following extensions!

Extensions

Now that you know how all the classes interact change and expand your Ant Farm classes to do the following.

  1. Give Food and WorkerAnt weight. Start each food item with the weight of 5,000,000 micrograms and
    each ant with a weight of 1,000 micrograms plus or minus 300 micrograms.
    Ants can carry up to 20 times their own body weight.
    When an ant takes a bite from the food, the food weight
    is decrease by 20 times the ant’s body weight, which is the amount carried off by the ant.
    When the food weight gets to zero have the food removed from the grid.

    You do not need the constants BITE_SIZE nor the instance variable bite any more. Remove all reference from the Food,
    Cake and Cookie classes.

    Remember to use constants for values you create and to update the toString methods!

  2. When WorkerAnts come back to a food location they remembered, and the food has disappeared, change the remembered food
    location to inidcate the food is gone. This information should be propagated to the rest of the ants.

    This is tricky to figure out. Do not add any additional instance fields. When a Food‘s weight becomes zero, it removes itself
    from the grid. Make sure the food object only shares it’s location if it is in the grid!
    The AntWorker makeMove method now checks to see if the food is not at the location where it is suppose to be. If this is the case,
    then change the food location to a bogus location that is not found in the grid! The method
    getDesiredDirection will have to be altered slightly for this process to work, plus the method shareFoodLocation will
    have to be altered . It might be helpful to write private
    help methods isFoodLocationInGrid(Location) and isBogusLocation(Location) that determines if a food location is still
    in the grid or is a bogus location. To get the logic correct for shareFoodLocation create a matrix with all the possiblities:

    null Good Bogus
    null
    Good
    Bogus
  3. Add energy to the WorkerAnt class.
    Ants should start with 100 units of energy and for each step the ant should lose energy by:

    • If the ant cannot move it looses 1 unit of energy and 1 microgram of weight.
    • If the ant can move and it is not carrying any food it looses 2 units of energy and 2 micrograms of weight.
    • If the ant can move and it is carrying food it looses 2 units of energy plus the amount it is carrying divided by 10,000
      units of energy. It also losses 3 micrograms of weight.
  4. Ants gain energy when they find food. They should eat 1/4 of their body weight of food, which in turn is converted into
    (food eaten) / 1000 units of energy. Weight is increased by
    (food eaten) / 200 micrograms. Remember the ant’s bite of food is still 20 times the ant’s body weight.
  5. Ants die when their energy or weight is reduced to 0. If they are carrying food when they die a food item should be placed in the cell that
    the ant dies in. The food created should be randomly selected (cake or cookie) with the weight of food being carried by the ant. You
    could add what kind of food the ant is carrying, then drop that same kind of food when the ant dies.
Leave a response »

Vocabulary list

Ms. Martin : March 21, 2010 6:51 pm : 2009 AP CS A
Concept Definition
Abstract method A method that is declared (as in an interface) but not implemented. Abstract methods represent the behavior that a class promises to implement when it implements an interface.
Accessor Instance method that provides information about the state of an object without modifying it.
Behavior A set of actions an object can perform, often reporting or modifying its internal state.
Client code Code that interacts with a class or objects of that class.
Code Reuse Practice of writing program code once and sing it in many contexts (inheritance, parameterization are examples of code reuse techniques).
Encapsulation Hiding implementation details of an object from its clients. Provides abstraction and protects the integrity of an object.
extends Keyword used to establish an inheritance relationship.
Field A variable inside an object that makes up part of its internal state.
implements Keyword used to implement an interface.
Implicit parameter The object that is referenced during an instance method call.
Inheritance A programming technique allowing a derived class to inherit all of a base class’ state and behavior and extend its functionality.
Inheritance hierarchy A set of hierarchical relationships between classes of objects (is-a relationships).
Instance method A method inside an object that operates on that object.
Interface A type that consists of a set of method declarations; when classes promise to implement an interface, you can treat those classes similarly in your code
Mutator Instance method that modifies the object’s internal use.
Object A programming entity that contains state (data) and behavior (methods).
Object-oriented Programming Reasoning about a program as a set of objects rather than as a set of actions.
Override To implement a new version of a method to replace code that would otherwise have been inherited from a superclass. No special syntax is required.
State A set of values (internal data) stored in an object.
Subclass Child or derived class in an inheritance relationship.
Superclass Parent class in an inheritance relationship.
this Java keyword that allows reference to the implicit parameter inside a class.
1 Comment »

Jumper class

Ms. Martin : March 21, 2010 6:34 pm : 2009 AP CS A

You will complete the Jumper class as detailed in the GridWorld case study part 3 document.  I’ve rewritten some of the instructions here — follow these!!

Requirements

You will create a class called Jumper. This actor can move forward two cells in each move. It “jumps” over rocks and flowers. It does not leave anything behind it when it jumps.

Before you get going, you need to figure out how you will address the following situations:

  1. What will a jumper do if the location in front of it is empty, but the location two cells in front contains a flower or a rock?
  2. What will a jumper do if the location two cells in front of the jumper is out of the grid?
  3. What will a jumper do if it is facing an edge of the grid?
  4. What will a jumper do if another actor (not a flower or a rock) is in the cell that is two cells in front of the jumper?
  5. What will a jumper do if it encounters another jumper in its path?
  6. Are there any other tests the jumper needs to make?

Design

Several design decisions need to be considered:

  1. Which class should Jumper extend?
  2. Is there an existing class that is similar to the Jumper class?
  3. Should there be a constructor? If yes, what parameters should be specified for the constructor?
  4. Which methods should be overridden?
  5. What methods, if any, should be added?
  6. What is the plan for testing the class?

Code

Implement the Jumper and JumperRunner classes.

Test

Carry out the test plan to verify that the Jumper class meets the requirements.  This will involve putting an instance of your Jumper class into all the situations outlined in the requirements as special cases.

Leave a response »

Rockin' coder raps

Ms. Martin : March 15, 2010 8:52 pm : 2009 AP CS A

Nice work on the classes, arrays and ArrayList quiz!  I loved reading the extra credit, as usual!

The rockin’ coder loves Java
His codes are hotter than lava
He writes code faster than the speed of light
When it compiles the whole world is in flight

The gangsta coder makes his way
Writing lines of code to save the day.
He compiles often and knows to debug;
this rockin’ coder’s a computer thug!

I’m from 8 mile
Where only the hardest compile
We always do it in style
Because we ain’t had cast for a while
Don’t hit me on the nextel chirp
I will not have a conversation about work

I like writing code, I’m into it
My bars are like the loops I write, they’re infinite

This rockin’ coder we really need
We need the class names and the typin’ speed
We need no errors and code that runs
The rockin’ coder will keep it fun

This coder codes so fast
Who used to code slow inside his past
He coded millions of lines
In a short amount of time
Because he recognizes java signs
While enjoying eating a lime

I been codin’ like a boss;
no need to throw and toss;
like some butter on a skillet;
man, I ain’t nuttin to deal wit

The rockin’ coder is my name,
Initialized variables are my game
All of my code is clean and tidy
Bracketed, commented, the sign of the mighty.
Every compiler wants me to take ‘em for a raide
Just watch what happens when my fingers fly!

I write me some code an’ it’s all right
I know it keeps you up ’till late at night
Keep all your keystrokes in my array
Schools be usin’ Linux at the end of the day
I don’t import much, just the classes I need
You want my advice, you best follow my lead
You can challenge me if you’d like a dare
But nothin’ you code could even compare

We be codin’
java, our rhymes are hotter
than lava.
I be gettin’ hella calls
with hella job offas

1 Comment »
« Page 1, 2, 3, 4, 5 »