Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3309312
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 17, 20262026-05-17T21:37:33+00:00 2026-05-17T21:37:33+00:00

I’m currently trying to implement the game of Nim using Java, I want to

  • 0

I’m currently trying to implement the game of Nim using Java, I want to be able to have one player act as the server and another as the player.

I’m fairly new to Java networking and have only had experience using basic TCP/IP where the human client connects to a computer host.

The trouble I’m having is that I need to be able to differentiate between the different players whilst implementing the protocol for the game (The protocol being the logic for the game).

As it stands I can let one player (Client) interact with the Server. All that happens is the Client can play the game but there is no oppostion (The Server merely tracks the state of the game e.g. How many sticks left, valid input etc..).

How would I go about adding a second player to take the place of the host?

Edit:

The Client and Server code has been posted, it is the code I have used and I’m quite comfortable with, the question I am asking is would it be a suitable base to implement a multi-player game or would I need to do something completely different?

My Nim Protocol: (Untested)

public class NimLogic 
{
    private static final int WAITING = 0;
    private static final int EVALUATING = 1;
    private static final int ANOTHER = 2;
    private int currentState = WAITING;
    private int theInput = 0;
    private int totalSticks = 10;

    String processInput(String input) {
        String theOutput = null;

        try 
        {
            theInput = Integer.parseInt(input);
        } 
        catch (Exception e) 
        {
            // Ignore conversion error
        }

        switch (currentState) 
        {
        case WAITING:
            theOutput = "Take how many sticks?";
            currentState = EVALUATING;
            break;

        case EVALUATING:

            if(theInput == 1 | theInput == 2 | theInput == 3)
            {
                if (theInput < totalSticks) 
                {
                    totalSticks -= theInput;
                    theOutput = "There are" + totalSticks + " left.";
                } 
                else if (theInput > totalSticks) 
                {
                    theOutput = "Error: You cannot take more sticks than that are available";
                    currentState = EVALUATING;
                } 
            }

            if(totalSticks == 1)
            {
                theOutput = "Game Over! Play again? (Yes = 1, No = 0)...";
                currentState = ANOTHER;
            }
            break;

        case ANOTHER:
            if (theInput == 1) 
            {
                totalSticks = 10;
                currentState = EVALUATING;
                theOutput = "Take how many sticks?";
            } 
            else 
            {
                theOutput = "Bye.";
            }
        }
        return theOutput;
    }
}

Thanks for all the help!

Edit:

Client

public class Client
{
   @SuppressWarnings("static-access")
public static void main(String machine[])
   {
      Socket kkSocket = null;
      PrintStream os = null;
      DataInputStream is = null;

      try
      {
         kkSocket = new Socket(machine[0], 4444);
         os = new PrintStream(kkSocket.getOutputStream());
         is = new DataInputStream(kkSocket.getInputStream());
      }
      catch(UnknownHostException e)
      {
         System.err.println("Socket Connect failed on " + machine[0]);
      }
      catch (IOException e)
      {
         System.err.println("Streams failed on " + machine[0]);
      }

      if (kkSocket != null && os != null && is != null )
      {
         try
         {
             String fromServer, fromClient;

             while((fromServer = is.readLine()) != null && !fromServer.equals("Bye."))
             {
                fromClient = JOptionPane.showInputDialog(fromServer);
                os.println(fromClient);
             }
             JOptionPane.showMessageDialog(null, "Goodbye, keep smiling.");
             os.close();
             is.close();
             kkSocket.close();
          }

         catch (UnknownHostException e)
         {
            System.err.println("Can't connect to " + machine[0] + e);
         }
         catch (IOException e)
         {
            e.printStackTrace();
            System.err.println("I/O failed on " +machine[0]);
         }
      }
   }
}

Server

public class Server
{
   public static void main(String arg[])
   {
      ServerSocket serverSocket = null;

      try
      {
         serverSocket = new ServerSocket(4444);
      }
      catch (IOException e)
      {
         System.err.println("Can't listen on 4444 -> " + e);
         System.exit(1);
      }

      Socket clientSocket = null;
      try       // allow the client to connect
      {
         clientSocket = serverSocket.accept();
      }
      catch (IOException e)
      {
         System.err.println("Failed accept on 4444 -> " + e);
         System.exit(1);
      }

      try
      {
         DataInputStream is =
            new DataInputStream(new BufferedInputStream
                           (clientSocket.getInputStream()));
         PrintStream os =
            new PrintStream(new BufferedOutputStream
              (clientSocket.getOutputStream(), 1024), false);
         GuessState kks = new GuessState();
         String inputLine, outputLine;

         outputLine = kks.processInput(null);
         os.println(outputLine);
         os.flush();

         while((inputLine = is.readLine()) != null
                && !outputLine.equals("Bye."))
         {
            outputLine = kks.processInput(inputLine);
            os.println(outputLine);
            os.flush();
         }
         os.close();
         is.close();
         clientSocket.close();
         serverSocket.close();
      }
      catch (IOException e)
      {
         e.printStackTrace();
      }
   }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-17T21:37:33+00:00Added an answer on May 17, 2026 at 9:37 pm

    I’m not quite sure if I’m answering your question here, so apologies if I’m not. Also, it’s been a little while since I did any Java networking code, so there might be a few wrinkles here which hopefully others can sort out.

    The following is a bit of a brain dump of the changes I’d probably make, for better or worse…

    • Rework the networking code to accept multiple connections. Normally you’d do this by handing off the socket returned by ServerSocket.accept to a thread to process. If you were dealing with a lot of connections, you could do it using NIO instead, but that’s probably too far to fast for now.
    • Separate the game state from the client conversation code. To keep things simple, embed the client conversation code in the thread object. The game state needs to be in an object that’s shared between all the threads servicing the socket.
    • I’d recommend making the game state a proper ‘domain object’ rather than having it parsing strings etc. It should have operations like ‘take(clientID, int)’ rather than ‘processInput’.
    • Consider using the observer pattern to distribute events from the domain object to the socket threads. Examples of events might be ‘turnTaken’ or ‘gameComplete’.
    • Embed the notion of ‘turns’ into the game object, and have the server broadcast an event to the socket threads announcing whose turn it is.

    Hope that gives you a starter for ten?

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want use html5's new tag to play a wav file (currently only supported
I am trying to loop through a bunch of documents I have to put
I'm making a simple page using Google Maps API 3. My first. One marker
I am currently running into a problem where an element is coming back from
I have a JSP page retrieving data and when single or double quotes are
link Im having trouble converting the html entites into html characters, (&# 8217;) i
this is what i have right now Drawing an RSS feed into the php,
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.