1. 1 Project Definition

advertisement
JAVA CARD GAME
TABLE OF CONTENTS
Chapter One Introduction__________________________________________________ 3
1. The Background Overview _________________________________________________ 3
1.1 Project Definition ________________________________________________ 4
1.2 Project General Information ________________________________________ 5
1.2.1 Game TwentyFour ______________________________________________ 5
1.2.2 Unified Modeling Language _______________________________________ 5
1.2.3 Java Language _____________________________________________________ 5
1.2.4 Client and Server ____________________________________________________ 5
1.2.5 TCP/IP and UDP/IP Communications ________________________________ 6
1.2.6 Socket and programming socket in Java __________________________________ 6
1.2.6.1 Server side socket _______________________________________________ 6
1.2.6.2 Client side socket _______________________________________________ 7
1.2.6.3 Ports: _________________________________________________________ 7
1.2.7 Multithread _________________________________________________________7
1.2.8 Working steps among of socket, client and the protocol of the project ___________7
Chapter Two OOAD ______________________________________________________ 9
2. Object Orient Analysis and Design ______________________________________9
2.1 Plan and Elanborate phase __________________________________________9
2.1.1 Requirement _______________________________________________________9
2.1.2 Identifying Use case ________________________________________________ 11
2.1.3 Use case Diagram _________________________________________________ 13
2.1.4 Ranking Use case __________________________________________________ 13
2.2 Build phase ________________________________________________________ 13
2.2.1 Analysis phase ____________________________________________________ 13
2.2.2 Conceptual Model _________________________________________________ 15
2.2.3 System Sequence Diagrams _________________________________________ 15
2.2.4 Contract of Calculate TwentyFour Use case _____________________________ 16
2.2.5 Sequence Diagram of Calculate TwentyFour Use case _____________________17
2.3 Design phase ____________________________________________________ ____ 17
2.3.1 Real Use case ____________________________________________________ 17
2.3.2 Calculate TwentyFour Real Use case ___________________________________17
2.3.3 Design Class Diagram ______________________________________________ 19
2.3.4 Summary ________________________________________________________ 20
2.4 Develop _____________________________________________________________ 20
2.4.1 Server Class ______________________________________________________ 21
2.4.2 TwentyFour Class _________________________________________________ 21
2.4.3 Card Class ___________________________________________________ ____ 22
2.4.4 PlayThread Class __________________________________________________ 22
2.4.5 CSProtcol Class __________________________________________________ 22
2.4.6 Player Class ______________________________________________________ 23
Chapter Three Database ______________________________________________________ 23
3 Database _______________________________________________________________23
3.1 Database Design and Development _____________________________________23
3.2 Structured Query Language (SQL) ____________________________________ 24
3.3 Registering A Database As An ODBC Data Source ______________________ 24
1
JAVA CARD GAME
Chapter Four Tour of Java Card Game ______________________________________25
4. Game TwentyFour Demonstration ________________________________________25
4.1 Web page ___________________________________________________________ 25
4.1.1 Home page ______________________________________________________ 25
4.1.2 Sign up now web page _____________________________________________ 26
4.1.3 TwentyFour web page _____________________________________________ 26
4.2 Alternative Courses ___________________________________________________ 30
4.2.1 Login unsuccessful ________________________________________________ 30
4.2.2 Choosing the Clean button to redisplay cards ___________________________ 31
4.2.3 Requesting a Right Answer ________________________________________ 32
4.2.4 Clicking the card or operator in wrong case ____________________________ 32
Conclusion _____________________________________________________________33
Appendix _______________________________________________________________35
I List of Referece _____________________________________________________35
II List of Software Use In The Project ___________________________________ 35
III UML Appendix ___________________________________________________ 36
2
JAVA CARD GAME
CHAPTER ONE INTRUDUCTION
1 The Background Overview
This project is the final thesis requested by the Copenhagen Engineering College for the
completion of the engineering diploma study. The aim of this project is to create a java card
game and master the skills of object-oriented analysis and design using UML, which stands
for Unified Modelling Language. The main structure of the program uses a client/server
model to provide a convenient way to interconnect programs.
This report contains of four chapters and IV appendixes
The method used in this report is shortly described as:
The chapter 1 is an introduction where client/server model is discussed. The java.net
package and the computer communicate model also are discussed in this chapter.
The chapter 2 uses Object Oriented Analysis and Design (UML ) to describe the problem
domain of the project going throw the phases plan and elaborate, the build and develop
phase. It ends with a simple class diagram.
The chapter 3 describes the general information about database, lists the SQL commands
used in the project.
The chapter 4 is a tour of the application and also can be considered as the testing of the
program too.
Fig 1. The playing desk of the Java card game TwentyFour.
3
JAVA CARD GAME
1. 1 Project Definition
To create a Java program which contains a card game (Twenty-four). It should be possible to
play the game as a client server program over the Internet. The project should contain
implementation of a client as an applet and a server as an application. The server should also
be connected to a database where information about different players could be maintained.
The application should be implemented in Java using the tools used at the department for
Electrical Engineering and Information Technology (EIT) at the Engineering College of
Copenhagen (IHK) namely Borland’s JBuilder, Microsoft’s Access database and other tools
used by the students.
The purpose of the project is to:
Implement a large java program where the code could possibly be used in the schools java
lectures.
 Create a class design using Unified Modelling Language (UML).
 Briefly describe the client server paradigm.
 Give the student experience in working in the Java environment.
The outcome of the project should be:
 Documentation of the analysis and design as far as time allows.
 Implementation of the Java code.
 Test of the implemented Java code. First on the local machine then if time allows on the
intranet.
It must be outlined, that it is important that the project should concentrate more on the
programming side of the project rather than on the design side. The design of each class
should not be the most important issue.
Peter Overgaard
4
JAVA CARD GAME
1. 2 The Project General Information
1.2.1 The game TwentyFour
The game –TwentyFour is a simple card game. Four cards are randomly chosen from the
card deck and shown to the players. They players are supposed to make an arithmetical
expression using card values of all four cards and arithmetic operators +, - , / , * . The
result of this mathematical expression must be 24. The winner is the first one who solves the
problem. Usually two people play the game together, the winner for each game collects the
four cards, then a new game start again, the player who collects whole deck of cards will be
the final winner. The current program allows one player to play the game with computer.
The game TwentyFour has been played in China for many years. Almost all the kids learn
this game from the older generation and play it for fun. A Chinese girl brought this game to
the United States after immigration. She designed a card deck for this game and obtained a
patent. You might find there are game Twentyfour cards for sale in store and over Internet
(http://www.pahomeschoolers.com/24.html). There are also some primary schools that have
the game club for the children to play this game after class. The math forum web site, a web
site run by Drexel University for math education, recommends game TwentyFour.
(http://mathforum.org/dr.math/problems/joshipowell.10.6.00.html)
1.2.2 Unified Modelling Language
Writing software like constructing a building, the more complicated the underlying system,
the more critical the communication among everyone involved in creating and deploy the
software. The UML emerged in last decade, it gives everyone from business analyst to
designer to programmer a common vocabulary to talk about software design.
Most of UML techniques of the project are referred to the book Applying UML And Patterns
by Craig Larman.
1.2.3 Java Language
Because updated version of the Card Game might be published on Internet in the future, Java
language is chosen to be the programming language in this project. Unlike any other
programming language (C, C++, ...), Java is designed to work easily within the World Wide
Web of computers through common browsers. Almost all the browsers are now Javaenabled, that means a activate Java program can come across the network and run on the
client side computers. On the other hand, another important property of Java is that it is
platform-independent.
1.2.4 Client and Server
The client /server model has become one of the central ideas of network computing. More
and more business applications being written today use the client/server model. In general all
the machines on the Internet can be categorized as two types: servers and clients. Those
machines that provide services to other machines are servers. And the machines that used to
connect to those services are clients. The client /server model provides a convenient way to
interconnect programs that distributed efficiently across diferent location especially in a
network. Client/server idea also can be used by programs within a single computer which is
the way the project is programmed and tested. In client/server model, one server is activated
5
JAVA CARD GAME
and awaits client requests. For example, the server program of the project runs first to wait a
request from the client Applet. As soon as a player download the TwentyFour applet and
login successfully, the client forwards the new game request to the server application at the
server machine, the server program processes this request then send 8 integer numbers back
to the client in player’s computer, which displays 4 cards for the player with matching face
values.
1.2.5 TCP/IP and UDP/IP communications
There are two communication protocols which can use for socket programming: datagram
communication and stream communication. The datagram communication protocol, known
as UDP (user data protocol), is a connectionless protocol; the stream communication
protocol is knows as TCP (Transmission Control Protocol), a connection –oriented protocol.
All the communication on the Internet is using either the TCP or UDP. Comparing the
safety between UDP and TCP, TCP is more desirable of the communication protocol for the
client/server model to insurance no missing data during transmission. When the
client/server pair wants to communicate to each other reliably, they need to establish a
connection and send data back and forth over the connection by using TCP/IP. TCP
provides a point-to point chancel to guarantee that data sent from one end the connection
gets to the other end in the same order it was sent.
Generally, coding Java program, which will communicate over the network, is programming
at the application layer. The programmer doesn’t need to concern with the TCP and UDP
layers. Instead, the programmer can use the classes in the java.net package. These classes
provide system-independent network communication.
1.2.6 Socket and programming socket in Java
A socket is one end point of a two-way communication link between two programs running
on the network. To communicate over the TCP, client’s program and server’s program are
both bind a socket to their end of connection. Each reading from and writing to of the client
and the server go thought the socket and then other procession.
1.2.6.1 Server side socket:
Normally the server runs on a specific computer with a socket that is bound to a specific port
number. Once it has successfully bound the port, it listens for incoming connection attempts
through the socket. When it detects a connection request from a client, it accepts the
connection. Upon the acceptance, the server creates a new socket with a different port to
communicate with the client. So that it can continue listening to other connection request by
using the original socket
1
Original socket
Client socket
1. Client’s connection attempt.
2. Server use new connection socket reading
from or writing to information with the client.
Connection socket
Client process
2
Server process
Figure 2: Server socket and client socket
6
JAVA CARD GAME
1.2.6.2 Client side socket
Client send a connection request with the hostname of the computer on which the sever is
running and the port number to which the server is connected. If the connection is accepted,
the socket is successful created and the client can use the socket to communicate with the
server.
1.2.6.3 Ports:
How does the computer know where to forward the data during the communication? The
port is used to map incoming date to a particular running process. Generally speaking, data
transmitted over the Internet is accompanied by addressing information that identifies the
computer and the port for which it is destined. Ports are identified by a 16-bit number as well
as the computer is identified by a 32-bit IP address. Connection-based communication such
as TCP, the server binds a socket to a specific port number. This has the effect of registering
he server with the system to receive all data destined for the port.
here are permanent port numbers known “well-know port number” which is reserved by
some popular service or process. For example Hypertext Transfer Protocol (HTTP)
application has the port number of 80; the range of well-know port is from 0 to 1023.
Port number 9693 is used in this project. The number is randomly chosen.
1.2.6.4 Java socket programming
Java provides class ServerSocket and class Socket in the java.net package. The server
program uses the ServerSocket to implement a socket used to listen to and accept connection
of clients. The class Socket is used in client program with the known hostname and the
assigned port number local to the host.
1.2.7 Multithread
There are several methods and techniques that could be used to implement the client/server
pair. As far as the server concerned, multithread is used in order to realize the server
supporting multiple clients. Because no more than one server socket can listen to a particular
port at one time, the server program tends to be heavily multi-thread. Normally the sever
socket listening on the port will only accept the request of connection. It then passes off the
actual processing of connection to a separate thread. The multithread services the
communication on different port.
Multithread may cause error when there are more than one procession retrieve a data form a
database at same time. This problem is known as “shared data”. Java provides a method to
avoid multithread access the database at same time.
1.2.8 Working steps among of socket, client and the protocol of the project
.
In the project the server side program is always running, when client side program is
executed too, those two processes communicate with each other using inter process
communication. Both processes create and send messages; the processes receive messages
and respond by sending messages back. As all client/server pairs must have some protocol
by which they speak to each other, otherwise, the data that passes back and forth would be
7
JAVA CARD GAME
meaningless. The client/server protocol is used to accomplish the task between the two
processes in this project.
A dedicated computer
Serve
Socket
client/server protocol
Client
port
Fig 3 client/server model in a dedicated computer
As mentioned early, the server runs with a socket that is bound to a port number (“9693” is
used in this project). Once the communication is setup between the server and client, the
client/server protocol works as a translator to make the client and server understanding each
other. Once the client sends a piece of message to server, there is a key word located in the
front. The server received the message then sends it to protocol to process it. The protocol
process the message according to the key word in the message to create a correspond answer
to server who will send it out to client.
1
Login message
Client
protocol
2
Server
Welcome message
1.server sends the login message to protocol
2. protocol process the message ,create the
answer: welcome message
Figure 4 Example of the communication among server, client and protocol
In the project there are only a few key words used in the protocol. The following list
contains those key words server.
Key word
Server’s action
UserID
Finding out this player’s information. Sending the name and the grade back
to client with welcome message.
Randomly generate 8 integers to be the face and value of four cards
Adding a new record into the database for new player, assigned a UerID and
sending it with welcome message out to client
Calculating the result of the mathematic expression, then sending
corresponds message to client. if need, updating the grade in database
Cards
NewRecord
ResultCheck
Fig 5
The key words and server’s action in the client/server protocol
During the conversation between the client and server in the project, once the client send out
a request statement with the keyword, the client’s process start to listen to the response from
the server. Because the server’s response is created according to the keyword sent by the
8
JAVA CARD GAME
client side, so client process knows what kind of format response is coming from the server.
The corresponding getServerMessage() method will receive that response in right way.
CHAPTER TWO OOAD
2 Object Oriented Analysis and Design
The object-oriented analysis and design has following major steps to develop an application:
 Plan and Elaborate ---planning, defining requirements, building prototypes.
 Build--- making a construction of system
 Develop--- implementing the system into use
2.1 Plan and Elaborate phase
The plan and elaborate phase is the preliminary step of the investigation of the OOAD of the
project. It includes the requirement specification, glossary, use case, use case diagram, draft
conceptual diagram and others.
2.1.1 Requirement

Overview statement: The project is to program a java card game TwentyFour to be
played over the Internet.

Customers: any player, who likes to have a quick arithmetic brain.

Goals: The goal of the project is to create a card game, which can implement game
TwentyFour over intranet.

System Function are what the system is supposed to do
Client system function for the player
Ref#
Function
R1.1
Once the TwentyFour is downloaded into the player’s
computer, a login applet is shown and waits the player
entering the user ID.
R1.2
Submit user ID, There is a default userID (guest)
R1.3
Client should display a playing deck with four kinds of
Ace card, all the arithmetic operator and others function
buttons after the player logged in successful.
R1.4
Client displays new set of four playing cards after player
click ask to play a new game..
R1.5
Client should display the card value after player click a
card
R1.6
Client should hid the card after player clicked it
R1.7
The client redisplay all the original four cards if the
player want to replay the game and delete the content
R1.8
The client should renew the entire valuable to be the
initial value after the player replay the game
R1.9
The client should show an error message if the player
Category
Evident
Evident
Evident
Evident
Evident
Evident
Evident
Hidden
Evident
9
JAVA CARD GAME
R1.10
R1.11
R 1.12
R1.13
R1.14
R1.15
R1.16
R1.17
click the card twice
The client should show a error message if the player
click the operator button before clicking the card
The client should be able to find a right answer if there
has at least one solution.
As soon as the applet was downloading by the player,
the client should create an off-screen image array to be
used later.
The client should increate the counter after player click
the card..
If four cards all had been selected, the operator buttons
Can’t be used
If the user doesn’t enter a right user ID, a message will
be displayed to advice the player re-enter the ID
Client should displays a right formula
Client should displays the note of operator clicked by
player
Client system function for communicating with the server
Ref#
Function
R1.20
Client send out user ID to server after player click the
submit button
R1.21
Client create a socket to request a connection to server
R1.22
Client send the player’s formula to server after player
selected all the four cards
R1.23
Client read form the socket to get cards information
form the server
R1.24
Client read from the socket to get the result after player
sends out the formula.
R1.25
Client read the socket to get the response of the server
after player clicked the login button
R1.26
Client ask server to sent out a new set of cards
information
Client System function for sign up a new player
Ref#
Function
R3.1
The signIn applet should display if a new player asked
to register.
R3.2
After the player click the submit button, the signIn
should check all the content before write those
information to server.
R3.3
The signIn should clear all the information the player
had entered after the player clicked Reset button
R3.4
Listen to the socket after sent out the player’
information and display the answering message gotten
form the server
R3.5
Create a socket to connect to the server
R3.6
This applet displays a error message if not all forms are
filled.
Evident
Hidden
Hidden
Hidden
Evident
Evident
Evident
Evident
Category
Hidden
Hidden
Hidden
Hidden
Hidden
Hidden
Hidden
Category
Evident
Evident
Evident
Hidden
Evident
Evident
10
JAVA CARD GAME
Server system function
Ref#
Function
R2.1
The server should create a socket with a port number to
listen the connection request of client
R2.2
The server should always listen to the original socket
R2.3
The server generate 8 random number and write all the
number out to client
R2.4
The server should accept the connection request from
the client and make a new socket to connect with it.
R2.5
The server should check the result of the formula sent
by client.
R2.6
The server connect to the userlist table of the database
db2,
R2.7
The server should be able to find the player’s
information form the table and sent it out to client if a
right userID is available,
R2.8
The server answer a error message if no UseID found
R2.9
The server add a new record to the table if there are new
player had signed in.
R2.10
The server increase or the user’s grade if the formula
equals to ‘24’.
R2.11
Assign a userID for new player.
R2.12
The server send out a erroror message if the the formula
doesn’t equals to ’24’

Category
Hidden
Hidden
Hidden
Hidden
Hidden
Hidden
Hidden
Hidden
Hidden
Hidden
Hidden
Hidden
System attributes:
Attribute
Client operation system
Server operation system
GUI interface
Detail
Java enable platform
Microsoft Windows 98 or higher
Java applet interfaced with through mouse or
keyboard
2.1.2 Identifying Use case
A use case is used to describe the requirements of a system at preliminary step of the
analysis. It is a narrative document that illustrates the sequence of events of an external actor
using a system to complete a process. At the prior analysis stage, only high-level use cases
are written in here as following:
Use Case: Sign In
Actor:
Purpose:
Overview:
Type:
One Player
Add a new player’s information into the database and assign a userID to player
A new player click the Sign In Now in the home page of the project to open a
SignIn applet, submit the information into the database and get a userID
Essential
11
JAVA CARD GAME
Use case: Log in
Actor:
Propose:
Overview:
Type:
One player
Login the player with the userID to the server.
A player submit the userID, server fetch the player’s information from the data
base and inform the client display the playing desk to the player
Essential
Use Case: Play New Game
Actor:
Purpose:
Overview:
Type:
One player
Play a new game, a set of four playing cards are displayed.
The player chooses the NewGame button to start a game. Client gets the cards
Information form server and display them to player
Essential.
Use Case: Calculate TwentyFour
Actor:
One player
Purpose:
The player plays with the cards and operator, sent out the formula and
displaythe result.
Overview:
Player chooses all the four cards with desirable operators, and then sends it to
server to check the result. If the answer is right, The server increase the
player’s grade in database.
Type:
Primary and essential
Use Case : Replay the game
Actor:
One player
Purpose:
The player re-play the cards to create a new formular.
Overview:
After the player found a mistake in the formula, the one button can be chose to
re-appear all the cards to its initial position.
Type:
Secondary
Use case : Setup Server
Actor:
Administrator
Purpose:
Make the server to be active and wait a connection request of a Client.
Overview:
The administrator runs the server application
Type:
Essential
Use Case: Ask a right answer
Actor:
One player
Purpose:
Give one of the formula which can get “24”
Overview: The player press one button to let the system displays an arithmetic formula,
which equals ‘24’.
Type:
Secondary
12
JAVA CARD GAME
2.1.3 Use Case Diagram
Fig 6: use cases diagram
2.1.4 Ranking Use Cases
In general the use cases need to be ranked to get an overview how to arrange use case in
different the develop cycle. The overreaching strategy is first pick up the use case that
significantly influences the core architecture. The high ranking use case is going to be
tackled in first develop cycle. Qualities that are involving significant research and time
increase the ranking of use cases. Based on the ranking criteria, all use cases of the project
are ranked as the following turn (low number with high ranking):
1.
2.
3.
4.
5.
6.
7.
Calculate TwentyFour
Play new game
Setup server
Login In
Sign In
Replay game
Ask the Answer
2.2 Build phase
2.2.1 Analysis Phase
According to the ranking of use cases, the Calclulate TwentyFour use case is tackled first so
that expanded Calculate TwentyFour use case is the starting point at this development cycle.
(Only the Calculate TwentyFour expanded use case is shown in this chapter, the rest of use
cases analyses are referred to the appendix.)
13
JAVA CARD GAME
Expend Use Case
Use Case: Calculate TwentyFour
Actor:
One player
Purpose:
Let the player play with the four cards and operators, send out the formula
Overview:
Player finds a arithmetic formula might get the right answer by choosing all
the four cards with operators. Once all the four cards have been chosen, the
player can send out the formula to let the server check the result. If the
answer is right, server increase the player’s grade in database.
Type:
Primary and essential
Cross
Reference:
Function R1.5, R1.6, R1.13, R1.14, R1.22 R1.24, R2.2, R2.5, R2.6, R2.10,
R1.9, R1.10, R2.12
Typical Course of Events
Actor
Client system
Server system
1.This use case begin
when player click a card
2. Increase the counter number,
display the card value and disappear
the card
3. Choose a operator
4. Show the operator following the
card ‘s value
5. Choose a card
6. Increase the count number, display
the card value and disappear the card
7 Choose a operator
8. Show the operator following the
second card ‘s value
9. Choose a card
10. Increase the counter number,
display the card value and disappear
the card
11.Choose a operator
12. Show the operator following the
third card ‘s value
13 Choose the last card
14. Increase the counter number,
display the card value and disappear
the card
15. Send out the formula
16. Write the formula to server
17. Check the result,
and increase player’s
grade in the database.
And send a feedback to
client.
18. Display the server’s response
Alternative Courses:
¨Line2, 6,10,14: Player chose a operator or other functional button when it is turn to choose a
playing card. An error message displayed to player.
Line 4,8, 12: Player chose a card when it is a turn to choose a operator, a error message
displayed.
Line 17:
The result doesn’t equal “24”, The server system will don’t increase the
player’s grade in the database.
14
JAVA CARD GAME
2.2.2 Conceptual Model
The conceptual model illustrates meaningful concepts in a problem domain, it represent the
real world things, not of software components. This static structure diagram may consist of
concepts, association between concepts and attributes of concepts.
Referring to the RS of the project, some of noun phrasings are selected to be the candidate
concepts or association and attributes. Combining those noun phrasings yields a conceptual
model.
Fig 7 Conceptual model
2.2.3 System Sequence Diagrams
A system sequence diagram is used to illustrate events form the actor to systems. A system
event is eternal input generated by an actor to a system and a system operation is an
operation of the system that executes in response to a system event. The Calculate
TwentyFour use case has three system event: ClickCard, ClickOperator, SentFormula.
Fig 8 Calculate TwentyFour use case system diagram
15
JAVA CARD GAME
2.2.4 Contracts of Calculate TwentyFour Use case
The contracts of use case descript what an operation of system commit to achieve. Though
the definition of contracts, the system behaviors is created.
Contract for ClickCard
Name: ClickCard
Responsibilities: Save the value of the card and display it to the playing desk.
Type: Client System
Cross Reference: Function R1.5, R1.6, R1.13, R1.14, R1.9
Output:
Pre_condition: Client displays four playing card already.
Post_condition:
. TwentyFour.counter modified
. TwentyFour.textField modified
. The state of card modified
. The state of operator modified
. Card:mouseDown accosiation created
Contract for ClickOperator
Name: ClickOperator
Responsibilities: Catch the note of operator and display it to the playing desk.
Type: Client System
Cross Reference: Function R1.17, R1.10;
Output:
Pre_condition: At least one playing card is selected by player.
Post_condition:
.The state of the operator modified.
.The state of the card modified.
.TwentyFour.textField updated.
Contract for SendFormula
Name: SendFormula
Responsibilities: Send the formula to the server, receive the response of server and display it
in the playing desk.
Type: Client/Server System
Cross Reference: Function R1.22, R 1.24, R2.5, R2.6, R2.10, R 2.12
Output:
Pre_condition: All playing cards are selected.
Post_condition:
. A writeToServer association was formed.
. A readFromClient association was formed.
. A writeToClient association was formed.
. A ClientServerPortocol object was created.
. The database connected.
. A findRecord associaton was formed.
. A addGrade association was formed.
. A updateRecord association was formed.
16
JAVA CARD GAME
2.2.5 Sequence Diagram of Calculate TwentyFour Use case
Sequence diagram is one of the most important part of object-orient analysis and design. The
diagram descripts the messages interaction between instances in the class model. Generally
there are two kind of interaction diagram: one is Collaboration and another is the sequence
diagram, which is used in this project as it can more clearly define the chronological order of
messages interaction
The following sequence diagram illustrates the scenario of the player calculating the
twentyfour The staring point for that interactions is to fulfill the post-condition from the
contract defined above.
Fig 9 Calculate TwentyFour Use case sequence diagram
2.3 Design Phase
2.3.1 Real Use Case: considers how to implement the use case. It describes the actual design
of use case in term of concrete input and output technology.
2.3.2 Calculate TwentyFour Real use case
Actor:
Purpose:
Overview:
Type:
One player
Let the player play with the four cards and operators, send out the formula,
Display the result.
Player create an arithmetic formula might get the right answer by choosing
all the four cards with operators. Once all the four cards have been chosen,
the player can send out the formula to the server. If the answer is right,
server increase the player’s grade in database and the Client display the
Server’s response
Primary and essential
17
JAVA CARD GAME
Cross
Reference:
R1.5,R1.6,R1.13,R1.14,R1.22,R1.24,R2.2,R2.5,R2.6,R2.10,R1.9,R1.10,R2.12
A
C
B
-
+
E
*
/
D
Sent
NewGame
Fig 10 Interface of Calculate TwentyFour use case
Typical Course of Events
Actor
Client system
Server system
1.This use case begin
when player click one
card, for example the A
card clicked.
2.Display A in the E, disappear the A
card and modify the counter
3. Choose a operator “+”
4. Display “A +” in the E
5. Choose B card
6 Hide the B card, Display “A+B” in
the E , counter modified
7 Choose a operator “-“
8. Display “A+B-“ in the E
9. Choose C card
10. Display “A+B-C” in the E, hide
the C card and modify the counter
11.Choose a operator “*”
12. Display “A+B-C*” in the E
13 Choose the D card
14. Increase the counter, Display
“A+B-C*D” in the E. Hide D card
too.
15. Choose the button 16. text of the E , prefix with Key 17. Check the result,
Send.
word ,then write it out to server.
and change player’s
grade in the database.
And send a feedback to
client.
18. Display the server’s response
18
JAVA CARD GAME
Alternative Courses:
¨Line2, 6,10,14: Player chose an operator when it is turn to choose a card. An error message
is displayed to player.
Line 4,8, 12: Player choose a card when it is a turn to choose a operator, a error message
is displayed.
Line 17:
The result doesn’t equal “24”, The server system will decrease the player’s
grade in the database.
2.3.3 Design class diagram
The design class diagram illustrates the specifications for software classes and interface. It
extends the illustration that was created on prior analysis designing steps. In contrast with
the conceptual model and the interaction diagram, the design class diagram shows
definitions for software entities and the details of the attributes and associations are added to
the class. Usually the design class diagrams and the interaction diagrams are created in
parallel, even though in this project the presentation of design class diagram follows the
creation of interaction diagram (sequence diagram), many classes, method names and
relationships already had been sketched out in the early design steps. The UML tools, like
Together could update the class model automatically when working on an interaction
diagram.
The following figure (Fig 10) is the class diagram of use case Calculate TwentyFour. The
class model represents a static software model that inherited almost all class, methods,
attributes and visibility between two classes form the sequence diagram and conceptual
model (Fig 7 and Fig 9).
During the analysis, the ideas grow up time by time. The class MultiThread is separated
from the server class dealing with multiple clients’ connection problem at this stage
Fig11 Design class diagram of Calculate TwentyFour Use case
19
JAVA CARD GAME
2.3.4 Summary
As mentioned earlier, use cases organize the iterative development cycles. The other use
cases tackled with lower propriety had been analyzed with the same procession in the next
development cycles after finishing the first iteration cycle for Calculate TwentyFour use
case. Those development cycles are referred in the following appendix.
The main part of this phase involves responsibility assignment, which is done using
sequence diagram and GRASP (General Responsibility Assignment Software Patterns). Poor
assignment would lead to system and components hard to maintain, understand or reuse. A
good assignment should support that the class has low coupling (the class is not dependent
on too many other class, connected loosely) and high cohesion (the class has relatively small
number of methods, highly related the responsibility and does not do a lot of work)
Through the GRASP, the final class diagram is constructed after finished all development
cycles.
Fig12 The final class diagram
2.4 Develop
The section is going to describe the implements in detail at each class in the project. All class
will be constructed using those necessary prosperities from the design of the particular use
case. The classes become heavier while the more use cases being implemented.
20
JAVA CARD GAME
2.4.1 Server class
Server class is constructed firstly to creating a new ServerSocket object to listen on a
specific port “9693”, The ServerSocket is a java.net class which provides a systemindependent implementation of the server side of a client/server socket connection. Threads
start() function is called after the server accepted the connection request of the client. Then
the server is free to listen new connection request from other client on the original port
“9693”. It services multiple client simultaneously
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(9693);
} catch (IOException e) {
System.err.println("Could not listen on port: 9693.");
System.exit(1);
}
new PlayThread(serverSocket.accept()).start();
2.4.2 TwentyFour class
TwentyFour class is extended from the Applet so that it inherits the attributes and behaviors
of the super class. The InitT() function of TwentyFour is connecting with server. It opens a
Socket to connect to the server running on the hostname and port specified and Create a new
printWrite and BufferedReader: out and in.
socket = new Socket("afg4",9693);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader( new InputStreamReader
(socket.getInputStream() ));
For the use cases Play new game and Culculate TwentyFour, some displaying panels are
built to show four cards and operator buttons to player. A two demotion array is created to
store the off-screen images of cards. AddNotify() method is called to make sure the peer of
component was created before createOffScrImage() method is excused. MediaTracker class
is used to load the image asynchronously, two important methods in this class are
addImage(image,id) and waitForID(id). Once the images have been added for tracking,
waitForID() enables tracking.
public void createOffScrImage(Image image1){
try{
cardsImg = getImage(getCodeBase(), "Cards.gif");
cardImages = new Image[4][13];
for (int i = 0;i<4;i++){
for (int j=0;j<13;j++){
cardImages[i][j]=createImage(71,96);//off-Screen image
Graphics g = cardImages[i][j].getGraphics();
g.clipRect(0,0,71,96) ;
g.drawImage(image1,-j*71,-i*96, this);
}}
System.out.println(cardImages[0][12].getWidth(this));
} catch(Exception e) { e.printStackTrace(); }
21
JAVA CARD GAME
This class grew and was modified as the functions of all use cases were implemented step by
step. A corresponding getServerMessage method is called to receive the response of server in
different case. Considering all of the combination of cards and operators in a way which the
result of the combination equaling “24”, the autoCalculation () method is used to find one of
the right answer to player for each game.
2.4.3Card Class
Card class is extended form Canvas class of Java. This class inherits the attributes and
behaviors of the Canvas class. The paint( ) method is overridden to paint the playing cards .
When a player clicks one of the playing card, the mouseDown() method of this class will
responses this action
2.4.4 PlayThread Class
Class PlayThread hands the socket passed by server in order to let the server goes back to
listening for the connection form other clients. The PlayThread object communicates with
the client by reading from and writing to the socket. The string from client side will be
processed in the object of CSProtocol. The StringTokennizer is used to break a string into its
component tokens are separated form one another by delimiters, for example, white-space
characters such as blank, tab, new line and carriage return. Other characters may also be used
as delimiter to separate tokens.
while((clientString =in.readLine())!=null){
StringTokenizer tokens = new StringTokenizer (clientString);
serverString = protocal.processInput(tokens);
out.println(serverString);
out.flush();
}
An instance of class StringTokenizer is created during the while loop. This StringTokenizer
constructor takes the clientString as the argument and creates a StringTokenizer for token, which will
be the parameter of CSProtocol. The Flush() method is used next to the using printerWriter to
inform the client side to prepare to receive the data.
2.4.5 CSProtocol Class
Class CSProtocol implement conversation between client and server. It keeps track of where
the client and the server are in the communication and serves up the server’s response to the
client’s statement and adds or retrieves the data form database. ConnectDatabase( ) method
is excused in the constructor of CSProtocol.
String url= "jdbc:odbc:db2";
String username= "Jean";
String password ="9693";
try {
Class .forName("sun.jdbc.odbc.JdbcOdbcDriver");
con= DriverManager.getConnection( url, username, password);
statement = con.createStatement();
}catch......
22
JAVA CARD GAME
The URL specifies the protocol for the communication “jdbc”, the subprotocol
communication “odbc” and the database name “book”. The forName method of class of
Class is called to load the class definition for the database driver that must be loaded before
the program can connect to the database.
After a instance of CSProtocol was created with the token parameter in the PlayThread class,
according to the keywords as already mentioned before, the token will be manipulated in
different way, then general a corresponding outputLine to be send to client.
2.4.6 player Class
Class player only has the a few information of player in the current version program. It will
be developed in the later version.
CHAPTER THREE DATABASE
3. Database
The database is an integrated collection of data. A database system consists of the date itself,
hardware on which the data resides, the software that controls the storage and retrieval of
data. The database system not only have file-procession capabilities, they organize data in
such a way to satisfy sophisticated queries. SQL (Structured Query Language) is used to
make queries among database.
3.1 Database design and development
The database is composted of tables. Fig.14 illustrates a sample table that contained four
flied :Index, First Name, Last Name, UserID. Fig 15 has three field: Number, UserID and IP
address.
Field
Description
First Name
Last Name
Email
UserID
The player’s first name
The player’s last name
The player’s email address
The player’s ID number, this is the primary key field for this
database
The player’s mark
Grade
Fig 13 Player table in the database
23
JAVA CARD GAME
Field
Description
Number
UserID
The number of online player, type is AutoNumber.
The UserID number, which allows the database to connect
each player with Ip address. It must also appear in the Players table.
The player’s computer address.
IP address
Fig 14 Onlinlist table in the database
According to the Rule of Entity Integrity, the primary key uniquely identifies each record in
a table. Every record in a table must have a unique value in the Primary key field. In the
table Player, the UserID is assigned to be the play’s email address, which is unique over the
Internet. The UserID also appear in the table Onlinelist. It is referred to as a Foreign key to
enable the information from multiple tables to be joined together for analysis purpose. The
following figure illustrates the relationship between a primary key and its corresponding
foreign key.
Player
First name
Last name
Email
UserID
Onlinelist

Number
UserID
IP addresss
1
Fig 15. The relationship between table Player and Onlinelist.
In the project, Microsoft Access database is used. Java program can easy access an Access
database using a relational database management system (DBMS). The Onlinelist table is
not used in the current version of game. It is going to add when the server’s frame will show
the number of online player.
3.2 Structured Query Language (SQL)
SQL is commonly used to make queries among relational database systems. Java has a
capacity to let programmer to write code using SQL queries to access the information in
relational database systems. Within the present version project, the database contains two
tables, so only a few SQL queries had been used in the project.



Retrieving the information that satisfies give criteria
“Select * From Table name Where criteria”
Adding new record into a table
“Insert Into Table name (field1, field2, ……) Values ( value1, value2, …..)”
Update a record in database
“ Update Table name Set field1= value1, field2 = value2, ….Where criteria”
3.3 Registering a database as an ODBC Data Source
To connect with a database in Microsoft Window computer, an ODBC data source must be
registered with through the ODBC Data Source option in the Windows Control Panel.
24
JAVA CARD GAME
CHAPTER FOUR
Tour of Java Card Game –TwentyFour
4. Game TwentyFour Demonstration
This chapter demonstrates an example explaining how to play the Java card game—
TwentyFour. It also is a test to check if the program meets the requirements of the project.
The goal of the game is to construct the number 24 out of those four playing cards. Each
card only can be clicked once and all four cars have to be used. As the rules of the game, the
face cards A , J , Q, K are assigned with the following value: A (Ace) = “1”; J (Jack) =
“11”; Q (Queen) = “ 12”; K (King) = “13”. The starting point of this demonstration is the
home page of this project.
4.1 Web page.
4.1.1 Home page
The home page of this project contains two links: Java Card game—TwentyFour and Sign
Up now. The Sign Up Now links to the SignIn Applet and the TwentyFour link is the
TwentyFour Applet.
4.1.2 Sign Up Now web page
 The player sign in the form to get a uerID.
25
JAVA CARD GAME

Fill the form, then click Submit button. If sign in successful,
Click the
Submit
.
4.1.3 TwentyFour web page
Reset button will clear all information in the
forms in case there is any typing error.

The page first show a login form to let the player login.

If login successful, the playing desk is displayed with four kinds of ace cards.
Player’s grade
26
JAVA CARD GAME
The welcome message is displayed in the textArea , the current grade of player is 1040. The
initial grade is assigned to be 1000 for each player in database.

.After the player clicked the NEWGAME button, four cards should displayed
according to the values generated randomly by server side program.
Clicked
In this case, The first card is a diamond ‘8’, the second card is a heart ‘Ace’, the third one is
club ‘6’, the last one is heart “King”, There are a few combinations of the cards and
operator that can generate the arithmetic result to be “24” , this chapter only demonstrated
one of the method ((13-8-1)*6)as following steps.

First click the heart ‘King’.
The card
disappeared
Displaying the card value 13

Second click the Minus (--) button.
27
JAVA CARD GAME
Displaying ’ – ’

Next click the diamond ‘8’, the card disappeared and value is showed up as expected.
The card
disappeared
Displaying ’ 8 ’

The following step is clicking the Minus(--) button again,
Displaying ’ – ’ again
28
JAVA CARD GAME

Then continuing to click the heat “Ace”, the value 1 should be displayed next to
minus notion.
Displaying ‘ 1’ followed the ‘ - ‘

The next step is clicking the Mutiplay(*) button .
Clicking this button
Displaying ’’*’

The last club’6’ is clicked in here. In this case all the four playing cards aren’t
visible, it is ready to send the arithmetic formula out to server.
29
JAVA CARD GAME
All cards had been chosen , ready
to write the formula to server

Finally, clicking the send button , the server’s response should displayed in the
textArea, As the answer equals to‘24’, so the server programs should update the
grade of the player in the database to be 1050.
Clean button set to be
not able
Displaying the current grade.
4.2 Alternative Courses Testing
In some case the player may make a wrong action during a game. For example, clicked an
undesired card or operator, clicked a card twice etc. The project also has an auto calculation
function to help player find out the answer if players can’t solve the problem .
4.2.1 Login unsuccessful
If the UseID is not available in the database, the error message should be appended in the
textArea to tell the player to re-login.
30
JAVA CARD GAME
4.2.2 Choosing the Clean button to redisplay cards
In case undesired cards or operators chosen,
Clicking Clear button to reset the textField and
display shade ‘9’ and ‘king’ again.
31
JAVA CARD GAME
4.2.3 requesting a right answer
One of important alterative course is the Answer function, which can show one of the right
formulas to player. In this case Send button is disabled, the player has to start a new game.
Answer
Click this button to get a right anwser.
4.2.3 Clicking the card or operator in wrong case.
As the rules of the game TwentyFour, each playing card has to and only can be selected once
during a game. One operator has to be selected after the card. In case the player click one of
the cards after another card , the error message should be shown in textArea.

Clicking two cards in sequence
If click the
heart ’10’ in
this case
Error message
There is a
card already
32
JAVA CARD GAME

Clicking two operators in sequence
If click the
Divide button
Error message

Send button only can be pressed in case all the four cards have already selected.
Otherwise an error message will tell player to make a right click.
If clicked the Send button before
all cards had been selected, error
message shown up
33
JAVA CARD GAME
Conclusion
The goal of the project as mentioned earlier is to create a Java program that contains a card
game (Twenty-four). At the time of writing report, the client/server model game could be
played over the intranet smoothly.
The advantages of the Object Oriented Analysis and Design with Unified Modeling
Language provide an efficient way to build the class construction of the project. After
reversed the final class model using Together 5, the skeleton of class is the starting point of
implementing the Java card game.
At current developing level, the game still remains a few functions to be developed in the
coming future. Duo to the lack of time, those two parentheses function has not been
implemented. (With those function the playing desk would be interfaced more friendly).
The update version of the Java card game might include the following aspect:
1. Implementing the PHP technology to work on other kind of database. This feather may
let the game can be played over Internet more freedom.
3. Adding a chat room.
4. Improve the frame of server more friendly for administer to maintain the game.
5. Add parentheses.
34
Download