Multiplayer Distributed Game

Hi,
I have written a 2 player distributed TicTacToe game and am having some problems converting it into a multiplayer game. I have tried countless methods to do this, unfortunately to no avail. I have attached the server code with the hopes that someone might have experience with this and will be able to give me a hand. Also, sorry for the length of this post but I thought it would be easier to supply the entire server code so you could see what I am trying to accomplish. Thanks.
import java.net.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.util.*;
public class TicTacToeServer extends JFrame {
     static protected Set activePlayers = new HashSet();
     static final int DEFAULT_PORT = 5000;
     private JTextArea output;
     private JScrollPane scrollPane;
     private Board board;
     public TicTacToeServer(String args[]) {
          super("Tic Tac Toe Server");
          output = new JTextArea();
          scrollPane = new JScrollPane(output);
          getContentPane().add(scrollPane, BorderLayout.CENTER);
          setSize(300,300);
          setVisible(true);
          int port = DEFAULT_PORT;
          if (args.length > 0) {
               try {
                    port = Integer.parseInt(args[0]);
               catch(NumberFormatException e) {
                    display(e.toString());
          board = new Board(this);
          try {
               ServerSocket server = new ServerSocket(port);
               Socket connection;
               while (true) {
                    display("Waiting for players to connect...");
                    connection = server.accept();
                    ClientResponseHandler newPlayer = new ClientResponseHandler(connection, board, this);
                    activePlayers.add(newPlayer);
                    newPlayer.start();
          catch(Exception e) {
               display(e.toString());
     public void display(String s) {
          output.append(s + "\n");
     public static void main(String args[]) {
          new TicTacToeServer(args);
class ClientResponseHandler extends Thread {
     private Socket connection;
       private BufferedReader in;
       private PrintWriter out;
       private Board board;   
       private int playerNumber;
     private TicTacToeServer server;
     public ClientResponseHandler(Socket connection, Board board, TicTacToeServer server) {
          this.connection = connection;
          this.board = board;
          this.server = server;
         server.display("A player has connected");
          try {
               in  = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                out = new PrintWriter(connection.getOutputStream(), true);
          catch(Exception e) {
               server.display(e.toString());
     public synchronized void sendChatMessage(String msg) {
          if (out != null) {
               out.println("Chat" + msg);
               out.flush();
     public void run()  {
          playerNumber = board.addPlayer(out);
          if (playerNumber != -1)
               parsePlayerInput();
          else    
               out.println("Player limit reached");
          closeLink();
     private void parsePlayerInput() {
          String inputFromPlayer;
          boolean done = false;
          try {
               while (!done) {
                    if((inputFromPlayer = in.readLine()) == null)
                         done = true;
                    else {
                         server.display("Client --> Server: " + inputFromPlayer);
                          if (inputFromPlayer.startsWith("Socket is closed"))
                              done = true;
                         else if (inputFromPlayer.startsWith("Chat")) {
                              Iterator iter = server.activePlayers.iterator();
                              while (iter.hasNext()) {
                                   ClientResponseHandler t = (ClientResponseHandler) iter.next();
                                   if (t != this)
                                        t.sendChatMessage(inputFromPlayer.substring(4));
                         else
                              parsePlayerCellLocation(inputFromPlayer);
          catch(IOException e) {
               server.display(e.toString());
     private void parsePlayerCellLocation(String inputFromPlayer) {
               if (inputFromPlayer.startsWith("Client clicked cell ")) {
                    try {
                         int clientCellLocation = Integer.parseInt(inputFromPlayer.substring(20,21).trim());
                         board.tryMove(playerNumber, clientCellLocation);
                    catch(NumberFormatException e) {
                         server.display(e.toString());
     private void closeLink() {
          try {
               board.delPlayer(playerNumber);
                connection.close();
                server.display("Client connection closed by player " + playerNumber + "\n");
         catch(Exception e) {
               server.display(e.toString());
class Board {
     private int board[];
     private Player player[];
     private int numPlayers;
       private boolean gameEnabled, isGameOver;
     private int currentPlayerNumber;
     private TicTacToeServer server;
     public Board(TicTacToeServer server) {
          this.server = server;
          board = new int[9];
         initializeBoard();
          player = new Player[2];
             player[0] = new Player("X");
         player[1] = new Player("O");
          numPlayers = 0;
         gameEnabled = false;
         isGameOver = false;
     private void initializeBoard() {
          for(int i = 0; i < 9; i++)
               board[i] = -1;
     synchronized public int addPlayer(PrintWriter out) {
          if (numPlayers == 2)  
               return -1;          
          player[numPlayers].setOutput(out);
          String token = player[numPlayers].getToken();
          server.display("Server --> Client: Player connected " + token);
          player[numPlayers].sendMessage("Player connected " + token);
          numPlayers++;
          if (numPlayers == 2) {  
               gameEnabled = true;
               currentPlayerNumber = 0;
               player[currentPlayerNumber].sendMessage("Game is ready to begin");  
          return numPlayers - 1;
     synchronized public void delPlayer(int playerNumber) {
          player[playerNumber].disable();
          if (numPlayers == 2) {
               int otherId = (playerNumber + 1) % 2;
               player[otherId].sendMessage("Player exited");
                player[otherId].disable();
          numPlayers = 0;
         gameEnabled = false;
             isGameOver = false;
         initializeBoard();
     synchronized public void tryMove(int playerNumber, int cellNumber) {
          if (!gameEnabled)                
               player[playerNumber].sendMessage("Only 1 player connected");
          else if (isGameOver)
               player[playerNumber].sendMessage("Game over");
         else if (currentPlayerNumber != playerNumber)    
                player[playerNumber].sendMessage("Not your turn");
         else if (cellOccupied(cellNumber))       
                player[playerNumber].sendMessage("Cell occupied");
         else {       
                board[cellNumber] = playerNumber;
               player[playerNumber].sendMessage("Valid move " + cellNumber);
                currentPlayerNumber = (currentPlayerNumber + 1) % 2;  
                player[currentPlayerNumber].sendMessage("Update opp " + cellNumber);
               if (gameOver()) {
                    player[playerNumber].sendMessage("Player won");   
                  player[currentPlayerNumber].sendMessage("Player lost"); 
                  isGameOver = true;
     private boolean cellOccupied(int cellNumber) {
          return (board[cellNumber] != -1);
     private boolean gameOver() {
          if (sameVals(0,1,2) || sameVals(3,4,5) || sameVals(6,7,8) ||
               sameVals(0,3,6) || sameVals(1,4,7) || sameVals(2,5,8) ||
               sameVals(0,4,8) || sameVals(6,4,2))
               return true;
               return false;
     private boolean sameVals(int c1, int c2, int c3) {
          if ((board[c1] == board[c2]) && (board[c2] == board[c3]) && (board[c1] != -1))
               return true;
          return false;
class Player {
     String token;
     PrintWriter out;
     public Player(String token) {
          this.token = token;
         out = null;
     public void setOutput(PrintWriter out) {
          this.out = out;
     public String getToken() {
          return token;
     public void disable() {
          out = null;
     public void sendMessage(String msg) {
          out.println(msg);
}

I suggest you seperate you network handling logic from your game code.
Then debug the message sent and received.
BTW: And use a code formatter.
I have a simple example chat program here.
http://www.jtoolkit.org/space/Point+to+Point.html

Similar Messages

  • URGENT: Multiplayer Online Game

    What would be the best way to make a multiplayer online game? I know how to create a game using an applet. Do I need to use a servlet? I know nothing about comunicating across the internet using java. Thanks.

    no you dont need a servlet, nor an applet.. just write it. you choose servet vs. applet vs app when you ask 'how do i want them to get it?" then that helps you decide limitations of the game..
    do you mind them dl'ing a client manually?
    do you want it put into a web page for auto download?
    do you want it to be a web page? (sorta dull dont ya think? click right to go right, click left arrow to go left.. reminds me of wumpus hunting!)
    so, then you need to figure out how to communicate over a wire... advanced java networks is a good book for that.. gives a good smattering of rmi, corba, sockets, etc etc..
    so once you realize sockets is the answer then go look at java.io, java.net and what not.. follow the tutorials.. ask some questions along the way and walla.. you have a simpel client/server.. after that, start writing your game.
    enjoy.

  • Multiplayer Flash Game

    Hello, i must develop a multiplayer flash game. Ok i'm
    studying and try more example but is there some code example
    online?
    i research source of a easy multiplayer game but i dont
    find..

    Hi,
    I have an online multiplayer flash chess game based on FMS
    SharedObject/Audio/Video. You may have a look at
    http://go.avmeeting.net
    But I can't send you the code because there are more than 20
    thousand lines in more than 20 .fla and .as files.
    You may try to play a game between at least two computers.
    Have fun!
    Jeffrey

  • [HELP] Online Multiplayer Quiz Game!

    Hi, I am wondering if it is possible to make online multiplayer quiz game.
    With that I mean over the LAN network.
    Like it use the bluetooth and you connect to it.
    Like the quiz is to answer 0-20 on german and when you click check it will send the answer to the other phone. Like if my mom have it and says whats wrong and right you know. It would be neat if you did help me!
    Thanks, Sander over here!
    In ActionScript 3 to Air for IOS.

    multiplayer games are for advanced programmers.
    the easiest way to start multiplayer gaming with flash is it use adobe's rtmfp peer-to-peer connections.  here's an excerpt from a book (Flash Game Development: In a Social, Mobile and 3D World) i wrote:
    Multiplayer Games
    With multiplayer games data needs to be communicated among the players.  When a player makes a move (changing the game state) the updated game state needs to be communicated to all the other players. In addition, that communication needs to occur in a timely manner. 
    With turn based games (like card games) that communication among players can take as long as few seconds without degrading the game experience. With real time games (like shooter games), even a 250 millisecond delay in communicating game state leads to a significantly degraded player experience. Consequently, real time multiplayer games require substantial expertise to successfully develop and deploy.
    There are two fundamentally different ways that communication among players can be accomplished. Players can communicate via a server (server based games) or they can communicate directly from player to player (peer-to-peer) games.
    Server Based Multiplayer Games
    Generally, the code in each player’s Flash game handles the player’s input, transmits player data to the server, receives other players' data and displays the game state. The server receives player data, validates the data, updates and maintains game state and transmits each player’s data to the other players.
    The code used on the server cannot be ActionScript so you will need to learn a server-side coding language like php or c#.  Server-side coding is beyond the scope of this book so I will not cover server based multiplayer games except to say you need to have advanced coding skills in, at least, two languages (ActionScript and a server-side language) to create these game types.
    Peer-to-peer games
    Since Flash player 10, you can create multiplayer games without the need of an intermediary server to facilitate player communication.  The Flash player can use a protocol (Adobe's Real-Time Media Flow Protocol) that allows direct peer-to-peer communication.
    Instead of using server-side code to handle the game logic and coordinate game state among players, each peer in the network handles their own game logic and game state and communicates that directly to their peers and each peer updates their game state based on the data received from others.
    To use peer-to-peer networking each peer must connect with an Adobe server.  Peer-to-peer communication does not go through that server (or it that would not be peer-to-peer) but peers must stay connected with the Adobe server in order to communicate with each other.
    To communicate with the Adobe server you should use your own server URL and developer key. That URL and key can be obtained at http://www.adobe.com/cfusion/entitlement/index.cfm?e=cirrus.

  • How to create a turn-based multiplayer online game?

    Hello. This is my first time here. I am familiar with programming games and have been doing so for 20 years. However, I'm completely new to using Java to do so. In the past, I wrote games in BASIC, Blitz, and C++ using DirectX. Being familiar with C/C++, the Java language syntax is not a hurdle for me.
    I've never created a networking game, but I feel that if I tried to create one using one of the programming languages I already know that I would succeed at doing so. (I'm just trying to show that I feel confident in programming with the languages that i know)
    The dilemma here is that someone else would like me to program a turn'based multiplayer game for them in Java.
    I've downloaded the NetBeans 4.1 IDE and uncovered a lot of terms and such that I'm unfamiliar with.
    What I'm looking for from you guys is an overview of what I need to do to achieve my ultimate goal of creating this online game.
    As a reference, I need to create a game very similar to this one:
    http://www.tacticsarena.com/play/
    Click on the "Launch Game: Tactics Arena Online" link to see the game.
    Create a new account to play (accounts are free).
    Upon starting the NetBeans IDE, I found that I could create several different types of projects. I guess first of all, I need to know what kind of project is best suited to make this type of game.
    To name a few, I have to select from:
    Java Application
    Java Class Library (is this an Applet?)
    Web Application
    Enterprise Application
    EJB Module
    Then I guess I would like to know if any of the above projects would be used to make the clients interface or the server side software or both? Or do I need to use some other kind of software/programming language/etc. to create the server side? (As a side note, typically what kind of Operating system would the server be using? I ask because I may set one up myself for testing purposes.)
    Somewhere I came upon the term 'Servlet'. Is this some kind of Java server application? Do I need/want to be using this?
    As you can see, I'm very lost at where to begin. I'm not at all unfamiliar with programming. I'm just unfamiliar with Java.
    WolRon

    Hi WolRon
    I am in the process of learning Java myself and from what i have read, you have a long road ahead of you!
    To start this Project the following will be essential for you to know:
    Applets - if this is going to an online game
    Multiple Threads - for the Server side
    Swing - for the GUI on both sides
    AWT - help work with the user input (mouseListeners, buttonListeners, etc)
    And knowledge of a database.
    those are the most obvious things that you will need to understand.
    I strongly suggest buying a Java book from which you need to start at the beginning. Although the concept of OOP is the same through most languages Java has terms - as do all languages- that will be different from the other languages. Starting at the beginning will be beneficial to your Java coding future.
    Good luck.

  • Online Multiplayer Table Game Framework

    I'm another person who is considering creating an online multiplayer java based game with a collection of different tables to which users can connect. This would be similar to the yahoo games or any of the online poker games.
    Does anyone know of a java framework for creating the server part for these types of games? I've looked but couldn't find any.

    You will probably have to build it from scratch. I suggest reading the Networking section of the Java Tutorial - http://java.sun.com/tutorial .

  • Is there some multiplayer online games... but for three or more players?

    Hi, somebody knows a multiplayer game but for more than 2 gamers?
    Thanks

    Many panels can do this.  Specifically, I think tint2 would be the easiest to configure for something like the Win3.1 style of iconifying.  Just set the tint2rc to only show iconified items, have all transparent backgrounds, and to show only icons and no text.
    EDIT: I guess this depends on whether you'd want to be able to drag the icons around.  Tint2 would not allow this.  They'd just show when the window was iconified, and could be clicked on to show the window again.  As another option, Rox desktop manager does something like this if I'm remembering right (it's been a while).
    Last edited by Trilby (2013-11-03 21:38:01)

  • Lags in Multiplayer/Online Games (4S)

    Hallo,
    I have been using the new iPhone 4S for a couple of days now. Everything is good except for some decent lagging in online games.
    I have two games which are graphics-intensive.
    These are:
    - MetalStorm
    - Asphalt 6: Adrenaline
    both games work perfectly in Offline/Single player mode.
    Once I choose to play online the lags start. They range from once in 2 seconds to once in 20 seconds on average. The lag time is around 0.2 of a second. Pretty small lag, but takes a lot (if not everything) from good gaming experience and irritates a lot.
    This is not a problem with my internet. I have played with friends on WiFi Locally in the multiplayer mode. This is also not a problem with my router because my friends have the iPhone 4 and I also have an iPod touch. The problem occurs ONLY on the iPhone 4S (which is funny since it is supposed to be the fastest iOS Device).
    I have read somewhere that airplane mode could help, but it does not change anything.
    Does anyone have such a problem? Any suggestions?

    Hallo,
    I have been using the new iPhone 4S for a couple of days now. Everything is good except for some decent lagging in online games.
    I have two games which are graphics-intensive.
    These are:
    - MetalStorm
    - Asphalt 6: Adrenaline
    both games work perfectly in Offline/Single player mode.
    Once I choose to play online the lags start. They range from once in 2 seconds to once in 20 seconds on average. The lag time is around 0.2 of a second. Pretty small lag, but takes a lot (if not everything) from good gaming experience and irritates a lot.
    This is not a problem with my internet. I have played with friends on WiFi Locally in the multiplayer mode. This is also not a problem with my router because my friends have the iPhone 4 and I also have an iPod touch. The problem occurs ONLY on the iPhone 4S (which is funny since it is supposed to be the fastest iOS Device).
    I have read somewhere that airplane mode could help, but it does not change anything.
    Does anyone have such a problem? Any suggestions?

  • No multiplayer on game centre

    My iPad is running iOS 4.2.1, which means that it has game centre. I understand that fruit ninja version 1.5 has game centre integration which has multiplayer. However, when I use my iPad and select new game, it only has classic, xen mode and arcade mode but no multiplayer while my iPhone has all three including multiplayer mode.. I upgraded to the latest version of fruit ninja but nothing... Please help,this is killing me... Really looking forward to play multiplayer on the iPad...
    Message was edited by: Game centre

    So is it true that you cannot play multiplayer games designed for the iPhone on the iPad? Then isn't it kinda dumb, since iPhone and iPod touch games are designed to work on the iPad? However, if you look under the game centre apps designed for iPhone on the iPad, fruit ninja is listed? So I don't know, is there a problem with the app or iPad? Please help
    Message was edited by: Game centre
    Message was edited by: Game centre

  • Multiplayer Java Game with java networking ???

    Hi everybody. I responsed a new university finising project. I will create a new game that multiplayer on a server. I am in a simple level on java. I have no java networking or no jdbc info. I belive I can success but I have no idea about which map i should follow. I will wait for your suggestions.
    (Or can I find a muliplayer game sample with java networking?)

    Maybe you could use RMI if you haven't got latency problems (that u will encounter certainly if you intend to use it with 56k modem).
    It's quite flexible and in java 5 also more usable.

  • New Alternative Serialization classes for Multiplayer Network Games

    Hello Games Developers,
    I've been working on an alternative Serialization technique that attempts to over-come the de-serialization problems of garbage collection and object-finding on the client side.
    I'd like people to try it out and also I need some know-how on HotSpot optimisation, please check out the progress at the Serialization forum at
    http://forum.java.sun.com/thread.jspa?messageID=3990301
    Cheers,
    Keith

    Well, your game is great and all, but the code is really in-depth. We aren't looking for something that complex, just the basics for right now. I have to have something simple to build with right now in order to eventually make something amazing.

  • Distributed Game Development - What are appropriate & latest technologies?

    I have a situation. Its more like a design and use of appropriate technology sort of question.
    I am developing a board game say, chess - but it will be played by upto 4 users or only one user (AI).
    Client sides are applets;
    Game logic running on Glassfish Server.
    Applet to Backend communiction -> web services
    ...but question is How Backend notify all other players' boards to update clients(applets) on their side with new move?
    Thanks for your favor in anticipation.

    I have a situation. Its more like a design and use of appropriate technology sort of question.
    I am developing a board game say, chess - but it will be played by upto 4 users or only one user (AI).
    Client sides are applets;
    Game logic running on Glassfish Server.
    Applet to Backend communiction -> web services
    ...but question is How Backend notify all other players' boards to update clients(applets) on their side with new move?
    Thanks for your favor in anticipation.

  • New multiplayer 3d game called SHOCKLANDER

    Hi all,
    This is my recent work , comments are appreciated.
    You can play the game from the link below:
    http://www.shockland.com/games/shocklander/shocklander_game_detail_v.jsp
    Best regards
    Ege Karaosmanoglu
    www.shockland.com

    Thanks Dean,
    You are right , I can add arrow keys to navigate also.
    regards
    Ege
    quote:
    Originally posted by:
    Newsgroup User
    Hi Ege,
    Very nice graphics.
    Game took a while to load. I didn't find the navigation all
    that easy. I
    prefer arrow keys to letters. And, moving the mouse to angle
    the camera
    didn't seem all that friendly either.
    I didn't explore the game too much. Looked interesting moving
    around.
    regards
    Dean
    Director Lecturer / Consultant / Director Enthusiast
    http://www.fbe.unsw.edu.au/learning/director
    http://www.multimediacreative.com.au
    email: [email protected]

  • Multiplayer Applet Game I made

    Hey Everyone. I made an online 2 player head to head picture puzzle game which I call Jeuno Jumble.
    It's a lot of fun and it runs really smoothly by my standards. I'm looking for people to give it a try and possibly provide feedback on design or technical issues that may arise.
    Here's the link:
    [http://www.jeuno.ca/jumble/multiplayerbeta/JeunoJumbleMP.php]
    Thanks for your help and I hope to see you in the game room.

    Humm.. I visited your link and got the message "Applet crashed."
    This is from the Java console (Opera, JavaScript disabled)
    java.security.AccessControlException: access denied (java.net.SocketPermission www.jeuno.ca:80 connect,resolve)
         at java.security.AccessControlContext.checkPermission(Unknown Source)
         at java.security.AccessController.checkPermission(Unknown Source)
         at java.lang.SecurityManager.checkPermission(Unknown Source)
         at com.opera.AppletContext.checkConnect(AppletContext.java:134)
         at com.opera.AppletContext.getAudioClip(AppletContext.java:202)
         at java.applet.Applet.getAudioClip(Unknown Source)
         at java.applet.Applet.getAudioClip(Unknown Source)
         at JeunoJumbleLobby.init(JeunoJumbleLobby.java:62)
         at com.opera.AppletPanel.runHandlerThread(AppletPanel.java:438)
         at com.opera.AppletPanel.run(AppletPanel.java:334)
         at java.lang.Thread.run(Unknown Source)Well it just might be because of a corporate firewall.
    db

  • Multiplayer online Game

    What I need to use to develop amultiplayer online game ..say a TicTacToe Game, 2 player can start one instance, another two play can start anathor game and so on..
    Is it possible with J2SE, or I need to use J2EE?

    jwenting wrote:
    Not even a servlet container. Could be a standalone tcp server running next to a regular webserver like Apache.
    The webserver serves the applet and static html it's displayed in, applet connects to the standalone server using a custom protocol (it does need to run on the same host to be accessible of course).Yep, even that. Although I'd posit that using a servlet container would probably be simpler, and alleviate some of the more bothersome low-level networking hassle. But yep, it's worth considering.

Maybe you are looking for

  • Error while running jBoss Server

    After giving the run.bat command from command prompt and after setting the class path to JBOSS_HOME:C:\jBoss\JBoss-2.4.4 path:C:\jBoss\JBoss-2.4.4\bin The error which is being displayed is [ERROR,Default] java.net.MalformedURLException [ERROR,Default

  • Airport: Not Configured after 10.4.7 update

    I just bought a new macbook 2.0Ghz, proceeded through the first-time installation wizard setup my wifi settings, and everything worked fine. At first boot in macosx i had my wifi working and i was able to browse and download things. I installed the 1

  • Playing DVD from Mac to Apple TV

    Hi there, I recently purchased Apple TV and would like to know if it is possible to view  my wedding film on dvd from my mac to my apple tv. When i turn on Apple TV Airplay mirroring the screen on my mac and my TV is grey and white checkered and it w

  • Servlet calling a BAPI Web Service...

    Hi everyone, I downloaded the wsdl file for the BAPI_USER_GETLIST. I created a Deployable Proxy that points to this wsdl file. I created a Web modul project with a servlet. I also created an Enterprise application project that contains my Web modul p

  • Internal Speakers and Digital Output

    Hi, I plugged in my iPod Nano yesterday to update it, and ever since, can't assign my inbuilt speakers as the audio output. The only option is "DIGITAL OUT", which has no output controls. I've repaired permissions, plugged the iPod in and out, and re