NEW: For a prettier blog interface, see the Wordpress version!


Final project

Final project

bogNeill and Gretch
connect4Alexia, Lori and Marge (limit01)
endKenny, Michael and Stephanie
ethersphereToppy and Athena
fieldsFelix, Jaime Kid
fruitsClarissa and JV
ltcol2Manny-ligaw and Friends (James, Mond and Paolo)
pacmanEnzo, Samuel and Vince
ragnarokLui and Jaze
smileyGen, Keoma and Kristina
snakeMa. Fatima and Christina
trappedPaowiee and Cricket

See CS21B.Plans


28. Linked list lecture postponed to Tuesday, March 2

I have CS161 finals for seniors from 1:30 to 3:30 today, so please use class time to work on milestone 2.

This is:

Feel free to ask your classmates for help or help your classmates figure things out. You can share tips, talk about bugs you encountered, and even look at other people's source code. However, you are responsible for making sure that you understand the code in your program. What you get out of an education is only as much as you put in - if you just copy and paste, you'll have a hard time later on! =)

Milestone 2: Networking

  • 15 points: Two-player game
  • 20 points: A server that can accept all the people who try to connect to it. The server should make it easier for people to find people to play with, and should automatically set up the game once the player chooses opponents.

These milestones are guidelines. If you miss them or do not implement them exactly, I want you to send me detailed notes on what you _are_ doing. You are responsible for your results. If you miss the milestones and do not complete your project, you may want to reevaluate your priorities or learn how to manage your time wisely. =)


27. Lecture on stacks and queues


A short quiz will be given, then the rest of the time will be allotted for projects. The deadline for milestone 1 (basic networking) has been extended to tonight, 2004.02.24 11:59:59 PM.

Milestone 2: Networking (20 points total)

Due Monday 2004.03.01, 11:59:59 PM

  • 15 points of 20: Play a two-player game where one player connects to another.
  • 20 points of 20: If you have a game that can take any number of players, any number of players should be able to connect to a game. If you have a game that takes only a certain number of players (ex: 2), you should have a server that allows people to meet other people who want to play that game. Your program should take care of setting up the appropriate connections.

Again, submit your source code and your notes on:

  • changes you made
  • problems you encountered
  • solutions found
  • problems you still haven't solved
  • next step


26. Common networking errors

Due 2004.02.23 11:59:59 PM: Source code and detailed notes on

  • changes made
  • problems encountered
  • solutions tried/found
  • outstanding problems
  • plans for next step

I don't expect everyone to have a fully-working game by tomorrow, so most of your partial points will come from the notes. "It doesn't work." isn't enough; I need to know why it doesn't work, if it used to work before, what you've tried doing to get it to work, why you think it doesn't work, etc.

Along the way to your first milestone, you may have encountered the following problems:

  • ObjectInputStream seems to hang when you create it.

That happens when both sides of the connection try to create object input streams at the same time, but the other side hasn't opened an object output stream yet. Fix: create the object output stream first before you create the input stream.

ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
  • Your program lags terribly.

How are you doing your networking and repainting code? If you're doing animation, repaint() should be in one thread and your networking code should be in another. You shouldn't do them in the same thread because then repaint() will only happen whenever something is received from the socket connection. Also, make sure you have delays somewhere! while (true) { repaint(); } means your CPU will spend most of its time repainting. Add a Thread.sleep in that loop so that your computer has time to do other things.

  • You can't write certain objects over the stream.

Make sure the object is serializable and all of its attributes are either transient or serializable as well. You really shouldn't be sending your entire application over the network - what is the other side going to do with all those textfields? Mark many of your attributes transient or create a small, simple object that encapsulates the data you need to send.

  • You've sent an object over the network connection and you're calling methods on it on the other side, but the one on the first computer isn't changing!

That's the way it works. If you send an object from computer A to computer B, computer B isn't working on the original object but on a copy of it. Any changes on A won't be automatically sent to B and vice versa. The correct thing to do is examine the object and perform different actions locally.

If you really need to get something like this working and you have plenty of spare time, read up on RMI (Remote Method Invocation). It's out of the scope of CS21B, though.

For tonight, I want lots and lots of notes.

TOMORROW: Data structures (stacks, queues and linked lists).

25. 2004.02.17 Number systems

Categories: None -- Permalink, Comment form
  • Converting from any base to base 10
  • Converting from base 10 to any base
  • Binary (base 2)
  • Octal (base 8)
  • Decimal (base 10)
  • Hexadecimal (base 16)

24. 2004.02.12 Object serialization over networks

Categories: None -- Permalink, Comment form

If you don't have a project yet, please approach me.

At the end of this session, please e-mail me:

  • a description of how you will turn your game into a multi-player networked game
  • the kind of data that needs to be sent from the client(s) to the server and vice versa
  • descriptions of these as classes

For example, here's a description of a simple one-player game:

CHASE ME! In this game, the player tries to click on a circle that is randomly moving around the screen.

A possible multi-player version of this could be:

CHASE ME! is a two-player game where one player controls a circle and the other player tries to click on it.

Description of data sent over the network:

Let's say that player A controls the circle and player B controls the
pointer. A will act as the server. B connects to A.

At the start of the game -------------------------------------------------
A to B: GameInfo object (starting location, radius of circle, A's name)
B to A: GameInfo object (starting location, (ignore radius), B's name)

During the game ----------------------------------------------------------

Whenever A moves the mouse:
    A to B: GameMove object (new location)
Whenever B moves the mouse:
    B to A: GameMove object (new location)

Whenever A receives a GameMove object, it will update the position of
the pointer and repaint the screen. If the position of the pointer is
inside the circle, add to B's score and note the current time. 
scoring if the circle was last caught less than 5 seconds ago. 

Whenever B receives a GameMove object, it will update the position of
the circle on the screen.

23. 2004.02.10 Object serialization

Categories: None -- Permalink, Comment form
  • Lecture
  • Quiz
  • Exercise

Important notes:

  • The data class should implement the Serializable interface. (No extra methods.)
  • To prepare for writing objects to a stream, create an ObjectOutputStream around a FileOutputStream or a socket's output stream.
  • To write an object to a stream, call the object output stream's writeObject method.
  • If you're writing the same object two or more times, any changes in the object will not get saved unless you call reset on the object output stream before writing a second time.
  • The resulting data is binary. DO NOT EDIT THE FILE.
  • To prepare for reading objects from a strean, create an ObjectInputStream around a FileInputStream or a socket's input stream.
  • To read an object from a stream, call the object input stream's readObject method. This returns a generic Object, so you might have to cast it to your needed class.
  • readObject can throw a ClassNotFoundException if it reads an unknown class.

22. 2004.02.05 No classes. Assignment: Improvements on the chat server

Categories: None -- Permalink, Comment form

It would be nice to send messages to other people. Private messages. On IRC, this is handled with the /MSG nickname message command. (By now you've probably realized that we are working on something that looks like an IRC server...)

Modify your multi-client broadcast servers so that clients can chat with everyone connected _and_ also send private messages to each other. Again, you are allowed to talk to anyone as long as you type everything yourself (no cut-and-paste). =)

E-mail me ([email protected]) your work by 23:59:59 Mon 2004.02.09. This will be treated as another 5 points.

21. 2004.02.03 Multi-client networking

Categories: None -- Permalink, Comment form
Code analysis
  • Why do we need to handle sending/receiving per client in separate threads?
  • Why do we need to keep a Vector of the connections?
Programming exercise (15 points, groups of max. 2)
  • Modify MultiBroadcastServer so that when a message is sent, " sent: " is seen on all clients except the one that originally sent it. The client that originally sent the message will see "You sent: " instead.

(5 points)

This will be considered a 5-point group quiz (max. two per group). Modify the code, add your names and ID numbers, and e-mail your submission to [email protected]. This should take less than 15 minutes.

  • Modify MultiBroadcastServer to allow people to identify themselves with nicknames when they connect to a server.

HINT: How can you distinguish nickname-requests from normal text? One way to do this is to use a special first word. For example, nick messages can be of the form /NICK

(5 points)

  • If people can set nicknames, how can you make sure that no two people have the same nickname at any given time? Modify MultiBroadcastServer so that no two people can have the same nick at a time. If two people ask for the same nick when they connect, then add characters to the later one until it's unique. (Example: If two people try to connect with the Guest nick, the second one will be Guest^. If someone's already named Guest^, then Guest^^, etc.) If a person tries to change to a nick that's already taken, simply deny the request.

(5 points).

20. 2004.01.26 Applications and threads

Categories: None -- Permalink, Comment form

Submit 1/2 sheet of paper or e-mail by the end of the period. If you do not finish all the items today, submit your finished work by Saturday. This will be graded as homework.

If you finish early, help other people understand applications and threads, or work on making a graphical chat client or a very simple networked game like rock-paper-scissors or tic-tac-toe.

19. 2004.01.24 Threads

Categories: None -- Permalink, Comment form

This sample program demonstrates two threads.

public class ThreadDemo
    public static void main(String args[])
        PrintingThread a = new PrintingThread("Hello", 1000);
        PrintingThread b = new PrintingThread("World", 500);


class PrintingThread extends Thread
    private String message;
    private int delay;
    public PrintingThread(String message, int delay)
        this.message = message;
        this.delay = delay;

    public void run()
        for (int i = 0; i < 10; i++)
            catch (InterruptedException ex)
EXERCISE: Modify this code to print to the same file ("output.txt"). output.txt should contain a mix of output from the two threads.

HINT: Open the file in ThreadDemo, then pass the PrintWriter in the constructor of PrintingThread.

CHALLENGE: Can you use Threads to allow someone to simultaneously send and receive messages? Here's the pseudocode:

Main program:
    Open the socket connection
    Create a ListeningThread and pass the socket connection to it
    Create a SendingThread and pass the socket connection to it
    Open an input stream reader around the socket's input stream.
    Open a buffered reader around that input stream reader
    While you can still read from the buffered reader (!= null)
        Read a line (this waits)
        Print it out

    Open a print writer around the socket's output stream
    In an infinite loop
        Use JOptionPane.showInputDialog to get text from the user
        Print the text to the print writer

18. 2004.01.22 Networking exercises

Categories: None -- Permalink, Comment form


Categories: None -- Permalink, Comment form

Don't forget, your midterms are on Monday, January 19, 2004, from 4:30 PM to 6:00 PM at CTC 104.

15. 2004.01.15: StringTokenizer

Categories: None -- Permalink, Comment form

See exercises at CS21B.Exercises

14. 2004.01.13: Files exercise

Categories: None -- Permalink, Comment form

Sorting lines in a file

13. 2004.01.08: Files and Streams

Categories: None -- Permalink, Comment form

Please see CS21B.Streams

12. 2004.01.06: Welcome back, project work

Categories: None -- Permalink, Comment form

11. 2003.12.18: Project work

Categories: None -- Permalink, Comment form

We won't meet for class today. Have fun working on your project! =) Feel free to e-mail me if you need more help. You can also ask the other teachers in the CS department. (They're friendly. They don't bite.)

10. 2003.12.16: Release of project specifications

Categories: None -- Permalink, Comment form

CS21b - Introduction to Computing II (Project 1) (Amarra, Chua, Jongko, Sarmenta, Sy)

Project Title: PaintAShape

Project Deadline: Class Diagram & Java Files, January 7, 2004, 11:59 pm, or as specified by your teacher

Project Description:

This project is to be done in groups of one, two or three members. We strongly encourage you to form groups of two for experience in groupwork (better than just working on your own) and easier communication (hard to organize groups of three during Christmas break!).

You are to create an applet that allows shapes to be created and manipulated. Ovals, Rectangles and Lines are the basic shapes that can be created. A palette should be displayed on the left side of the applet containing at least the following selections: Oval, Rectangle, Line, Delete, Clear, Fill Color, Pick Color

The following functions should be supported:

  • Shape creation The palette on the left side of the frame should display the following shapes for creation: Oval, Rectangle and Line. When the shape is selected and you click on a location on the canvas, this will cause the shape to be created. For Ovals and Rectangles, the location of the initial mouse position is the upper left corner of the shape. As you drag the mouse, the pointer will represent the lower right corner of the shape (like the paint application). The size of the shape will be determined by how far you drag the mouse with respect to its initial position. For Lines, the location of the initial mouse position is the first endpoint. As you drag the mouse, the pointer will represent the other endpoint.
  • Select/Deselect Clicking on a location inside the shape will cause the shape to be selected. When you click the mouse on a new location outside the shape, this will cause the selected shape to be deselected. Clicking on a point near a line (allow programmers to modify this easily) should select the line.
  • Resize After a shape is selected, you can resize the object by clicking on one of the borders of the shape. You can drag the border to a new location, causing the shape to expand or contract. For lines, resize can be performed by dragging either of the line's points.
  • Move While the shape is selected, dragging the mouse will cause the object to move to the new mouse location.
  • Delete A Shape If a shape is selected and Delete from the palette is selected, the shape will be removed from the canvas.
  • Clear the canvas When Clear is selected from the palette, all the shapes currently drawn on the canvas will be deleted.
  • Fill Color When a shape is selected, then Fill Color is chosen from the palette, a color selection will be presented to the user, and the selected color will cause the shape to be filled with the color. Lines cannot be filled.
  • Pick Color When this is selected, the subsequent shape creation will cause the outline of the shape to be drawn in the selected color.

You will need to submit a class design (Class Diagram) and a working system by January 7.

Grading Scheme:

+5Users can draw circles.
+5Users can draw squares.
+5Users can draw lines.
+5Users can control the position when the shape is added.
+5Users can control the size when the shape is added.
+10Users can select shapes
+10Users can move shapes.
+5Users can delete a shape.
+5Users can clear the canvas.
+5Users can selectively color the shapes (fill the shapes).
+5Users can draw a shape (outline) in a particular color.
+10Users can resize shapes.
+15The program is neatly designed.
+10Quiz after project
105Highest possible grade

Guidelines for good design: No unnecessary attributes or methods. No unneccessary access to other objects' data. Flexible code (but not too flexible). Sensible object-oriented design.

To earn full marks, document your code, optimize it, and make sure you consistently follow coding conventions.

FEATURES: Important note about bonuses! You will be given up to 5 points for interesting extra features. However, these points will be shared among all groups that have the same (or very similar) feature in their project in the class. If a feature is worth 5 points and two groups implement the same feature independently, each group will receive 2.5 points. If you implement multiple features, the feature that gets you the maximum number of points will be included in your grade.


2003.12.20At least one submission of whatever work you have so far, progress report, and plans for future
2003.12.27At least one submission of whatever work you have so far, progress report, and plans for future
2004.01.03At least one submission of whatever work you have so far, progress report, and plans for future

Submit these through e-mail. Feel free to submit intermediate parts.

For progress report/plans for future, please add something like this to the body of your e-mail:

_ Users can draw circles.
_ Users can draw squares.
_ Users can draw lines.
_ Users can control the position when the shape is added.
_ Users can control the size when the shape is added.
_ Users can select shapes
_ Users can move shapes.
_ Users can delete a shape.
_ Users can clear the canvas.
_ Users can selectively color the shapes (fill the shapes).
_ Users can draw a shape (outline) in a particular color.
_ Users can resize shapes.

_: Not done
o: In progress
X: Finished



9. 2003.12.11: DrawingApplet continuation

Categories: None -- Permalink, Comment form

8. 2003.12.09: DrawingApplet continuation

Categories: None -- Permalink, Comment form
  • Discussion of different approaches
Starting out
  • interface
  • displaying shapes
  • mouse listener and mouse motion listener demo
  • stubs
  • UML
  • focused on the circle
  • studied the old files then worked on selection

Approach 1: objects are responsible for determining if a point is inside them. Each shape has a contains(int x, int y) method.

Approach 2: GraphicsCanvas gets the X, Y, and size of the different shapes, then calculates whether a point is inside.

Compare the two and analyze their advantages and disadvantages.

7. 2003.12.04: DrawingApplet

Categories: None -- Permalink, Comment form

The client wants you to make a simple drawing program that allows the user to add, move, resize and delete circles, squares and lines.


  • Learn how to work effectively in a small team.
  • Break down a large problem into smaller tasks and plan your implementation.
  • Use object-oriented principles to simplify your design and make your code more flexible.
  • Review your high school geometry. ;)

This is a big project, so break it down into smaller tasks and plan accordingly.

6. 2003.12.02: Encapsulation

Categories: None -- Permalink, Comment form

Pass your homework. =) (UML diagrams and suggestions for someone else's work.)

Aha! Solution to the black canvas problem

To all the people who had problems with black canvases:

Quick fix: In your GraphicsCanvas's paint(Graphics g) method, add the following as the first line:

Explanation: super.paint(g) calls the paint method defined by the superclass, JPanel. Apparently, JPanel's paint(Graphics g) method does something important. When we override that in GraphicsCanvas, the old code does not get called any more - it gets replaced by our code. super.paint(g) makes sure that the old code gets called.

Refactoring quiz

Study the code on the board and answer the questions given. Write your name and your answers on one whole sheet of paper and pass it at the end of 10 minutes.

Refactoring exercise

After passing your paper forward, create a new project in Eclipse and type in the provided CarApplet. Improve the design

Export your project as a ZIP file.

5. 2003.11.27

Categories: None -- Permalink, Comment form

Introduction to Eclipse

Today, we'll try out Eclipse, an integrated development environment (IDE) for Java and other programming languages.

Implement the shapes system we discussed last session.

Last session, you implemented the shapes system as a team. To reinforce the lessons that you learned and to practice using Eclipse, write all of the classes in the system from scratch.

You will need to define the following classes:

  • Square: Draws a square. (easiest)
  • Circle: Draws a circle.
  • GraphicsCanvas: Contains squares, circles and other shapes.
  • GraphicsApplet: Creates a GraphicsCanvas and shapes. Adds the shapes to the graphics canvas.
  • Shape: An interface that specifies the paint method.

You'll be adding another class to the system, so write the GraphicsCanvas to take advantage of the Shape interface. You may define the superclass BasicShape if you want to.

Create a Person class - a stick figure shape

The only classes that should change in your program are:

  • GraphicsApplet: Add a person to the GraphicsCanvas.
  • Person: New class that draws a stick figure.
Create another class that draws a stick figure shape.
  • You can draw any animal or human shape.
  • Follow Java naming conventions.
If there is still time, create variations of the Person class or other shapes.


  • Wizard
  • Fairy
  • Elvis

Now we're going to practice reading other people's code.


Now we're going to get the different objects to act.

  • Add a public void act() method to the Person class that changes the position of the hands. (See board for illustration.)
  • Add a public void act() method to another class that makes that shape do something interesting.
  • Leave the other classes alone - do not add act() methods to them.
  • Add a way for the GraphicsCanvas to call the act() method on te objects that have it. What would you need to do in order to get this to work?
  • Add a button to the GraphicsApplet that tells the GraphicsCanvas to call the act() method on the objects that have it.

Document your changes on the piece of paper. If there is still time, you can add more complicated actions.

Analysis again
  • Return to your old computer.
  • On your piece of paper (the one that contains the UML diagram of the _other_ system), draw a line and write "My system". You may need another sheet of paper.
  • Without referring to the other person's notes, find out what changes were made to your system and list them.
  • Do you agree with all the changes? Do you think something could be improved? Write your opinions down on your paper.
  • Pass your paper forward.
At home

If you want to really get the hang of object-oriented design and development, practice is essential.

Revisit your final project. Is there a way you can make the design more object-oriented and flexible? If you no longer have a copy of your source code, see if you can come up with a new design based on the ideas you had before. Practice by redoing it.

4. 2003.11.25: Implementing the design

Categories: None -- Permalink, Comment form

Today, we will practice implementing the UML design we talked about last time.

Step 1: Implementation of the different classes

For this exercise, you will need to form teams of 4 - 5 people. (No group should have fewer than 4 people.) Discuss the table below and decide who will implement what class. Each person should work on only one class. Square is the simplest class, while GraphicsCanvas is the most complex class.

Square Define a Square class according to the UML diagram of the quiz last session. This class should draw the outline of a square.
Circle Define a Circle class according to the UML diagram of the quiz last session. This class should draw the outline of a circle.
FilledSquare (for groups of 5 people) Define a FilledSquare class with the same methods and attributes as the Square class. This class should fill in a square.
GraphicsCanvas Define a GraphicsCanvas class according to the UML diagram of the quiz last session. This class should display all the circles, squares (and filled squares) added to it.
GraphicsApplet You can think of yourself as the user, and the other people in the group develop for you according to the specifications. Define a GraphicsApplet that extends JApplet and displays several circles, squares (and filled squares) by adding them to a GraphicsCanvas. Make sure you know what to expect as the output. (Draw it on the piece of paper.) You may complain loudly if the other classes don't do what you expect them to do. ;)

Write down the classes and the people assigned to work on them on 1/2 sheet of paper.

Work on the classes on separate computers. You will be able to write your programs, but you might not be able to compile them because of dependencies (ex: GraphicsApplet requires GraphicsCanvas). If you followed the specifications exactly, though, you will be able to copy all the files into one directory and compile it without errors.

After you finish your work, copy it to one computer and try to compile and run it. Did it work exactly as expected? If so, then write down:

1st try: Success!
If not, write down

1st try: <reason why it didn't work>
and let the person responsible for that class correct his or her errors. Every time you compile the program, make another entry for that try and write down your notes. Repeat until your program works to your satisfaction.

Pass this sheet of paper to me after you have gotten it to work as expected. Make sure that everyone in your team has a copy of the latest source code.

Meanwhile, I will code the solution on the main computer. (Will I finish it before you, even if I'm working by myself? =) )

Step 2: Modify GraphicsCanvas to use Objects.

I will demonstrate this on the main computer. You can follow along on your own computers to see how to apply the concepts.

Step 3: Interfaces

There will be a brief lecture on interfaces. We will define our own interface and modify the classes accordingly.

Step 4: Inheritance

We will take a look at the common code shared by the different shapes and define a BasicShape class.

Step 5: Adding a new class: Triangle

To take advantage of our spiffy architecture, we will define a Triangle class.

3. 2003.11.20 Inheritance

Categories: None -- Permalink, Comment form

Quiz: UML

  • What is inheritance?
  • How can it help us simplify our code?
  • When does it make sense?

(OpenOffice 1.1 (SXI), Microsoft Powerpoint (PPT))

2. 2003.11.18 Basic UML

Categories: None -- Permalink, Comment form

1. 2003.11.13 Introductions

Categories: None -- Permalink, Comment form

Brief overview of class, survey

Previous day | Next day

I'd love to hear about any questions, comments, suggestions or links that you might have. Your comments will not be posted on this website immediately, but will be e-mailed to me first. You can use this form to get in touch with me, or e-mail me at [email protected] .

Page: C S 21B
Updated: 2004-11-21
NOTE: ANTI-SPAM MEASURE NOW IN PLACE. Please answer the following question with the right number in order to send me your comment.
What is two minus one? (hint: one ;) )