Sunday, July 29, 2007

A game of Tic-Tac-Toe that can be played between two client applets

This Java swing tip illustrates a game of Tic-Tac-Toe that can be played between two client applets. The two clients are connected through a socket. Therefore, developer may also customize this game to be played over a local network or internet.

import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import javax.swing.*;

public class TicTacToeServer extends JFrame {

private byte board[];
private boolean xMove;
private JTextArea output;
private Player players[];
private ServerSocket server;
private int currentPlayer;

public TicTacToeServer()
{
super( "Tic-Tac-Toe Server" );

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

// set up ServerSocket
try {
server = new ServerSocket( 5000, 2 );
}
catch( IOException e ) {
e.printStackTrace();
System.exit( 1 );
}

output = new JTextArea();
getContentPane().add( output, BorderLayout.CENTER );
output.setText( "Server awaiting connections\n" );

setSize( 300, 300 );
show();
}

// wait for two connections so game can be played
public void execute()
{
for ( int i = 0; i <>) {
try {
players[ i ] =
new Player( server.accept(), this, i );
players[ i ].start();
}
catch( IOException e ) {
e.printStackTrace();
System.exit( 1 );
}
}

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

}

public void display( String s )
{
output.append( s + "\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 loc,
int player )
{
boolean moveDone = false;

while ( player != currentPlayer ) {
try {
wait();
}
catch( InterruptedException e ) {
e.printStackTrace();
}
}

if ( !isOccupied( loc ) ) {
board[ loc ] =
(byte) ( currentPlayer == 0 ? 'X' : 'O' );
currentPlayer = ( currentPlayer + 1 ) % 2;
players[ currentPlayer ].otherPlayerMoved( loc );
notify(); // tell waiting player to continue
return true;
}
else
return false;
}

public boolean isOccupied( int loc )
{
if ( board[ loc ] == 'X' || board [ loc ] == 'O' )
return true;
else
return false;
}

public boolean gameOver()
{
// Place code here to test for a winner of the game
return false;
}

public static void main( String args[] )
{
TicTacToeServer game = new TicTacToeServer();

game.addWindowListener( new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);

game.execute();
}
}

// Player class to manage each Player as a thread
class Player extends Thread {
private Socket connection;
private DataInputStream input;
private DataOutputStream output;
private TicTacToeServer control;
private int number;
private char mark;
protected boolean threadSuspended = true;

public Player( Socket s, TicTacToeServer t, int num )
{
mark = ( num == 0 ? 'X' : 'O' );

connection = s;

try {
input = new DataInputStream(
connection.getInputStream() );
output = new DataOutputStream(
connection.getOutputStream() );
}
catch( IOException e ) {
e.printStackTrace();
System.exit( 1 );
}

control = t;
number = num;
}

public void otherPlayerMoved( int loc )
{
try {
output.writeUTF( "Opponent moved" );
output.writeInt( loc );
}
catch ( IOException e ) { e.printStackTrace(); }
}

public void run()
{
boolean done = false;

try {
control.display( "Player " +
( number == 0 ? 'X' : 'O' ) + " connected" );
output.writeChar( mark );
output.writeUTF( "Player " +
( number == 0 ? "X connected\n" :
"O connected, please wait\n" ) );

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

try {
synchronized( this ) {
while ( threadSuspended )
wait();
}
}
catch ( InterruptedException e ) {
e.printStackTrace();
}

output.writeUTF(
"Other player connected. Your move." );
}

// Play game
while ( !done ) {
int location = input.readInt();

if ( control.validMove( location, number ) ) {
control.display( "loc: " + location );
output.writeUTF( "Valid move." );
}
else
output.writeUTF( "Invalid move, try again" );

if ( control.gameOver() )
done = true;
}

connection.close();
}
catch( IOException e ) {
e.printStackTrace();
System.exit( 1 );
}
}
}

// Client for the TicTacToe program
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import javax.swing.*;

// Client class to let a user play Tic-Tac-Toe with
// another user across a network.
public class TicTacToeClient extends JApplet
implements Runnable {
private JTextField id;
private JTextArea display;
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;

// Set up user-interface and board
public void init()
{
display = new JTextArea( 4, 30 );
display.setEditable( false );
getContentPane().add( new JScrollPane( display ),
BorderLayout.SOUTH );

boardPanel = new JPanel();
GridLayout layout = new GridLayout( 3, 3, 0, 0 );
boardPanel.setLayout( layout );

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 <>)
{
for ( int col = 0;
col <>[ row ].length; col++ ) {
board[ row ][ col ] =
new Square( ' ', row * 3 + col );
board[ row ][ col ].addMouseListener(
new SquareListener(
this, board[ row ][ col ] ) );

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

id = new JTextField();
id.setEditable( false );

getContentPane().add( id, BorderLayout.NORTH );

panel2 = new JPanel();
panel2.add( boardPanel, BorderLayout.CENTER );
getContentPane().add( panel2, BorderLayout.CENTER );
}

// Make connection to server and get associated streams.
// Start separate thread to allow this applet to
// continually update its output in text area display.
public void start()
{
try {
connection = new Socket(
InetAddress.getByName( "127.0.0.1" ), 5000 );
input = new DataInputStream(
connection.getInputStream() );
output = new DataOutputStream(
connection.getOutputStream() );
}
catch ( IOException e ) {
e.printStackTrace();
}

outputThread = new Thread( this );
outputThread.start();
}

// Control thread that allows continuous update of the
// text area display.
public void run()
{
// First get player's mark (X or O)
try {
myMark = input.readChar();
id.setText( "You are player \"" + myMark + "\"" );
myTurn = ( myMark == 'X' ? true : false );
}
catch ( IOException e ) {
e.printStackTrace();
}

// Receive messages sent to client
while ( true ) {
try {
String s = input.readUTF();
processMessage( s );
}
catch ( IOException e ) {
e.printStackTrace();
}
}
}

// Process messages sent to client
public void processMessage( String s )
{
if ( s.equals( "Valid move." ) ) {
display.append( "Valid move, please wait.\n" );
currentSquare.setMark( myMark );
currentSquare.repaint();
}
else if ( s.equals( "Invalid move, try again" ) ) {
display.append( s + "\n" );
myTurn = true;
}
else if ( s.equals( "Opponent moved" ) ) {
try {
int loc = input.readInt();

board[ loc / 3 ][ loc % 3 ].setMark(
( myMark == 'X' ? 'O' : 'X' ) );
board[ loc / 3 ][ loc % 3 ].repaint();

display.append(
"Opponent moved. Your turn.\n" );
myTurn = true;
}
catch ( IOException e ) {
e.printStackTrace();
}
}
else
display.append( s + "\n" );

display.setCaretPosition(
display.getText().length() );
}

public void sendClickedSquare( int loc )
{
if ( myTurn )
try {
output.writeInt( loc );
myTurn = false;
}
catch ( IOException ie ) {
ie.printStackTrace();
}
}

public void setCurrentSquare( Square s )
{
currentSquare = s;
}
}

// Maintains one square on the board
class Square extends JPanel {
private char mark;
private int location;

public Square( char m, int loc)
{
mark = m;
location = loc;
setSize ( 30, 30 );

setVisible(true);
}

public Dimension getPreferredSize() {
return ( new Dimension( 30, 30 ) );
}

public Dimension getMinimumSize() {
return ( getPreferredSize() );
}

public void setMark( char c ) { mark = c; }

public int getSquareLocation() { return location; }

public void paintComponent( Graphics g )
{
super.paintComponent( g );
g.drawRect( 0, 0, 29, 29 );
g.drawString( String.valueOf( mark ), 11, 20 );
}
}

class SquareListener extends MouseAdapter {
private TicTacToeClient applet;
private Square square;

public SquareListener( TicTacToeClient t, Square s )
{
applet = t;
square = s;
}

public void mouseReleased( MouseEvent e )
{
applet.setCurrentSquare( square );
applet.sendClickedSquare( square.getSquareLocation() );
}
}

source: http://java-tips.org

Saturday, July 28, 2007

Cry on my shoulder

Download here

If the hero, never comes to you
If you need someone, you're feeling blue
If you wait for love, and you're alone
If you call your friends, nobody's home
You can rum away, but you can't hide
Through a storm and through a lonely night
Then I'll show you there's a destiny
The best things in life, they are free

But if you wanna cry: cry on my shoulder
If you need someone, who cares for you
If you're feeling sad, your heart gets colder
Yes I show you what real love can do

If your sky is grey oh let me know
There's a place in heaven, where we'll go
If heaven is, a million years away
Oh just call me and I'll make your day
When the nights are getting cold and blue
When the days are getting hard for you
I will always stay by your side
I promise you, I'll never hide

But if you wanna cry: cry on my shoulder
If you need someone, who cares for you
If you're feeling sad, your heart gets colder
Yes I show you what real love can do

But if you wanna cry: cry on my shoulder
If you need someone, who cares for you
If you're feeling sad, your heart gets colder
Yes I show you what real love can do

Sunday, July 15, 2007

Take me home coutry road

Download here

This song appears on twenty-one albums, and was first released on the poems, prayers and promises album. this version has also been released on the very best of john denver (double cd), this is
Denver, the country roads collection and the rocky mountain collection albums. it has been rerecorded on the greatest hits vol 1, take me home country roads & other hits, changes, favourites
Ce of america, john denver (italian) and country classics albums. it has been rerecorded again on the a portrait and the john denver collection - take me home, country roads albums, and again on
Love again and a celebration of life albums. live versions also appear on the an evening with john denver, live in london, live at the sydney opera house, the wildlife concert and the best of jo
Nver live albums.

Almost heaven, west virginia
Blue ridge mountains
Shenandoah river -
Life is old there
Older than the trees
Younger than the mountains
Growin like a breeze

Country roads, take me home
To the place I belong
West virginia, mountain momma
Take me home, country roads

All my memories gathered round her
Miners lady, stranger to blue water
Dark and dusty, painted on the sky
Misty taste of moonshine
Teardrops in my eye

Country roads, take me home
To the place I belong
West virginia, mountain momma
Take me home, country roads

I hear her voice
In the mornin hour she calls me
The radio reminds me of my home far away
And drivin down the road I get a feelin
That I should have been home yesterday, yesterday

Country roads, take me home
To the place I belong
West virginia, mountain momma
Take me home, country roads

Country roads, take me home
To the place I belong
West virginia, mountain momma
Take me home, country roads
Take me home, now country roads
Take me home, now country roads

Thursday, July 05, 2007

How to copy one file to another through channel

This Java tips illustrates a method of copying one file to another file through channel. A channel is created both on source as well as destination and then the file is copied between those two channels.
try {

// Create channel on the source
FileChannel srcChannel =
new FileInputStream("srcFilename").getChannel();

// Create channel on the destination
FileChannel dstChannel =
new FileOutputStream("dstFilename").getChannel();

// Copy file contents from source to destination
dstChannel.transferFrom(srcChannel, 0, srcChannel.size());

// Close the channels
srcChannel.close();
dstChannel.close();

} catch (IOException e) {
}

source: http://java-tips.org

Wednesday, July 04, 2007

How to play a sound file in an Applet

This Java tip illustrates a method of playing audio files in Java applets. Developer needs to to take care that the audio clip resides on the same web server where your applet resides. Some time it may be the case that the developer may need to sign the applet to get the audio file from the server.
public void init() {

// The first thing is to load the audio clip
AudioClip clip = getAudioClip(getDocumentBase(),
"http://server.com/clip.au");

// Play the audio clip
clip.play();

// Stop playing audio clip
clip.stop();

// In case audio clip needs to be played continuously
clip.loop();
}

Tuesday, July 03, 2007

How to get current date time?

You can get current date and/or time in Java using the following method. You may change the date format in the constructor of SimpleDateFormat to get the result in a different format:
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

private String getDateTime() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}