Java-Gaming.org Hi !
Featured games (83)
games approved by the League of Dukes
Games in Showcase (513)
Games in Android Showcase (120)
games submitted by our members
Games in WIP (577)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
   Home   Help   Search   Login   Register   
  Show Posts
Pages: [1]
1  Game Development / Newbie & Debugging Questions / Re: Wait for network input thread to receive vector on: 2012-10-30 21:31:07
The server doesn't seem to send the updated version of the tanks vector to the client. After receiving it the first time, the vector on the client side remains the same.

http://pastebin.com/dUBb4WM4 <-- write/readObject

I changed the code from write/readObject to write/readUnshared. Unfortunately, it's still not working.

http://pastebin.com/UrqMCBNy <-- write/readUnshared

(Output at the bottom)

What am I doing wrong?
2  Game Development / Newbie & Debugging Questions / Re: Wait for network input thread to receive vector on: 2012-10-26 19:54:46
Wait for the Vector<Tank> to be created (use any synchronization primitive that's handy -- I'm a fan of BlockingQueue), then pass it as a parameter to GameBoard's constructor.

meaning
Quote
have the client wait for the thread to receive it before constructing the GameBoard.
right?

I'd hoped to keep Client clean of Vector<Tank> and all the other things that are going to be sent through the socket by giving GameBoard direct access to the input thread.

I've never used BlockingQueue before, but I'll read up on it and see what I can come up with. In the meantime, all hints are appreciated! ;-)
3  Game Development / Newbie & Debugging Questions / Wait for network input thread to receive vector on: 2012-10-26 19:26:58
Hi!

I have a multi-threaded server waiting for incoming connections. When a client connects, an input and an output thread are created to handle I/O to that client. The server's output thread starts to send a Vector<Tank> to the client.

The client, when constructed, joins the server and creates a thread to handle all input coming from the server. The thread starts when constructed and waits for the Vector<Tank> to be sent. After joining, the client creates a GameBoard, giving it a reference to the input thread. The GameBoard, when constructed, tries to retrieve the Vector<Tank> from the input thread.

The issue is, the GameBoard is constructed before the input thread can receive the Vector<Tank>. I need the GameBoard constructor to wait for the input thread to receive it's first update of the vector, or have the client wait for the thread to receive it before constructing the GameBoard. I hope this makes sense!

If there's an easier solution to this mess, then please tell me. Also, if you notice anything else that's wrong or could be better, don't hesitate to mention it. Thanks! Smiley

-CLIENT-
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
package tw.client;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataOutputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;


public class Client implements ActionListener {

   // Frame
   private               JFrame      frame      = null;
   public static final    int       W_WIDTH    = 800;
   public static final    int       W_HEIGHT    = 600;
   private               JButton      joinButton   = null;
   
   // Network
   private static final    int             PORT    = 2720;
   private               Socket            socket   = null;
   private                InputThread       input   = null;
   private               DataOutputStream    output   = null;
   
   // Game loop and game board
   private static final    int       FRAMES_PER_SECOND    = 25;
   private static final    int       SKIP_TICKS         = 1000 / FRAMES_PER_SECOND;  
   private             GameBoard    gameBoard;
   private             boolean    running          = true;
     
   
   /**
    * Client constructor.
    * Initializes a frame, game board and network connection.
    */

   public Client() {      
      // Initialize the frame
      frame = new JFrame("Tank Wars - Client");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setSize(W_WIDTH, W_HEIGHT);
      frame.setLocationRelativeTo(null);      
      frame.setResizable(false);
      frame.setVisible(true);        
     
      // Initialize network connection
      joinServer();
     
      // Add game board to frame
      gameBoard = new GameBoard(input, output);
      //gameBoard.setVisible(false);      
      frame.add(gameBoard);
      gameBoard.requestFocusInWindow();
     
      // Start game loop
      run();
     
      // Initialize join button
      /*joinButton = new JButton("Join");
      joinButton.setActionCommand("Join");
      joinButton.addActionListener(this);
      frame.getContentPane().add(joinButton);*/

   }
   
   @Override
   public void actionPerformed(ActionEvent e) {
      if (e.getActionCommand() == "Join") {
         //client.joinServer();
         joinButton.setEnabled(false);
         joinButton.setVisible(false);
         gameBoard.setVisible(true);
         frame.validate();
         
         // Start game loop
         run();
      }      
   }
   
   /**
    * Starts the game loop.
    */

   private void run() {
      // While client is not connected to server
      /*while (!client.isConnected()) {
         System.out.println("Client not connected to server.");
      }*/

     
      long nextGameTick = System.nanoTime() / 1000000;
      long sleepTime;
     
      while (running) {
         gameBoard.updateGame();
         gameBoard.repaint();
         
         nextGameTick += SKIP_TICKS;
         sleepTime = nextGameTick - System.nanoTime() / 1000000;

         if (sleepTime > 0) {
            try {
               Thread.sleep(sleepTime);
            }
            catch(Exception e){
               e.getStackTrace();
            }
         } // if
      } // while
   } // run
   
   /**
    * When called, establishes connection to server.
    */

   public void joinServer() {
      try {
         // Open socket to server
         System.out.println("Initializing ...");
         InetAddress addr = InetAddress.getLocalHost();
         socket = new Socket(addr, PORT);
         System.out.println("The new socket: " + socket);
         
         // Initialize I/O
         input = new InputThread(socket);
         output = new DataOutputStream(socket.getOutputStream());
         
      } catch(Exception e) {
         e.printStackTrace();
      }
   }  
   
   /**
    * Stops the game loop.
    */

   public void stop() {
      running = false;
   }
   
   /**
    * MAIN METHOD
    * @param args
    */

   public static void main(String[] args) {
      new Client();
   }
}



-InputThread-
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
package tw.client;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.Vector;

import tw.Projectile;
import tw.Tank;


public class InputThread extends Thread {
   
   private    ObjectInputStream    in               = null;
   private    boolean          running            = true;
   
   private      int               playerNr         = 0;
   private    Vector<Tank>      updatedTanks      = null;
   private      Vector<Projectile>   updatedProjectiles    = null;        
   
   
   /**
    * ClientThread constructor.
    */

   public InputThread(Socket socket) {
      // Initialize input stream
      try {
         in = new ObjectInputStream(socket.getInputStream());
      } catch (IOException e) {
         e.printStackTrace();
      }
     
      // Initialize empty tank vector
      updatedTanks = new Vector<Tank>();
     
      start();
   }  
   
   
   /**
    * Run method, called when thread is started.
    */

   @SuppressWarnings("unchecked")
   public void run() {
     
      // Receive player number from server
      try {
         playerNr = in.readInt();
         System.out.println("playerNr " + playerNr);
      } catch (IOException e1) {
         e1.printStackTrace();
      }
     
         // Receive current turn and entity vector
         try {
            while (running) {
               updatedTanks = (Vector<Tank>) in.readObject();
            }
         }
         catch (IOException e) {
            e.printStackTrace();  
         }
         catch (ClassNotFoundException e) {
            e.printStackTrace();
         }
   } // run  
   
   
   /**
    * Sets 'running' to 'false', stopping the input loop.
    */

   public void stopRunning() {
      running = false;
   }
   
   
   /**
    * Getter of the property <tt>playerNr</tt>
    * @return Returns playerNr
    * @uml.property name="playerNr"
    */

   public int getPlayerNr() {
      return playerNr;
   }
   
   
   /**
    * Getter of the property (vector) <tt>updatedEntitites</tt>
    * @return  Returns the updatedEntities vector.
    * @uml.property  name="updatedEntities"
    */

   public Vector<Tank> getUpdatedTanks() {      
      return updatedTanks;
   }
}



-GameBoard-
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
package tw.client;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Vector;

import javax.swing.JComponent;

import tw.Projectile;
import tw.Tank;


/**
 * .
 */

public class GameBoard extends JComponent implements KeyListener {
   
   // Network
   private InputThread         input      = null;
   private DataOutputStream    output       = null;
   
   // Status panel
   private StatusPanel       statusPanel   = null;
   
   // Players and entities
   private int               playerNr   = 0;
   private Vector<Tank>       tanks      = null;
   private Vector<Projectile>   projectiles   = null;
   private Tank            pTank      = null;
   
   
   /**
    * GameBoard constructor.
    * @param client
    */

   public GameBoard(InputThread input, DataOutputStream output) {
      // Give access to input thread and output stream
      this.input = input;
      this.output = output;
     
      // Setup panel
      setFocusable(true);
      setBackground(Color.LIGHT_GRAY);
      setDoubleBuffered(true);
      setSize(Client.W_WIDTH, Client.W_HEIGHT);

      // Setup key listener
      addKeyListener(this);
      //setFocusTraversalKeysEnabled(false);
     
      // Get playerNr and tanks from server
      playerNr = input.getPlayerNr();
      tanks = input.getUpdatedTanks();
     
      // Set pTank to tank matching playerNr
      for (int i = 0; i < tanks.size(); i++)
         if (tanks.get(i).getPlayerNr() == playerNr)
            pTank = tanks.get(i);      
     
      // Initialize status panel
      statusPanel = new StatusPanel(pTank, playerNr);
      add(statusPanel);
      this.revalidate();
   }
   
   
   /**
    * Update logic
    */

   public void updateGame() entitieset updated entities
      tanks = input.getUpdatedTanks();
     
      // Get playerNr of currently active tank
      int activeTank = 0;
      for (int i = 0; i < tanks.size(); i++)
         if (tanks.get(i).isActive())
            activeTank = tanks.get(i).getPlayerNr();
     
      // Update status panel
      statusPanel.update(activeTank);
   }
   
   
   /**
    * Render entities
    */

   public void paintComponent(Graphics g) {
      // Clear off-screen bitmap
      super.paintComponent(g);
     
      // Cast to Graphics2D for more options
      Graphics2D g2d = (Graphics2D) g;
     
      // If there are entities in the entity vector and they are alive, draw those entities
      if (tanks != null) {
         for (int i = 0; i < tanks.size(); i++) {
            if (tanks.get(i).isAlive())
               tanks.get(i).draw(g2d);
         }
      }
   }
   
   
   
   ////////////////////////////
   // - HANDLING KEY INPUT - //
   ////////////////////////////
   
   /**
    * Key input - when key is pressed.
    */

   public void keyPressed(KeyEvent e) {
      int key = e.getKeyCode();
     
      if (pTank.isActive())
         if (key == KeyEvent.VK_UP || key == KeyEvent.VK_DOWN || key == KeyEvent.VK_LEFT || key == KeyEvent.VK_RIGHT) {
            try {
               output.writeInt(key);
               System.out.println("Client output: " + key);
            }
            catch (IOException e1) {
               e1.printStackTrace();
            }            
         }
         
   }
   
   /**
    * Key input - when key is released.
    */

   public void keyReleased(KeyEvent e) {
      int key = e.getKeyCode();
     
      if (pTank.isActive())
         if (key == KeyEvent.VK_SPACE)
            try {            
               output.writeInt(key);
               System.out.println("Client output: " + key);
            }
            catch (IOException e1) {
               e1.printStackTrace();
            }
   }
   
   public void keyTyped(KeyEvent e) {
      // do nothing
   }
}
4  Game Development / Newbie & Debugging Questions / Re: 2D turn based multiplayer game on: 2012-10-15 12:50:15
Hi, I'm back!

I gave up on this project a couple of weeks after starting this thread. It simply was way too frustrating.

Quote
If you've never written a java based game before, starting with a threaded, networked, multiplayer game is a tall order.
That's what made it so frustrating. This was part of a Java course I had about a year ago at my university. It was an 8 week course and this project was just one part of it. We never had any Java lessons before that course, never got to make a single game and never wrote a single line of network code. Still the teacher referred to it as being a "small" project that shouldn't be an issue. Yeah right!

Anyhow, I'm back at it because I can't stand leaving things unfinished. While I'm trying to get back into Java and whatever crappy code I wrote back then, I've got a couple of new questions.

Quote
(basically a thin client without any gamelogic, and only displaying the scene and sending/receiving commands)
That's what I'm aiming for. Now there's some confusion on where to put what and how the components should interact with one another. I've decided to get the frame for my client right before trying to finish the server. This is what I've got so far:

Game
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
package tw.client;

import javax.swing.JFrame;


public class Game extends JFrame {

   public static final int W_WIDTH = 800;
   public static final int W_HEIGHT = 600;
   
   private static final int FRAMES_PER_SECOND = 25;
   private static final int SKIP_TICKS = 1000 / FRAMES_PER_SECOND;
   
   private GameBoard gameBoard;
   private boolean running = false;
   
   public static ClientThread client;
   
   public Game() {
     
      // Initialize the frame
      setTitle("Game Client");
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setSize(W_WIDTH, W_HEIGHT);
      setLocationRelativeTo(null);      
      setResizable(false);
      setVisible(true);
     
      // Add board to frame and give focus
      gameBoard = new GameBoard();
      add(gameBoard);
      gameBoard.requestFocusInWindow();
     
      // Start game loop
      running = true;
      run();
   }
   
   /**
    * Stops the game loop.
    */

   public void stop() {
      running = false;
   }

   /**
    * Starts the game loop.
    */

   private void run() {
      long nextGameTick = System.nanoTime() / 1000000;
      long sleepTime;
     
      while (running) {
         gameBoard.updateGame();
         gameBoard.repaint();
         
         nextGameTick += SKIP_TICKS;
         sleepTime = nextGameTick - System.nanoTime() / 1000000;

         if (sleepTime > 0) {
            try{
               Thread.sleep(sleepTime);
            }catch(Exception e){}
         }
      }
   }

   
   /**
    * MAIN METHOD
    * @param args
    */

   public static void main(String[] args) {
      client = new ClientThread();
     
      new Game();
   }
}


ClientThread
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
package tw.client;

import java.awt.*;
import java.io.IOException;
import java.net.*;

public class ClientThread implements Runnable {

   private static final int PORT = 2727;
   
   public void Client() throws IOException {
      init();
   }
   
   public void init() throws IOException {
      System.out.println("Initializing ...");
      InetAddress addr = InetAddress.getLocalHost();
      Socket socket = new Socket(addr, PORT);
      System.out.println("The new socket: " + socket);
   }
   
   public void run() {
      // Receive data from server
     
      // Send requests to server      
   }

}


GameBoard
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
package tw.client;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;

import javax.swing.JComponent;
import javax.swing.text.html.parser.Entity;


/**
 * .
 */

public class GameBoard extends JComponent implements KeyListener {
   
   //private StatusPanel statusPanel;
   private ArrayList<Entity> entities;
   
   public GameBoard() {
     
      // Setup panel
      setFocusable(true);
      setBackground(Color.LIGHT_GRAY);
      setDoubleBuffered(true);
      setSize(Game.W_WIDTH, Game.W_HEIGHT);

      // Setup key listener
      addKeyListener(this);
      //setFocusTraversalKeysEnabled(false);
         
      // Add status panel
      /*statusPanel = new StatusPanel();
      add(statusPanel);
     
      // Container for all entities
      entities = new ArrayList<Entity>();*/

   }
   
   /**
    * Update game.
    */

   public void updateGame() {
      // Receive game data from server to update gameBoard/entities
   }
     
   /**
    * Draw game.
    */

   public void paintComponent(Graphics g) {
      // Clear off-screen bitmap
      super.paintComponent(g);
     
      // Cast to Graphics2D for more options
      Graphics2D g2d = (Graphics2D) g;
     
      // Draw updated gameBoard/entities
   }
   
   
   // Handling key input
   /////////////////////////////////////////////
   /**
    * Key input - when key is pressed.
    */

   public void keyPressed(KeyEvent e) {
      // Ask server if my turn
      // If my turn:       Send request to server to change angle/power of gun
      // If not my turn:    Display some msg
   }
   
   /**
    * Key input - when key is released.
    */

   public void keyReleased(KeyEvent e) {
      // Ask server if my turn
      // If my turn:      Send request to change ammunition and/or fire gun
      // If not my turn:    Display some msg
   }
   
   public void keyTyped(KeyEvent e) {
      // do nothing
   }

}


The updateGame method is the receiving one, the key input methods the sending ones (through the clientThread obviously).

* What is the best way to make them interact with the server through the clientThread? What is the easiest way to give them access to clientThread?
* The size of all the game data (entities, player status etc) is probably not that big. Can I push the whole entity array from the server to the clients for every update, or should I only send data for those things that have been altered in some way?

Cheers!

EDIT: made the clientThread "public static".
5  Game Development / Newbie & Debugging Questions / Re: JPanel KeyListener not responding. on: 2012-03-02 23:13:56
Hehe, had a feeling that was a bad idea. Anyhow, I solved it by not requesting focus in the GameBoard constructor but rather in the class that adds the GameBoard:

1  
2  
3  
gameBoard = new GameBoard();
add(gameBoard);
gameBoard.requestFocusInWindow();


Now it seems to work the way it should!
6  Game Development / Newbie & Debugging Questions / JPanel KeyListener not responding. on: 2012-03-02 16:32:54
I have a class extending JPanel and implementing a KeyListener. For some reason, the KeyListener does not respond to keys being pressed or released until I hit the TAB key once. I assume that the panel doesn't have focus for some reason, which I thought setFocusable(true); and requestFocus(); would fix. What am I doing wrong?

EDIT: I placed requestFocus() in the updateGame() method and now it works. The updateGame() method is being called from an outside class that's extending JFrame (where my game loop is). Is this solution "ok", or should I make it some other way?

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
package tw;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;

import javax.swing.JPanel;

/**
 * .
 */

public class GameBoard extends JPanel implements KeyListener {
   
   private Tank tank;
   
   public GameBoard() {
     
      // Setup panel
      setFocusable(true);
      requestFocus();
      setBackground(Color.WHITE);
      setDoubleBuffered(true);
      setSize(GameServer.W_WIDTH, GameServer.W_HEIGHT);

      addKeyListener(this);
      //setFocusTraversalKeysEnabled(false);
           
      // Initialize entities
      tank = new Tank(1, true, 200, 100, 1);
   }
   
   /**
    * Update game logic
    */

   public void updateGame() {
      //System.out.println("updating");
      tank.update();
   }
     
   /**
    * Draw game objects
    */

   public void paintComponent(Graphics g) {
      super.paintComponent(g);
     
      //System.out.println("drawing");
      tank.draw(g);
           
      Toolkit.getDefaultToolkit().sync();
      g.dispose();
   }
   
   
   // Handling key input
   /////////////////////////////////////////////
   /**
    * Key input - when key is pressed.
    */

   public void keyPressed(KeyEvent e) {
      System.out.println("KEY PRESSED!");
      tank.keyPressed(e);      
   }
   
   /**
    * Key input - when key is released.
    */

   public void keyReleased(KeyEvent e) {
      System.out.println("KEY RELEASED!");
      tank.keyReleased(e);        
   }
   
   public void keyTyped(KeyEvent e) {
      // do nothing
   }

}
7  Game Development / Newbie & Debugging Questions / Re: 2D turn based multiplayer game on: 2012-03-02 04:04:51
I'm struggling a bit with key input. I did some Java tutorials and had everything working just fine, until I decided to move things around and now the input seems to do nothing. I then tried to go back as far as possible, but I still can't seem to get things working again. The tank is being drawn, but that's about it. Might be cause it's 5am, but I just don't see it ..

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;

import javax.swing.JPanel;
import javax.swing.Timer;


/**
 * .
 */

public class GameBoard extends JPanel implements ActionListener {
   
   // Timer
   private Timer timer;
   
   // Entities
   //private ArrayList<Entity> entities;
   private Tank tank;
   
   public GameBoard() {
     
      addKeyListener(new TAdapter());
      setFocusable(true);
      setBackground(Color.WHITE);
      setDoubleBuffered(true);      
      setSize(GameServer.W_WIDTH, GameServer.W_HEIGHT);
     
      // Initialize entities
      //entities = new ArrayList<Entity>();
      //entities.add(new Tank(1, true, 10, 10, 1));
      tank = new Tank(1, true, 200, 100, 1);
     
      // Timer
      timer = new Timer(5, this);
        timer.start();
   }
   
   public void doLogic() {
      /*for (int i = 0; i < entities.size(); i++)
         entities.get(i).update();*/

     
      tank.update();
   }
     
   public void paintComponent(Graphics g) {
      super.paintComponent(g);
     
      /*for (int i = 0; i < entities.size(); i++) {
         if (entities.get(i).isAlive())
            entities.get(i).draw(g);
      }*/

     
      tank.draw(g);
           
      Toolkit.getDefaultToolkit().sync();
      g.dispose();
   }
   
   public void actionPerformed(ActionEvent e) {
      doLogic();
      repaint();
   }
   
   private class TAdapter extends KeyAdapter {
      public void keyReleased(KeyEvent e) {
         tank.keyReleased(e);
      }
     
      public void keyPressed(KeyEvent e) {
         tank.keyPressed(e);
      }
   }

}
8  Game Development / Newbie & Debugging Questions / 2D turn based multiplayer game on: 2012-02-28 20:29:49
I want to make a 2D turn based multiplayer "Tank Wars" game. Now, the problem is, I've never actually made a single Java game. While I go through a couple of tutorials on Java game programming, I thought I throw out a couple of ideas about the game structure and a question or two.

Classes
  • Game (main, initResources, gameLoop, endGame) - contains a StateManager
  • StateManager (setCurrentState, updateState, drawState) - contains several States
  • State (abstract init, abstract update, abstract draw) - base class for different game states
  • MenuState (init, update, draw) - here you can choose to host (triggers a host and client thread) or join (triggers a client thread), switches to GameState
  • GameState  (init, update, draw) - contains all the entities, updates game logic etc
  • Entities (get/setPos, get/setAlive, abstract update, abstract draw) - base class for all entities, like players/tanks, projectiles etc

Kind of a rough description but I hope you catch my drift.

Now I'm still pretty shaky when it comes to certain concepts. First of all, is it a good idea or even possible to make host/client threads the way I described above? Let's say we have two players:

Player A
1) Clicks the "Host Game" button
2) A host thread is started in the background acting as the server
3) A client thread is started, connecting to the server
4) The State changes from MenuState to GameState
5) The client thread receives information from the server in order to update the GameState
6) The GameState draws the scene using the updated info

Player B
1) Clicks the "Join Game" button
3) A client thread is started, connecting to the server
4) The State changes from MenuState to GameState
5) The client thread receives information from the server in order to update the GameState
6) The GameState draws the scene using the updated info

This is roughly how I imagine it to be, but since I haven't actually made a multiplayer game before, I have no idea.

Another thing is, where exactly do I put all the instances of my entities? Is there an instance of every entity on the server and on every client, only that the entities are not being drawn on the server but only their status is being updated through the input provided by the clients and then sent out to all clients in order to redraw those entities? Could someone give me a simple example of how this usually is done in games like this?

Well, I'm off to the tutorial section!

Cheers!
Pages: [1]
 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

Longarmx (52 views)
2014-10-17 03:59:02

Norakomi (43 views)
2014-10-16 15:22:06

Norakomi (33 views)
2014-10-16 15:20:20

lcass (38 views)
2014-10-15 16:18:58

TehJavaDev (68 views)
2014-10-14 00:39:48

TehJavaDev (68 views)
2014-10-14 00:35:47

TehJavaDev (60 views)
2014-10-14 00:32:37

BurntPizza (73 views)
2014-10-11 23:24:42

BurntPizza (45 views)
2014-10-11 23:10:45

BurntPizza (86 views)
2014-10-11 22:30:10
Understanding relations between setOrigin, setScale and setPosition in libGdx
by mbabuskov
2014-10-09 22:35:00

Definite guide to supporting multiple device resolutions on Android (2014)
by mbabuskov
2014-10-02 22:36:02

List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!