Académique Documents
Professionnel Documents
Culture Documents
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;
try
{
}
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
}
// 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];
}
}
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(!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)
{
}
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 */
}
}
else
{
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);
}
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;
outputPanel.add(outputArea);
outputPanel.add(new JScrollPane(outputArea));
c.add(outputPanel, BorderLayout.CENTER);
setSize(375,300);
}
else
{
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
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
{
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;
}
else
{
}
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;
}