12 Replies - 1501 Views - Last Post: 02 April 2013 - 10:35 AM Rate Topic: -----

#1 mdeey  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 01-April 13

2D JAVA GAME TCP SERVER/CLEINT SUPPORT

Posted 01 April 2013 - 05:29 PM

my name is MdeeY......i am new to this forum i just registered......i really need some help with 2d game TCP multiplayer.....the is about Spaceship Multiplayer i want to use TCP client and server to enable two people to control the spaceships from two computers or one computer by running the instance of the server then two instance of the client.

the space ship (player 1 ) is driven with W,A,S,D keys W to accelerate......A to turn left......S to decelerate....and D to turn right............so the objective now is to create a one Server to host two Client......the Server receives the keystroke from Client one and then send it to Client two and vice versa.....while the both Clients can see the movement of each other in realtime.......i did some research today i realised this can be done with "Serialisation " but i don't know how to implement that......i really need some help with this Norm...........

i uploaded the space ship race game on youtube please take a look

This post has been edited by modi123_1: 01 April 2013 - 05:34 PM
Reason for edit:: added media tag


Is This A Good Question/Topic? 0
  • +

Replies To: 2D JAVA GAME TCP SERVER/CLEINT SUPPORT

#2 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8334
  • View blog
  • Posts: 31,858
  • Joined: 06-March 08

Re: 2D JAVA GAME TCP SERVER/CLEINT SUPPORT

Posted 01 April 2013 - 05:49 PM

Here is a start

http://www.dreaminco...r-gui-optional/

It is like a chat room but instead of sending the text typed to each client you send the keystroke
Was This Post Helpful? 0
  • +
  • -

#3 mdeey  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 01-April 13

Re: 2D JAVA GAME TCP SERVER/CLEINT SUPPORT

Posted 01 April 2013 - 06:29 PM

View Postpbl, on 01 April 2013 - 05:49 PM, said:

Here is a start

http://www.dreaminco...r-gui-optional/

It is like a chat room but instead of sending the text typed to each client you send the keystroke



thanks for the link.....but the space ships are made from an image array do i have to serialize them too? if so how do i do it ? and also can u like give me example on how to change the string to keystroke...... for example my keystroke is like this

 

		
            if (Code == KeyEvent.VK_K)//If Player 2 pressed K, Space ship speed decreases by 10
               {
                  Velocity -=1;
                  
                     if(Velocity1<0) 
                  
                     Velocity1 = 0;
                  
               }
					


Was This Post Helpful? 0
  • +
  • -

#4 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8334
  • View blog
  • Posts: 31,858
  • Joined: 06-March 08

Re: 2D JAVA GAME TCP SERVER/CLEINT SUPPORT

Posted 01 April 2013 - 06:53 PM

It depends... serializing your space ship will work but it might be slow

Better to just send over the wire the events that modify it
As both clients are executing the same code they will react the same to the key-event received

When a user enter a key... don't react to that key directly on the client, send that key to the server, then the server broadcast that key to all clients that react only to these type of message receive from the server.

Same thing if you have a timer that moves an object. The Timer should be on the server that broacast that time slot event.
Was This Post Helpful? 0
  • +
  • -

#5 mdeey  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 01-April 13

Re: 2D JAVA GAME TCP SERVER/CLEINT SUPPORT

Posted 01 April 2013 - 07:18 PM


//Import PACKAGES
import java.net.*;
import java.io.*;
import java.util.logging.Logger;
import javax.swing.Timer;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
import java.lang.*;
import javax.swing.*;
import java.applet.*;


public class SpaceshipClient extends JPanel implements ActionListener, KeyListener
{

       public ImageIcon pictures0[];// This is the array of pictures0 that will be animated
       public ImageIcon pictures1[];// This is the array of pictures0 that will be animated

       public int player1spaceship = 13, player2spaceship = 13;
       public int x = 500, y = 368, x0 = 550, y0 = 368;// X and Y Cordinates for Positioning the Space ships
       public Timer AnimationTimer;//Timer to drive the animation and start the races
       public int Velocity = 0, Velocity1 = 0;// This keeps track of the two Space ships speed
       public String send = null;
      
       
   public SpaceshipClient()
   {
      try //Try Block to Display the Welcome Screen
       
         {
            //display a welcome dialog (JOptionPane) that includes the rules

          JOptionPane.showMessageDialog(null,"GAME INSTRUCTIONS \n\n" +"This game is a multiplayer space ship game\n" + "Player 1 space ship is Red\n" + "Player 2 space ship is Blue\n\n" + "The Object of this game is to\n" + "drive the two space ships around\n" + "the race track and try to reach\n" + "the finishing line as quick as possible\n" + "to gain first position while avoiding\n"+ "collision with the wall, center astroid and each other.\n\n" + "PLAYER 1 CONTROLS\n\n" + "W = Accelaration\n" + "S = Decelaration\n" + "D = Turn right\n" + "A = Turn left\n\n" + "PLAYER 2 CONTROLS\n\n" + "I = Accelaration\n" + "K = Decelaration\n" + "L = Turn right\n" + "J = Turn left\n");
       
         }
			
			
			
       catch(Exception e){
         }
       
		 
		 
		 
       try //Try Block to Play the Sound
         {
            URL eng = this.getClass().getResource ("Sounds/hotidle.wav");// This Loads the Sound Effect from the Directory
            AudioClip snd = JApplet.newAudioClip(eng);//Creating Instance of the Audio Clip
            snd.play();//This will play the sound effect only once
                        
         }
			
			
			
       catch(Exception e){
         }
         
            
         
   
    }     
                  
  
  
  
  
  
  
   {
           int i = 0;//This sets the number of pictures0 to Zero since its an array
           pictures0 = new ImageIcon[16];//Creating the instance of pictures0
           pictures1 = new ImageIcon[16];//Creating the instance of pictures0
           
           
           //This will allow the Key Presses 
           addKeyListener(this);
           setFocusable(true);
           setFocusTraversalKeysEnabled(false);
          
           // Method to load the 16 pictures0
           while(i < 16){
			  
               pictures0[i] = new ImageIcon("src/player1/spaceship"+i+".png"); // This loads the pictures0 from the directory 
                
               pictures1[i] = new ImageIcon("src/player2/spaceship"+i+".png");// This loads the pictures0 from the directory 
               
               i++;// starts the animation of the pictures0
           } 
      
   }
         
			
			  
	  
	  public void paintComponent( Graphics g ) {
     
	  
	  super.paintComponent(g);// This calls the super class paintComponent
      
	   Color c1 = Color.black;
      g.setColor( c1 );    
      g.fillRect(50, 100, 750, 500);  // surrounding space  
            
     // Color c2 = new Color(210, 105, 30);
      //g.setColor( c2 );
      //g.fillRect( 150, 200, 550, 300 ); // asteroid
      
      Color c3 = Color.white;
      g.setColor( c3 );
      g.drawLine( 425, 500, 425, 700 ); // finish line
          
		Color c4 = Color.blue;
      g.setColor( c4 );
      g.drawLine( 200, 250, 570, 325 );     
	            
           //draw the two Space ships to the screen, at the white line 
      pictures0[player1spaceship-1].paintIcon(this, g, y, x);
            
      pictures1[player2spaceship-1].paintIcon(this, g, y0, x0);
				
		Image image;
  		
  		ImageIcon i = new ImageIcon("src/images/near1.jpg");
  		image = i.getImage();
  		g.drawImage(image,150, 200, 520, 280, null);

				
 }
      
		
		
		
		 
        //This method is used to respond to Timers' event
       public void actionPerformed( ActionEvent e )
       {
       
            //Using Rectangles to detect collision between the Space ships and the Wall walls
            Rectangle  Wall = new Rectangle(49, 100, 715, 452);
            Rectangle  Asteroid = new Rectangle(150, 200, 520, 280);
            Rectangle Finishline = new Rectangle(425, 500, 1, 615);
                            
            int cordinate_x = x;
            int cordinate_y = y;
            int cordinate_x0 = x0;
            int cordinate_y0 = y0;
            
            //Move the Space ship forward base on the direction its facing
            if(player1spaceship == 1)
            
            { 
            
            cordinate_x -=Velocity1;
            
            }
				
				
             
            else  if(player1spaceship == 5)
            { 
            
            cordinate_y +=Velocity1; 
            
            }
            
				
				
           else if (player1spaceship == 9)
             
             { 
             
             cordinate_x +=Velocity1;
              
             }
             
				 
				 
				 
				 
            else if (player1spaceship == 13)
             
            { 
            
            cordinate_y -=Velocity1;
            
            }
				
				
				
         
            if(player2spaceship == 1)
            
            { 
            
            cordinate_x0 -=Velocity; 
            
            }
            
				
				
				
            else if(player2spaceship == 5)
             
              { 
              
              cordinate_y0 +=Velocity;
              
              }
				  
				  
				  
				  
            else if (player2spaceship == 9)
            
            { 
           
            cordinate_x0 +=Velocity;
            
             }
				 
				 
				 
				 
				 
             
            else if (player2spaceship == 13)
            
             {
             
             cordinate_y0 -=Velocity;
             
              }
            
				
				
				
            
            //Using Rectangles to detect collision between the two Space ships
            Rectangle  spaceship1 = new Rectangle(cordinate_y, cordinate_x, 50, 50);
            Rectangle  spaceship2 = new Rectangle(cordinate_y0, cordinate_x0, 50, 50);
            
               //This Detects the Collision between the Walls of the race track and the two Space ships                        
            if(!Asteroid.intersects(spaceship1) && Wall.inside(cordinate_y,cordinate_x) && (!spaceship1.intersects(spaceship2)))
               {
               
                  y = cordinate_y;
                  x = cordinate_x;
                  
                  //This checks and see if Player 1 hits Player 2 then the game ends
                  if(spaceship1.intersects(spaceship2))
                     System.exit(0);  
               }  
					
					
					
					
					      
                  if(spaceship1.intersects(spaceship2))
               {
               
               URL eng = this.getClass().getResource ("Sounds/CARCRASH.WAV");// This Loads the Sound Effect from the Directory
               AudioClip snd = JApplet.newAudioClip(eng);//Creating Instance of the Audio Clip
               snd.play();//Message to be displayed when the two Space ships crashed / collide
               System.out.println("Space ships Crashed Game Over \n" + "Connection Lost fROM server" );
               
               //Displays the a Message when the two Space ships crashed
               JOptionPane.showMessageDialog(null,"Space ships crashed!! \n\n" + "*****Game Over***\n\n" + "hit OK to Exit");
         
               System.exit(0);//Terminates the Game if Collision happens    
               }
					
					
					
					
					
					
					 if(!Asteroid.intersects(spaceship1) && Wall.inside(cordinate_y,cordinate_x) && (!spaceship1.intersects(spaceship2)))
               {
               
                  y = cordinate_y;
                  x = cordinate_x;
                  
                  //This checks and see if Player 1 hits Player 2 then the game ends
                  //if(Asteroid.intersects(spaceship2))
                     //System.exit(0);  
               }
					
					
					
					
					
					 
					       
                  if(Asteroid.intersects(spaceship2))
               {
               
					Velocity  = 0;
					Velocity1 = 0; 
					
               URL eng = this.getClass().getResource ("Sounds/geardown.WAV");// This Loads the Sound Effect from the Directory
               AudioClip snd = JApplet.newAudioClip(eng);//Creating Instance of the Audio Clip
               snd.play();//Message to be displayed when the two Space ships crashed / collide
                             
                                  
               }



					
					
					
					 if(!Asteroid.intersects(spaceship1) && Wall.inside(cordinate_y,cordinate_x) && (!spaceship1.intersects(spaceship2)))
               {
               
                  y = cordinate_y;
                  x = cordinate_x;
                  
                  //This checks and see if Player 1 hits Player 2 then the game ends
                  //if(Asteroid.intersects(spaceship2))
                     //System.exit(0);  
               } 
					
					
					
					
					
					
					  if(spaceship1.intersects(Finishline))
               {
               
               URL eng = this.getClass().getResource ("Sounds/ClappingCrowd.wav");
               AudioClip snd = JApplet.newAudioClip(eng);               
					snd.play();
					
           
               JOptionPane.showMessageDialog(null,"CONGRATULATIONS!!\n\n" + "Player 1\n\n"+ "YOU PLACED FIRST");
         
               System.exit(0);   
               }





               
						  if(spaceship2.intersects(Finishline))
               {
               
               URL eng = this.getClass().getResource ("Sounds/ClappingCrowd.wav");
               AudioClip snd = JApplet.newAudioClip(eng);               
					snd.play();
					
           
               JOptionPane.showMessageDialog(null,"CONGRATULATIONS!!\n\n" + "Player 2\n\n"+ "YOU PLACED FIRST");
         
               System.exit(0);   
               }




	
					       
                  if(Asteroid.intersects(spaceship1))
               {
                   Velocity = 0;
					    Velocity1 =0; 
 
               URL eng = this.getClass().getResource ("Sounds/geardown.WAV");
               AudioClip snd = JApplet.newAudioClip(eng);               
					snd.play();
                       
                  
               }
					
					
					
					
					
					
				

            //This Detects the Collision between the Walls of the race track and the two Space ships
            if(!Asteroid.intersects(spaceship2) && Wall.inside(cordinate_y0,cordinate_x0) && (!spaceship2.intersects(spaceship1)))
            {
            
                  y0 = cordinate_y0;
                  x0 = cordinate_x0;
                  
                  //This checks and see if Player 2 hits Player 1 then the game ends
                  if(spaceship2.intersects(spaceship1))
                     System.exit(0);                       
               }
               
					
					
					
					
            repaint();//Refresh the Screen
       
		 
		 
		 
         }
         
      //Method to start the animation / Race    
      public void Start_Accelaration()
      
         {
         AnimationTimer = new Timer(40, this);
         AnimationTimer.start();
         
         }
         
			
			
			
			
			

			
			
   //Returns the minimum size of the animation  
       public Dimension getMinimumSize()
       
          { 
          return getPreferredSize(); 
          }
   //Ends getMinimumsize method
   
   
	
	
	
	
	
	//Returns the preferred size of the animation
      public Dimension getPreferredSize()
      
          {
			  
          return new Dimension( 850, 650); 
          
			 
			 }
          
			 
			 
			 
			 
			 
			 
   //end getPreferredsize method
// Get Key pressed by user
   public void keyTyped(KeyEvent e)
   {
      
		
		throw new UnsupportedOperationException("Not supported yet.");
   
	
	}
	
	
         
   //Invoked when a key has been pressed.     
      public void keyPressed(KeyEvent e) 
          {
                
         int Code = e.getKeyCode();
          {  
          
			 			 
			 
			 
			 
			 
			 
          //Player 2
          
            if (Code == KeyEvent.VK_I)//If Player 2 pressed I, Space ship speed increases by 10
               {
					
					
					URL eng = this.getClass().getResource ("Sounds/tirespin.wav");// This Loads the Sound Effect from the Directory and play it when I key is pressed
               AudioClip snd = JApplet.newAudioClip(eng);
               snd.play();
					
					
                  Velocity +=1;
                  
                     
                  if(Velocity1>10) 
                  
                  Velocity1 = 10;
                  
               }
					
					
					
					
					
					
            if (Code == KeyEvent.VK_K)//If Player 2 pressed K, Space ship speed decreases by 10
               {
                  Velocity -=1;
                  
                     if(Velocity1<0) 
                  
                     Velocity1 = 0;
                  
               }
					
					
					
					
					
					
            if (Code == KeyEvent.VK_L)//If Player 2 pressed L, Space ship turns 22.5 Degrees Right           
               player2spaceship = (((player2spaceship+1)>16)? 1 : (player2spaceship+1));
             
               
					
					
               
            if  (Code == KeyEvent.VK_J)//If Player 2 pressed J, Space ship turns 22.5 Degrees Left
            
               player2spaceship =  (((player2spaceship-1)<1)? 16 : (player2spaceship-1));
               
            
            
				
				//Player 1
            
               
            if (Code == KeyEvent.VK_W)//If Player 1 pressed W, Space ship speed increases by 10
               {
					
					
					URL eng = this.getClass().getResource ("Sounds/tirespin.wav");// This Loads the Sound Effect from the Directory
               AudioClip snd = JApplet.newAudioClip(eng);//Creating Instance of the Audio Clip
               snd.play();
					
					
                 Velocity1 +=1;
                  
                     if(Velocity1>10)
                  
                      Velocity1 = 10;
                  
               }
					
					
					
					
					
					
            if (Code == KeyEvent.VK_S)//If Player 1 pressed S, Space ship speed decreases by 10
               {
					
					URL eng = this.getClass().getResource ("Sounds/geardown.wav");// This Loads the Sound Effect from the Directory
               AudioClip snd = JApplet.newAudioClip(eng);//Creating Instance of the Audio Clip
               snd.play();
					
					
                  Velocity1 -=1;
               
                     if(Velocity1<0)
							
							
                     
                     Velocity = 0;
                  
               }
					
					
					
					
					
					
            if (Code == KeyEvent.VK_D)
            
               player1spaceship = (((player1spaceship+1)>16)? 1 : (player1spaceship+1));//If Player 1 pressed D, Space ship turns 22.5 Degrees Right

               
             if (Code == KeyEvent.VK_A)
             
               player1spaceship =  (((player1spaceship-1)<1)? 16 : (player1spaceship-1));//If Player 1 pressed A, Space ship turns 22.5 Degrees Left
               
         }
     } 
      
		
		
		
		
		
   //Invoked when a key has been Released.
      public void keyReleased(KeyEvent e) 
      {
          
      }
   }






Was This Post Helpful? 0
  • +
  • -

#6 mdeey  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 01-April 13

Re: 2D JAVA GAME TCP SERVER/CLEINT SUPPORT

Posted 01 April 2013 - 07:25 PM

this is the code of the program without client and server implemented.........and i am totally new to Client/server application.........and this my school assignment which is due to be submitted in two weeks i really really need some help to do this.........i need to know how do i transfer the keystrokes and the timer to the server.....please give me some code examples maybe from the chat room application u suggested earlier.......thanks
Was This Post Helpful? 0
  • +
  • -

#7 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8334
  • View blog
  • Posts: 31,858
  • Joined: 06-March 08

Re: 2D JAVA GAME TCP SERVER/CLEINT SUPPORT

Posted 02 April 2013 - 03:36 AM

I am not to write your code.

In paintComponent() you read an Image and a .WAV from file. This is a very bad idea (ClientServer or not), a paintComponent() method is supposed to execute as fast as possible is less than 16 milliseconds, it is not the time an place to do disk I/O and why recretaing the Image at each call.

The actionPerformed() shou;ld tansfer the keystroke to the server which will do the change in speed/diretion/velocity and inform the Clients
Was This Post Helpful? 0
  • +
  • -

#8 mdeey  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 01-April 13

Re: 2D JAVA GAME TCP SERVER/CLEINT SUPPORT

Posted 02 April 2013 - 09:31 AM

View Postpbl, on 02 April 2013 - 03:36 AM, said:

I am not to write your code.

In paintComponent() you read an Image and a .WAV from file. This is a very bad idea (ClientServer or not), a paintComponent() method is supposed to execute as fast as possible is less than 16 milliseconds, it is not the time an place to do disk I/O and why recretaing the Image at each call.

The actionPerformed() shou;ld tansfer the keystroke to the server which will do the change in speed/diretion/velocity and inform the Clients


i think is not a good idea to use WAV files and images.....but is stated in my assignment question......here is the question maybe u could understand it better than i .......................https://www.dropbox.com/s/4wfjijsielyv3g4/DSPcw_main_1213_Sem2.doc
Was This Post Helpful? 0
  • +
  • -

#9 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8334
  • View blog
  • Posts: 31,858
  • Joined: 06-March 08

Re: 2D JAVA GAME TCP SERVER/CLEINT SUPPORT

Posted 02 April 2013 - 09:36 AM

View Postmdeey, on 02 April 2013 - 12:31 PM, said:

i think is not a good idea to use WAV files and images

There is nothing wrong in using Image and .wav
What is not a good idea is to read them from disk every time the paint() method is called which may be once every second.
Read both files at construction time. Create then your Image.
In the paint() method used that already instantiated Image and the read .wav.
Was This Post Helpful? 0
  • +
  • -

#10 mdeey  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 01-April 13

Re: 2D JAVA GAME TCP SERVER/CLEINT SUPPORT

Posted 02 April 2013 - 10:12 AM

View Postpbl, on 02 April 2013 - 09:36 AM, said:

View Postmdeey, on 02 April 2013 - 12:31 PM, said:

i think is not a good idea to use WAV files and images

There is nothing wrong in using Image and .wav
What is not a good idea is to read them from disk every time the paint() method is called which may be once every second.
Read both files at construction time. Create then your Image.
In the paint() method used that already instantiated Image and the read .wav.




how do i do that....give me some code examples......and i have implemented the client/server apps....... so i want to knw how to pass public void KeyPressed (KeyEven e ){
}
method to a DataOutputStream
Was This Post Helpful? 0
  • +
  • -

#11 farrell2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 849
  • View blog
  • Posts: 2,585
  • Joined: 29-July 11

Re: 2D JAVA GAME TCP SERVER/CLEINT SUPPORT

Posted 02 April 2013 - 10:16 AM

Do not read images and or wavs at object construction time. What happens when you create a List of 100 enemies, are you going to load the same image and wav 100 times? Load all of your images and audio when you start your game, then just reference the image and audio files needed for that object when you create it.
Was This Post Helpful? 0
  • +
  • -

#12 mdeey  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 01-April 13

Re: 2D JAVA GAME TCP SERVER/CLEINT SUPPORT

Posted 02 April 2013 - 10:24 AM

Yes that is how i created my program......i created an Array of 16 images that gets loaded when required....for example when the space ship turn right right facing image gets loaded.......so my problem is

how to pass public void KeyPressed (KeyEven e ){
}
method to a DataOutputStream
Was This Post Helpful? 0
  • +
  • -

#13 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8334
  • View blog
  • Posts: 31,858
  • Joined: 06-March 08

Re: 2D JAVA GAME TCP SERVER/CLEINT SUPPORT

Posted 02 April 2013 - 10:35 AM

View Postfarrell2k, on 02 April 2013 - 01:16 PM, said:

Do not read images and or wavs at object construction time. What happens when you create a List of 100 enemies, are you going to load the same image and wav 100 times? Load all of your images and audio when you start your game, then just reference the image and audio files needed for that object when you create it.

Sorry I met at GUI construction time. I think that I mentionned more than one that the whole idea was to access the disk only one for all Images and .WAV. If you need an Image as a parameter to another constructor sure that you'll use the already read one.

farrell2k is really fussy/particular/punctilious since a few days :)

View Postmdeey, on 02 April 2013 - 01:24 PM, said:

how to pass public void KeyPressed (KeyEven e ){
}
method to a DataOutputStream

Use an ObjectOutputStream. First thing explained in my tutorial.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1