Notes

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. =)

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)

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.

problems you still haven't solved

next step

26. Common networking errors

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.

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.

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.

readObject can throw a ClassNotFoundException if it reads an unknown class.

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

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). =)

5-point quiz on threads and applications

Demonstration of graphical chat client

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 sacha@sachachua.com. 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.

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
ListeningThread:
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
SendingThread:
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

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.)

Project Title: PaintAShape

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:

+5

Users can draw circles.

+5

Users can draw squares.

+5

Users can draw lines.

+5

Users can control the position when the shape is added.

+5

Users can control the size when the shape is added.

+10

Users can select shapes

+10

Users can move shapes.

+5

Users can delete a shape.

+5

Users can clear the canvas.

+5

Users can selectively color the shapes (fill the shapes).

+5

Users can draw a shape (outline) in a particular color.

+10

Users can resize shapes.

+15

The program is neatly designed.

+10

Quiz after project

+5

Features

105

Highest 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.

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.

SPECIAL NOTES FOR CS21B SECTIONS A AND B (Chua):

Date

Due

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

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

2004.01.03

At 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.
Legend:
_: Not done
o: In progress
X: Finished
Questions/notes/comments:

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

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:

super.paint(g);

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.

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.

Suggestions:

Wizard

Fairy

Elvis

Analysis

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

Make sure that your code has your name and e-mail address.

Make a ZIP file containing your code so far. E-mail it to sacha@sachachua.com and yourself with the subject "CS21B: Original by <your name&t;".

Stand up and move two seats to your left (wrapping around if necessary).

See the board for instructions on drawing interfaces.

Bring out a sheet of paper. Write your name, your e-mail address, and the name and e-mail address of the person whose code you are reviewing.

Prepare a UML diagram for that project.

Do you think the design can be improved? Improve it and list your changes underneath the UML diagram.

Modification

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.

Create a .ZIP file with all the code and e-mail it to sacha@sachachua.com, the author, and yourself with the subject "CS21B: Modified <author's name> by <your name>"

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.

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.