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

  • SEARCH
  • Home
  • 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 8465895
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T15:11:01+00:00 2026-06-10T15:11:01+00:00

so I’m working on a really simple multiplayer Java game, just one where you

  • 0

so I’m working on a really simple multiplayer Java game, just one where you click on the screen and your player moves to that spot in a straight line, and show all the other connected players your players movement, here are the three classes:

Bots:

import java.applet.Applet;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;


public class Bots extends Applet implements MouseListener, Runnable{

Thread gameLoop;
ArrayList<Player> players = new ArrayList<Player>();

//Socket stuff for multiplayer client
final static String SERVER_ADDR = "localhost";
final static int SERVER_PORT = 1025;
static Socket socket;
static volatile BufferedReader br;
static PrintWriter pw;


//Double buffer stuff
Graphics g; 
Image offscreen;
Dimension dim;

@Override
public void run() {
    //Starts the main game loop
    Thread t = Thread.currentThread();
    //Checks to see if the thread is alive
    while (t == gameLoop){
        try{
        Thread.sleep(1000/60);
        //Repaints the screen
        players.get(0).move();
        repaint();

        if (socket != null){
            sendMove();
        }
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

public void start(){
    gameLoop = new Thread(this);
    gameLoop.start();
}

public void stop(){
    gameLoop = null;
}

public void init(){
    this.setSize(640,480);
    dim = this.getSize();

    addMouseListener(this);

    //More double buffer stuff
    offscreen = createImage(this.getSize().width,this.getSize().height);
    g = offscreen.getGraphics();

    //Adds the initial player
    players.add(new Player(320,240,8,8,"Jeremy"));
    multiplayer();
}

public void paint(Graphics bufferGraphics){
    g = offscreen.getGraphics(); 
    g.clearRect(0,0,dim.width,dim.height);

    g.setColor(Color.BLACK);
    for (Player player: players){
        g.fillOval(player.x, player.y, player.width, player.height);
    }

    bufferGraphics.drawImage(offscreen,0,0,this);
}

public void multiplayer(){

    try {
        socket = new Socket(SERVER_ADDR, SERVER_PORT);
        InputStreamReader isr;
        isr = new InputStreamReader(socket.getInputStream());
        br = new BufferedReader(isr);
        pw = new PrintWriter(socket.getOutputStream(), true);
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    multiplayerThread();

}

public void sendMove(){
    //pw.println(players.get(0).name+":X"+players.get(0).x+":Y"+players.get(0).y);
}

public void multiplayerThread(){
    new Thread(){
        public void run() { 
            String line;
             try {
                while ((line = br.readLine()) != null) {
                    boolean newClient = true;
                    for (Player player: players){
                        if (line.startsWith(player.name)){
                            if (line.startsWith(players.get(0).name)){
                                //Do nothing
                                newClient = false;
                            } else {
                                String[] tempLine = line.split(":");
                                player.x = Integer.parseInt(tempLine[1].substring(1));
                                player.y = Integer.parseInt(tempLine[2].substring(1));
                                newClient = false;
                            }
                        }
                        System.out.println(line);
                    }
                    if (newClient && !line.contains("Welcome")){
                        String[] tempLine = line.split(":");
                        players.add(new Player (Integer.parseInt(tempLine[1].substring(1)),Integer.parseInt(tempLine[2].substring(1)),8,8,tempLine[0].substring(0)));
                    }

                }
             }
             catch (IOException ioe) {
             }
        }
    }.start();
}
@Override
public void mouseClicked(MouseEvent me) {
    // TODO Auto-generated method stub

}

@Override
public void mouseEntered(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mouseExited(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mousePressed(MouseEvent me) {
    // TODO Auto-generated method stub
    players.get(0).x2 = me.getX();
    players.get(0).y2 = me.getY();
    players.get(0).calculateMove();
}

@Override
public void mouseReleased(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

public void update(Graphics g) 
{ 
     paint(g); 
}
}

Player class:

    import java.awt.Rectangle;


public class Player {

    public String name;
    public int x;
    public int y;
    public int width;
    public int height;

    public int x2;
    public int y2;
    public int longest;
    public int numerator;
    public int shortest;
    public int dx1,dy1,dx2,dy2;
    public boolean moving;

    public Player(int x, int y, int width, int height, String name) {
        this.x = x;
        this.y = y;
        this.x2 = x;
        this.y2 =y;
        this.width = width;
        this.height = height;
        this.name = name;
    }

    public Rectangle getBounds(){
        Rectangle r;
        r = new Rectangle(x - width/2, y-height/2,width,height);
        return r;
    }

    public void move(){
        if (this.x2 != this.x && this.y2 != this.y){
            this.numerator += this.shortest ;
            if (!(this.numerator<this.longest)) {
                this.numerator -= this.longest ;
                this.x += this.dx1 ;
                this.y += this.dy1 ;
            } else {
                this.x += this.dx2 ;
                this.y += this.dy2 ;
            }
            this.moving = false;

        }
    }

    public void calculateMove(){
         int w = x2 - x ;
            int h = y2 - y ;
            int dx1 = 0, dy1 = 0, dx2 = 0, dy2 = 0 ;
            if (w<0) dx1 = -1 ; else if (w>0) dx1 = 1 ;
            if (h<0) dy1 = -1 ; else if (h>0) dy1 = 1 ;
            if (w<0) dx2 = -1 ; else if (w>0) dx2 = 1 ;
            int longest = Math.abs(w) ;
            int shortest = Math.abs(h) ;
            if (!(longest>shortest)) {
                longest = Math.abs(h) ;
                shortest = Math.abs(w) ;
                if (h<0) dy2 = -1 ; else if (h>0) dy2 = 1 ;
                dx2 = 0 ;            
            }
            this.shortest = shortest;
            this.longest = longest;
            this.numerator = longest >> 1 ;
            this.dx1 = dx1;
            this.dy1 = dy1;
            this.dx2 = dx2;
            this.dy2 = dy2;
            this.moving = true;
            }

}

And finally my BotsServer class:

    import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintWriter;

import java.net.ServerSocket;
import java.net.Socket;

import java.util.ArrayList;
import java.util.List;

class BotsServer
{
   private final static int PORT_NO = 1025;
   private ServerSocket listener;
   private List<Connection> clients;
   BotsServer() throws IOException
   {
      listener = new ServerSocket(PORT_NO);
      clients = new ArrayList<Connection>();
      System.out.println("listening on port "+PORT_NO);
   }
   void runServer()
   {
      try
      {
         while (true)
         {
            Socket socket = listener.accept();
            System.out.println("accepted connection");
            Connection con = new Connection(socket);
            synchronized(clients)
            {
               clients.add(con);
               con.start();
               con.send("Welcome!");
            }
         }
      }
      catch (IOException ioe)
      {
         System.err.println("I/O error: "+ioe.getMessage());
         return;
      }
   }
   private class Connection extends Thread
   {
      private volatile BufferedReader br;
      private volatile PrintWriter pw;
      private String clientName;
      Connection(Socket s) throws IOException
      {
         br = new BufferedReader(new InputStreamReader(s.getInputStream()));
         pw = new PrintWriter(s.getOutputStream(), true);
      }
      @Override
      public void run()
      {
         System.out.println("test");
         String line;
         try
         {
            while ((line = br.readLine()) != null){
                System.out.println(line);
               send(line);
            }
         }
         catch (IOException ioe)
         {
            System.err.println("I/O error: "+ioe.getMessage());
         }
         finally
         {
            synchronized(clients)
            {
               clients.remove(this);
            }
         }

      }

      private void send(String message)
      {
         pw.println(message);
      }

   }
   public static void main(String[] args)
   {
      try
      {
         System.out.println("ChatServer starting");
         new BotsServer().runServer();
      }
      catch (IOException ioe)
      {
         System.err.println("unable to create server socket");
      }
   }
}

The problem I believe is in the BotsServer class, I put:

System.out.println("test");

in the run but it is only ever getting called when clients first connect, should it be looping? Any help is great! Thanks!

  • 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-06-10T15:11:02+00:00Added an answer on June 10, 2026 at 3:11 pm

    BotServer.Connection is a Thread. The run method of a Thread is only called once. Your test print is inside run() but not inside any loop, so it will only get printed once per BotServer.Connection you start(). So the behavior you are seeing makes sense to me. Why do you think it should loop?

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

Sidebar

Related Questions

I have just tried to save a simple *.rtf file with some websites and
I am doing a simple coin flipping experiment for class that involves flipping a
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm working with an upstream system that sometimes sends me text destined for HTML/XML
I'm making a simple page using Google Maps API 3. My first. One marker
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I've got a string that has curly quotes in it. I'd like to replace
I am reading a book about Javascript and jQuery and using one of the

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.