Vous êtes sur la page 1sur 35

OnlineGameServer.

java
import
import
import
import
import
import
import
import

java.awt.*;
java.awt.event.*;
javax.swing.*;
java.io.*;
java.net.*;
java.util.Random;
java.util.List;
java.util.ArrayList;

public class onlineGameServer extends JFrame


{
final int NO_OF_PLAYERS = 3;
ArrayList<onlineGameServerThread> players = new ArrayList<onlineGameServerThread>();
ArrayList<String> playerNames = new ArrayList<String>();
int nextPlayer = -1;
String results;
boolean gameCompleted[] = new boolean[NO_OF_PLAYERS];
int totals[] = new int[NO_OF_PLAYERS];
JTextArea outputArea;
private ServerSocket serverSocket;
public onlineGameServer()
{
super("Online Game - Server");
addWindowListener
(
new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);

try
{

// get a server socket & bind to port 7500


serverSocket = new ServerSocket(7500);

}
catch(IOException e) // this is thrown by ServerSocket
{
System.out.println(e);
System.exit(1);
}
// create and add GUI components
Container c = getContentPane();
c.setLayout(new FlowLayout());
// add text output area
outputArea = new JTextArea(18,30);
outputArea.setEditable(false);
outputArea.setLineWrap(true);
outputArea.setWrapStyleWord(true);
outputArea.setFont(new Font("Verdana", Font.BOLD, 11));
c.add(outputArea);
c.add(new JScrollPane(outputArea));
setSize(400,320);
setResizable(false);
setVisible(true);
}
void getPlayers()
{
// output message
addOutput("Server is up and waiting for a connection...");
// game rules
String gameRules = "Rules of the game.\nHow do I play?\nEach player aims to score a total of 36 points.\nOn
each turn you roll three dice

which are totalled and added to your score from the previous turns.\nAs you near 36 you may choose to stand
on your score and not roll again during the game.\nAny player scoring more than 36 immediately loses.\nThe
winner is the player with the score nearest 36 points.";
addOutput("\nGames Rules\n----------------------------------------");
// outputs the length of game rules before compression on the server screen before login
addOutput("Length of original game rules : " + gameRules.length() + " characters\n");
addOutput(gameRules);
// compresses the game rules
CompressedMessage grules = new CompressedMessage(gameRules);
grules.compress();
// outputs the compressed game rules and its length on server screen before login
addOutput("\nLength of compressed game rules : " + grules.getMessage().length() + " characters\n");
addOutput(grules.getMessage());
// arrays containing valid usernames, passwords and gamertags
String usernames[] = {"Robert Smyth", "Mark Allen", "Davina Clark"};
String passwords[] = {"LuQuezz169", "amG4tyz", "Dw1wU9wy"};
String gamerTag [] = {"RSFeed", "Arken", "Darklark"}; // GamerTag will correspond to the player logged on i.e.
Robert Smyth = RSFeed
boolean playerLoggedOn[] = new boolean[NO_OF_PLAYERS];
int playerCount = 0;
while(playerCount < NO_OF_PLAYERS)
{
try
{
/* client has attempted to get a connection to server. The socket will communicate with this client */
Socket client = serverSocket.accept();
// get input & output streams

ObjectInputStream input = new ObjectInputStream(client.getInputStream());


ObjectOutputStream output = new ObjectOutputStream(client.getOutputStream());
// reads encrypted username and password
EncryptedMessage username = (EncryptedMessage)input.readObject();
EncryptedMessage password = (EncryptedMessage)input.readObject();
// outputs encrypted username and password
addOutput("\nLogin Details Received\n----------------------------------------");
addOutput("encrypted username : " + username.getMessage());
addOutput("encrypted password : " + password.getMessage());
// decrypts username and password
username.decrypt();
password.decrypt();
// outputs decrypted username and password
addOutput("decrypted username : " + username.getMessage());
addOutput("decrypted password : " + password.getMessage());
int pos = -1;
boolean found = false;
// check to ensure that player is registered to play
for(int l = 0; l < usernames.length; l++)
// if the username value equals the same username as in the array and the password value
matches the same password value as in the array, and the user is not logged on. Then log them in.
{
if(usernames[l].equals(username.getMessage()) &&
passwords[l].equals(password.getMessage()) && !playerLoggedOn[l])
{
playerLoggedOn[l] = true;
found = true;
pos = l;
}

}
// if the username and password are not valid entried the message beloe will be displayed in
the server window.
if(found == false)
{
addOutput("\nAccess Denied - Due to false boolean value");
}
if(found)//If found is true then...
{
// send Boolean value true to client
output.writeObject(new Boolean(true));
output.writeObject(gameRules);
/* spawn a new thread, i.e. an instance of class onlineGameServerThread
to run parallel with onlineGameServer and handle all communications
with this client */
onlineGameServerThread player = new onlineGameServerThread(input, output,
usernames[pos], gamerTag [pos], playerCount);
// add this thread to the array list
players.add(player);
// start thread - execution of the thread will begin at method run
player.start();
String name = usernames[pos];
playerNames.add(name);
playerCount++;
}
else
/* player is not registered therefore write a Boolean value
false to the output stream */
output.writeObject(new Boolean(false));
}
catch(IOException e) // thrown by Socket

System.out.println(e);
System.exit(1);

}
catch(ClassNotFoundException e) // thrown by method readObject
{
System.out.println(e);
System.exit(1);
}
}
nextPlayer = 0;
// add message to text output area
addOutput("\nAll players connected...Begin Game...\n");
}
void addOutput(String s)
{
// add message to text output area
outputArea.append(s + "\n");
outputArea.setCaretPosition(outputArea.getText().length());
}
synchronized void setNextPlayer(int player)
{
// find if all players have finished play
boolean b = allPlayersCompleted();
// if some players are still playing
if(!b)
{
// set variable to point to the next player in turn
int n = player + 1;
boolean found = false;
while(!found)
{
if(n == NO_OF_PLAYERS)
// if this is the last player go back to first player
n = 0;
// if this player is still in play set this player as the next player
if(!gameCompleted[n])
{
nextPlayer = n;

found = true;
}
n++;
}
}
}
synchronized boolean isMyTurn(int player)
{
// return true if this player is the next player otherwise return false
return player == nextPlayer;
}
synchronized void setGameCompleted(int player)
{
// set array element to true to indicate that this player has finished play
gameCompleted[player] = true;
}
synchronized boolean allPlayersCompleted()
{
boolean continueGame = true;
/* traverse the game completed array and test
values, if all contain true all players are awaiting the results */
for(int i = 0; i < gameCompleted.length; i++)
{
if(!gameCompleted[i])
continueGame = false;
}
return continueGame;
}
synchronized void updateTotal(int player, int[] dice)
{
for(int i = 0; i < dice.length; i++)
// add new dice results to current total
totals[player] += dice[i];
}

synchronized String getMessage(int player)


{
String str;
if(totals[player] > 36)
// if the player has scored more than 36 they immediatly lose the game
str = "Your final total of " + totals[player] + " is greater than 36...please wait for results";
else
// if the player has scored below 36 they can stand on their score
str = "Your total so far is " + totals[player] + " do you wish to stand?";
return str;
}
String getResults(ArrayList<Integer> score36, ArrayList<Integer> under36, ArrayList<Integer> over36)
{
String message = "---------------------------------\nResults\n---------------------------------\n";
/* a player(s) has scored 36 therefore traverse "score 36" category
and list players with scores */
for(Integer n : score36)
{
message += playerNames.get(n) + " scored " + totals[n] + " - ";
/* if the array list contains one element there is only
one winner, otherwise there are 2 or more joint winners */
if(score36.size() == 1)
message += "WINNER\n";
else
message += "JOINT WINNER\n";
}
// traverse "under 36" category and list players with scores
for(Integer n : under36)
message += playerNames.get(n) + " scored " + totals[n] + " - Too Low\n";
// traverse "over 36" category and list players with scores
for(Integer n : over36)
message += playerNames.get(n) + " scored " + totals[n] + " - Too High\n";
return message;
}

String getResults(ArrayList<Integer> under36, ArrayList<Integer> over36)


{
// the winner(s) is in the "under 36" category
String message = "---------------------------------\nResults\n---------------------------------\n";
/* if the array list contains one element there is only
one winner, otherwise there are 2 or more joint winners */
if(under36.size() == 1)
message += playerNames.get(under36.get(0)) + " scored " + totals[under36.get(0)] + " - WINNER\n";
else
{
int highest = Integer.MIN_VALUE;
int win = 0;
/* there is more than 1 player in the "under 36" category therefore
find score closest to 36 and count number of players with this score */
for(int n : under36)
{
if(totals[n] > highest)
{
highest = totals[n];
win = 1;
}
else
{
if(totals[n] == highest)
win++;
}
}
// traverse "under 36" category and list players with scores
for(Integer n : under36)
{
message += playerNames.get(n) + " scored " + totals[n] + " - ";
if(totals[n] == highest)
{
// this player's score matches the winning score
if(win == 1)
// there is only 1 player with the winning score
message += "WINNER\n";
else
/* more than 1 player has the winning score, this
player is a joint winner */
message += "JOINT WINNER\n";

}
else
// this player's score does not match the winning score
message += " Too Low\n";
}
}
// traverse "over 36" category and list players with scores
for(Integer n : over36)
message += playerNames.get(n) + " scored " + totals[n] + " - Too High\n";
return message;
}
String getResults(ArrayList<Integer> over36)
{
// there are no winners
String message = "---------------------------------\nResults\n---------------------------------\nThere Are No Winners!\n";
// traverse "over 36" category and list players with scores
for(Integer n : over36)
message += playerNames.get(n) + " scored " + totals[n] + " - Too High\n";
return message;
}
synchronized void setResults(int p)
{
// initialise 3 array lists to store the player numbers
ArrayList<Integer> score36 = new ArrayList<Integer>();
ArrayList<Integer> under36 = new ArrayList<Integer>();
ArrayList<Integer> over36 = new ArrayList<Integer>();
/* traverse player totals array and sort player into
categories according to score */
for(int i = 0; i < totals.length; i++)
{
if(totals[i] == 36)
/* if this player has scored 36 add their number
to "score 36" category */
score36.add(i);

else
{

if(totals[i] < 36)


/* if this player has scored under 36 add their
number to "under 36" category */
under36.add(i);
else
/* if this player has scored more than 36 add their
number to "over 36" category */
over36.add(i);

}
}
if(!score36.isEmpty())
// a player(s) has scored 36 exactly
results = getResults(score36, under36, over36);
else
{
if(!under36.isEmpty())
/* no players have scored 36 exactly therefore the
winner is in the "under 36" category */
results = getResults(under36, over36);
else
/* no players have scored 36 exactly or is in the
"under 36" category, therefore there are no winners */
results = getResults(over36);
}
}
// main method of class onlineGameServer
public static void main(String args[])
{
onlineGameServer gameServer = new onlineGameServer();
gameServer.getPlayers();
}
// beginning of class onlineGameServerThread
private class onlineGameServerThread extends Thread

ObjectInputStream threadInputStream;
ObjectOutputStream threadOutputStream;
String playerName;
String gameTag;
int playerNumber;
public onlineGameServerThread(ObjectInputStream in, ObjectOutputStream out, String name, String gTag, int

num)
{

// initialise input stream


threadInputStream = in;
// initialise output stream
threadOutputStream = out;
// initialise player name
playerName = name;
//initialise GamerTag
gameTag = gTag;
// initialise player number
playerNumber = num;

}
void goToSleep()
{
try
{
// this thread will sleep for 1000 milliseconds
this.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println(e);
System.exit(1);
}
}
public void run()
{
try
{
/* when method start() is called thread execution will begin at
the following statement */

String broadcastMessage = gameTag + " has got a connection.";


// add message to server text output area
addOutput(broadcastMessage);
// send message to client - for broadcast text output area
broadcast(broadcastMessage);
if(playerNumber == 0 || playerNumber == 1)
// if this is the first or second player, send this message to client
threadOutputStream.writeObject("Welcome to the game " + gameTag + "...you are waiting
for another player(s)...");
else
// if this is the third player, send this message to client
threadOutputStream.writeObject("Welcome to the game " + gameTag + "...other player(s)
connected...please wait");
String clientMessage;
boolean play;
boolean roundOver = false;
while(!roundOver)
{
// find if it is this player's turn to play
play = isMyTurn(playerNumber);
while(!play)
{
// while it is not the player's turn send thread to sleep
goToSleep();
// find if it is this player's turn to play
play = isMyTurn(playerNumber);
}
// send message to client
threadOutputStream.writeObject("Make a roll");
// read dice values from client
int[] dice = (int[])threadInputStream.readObject();
// create message
broadcastMessage = "\n" + gameTag + " has rolled " + dice[0] + "-" + dice[1] + "-" +
dice[2];

// add message to server text output area


addOutput(broadcastMessage);
// send message to client - for broadcast text output area
broadcast(broadcastMessage);
// update player's total
updateTotal(playerNumber, dice);
// get message to progress game
clientMessage = getMessage(playerNumber);
// send message to client
threadOutputStream.writeObject(clientMessage);
if(clientMessage.charAt(clientMessage.length()-1) == '?')
{
/* if the message sent to the client ends with '?'
(i.e. is the player going to stand), read reply */
String reply = (String)threadInputStream.readObject();
if(reply.equals("yes"))
{
addOutput(gameTag + " is standing");
// player is standing, send message to client
threadOutputStream.writeObject("You have chosen to stand on your
score...please wait for results...");
// set player completed marker
setGameCompleted(playerNumber);
// the game is finished, set variable to true to exit loop
roundOver = true;
}
else
{

addOutput(gameTag + " is still playing");


// playing is continuing play, send message to client
threadOutputStream.writeObject("Please wait for your next turn...");

}
}
else
{

addOutput(gameTag + "'s score has exceeded 36 ... out of game");


// set player completed marker

setGameCompleted(playerNumber);
// the game is finished, set variable to true to exit loop
roundOver = true;
}
// set next player to play
setNextPlayer(playerNumber);
} // end while
// find if all players have completed play
play = allPlayersCompleted();
while(!play)
{
// while waiting for other players to finish play send thread to sleep
goToSleep();
// find if all players have completed play
play = allPlayersCompleted();
}
if(results == null)
// if the results string has not yet been completed, set results string
setResults(playerNumber);
addOutput("Sending results to " + gameTag);
// send results string to client
threadOutputStream.writeObject(results);
// send game over command to client
threadOutputStream.writeObject("Game Over");
// close input stream
threadInputStream.close();
// close output stream
threadOutputStream.close();
}
catch(IOException e) // thrown by method readObject, writeObject, close
{
System.out.println(e);
System.exit(1);
}

catch(ClassNotFoundException e) // thrown by method readObject


{
System.out.println(e);
System.exit(1);
}
}
protected void broadcast(String str)
{
synchronized(players)
{
// traverse array list of threads
for (onlineGameServerThread sThread : players)
{
try
{
// send broadcast message to all players
sThread.threadOutputStream.writeObject("B" + str);
}
catch(IOException e) // thrown by method writeObject
{
System.out.println(e);
System.exit(1);
}
}
}
}
} // end of class onlineGameServerThread
} // end of class onlineGameServer

OnlineGameClient.java
//
//
//
//

Laura Gilliland
40038788
Monday
Group B

import
import
import
import
import
import
import

java.awt.*;
java.awt.event.*;
javax.swing.*;
java.net.*;
java.io.*;
java.util.Random;
java.util.Arrays;

public class onlineGameClient extends JFrame


{
// client socket
Socket socket;
// output stream - data sent to the server will be written to this stream
ObjectOutputStream clientOutputStream;
// input stream - data sent by the server will be read from this stream
ObjectInputStream clientInputStream;
// variables for the GUI components of the game
Container c;
JButton logonButton, rollButton, yesButton, noButton, startButton;
ButtonHandler bHandler;
JPanel gamePanel, buttonPanel, messagePanel, outputPanel, logonFieldsPanel, logonButtonPanel, myMovesLabel,
broadcastLabel;
JLabel usernameLabel, passwordLabel, dieImage1, dieImage2, dieImage3;

JTextArea outputArea, playerArea, broadcastArea;


JTextField username;
JPasswordField password;
ImageIcon[] diceImages = {new ImageIcon("blank.gif"), new ImageIcon("die_1.gif"), new ImageIcon("die_2.gif"), new
ImageIcon("die_3.gif"), new ImageIcon("die_4.gif"), new ImageIcon("die_5.gif"), new ImageIcon("die_6.gif")};
public onlineGameClient()
{
super("Online Game - Client");
addWindowListener
(
new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
/* the initial GUI will provide a text field and password field
to enable the user to enter their username and password and
attempt to logon to the game system */
// create and add GUI components
c = getContentPane();
c.setLayout(new BorderLayout());
// GUI components for the username
logonFieldsPanel = new JPanel();
logonFieldsPanel.setLayout(new GridLayout(2,2,5,5));
usernameLabel = new JLabel("Enter Username: ");
logonFieldsPanel.add(usernameLabel);
username = new JTextField(10);
logonFieldsPanel.add(username);
// GUI components for the password
passwordLabel = new JLabel("Enter Password: ");
logonFieldsPanel.add(passwordLabel);

password = new JPasswordField(10);


logonFieldsPanel.add(password);
c.add(logonFieldsPanel,BorderLayout.CENTER);
// panel for the logon button
logonButtonPanel = new JPanel();
logonButton = new JButton("logon");
bHandler = new ButtonHandler();
logonButton.addActionListener(bHandler);
logonButtonPanel.add(logonButton);
c.add(logonButtonPanel, BorderLayout.SOUTH);
setSize(300,125);
setResizable(false);
setVisible(true);
}
void setUpGame(boolean loggedOn, String mess)
{
// remove iniial GUI components (textfield, password field, logon button)
c.remove(logonFieldsPanel);
c.remove(logonButtonPanel);
// if the player has not logged on an error message will be displayed
if(!loggedOn)
{
outputPanel = new JPanel();
outputPanel.setBackground(Color.WHITE);
// add text area
outputArea = new JTextArea(12,30);
outputArea.setEditable(false);
outputArea.setLineWrap(true);
outputArea.setWrapStyleWord(true);
outputArea.setFont(new Font("Verdana", Font.BOLD, 11));
// add message to text area
outputArea.setText(mess);

outputPanel.add(outputArea);
outputPanel.add(new JScrollPane(outputArea));
c.add(outputPanel, BorderLayout.CENTER);
setSize(375,300);
}
else
{

// if the player has logged on the game GUI will be set up


messagePanel = new JPanel();
messagePanel.setLayout(new GridLayout(2,1));
// GUI components for broadcast messages area
JPanel broadcastPanel = new JPanel();
broadcastPanel.setLayout(new BorderLayout());
JLabel broadcastLabel = new JLabel();
broadcastLabel.setText("Broadcast Messages");
broadcastPanel.add(broadcastLabel, BorderLayout.NORTH);
broadcastArea = new JTextArea(15,30);
broadcastArea.setForeground(Color.GRAY);
broadcastArea.setEditable(false);
broadcastArea.setLineWrap(true);
broadcastArea.setWrapStyleWord(true);
broadcastArea.setFont(new Font("Verdana", Font.BOLD, 11));
broadcastPanel.add(broadcastArea, BorderLayout.CENTER);
broadcastPanel.add(new JScrollPane(broadcastArea), BorderLayout.CENTER);
messagePanel.add(broadcastPanel);
// GUI components for player messages area
JPanel playerPanel = new JPanel();
playerPanel.setLayout(new BorderLayout());
JLabel playerLabel = new JLabel();
playerLabel.setText("My Messages");
playerPanel.add(playerLabel, BorderLayout.NORTH);
playerArea = new JTextArea(15,30);
playerArea.setEditable(false);
playerArea.setLineWrap(true);

playerArea.setWrapStyleWord(true);
playerArea.setForeground(Color.BLACK);
playerArea.setFont(new Font("Verdana", Font.BOLD, 11));
// add the decompressed game rules to player message area
playerArea.setText(mess + "\n--------------------------\n");
playerPanel.add(playerArea, BorderLayout.CENTER);
playerPanel.add(new JScrollPane(playerArea), BorderLayout.CENTER);
messagePanel.add(playerPanel);
c.add(messagePanel, BorderLayout.EAST);
// panel that will contain the dice images and game buttons
gamePanel = new JPanel();
gamePanel.setLayout(new GridLayout(4,1));
gamePanel.setBackground(Color.WHITE);
dieImage1 = new JLabel(diceImages[0], SwingConstants.CENTER);
dieImage2 = new JLabel(diceImages[0], SwingConstants.CENTER);
dieImage3 = new JLabel(diceImages[0], SwingConstants.CENTER);
gamePanel.add(dieImage1);
gamePanel.add(dieImage2);
gamePanel.add(dieImage3);
// create game buttons, initially they are disabled
ButtonHandler bHandler = new ButtonHandler();
rollButton = new JButton("roll dice");
rollButton.addActionListener(bHandler);
rollButton.setEnabled(false);
yesButton = new JButton("yes");
yesButton.addActionListener(bHandler);
yesButton.setEnabled(false);
noButton = new JButton("no");
noButton.addActionListener(bHandler);
noButton.setEnabled(false);
buttonPanel = new JPanel();
buttonPanel.setBackground(Color.WHITE);

buttonPanel.add(rollButton);
buttonPanel.add(yesButton);
buttonPanel.add(noButton);
gamePanel.add(buttonPanel);
c.add(gamePanel, BorderLayout.CENTER);
setSize(500,500);
}
setResizable(false);
setVisible(true);
}
void sendLoginDetails()
{
try
{
// get username from text field and encrypt
EncryptedMessage uname = new EncryptedMessage(username.getText());
uname.encrypt();
// get password from password field and encrypt
EncryptedMessage pword = new EncryptedMessage(new String (password.getPassword()));
pword.encrypt();
// send encrypted username and password to server
clientOutputStream.writeObject(uname);
clientOutputStream.writeObject(pword);
}
catch(IOException e) // thrown by methods writeObject
{
System.out.println(e);
System.exit(1);
}
}
void addOutput(String s)
{
// add a message to the player text output area
playerArea.append(s + "\n");
playerArea.setCaretPosition(playerArea.getText().length());

}
void addBroadcast(String s)
{
// add a message to the broadcast text output area
broadcastArea.append(s + "\n");
broadcastArea.setCaretPosition(broadcastArea.getText().length());
}
void getConnections()
{
try
{
// initialise a socket and get a connection to server
socket = new Socket(InetAddress.getLocalHost(), 7500);
// get input & output object streams
clientOutputStream = new ObjectOutputStream(socket.getOutputStream());
clientInputStream = new ObjectInputStream(socket.getInputStream());
/* create a new thread of onlineGameClientThread, sending input
stream variable as a parameter */
onlineGameClientThread t = new onlineGameClientThread(clientInputStream);
// start thread - execution will begin at method run
t.start();
}
catch(UnknownHostException e) // thrown by method getLocalHost
{
System.out.println(e);
System.exit(1);
}
catch(IOException e) // thrown by methods ObjectOutputStream, ObjectInputStream
{
System.out.println(e);
System.exit(1);
}
}
void sendDice()
{
try
{
// an object of class Random is required to create random numbers for the dice

Random randomNumbers = new Random();


// get random numbers and store in an array
int dice[] = new int[3];
for(int i = 0; i < dice.length; i++)
dice[i] = 1 + randomNumbers.nextInt(6);
// sort array
Arrays.sort(dice);
// set the appropriate images
dieImage1.setIcon(diceImages[dice[0]]);
dieImage2.setIcon(diceImages[dice[1]]);
dieImage3.setIcon(diceImages[dice[2]]);
// send the dice values to the server
clientOutputStream.writeObject(dice);
}
catch(IOException e) // thrown by method writeObject
{
System.out.println(e);
System.exit(1);
}
}
void sendMessage(String message)
{
try
{
// send a message (i.e. "yes" or "no") to the server when called
clientOutputStream.writeObject(message);
}
catch(IOException e) // thrown by method writeObject
{
System.out.println(e);
System.exit(1);
}
}
void closeStreams()
{
try
{
// close input stream
clientOutputStream.close();

// close output stream


clientInputStream.close();
// close socket
socket.close();
}
catch(IOException e) // thrown by method close
{
System.out.println(e);
System.exit(1);
}
}
// main method of class onlineGameClient
public static void main(String args[])
{
onlineGameClient gameClient = new onlineGameClient();
gameClient.getConnections();
}

/* ----------------------------------------------------------------------beginning of class onlineGameClientThread


----------------------------------------------------------------------- */
private class onlineGameClientThread extends Thread
{
ObjectInputStream threadInputStream;
public onlineGameClientThread(ObjectInputStream in)
{
// initialise input stream
threadInputStream = in;
}

public void run()


{
// when method start is called thread execution will begin in this method
try
{
/* read Boolean value sent by server - it is converted to
a primitive boolean value */
boolean loggedOn = (Boolean)threadInputStream.readObject();
if(!loggedOn)
{
// call method to close input & output streams & socket
closeStreams();
// call method to display message
setUpGame(loggedOn, "Logon unsuccessful");
}
else
{

// if the client is logged on read the game rules


String rules = (String)threadInputStream.readObject();
// call method to set up game GUI
setUpGame(loggedOn, rules);
String message;
boolean roundOver = false;
// while game is in play
while(!roundOver)
{
// read a message from the server
message = (String)threadInputStream.readObject();
/* if the first character of the message is 'B' this
is a message for the broadcast text area */
if(message.charAt(0) == 'B')
/* remove the first character of the message and
add to broadcast output area */
addBroadcast(message.substring(1, message.length()));

else
// add message to the player text area
addOutput(message);
/* if the last character in the message is '?'
enable the yes button and the no button */
if(message.charAt(message.length()-1) == '?')
{
yesButton.setEnabled(true);
noButton.setEnabled(true);
}
// if player should make a roll enable the roll button
if(message.equals("Make a roll"))
rollButton.setEnabled(true);
// the game is finished, set variable to true to exit loop
if(message.equals("Game Over"))
roundOver = true;
}
// call method to close input & output streams & socket
closeStreams();
}
}
catch(IOException e) // thrown by method readObject
{
System.out.println(e);
System.exit(1);
}
catch(ClassNotFoundException e) // thrown by method readObject
{
System.out.println(e);
System.exit(1);
}
}
} // end of class onlineGameClientThread
// beginning of class ButtonHandler - inner class for event handling
private class ButtonHandler implements ActionListener
{

public void actionPerformed(ActionEvent e)


{
if(e.getSource() == logonButton)
// if the logon button is clicked call method sendLoginDetails
sendLoginDetails();
else
{
if(e.getSource() == rollButton)
{
/* if the logon button is clicked disable the roll
button and call method sendDice */
rollButton.setEnabled(false);
sendDice();
}
else
{
/* if the "yes" or "no" buttons have been clicked disable
both buttons */
yesButton.setEnabled(false);
noButton.setEnabled(false);
/* if the "yes" button was clicked call method sendMessage
with parameter "yes" */
if(e.getSource() == yesButton)
sendMessage("yes");
else
/* if the "no" button was clicked call method sendMessage
with parameter "no" */
sendMessage("no");
}
}
}
} // end of class ButtonHandler
} // end of class onlineGameClient

CompressedMessage.java
import java.io.Serializable;
import java.util.ArrayList;
public class CompressedMessage implements Serializable
{ // this instance variable will store the original, compressed and decompressed message
private String message;
public CompressedMessage(String message)
{
// initialise with original message
this.message = message;
}

public String getMessage()


{
// return (compressed or decompressed) message
return message;
}
private boolean punctuationChar(String str)
{ // check if the last character in the string is a punctuation
return(str.charAt(str.length()-1) == ',' || str.charAt(str.length()-1) == '.');
}
private String getWord(String str)
{ // if last character in string is punctuation then remove
if(punctuationChar(str))
str = str.substring(0, str.length()-1);
return str;
}
public void compress()
{
// array list to temporarily store previous words encountered in text
ArrayList<String> dictionary = new ArrayList<String>();
String compressedStr = "";
// splits message string into words, using space character as delimiter
String[] words = message.split(" \\s*");
for(int i = 0; i < words.length; i++)
{
int foundPos = dictionary.indexOf(getWord(words[i]));
if(foundPos == -1)
{ // word is not found therefore add to end of array list
dictionary.add(getWord(words[i]));
// add word to compressed message
compressedStr += getWord(words[i]);
}
else
/* match found in array list - add corresponding position

of word to compressed message */


compressedStr += foundPos;
if(punctuationChar(words[i]))
compressedStr += words[i].charAt(words[i].length()-1);
compressedStr += " ";
}
// store compressed message in instance variable
message = compressedStr;
}
public void decompress()
{
// array list to temporarily store previous words encountered in text
ArrayList<String> dictionary = new ArrayList<String>();
String decompressedStr = "";
int position;
// splits message string into words, using space character as delimiter
String[] words = message.split(" \\s*");
for(int i = 0; i < words.length; i++)
{
// test if the first character of this string is a digit
if (words[i].charAt(0) >= '0' && words[i].charAt(0) <= '9')
{

/* it is a digit - this indicates that this string represents


the position of a word in the previous words list.
convert this string to an int value */
position = Integer.parseInt(getWord(words[i]));
// get word at this position & add to decompressed message
decompressedStr += dictionary.get(position);

else
{

// this string is a word - add to previous words list


dictionary.add(getWord(words[i]));
// add word to compressed message
decompressedStr += getWord(words[i]);

}
if(punctuationChar(words[i]))
decompressedStr += words[i].charAt(words[i].length()-1);
decompressedStr += " ";
if(words[i].equals("36"))
dictionary.add(words[i]);
decompressedStr = decompressedStr + dictionary.add(words[i]);
}
// store decompressed message in instance variable
message = decompressedStr;
}
}

EncryptedMessage.java
import java.io.Serializable;
public class EncryptedMessage implements Serializable
{ // this instance variable will store the original, encrypted and decrypted message
private String message;
// this variable stores the key
static String KEY = "cable";
public EncryptedMessage(String message)
{ // initialise original message
this.message = message;
}
public String getMessage()
{ // return (encrypted or decrypted) message
return message;
}

public void encrypt()


{ /* this variable stores the letters of the alphabet and alphanumerical (in order) as a
string - this string will be used to encrypt text */
String charSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789";
String cipherText = "";
for(int i = 0; i < message.length(); i++)
{
// find position of plaintext character in the character set
int plainTxtCh = charSet.indexOf(message.charAt(i));
// get position of next key character
int keyPos = i % KEY.length();
// find position of key character in the character set
int keyCh = charSet.indexOf(KEY.charAt(keyPos));
/* add key character to plaintext character - this shifts the
plaintext character - then divide by length of
character reference set and get remainder to wrap around */
int cipherTxtCh = (plainTxtCh + keyCh) % 63;
/* get character at corresponding position in character reference
set and add to cipherText */
char c = charSet.charAt(cipherTxtCh);
cipherText += c;
}
message = cipherText;
}
public void decrypt()
{ /* this variable stores the letters of the alphabet and alphanumerical (in order) as a
string - this string will be used to decrypt text */
String charSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789";
String plainText = "";
for(int i = 0; i < message.length(); i++)
{
// find position of ciphertext character

int cipherTxtCh = charSet.indexOf(message.charAt(i));


// get position of next key character
int keyPos = i % KEY.length();
// find position of key character in the character set
int keyCh = charSet.indexOf(KEY.charAt(keyPos));
/* subtract original shift from character reference set length to
get new shift, add shift to ciphertext character then
divide by character reference set length and get remainder to
wrap around */
int plainTxtCh = (cipherTxtCh + (charSet.length() - keyCh)) % 63;
/* get character at corresponding position in character reference
set and add to plainText */
char c = charSet.charAt(plainTxtCh);
plainText += c;
}
message = plainText;
}
}

Vous aimerez peut-être aussi