Kamis, 14 April 2011

Loving U It Hurt Sometimes

Mencintaimu adalah hal terindah dalam hidupku
tapi kadang kau melukaiku dengan senyummu
kasihmu bukan untukku

kau mencintainya tapi sadarkah engkau bahwa dia tak mencintaimu
akulah satu-satunya orang yang mencintaimu lebih dari apapun
hatiku hanya untukmu, jiwa ragaku hanya untukmu
tapi kau palingkan itu dariku

bila aku didekatmu aku merasa bahagia
tapi sebaliknya bila kau didekatku kau tak merasa apa-apa
inikah cinta yang dilukai

aku percaya suatu hari kau akan menjadi milikku
Read more

Aplikasi Game Tic Tac Toe Berbasis Java Socket

DESKRIPSI UMUM SISTEM
Sistem yang dibangun melibatkan komponen client dan server. Pemain berada pada sisi client sedangkan pada sisi server terdapat server untuk game. Komponen – komponen tersebut dapat dijelaskan sebagai berikut :
• Permainan (game) menggunakan teknologi java.
• Pemain membangun koneksi persisten dengan server game yang menggunakan teknologi Server Socket. Koneksi tersebut menggunakan protokol Server Socket. Server dapat memonitor pemain-pemain yang sedang online, dapat mengirim pesan ke seluruh pemain, mempunyai hak untuk memutuskan koneksi pemain, serta dapat me-restart aplikasi server.
• Pemain dapat melakukan interaksi dengan pemain lain setelah tersambung dengan server game.
• Server game memegang kontrol komunikasi antara pemain yang tersambung dengannya.
• Server game memegang kendali segala perhitungan pada saat permainan berlangsung. Server ini menggunakan teknologi Server socket dan java socket.
SKENARIO SISTEM
1. Terdiri dari satu server dan client.
2. Client yang baru melakukan koneksi ke server akan di-broadcast ke seluruh client aktif masuk ke dalam waiting list.
3. Client dapat menantang client lain dalam waiting list untuk bermain tic tac toe.
4. Client yang telah memulai sesi game akan hilang dari waiting list dan server akan memberikan datagram & port tersendiri.
5. Bila suatu sesi permainan selesai client akan kembali masuk ke waiting list.

Implementasi pada Game Tic Tac Toe

Tic Tac Toe Dedicated Server

// Fig. 17.8: TicTacToeServer.java
// This class maintains a game of Tic-Tac-Toe for two
// client applets.
// Java core packages
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;

// Java extension packages
import javax.swing.*;

public class TicTacToeServer extends JFrame
{
private byte board[];
private JTextArea outputArea;
private Player players[];
private ServerSocket server;
private int currentPlayer;

// set up tic-tac-toe server and GUI that displays messages
public TicTacToeServer()
{
super( "Tic-Tac-Toe Server" );

board = new byte[ 9 ];
players = new Player[ 2 ];
currentPlayer = 0;

// set up ServerSocket
try
{
server = new ServerSocket( 5000, 2 );
}

// process problems creating ServerSocket
catch( IOException ioException )
{
ioException.printStackTrace();
System.exit( 1 );
}

// set up JTextArea to display messages during execution
outputArea = new JTextArea();
getContentPane().add( outputArea, BorderLayout.CENTER );
outputArea.setText( "Server awaiting connections\n" );

setSize( 300, 300 );
setVisible( true );
}

// wait for two connections so game can be played
public void execute()
{
// wait for each client to connect
for ( int i = 0; i < players.length; i++ )
{

// wait for connection, create Player, start thread
try
{
players[ i ] = new Player( server.accept(), i );
players[ i ].start();
}

// process problems receiving connection from client
catch( IOException ioException )
{
ioException.printStackTrace();
System.exit( 1 );
}
}

// Player X is suspended until Player O connects.
// Resume player X now.
synchronized ( players[ 0 ] )
{
players[ 0 ].setSuspended( false );
players[ 0 ].notify();
}

} // end method execute

// display a message in outputArea
public void display( String message )
{
outputArea.append( message + "\n" );
}

// Determine if a move is valid.
// This method is synchronized because only one move can be
// made at a time.
public synchronized boolean validMove(
int location, int player )
{
boolean moveDone = false;

// while not current player, must wait for turn
while ( player != currentPlayer )
{

// wait for turn
try
{
wait();
}

// catch wait interruptions
catch( InterruptedException interruptedException )
{
interruptedException.printStackTrace();
}
}

// if location not occupied, make move
if ( !isOccupied( location ) )
{

// set move in board array
board[ location ] =
( byte ) ( currentPlayer == 0 ? 'X' : 'O' );

// change current player
currentPlayer = ( currentPlayer + 1 ) % 2;

// let new current player know that move occurred
players[ currentPlayer ].otherPlayerMoved( location );

// tell waiting player to continue
notify();

// tell player that made move that the move was valid
return true;
}

// tell player that made move that the move was not valid
else
return false;
}

// determine whether location is occupied
public boolean isOccupied( int location )
{
if ( board[ location ] == 'X' || board [ location ] == 'O' )
return true;
else
return false;
}

// place code in this method to determine whether game over
public boolean gameOver()
{
return false;
}
// execute application
public static void main( String args[] )
{
TicTacToeServer application = new TicTacToeServer();

application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );

application.execute();
}

// private inner class Player manages each Player as a thread
private class Player extends Thread
{
private Socket connection;
private DataInputStream input;
private DataOutputStream output;
private int playerNumber;
private char mark;
protected boolean suspended = true;

// set up Player thread
public Player( Socket socket, int number )
{
playerNumber = number;

// specify player's mark
mark = ( playerNumber == 0 ? 'X' : 'O' );

connection = socket;

// obtain streams from Socket
try
{
input = new DataInputStream(
connection.getInputStream() );
output = new DataOutputStream(
connection.getOutputStream() );
}

// process problems getting streams
catch( IOException ioException )
{
ioException.printStackTrace();
System.exit( 1 );
}
}

// send message that other player moved; message contains
// a String followed by an int
public void otherPlayerMoved( int location )
{
// send message indicating move
try
{
output.writeUTF( "Opponent moved" );
output.writeInt( location );
}

// process problems sending message
catch ( IOException ioException )
{
ioException.printStackTrace();
}
}

// control thread's execution
public void run()
{
// send client message indicating its mark (X or O),
// process messages from client
try
{
display( "Player " + ( playerNumber == 0 ?
'X' : 'O' ) + " connected" );

// send player's mark
output.writeChar( mark );

// send message indicating connection
output.writeUTF( "Player " +
( playerNumber == 0 ? "X connected\n" :
"O connected, please wait\n" ) );

// if player X, wait for another player to arrive
if ( mark == 'X' )
{
output.writeUTF( "Waiting for another player" );

// wait for player O
try
{
synchronized( this )
{
while ( suspended )
wait();
}
}

// process interruptions while waiting
catch ( InterruptedException exception )
{
exception.printStackTrace();
}

// send message that other player connected and
// player X can make a move
output.writeUTF(
"Other player connected. Your move." );
}

// while game not over
while ( ! gameOver() )
{

// get move location from client
int location = input.readInt();

// check for valid move
if ( validMove( location, playerNumber ) )
{
display( "loc: " + location );
output.writeUTF( "Valid move." );
}
else
output.writeUTF( "Invalid move, try again" );
}

// close connection to client
connection.close();
}

// process problems communicating with client
catch( IOException ioException )
{
ioException.printStackTrace();
System.exit( 1 );
}
}

// set whether or not thread is suspended
public void setSuspended( boolean status )
{
suspended = status;
}

} // end class Player

} // end class TicTacToeServer


Tic Tac Toe Client

TicTacToe.java
public class Tictactoe {

public static void main(String[] args) {
// Create application frame.
TictactoeFrame frame = new TictactoeFrame();

// Show frame
frame.setVisible(true);
}
}



TicTacToeFrame.java
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.lang.Thread;

import javax.swing.*;

/**
* Sample application using Frame.
*
* @author
* @version 1.00 05/05/02
*/
public class TictactoeFrame extends JFrame implements Runnable{

private JTextField idField;
private JTextArea displayArea;
private JPanel boardPanel, panel2;
private Square board[][], currentSquare;
private Socket connection;
private DataInputStream input;
private DataOutputStream output;
private Thread outputThread;
private char myMark;
private boolean myTurn;
private String IPAddress;

/**
* The constructor.
*/
public TictactoeFrame() {

Container container = new Container();

// set up JTextArea to display messages to user
displayArea = new JTextArea( 4, 30 );
displayArea.setEditable( false );
this.getContentPane().add(new JScrollPane( displayArea ),BorderLayout.SOUTH);
//container.add( new JScrollPane( displayArea ),BorderLayout.SOUTH );

// set up panel for squares in board
boardPanel = new JPanel();
boardPanel.setLayout( new GridLayout( 3, 3, 0, 0 ) );

// create board
board = new Square[ 3 ][ 3 ];

// When creating a Square, the location argument to the
// constructor is a value from 0 to 8 indicating the
// position of the Square on the board. Values 0, 1,
// and 2 are the first row, values 3, 4, and 5 are the
// second row. Values 6, 7, and 8 are the third row.
for ( int row = 0; row < board.length; row++ )
{

for ( int column = 0; column < board[ row ].length; column++ )
{

// create Square
board[ row ][ column ] =
new Square( ' ', row * 3 + column );

boardPanel.add( board[ row ][ column ] );
}

}

// textfield to display player's mark
idField = new JTextField();
idField.setEditable( false );
container.add( idField, BorderLayout.NORTH );
this.getContentPane().add(idField, BorderLayout.NORTH);

// set up panel to contain boardPanel (for layout purposes)
panel2 = new JPanel();
panel2.add( boardPanel, BorderLayout.CENTER );
container.add( panel2, BorderLayout.CENTER );

IPAddress=null;
IPAddress=JOptionPane.showInputDialog(null,"Masukkan Ip Server anda",null);
if (IPAddress==null)
System.exit(0);

this.getContentPane().add(panel2, BorderLayout.CENTER);


/*MenuBar menuBar = new MenuBar();
Menu menuFile = new Menu();
MenuItem menuFileExit = new MenuItem();

menuFile.setLabel("File");
menuFileExit.setLabel("Exit");

// Add action listener.for the menu button
menuFileExit.addActionListener
(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
TictactoeFrame.this.windowClosed();
}
}
);
menuFile.add(menuFileExit);
menuBar.add(menuFile);

setTitle("Tictactoe");
setMenuBar(menuBar);
*/
setSize(new Dimension(400, 400));


// Add window listener.
this.addWindowListener
(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
TictactoeFrame.this.windowClosed();
System.exit(0);
}
}
);
show();
this.start();

}


public void start(){


try
{

// make connection
//connection = new Socket(InetAddress.getByName( "127.0.0.1" ), 5000 );
connection = new Socket(InetAddress.getByName( IPAddress ), 5000 );

// get streams
input = new DataInputStream(
connection.getInputStream() );
output = new DataOutputStream(
connection.getOutputStream() );
}

// catch problems setting up connection and streams
catch ( IOException ioException )
{
ioException.printStackTrace();
}

// create and start output thread
outputThread = new Thread( this );
outputThread.start();

}




public void run(){


try
{
myMark = input.readChar();
idField.setText( "You are player \"" + myMark + "\"" );
myTurn = ( myMark == 'X' ? true : false );
}

// process problems communicating with server
catch ( IOException ioException )
{
ioException.printStackTrace();
}

// receive messages sent to client and output them
while ( true )
{

// read message from server and process message
try
{
String message = input.readUTF();
processMessage( message );
}

// process problems communicating with server
catch ( IOException ioException )
{
ioException.printStackTrace();
}
}
}

/**
* Shutdown procedure when run as an application.
*/
protected void windowClosed() {

// TODO: Check if it is safe to close the application

// Exit application.
System.exit(0);
}


public void processMessage( String message )
{
// valid move occurred
if ( message.equals( "Valid move." ) )
{
displayArea.append( "Valid move, please wait.\n" );

// set mark in square from event-dispatch thread
SwingUtilities.invokeLater(

new Runnable()
{

public void run()
{
currentSquare.setMark( myMark );
}

}

); // end call to invokeLater
}

// invalid move occurred
else if ( message.equals( "Invalid move, try again" ) )
{
displayArea.append( message + "\n" );
myTurn = true;
}

// opponent moved
else if ( message.equals( "Opponent moved" ) )
{

// get move location and update board
try
{
final int location = input.readInt();

// set mark in square from event-dispatch thread
SwingUtilities.invokeLater(

new Runnable()
{

public void run()
{
int row = location / 3;
int column = location % 3;

board[ row ][ column ].setMark(
( myMark == 'X' ? 'O' : 'X' ) );
displayArea.append(
"Opponent moved. Your turn.\n" );
}

}

); // end call to invokeLater

myTurn = true;
}

// process problems communicating with server
catch ( IOException ioException )
{
ioException.printStackTrace();
}

}

// simply display message
else
displayArea.append( message + "\n" );

displayArea.setCaretPosition(
displayArea.getText().length() );

} // end method processMessage

// send message to server indicating clicked square
public void sendClickedSquare( int location )
{
if ( myTurn )
{

// send location to server
try
{
output.writeInt( location );
myTurn = false;
}

// process problems communicating with server
catch ( IOException ioException )
{
ioException.printStackTrace();
}
}
}

// set current Square
public void setCurrentSquare( Square square )
{
currentSquare = square;
}



private class Square extends JPanel
{
private char mark;
private int location;

public Square( char squareMark, int squareLocation )
{
mark = squareMark;
location = squareLocation;

addMouseListener(

new MouseAdapter()
{

public void mouseReleased( MouseEvent e )
{
setCurrentSquare( Square.this );
sendClickedSquare( getSquareLocation() );
}

} // end anonymous inner class

); // end call to addMouseListener

} // end Square constructor

// return preferred size of Square
public Dimension getPreferredSize()
{
return new Dimension( 30, 30 );
}

// return minimum size of Square
public Dimension getMinimumSize()
{
return getPreferredSize();
}

// set mark for Square
public void setMark( char newMark )
{
mark = newMark;
repaint();
}

// return Square location
public int getSquareLocation()
{
return location;
}

// draw Square
public void paintComponent( Graphics g )
{
super.paintComponent( g );

g.drawRect( 0, 0, 29, 29 );
g.drawString( String.valueOf( mark ), 11, 20 );
}

} // end class Square

}
Read more