Multithreading and Game

Hi guys,
I am in my first year of Java programming I have sort of hit a roadblock with an assignment we were given.
The assignment is about networking and the game that the players will play is Snakes and Ladders. I have successfully made the snakes and ladders game to work in the class Main.
I then created 2 more classes to allow the multiple players to connect and play the game. The class Server and the class Client.
Unfortunately at the moment I can only get 1 client to connect to the Server and I don't know how to get multiple connections.
I tried to re-draw the Gui for every new connection but I am not quite sure how to get each player to play the game and see the moves of the other players. Any ideas?
Class Main:_
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import java.awt.image.*;
public class Main implements ActionListener{
    boolean buttonPressed = false;
    SnakesAndLaddersGUI gui;
    int[] pos;
    JButton go = new JButton("Roll Dice");
    public Main() {
        gui = new SnakesAndLaddersGUI();
        pos = new int[5];
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(450, 450);
        JPanel controlPanel = new JPanel();
        controlPanel.setSize(450, 100);
        go.addActionListener(this);
        controlPanel.add(go);
        f.getContentPane().add(gui, BorderLayout.CENTER);
        f.getContentPane().add(controlPanel, BorderLayout.SOUTH);
        f.setVisible(true);
        gui.setNumberOfPlayers(5);
        for (int i = 0; i < 5; i++) {
            pos[i] = 0;
            gui.setPosition(i, 0);
        while (true) {
            if (buttonPressed) {
                move();
                buttonPressed = false;
    public void actionPerformed(ActionEvent e) {
        buttonPressed = true;
    public int PositionTest(int pos) {
        //the below conditions will lead to climbing ladders
        //or being eaten by snakes
        if (pos == 6) {
            return 16;
        } else if (pos == 11) {
            return 49;
        } else if (pos == 14) {
            return 4;
        } else if (pos == 24) {
            return 87;
        } else if (pos == 31) {
            return 9;
        } else if (pos == 35) {
            return 54;
        } else if (pos == 21) {
            return 60;
        } else if (pos == 44) {
            return 26;
        } else if (pos == 51) {
            return 67;
        } else if (pos == 56) {
            return 53;
        } else if (pos == 62) {
            return 19;
        } else if (pos == 64) {
            return 42;
        } else if (pos == 6) {
            return 16;
        } else if (pos == 73) {
            return 92;
        } else if (pos == 84) {
            return 28;
        } else if (pos == 78) {
            return 100;
        } else if (pos == 98) {
            return 80;
        } else if (pos == 95) {
            return 75;
        } else if (pos == 91) {
            return 71;
        } else {
            return pos;
    public void move() {
        try {
            int dice;
              Thread.sleep(500);
            for (int i = 0; i < 5; i++) {
                dice = (int) ((Math.random() * 10) % 6) + 1;
                if (pos[i] + dice < 100) {
                    while (dice > 0) {
                        System.out.print(dice);
                        System.out.println("\t" + i + "," + pos);
gui.setPosition(i, pos[i]++);
dice--;
Thread.sleep(100);//wait a tenth of second before climbing
//a ladder or being eaten by a snake
if (dice == 0) {//when dice is zero, the pieces have completed
//their move. we'll now test the current position
pos[i] = PositionTest(pos[i]);//set the current position
//to the position where it should be moved to
gui.setPosition(i, pos[i]);
Thread.sleep(100);
} else if (pos[i] + dice == 100) {
gui.setPosition(i, 101);
System.out.println("Player " + i + " won ");
} else if (pos[i] == 100) {
gui.setPosition(i, 101);
System.out.println("Player " + i + " won");
} catch (Exception evt) {
System.out.println(evt.getMessage());
public static void main(String[] a) {
new Main();
_*Class Server:*_import java.net.*;
import javax.swing.*;
public class Server extends Thread {
private final int PORT = 3000; //Port number
private ServerThread[] playerNumber = new ServerThread[5]; // number of people allowed to connect
private String threadName;
public Server()//Constructor
try {
ServerSocket ss = new ServerSocket(PORT);
int i = 0;
//wait for connections
while (true) {
Socket soc = ss.accept(); //Waits for client to connect
System.out.println("Connected Player " + i);
ServerThread s = new ServerThread(soc);
playerNumber[i] = s;
s.start();
threadName=s.getName();
System.out.print(threadName);
i++;
} catch (Exception e) {
e.printStackTrace(); //Displays Error if things go wrong....
public static void main(String args[]) {
new Server(); //Makes object (calls constructor)
}*_Class ServerThread_:*import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
* @author Lord Ra
class ServerThread extends Thread{
private PrintWriter out=null;
private BufferedReader in=null;
private Socket Soc;
public ServerThread(Socket soc) {
Soc=soc;
// Set up Buffered reader,writer
try {
out = new PrintWriter(Soc.getOutputStream(), true);
in=new BufferedReader(new InputStreamReader(Soc.getInputStream()));
communicateThread();
} catch (IOException ex) {
Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
public void communicateThread()
while(true)
try{
String s=in.readLine();
System.out.println(s);
out.println("Your are succssefully connected to server");
catch(IOException r)

Class Client*
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.net.*;
import java.io.*;
public class Client implements ActionListener {
    private final int PORT = 3000; //Port number
    private PrintWriter out = null;
    private BufferedReader in = null;
    SnakesAndLaddersGUI gui;
    int[] pos;
    JButton go = new JButton("Roll Dice");
    public Client() {//Constructor
        try {
//Try to connect to server at IP address/port combination
            Socket soc = new Socket("127.0.0.1", PORT);
            //Now get the 'streams' - you use these to send messages
            out = new PrintWriter(soc.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(soc.getInputStream()));
            out.println("Hello world \n");
            out.println("I have joined this game of Snakes and Ladders \n");
            gui = new SnakesAndLaddersGUI();
            pos = new int[1];
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setSize(450, 450);
            JPanel controlPanel = new JPanel();
            controlPanel.setSize(450, 100);
            go.addActionListener(this);
            controlPanel.add(go);
            f.getContentPane().add(gui, BorderLayout.CENTER);
            f.getContentPane().add(controlPanel, BorderLayout.SOUTH);
            f.setVisible(true);
            gui.setNumberOfPlayers(1);
            for (int i = 0; i < 1; i++) {
                pos[i] = 0;
                gui.setPosition(i, 0);
        } catch (Exception e) {
            e.printStackTrace(); //Displays Error if things go wrong....
    public static void main(String args[]) {
        new Client(); //Makes object (calls constructor)
    public void actionPerformed(ActionEvent e) {
        throw new UnsupportedOperationException("Not supported yet.");
}

Similar Messages

  • Can i edit my game center account to stop sharing friends and games from another apple id that associated with my own new apple id.how to reset it without losing my apple id and i can stiil use it?

    Can i edit my game center account to stop sharing friends and games from another apple id that associated with my own new apple id.how to reset it without losing my apple id and i can stiil use it? Because i've made lot of paid purchases using this apple id. In my game center account i have so many games data that i'd never installed.i wanna  stop sharing  friends and games with this xxx apple id in my old ipad version ios 4.2. and i can still keep using this apple id in my new ipad 3rd gen version ios 6 without sharing game and friends with this xxx apple id? and how to remove the games data that i never downloaded in my ipad but still registered at my game center account.i wanna keep using this apple id coz so many fav application i've purchased from this id. the answer as soon as possible if there is some one can help me to solve it.thank u for reading my question and very big thanks for anyone who  can give me a helpful answer.                 

    Why do you ask in the iWeb forum?

  • Browse and Games icons have disappeared

    Hi
    My browse, favorites and Games icons have completely disappeared, when I go to my app I can see all the games installed, however I can not find them on my blackberry. I have already tried to updated it but says I have the latest version of software.
    Could you please help me on what do it to recover them.
    Many Thanks

    If you don't know the restrictions code then do you know if it was  on the iPad when you last backed up ? If not then you can restore to that backup and it should be removed. If it was on the iPad when you last backed up then the only way to remove it is to reset the iPad back to factory defaults and you can then re-sync your content back to the iPad - you won't be able to restore to the backup as that will keep the code in place.

  • Java (.jar) applications and games on 5530XM

    Hello
    I have used the search option before asking, and I have manually searched some of the sub-forums (or boards) I thought could and would be relevant to my issue, and have seen no similar questions being asked. I have also worked with my good friend Google, and had no luck there, either. Most of the results were pirated software links, which is not necessarily bad, but does not help me resolve my issue.
    Now, I'm not sure this is the correct board to post this in, but I'm not too far off even if it isn't; so bear with me. Now, onto the question.
    I would like to know if it is possible to turn off the D-Pad emulator, and how one would go about doing that?
    Let me elaborate, for those who are not familiar with what I'm talking about:
    Namely, the 5530XM has an elegant solution for running non-touch apps and games (i.e.. those made for earlier revisions of the S60 OS, or even those legacy apps for S40), and it is as follows - the phone places the app/game interface in a window, scaled to the apps original rendering resolution, and then places a set of touch command buttons. It makes a Directional Pad, consisting of concentric circles, divided into 5 areas, 4 directions (up, down, left, right), and a general "OK" button (center). It also displays four "Letter-buttons", labeled "A", "B", "C" and "D", which have variable or no functions, depending on the app that is run. Finally it displays two function buttons, Left and Right Menu buttons, usually placed near the red and green phone button on phones with keypads. This works flawlessly for old apps and games, with the limitation that the interface is not multi-touch, meaning it will only accept one virtual keypress at a time.
    My problem with this setup is that some of the more recent Java applications are run as legacy as well; meaning ALL of the touch-aware apps and games that I have tried running. This is unacceptable for several reasons. First, some of them don't recognize the simulated commands, rendering the virtual D-Pad useless. What's more, the virtual interface covers a good portion of the app's original interface, making it impossible to use it. The apps and games I have tried are shipped as .jar, and are supposed to work with a touch interface. And they do, it's only that they're half-covered with an unneeded virtual D-Pad!
    I am open for all suggestions, I have the latest firmware installed, 20.0.080.C01.01, the phone is, as mentioned, 5530 XM (RM-604), and I haven't manually altered Java in any way. I am, however, ready and willing to go for some more serious tinkering if need be, even if it involves altering system files, hex editing and whatnot, and I won't cry to mama if I brick the phone, I know full well the range and scope of possible consequences. This would probably constitute breaking the rules, maybe even voiding the warranty, so I'm not asking for anyone to give an answer of that level here, publicly, but feel free to send a personal message or ask for my e-mail / IM screen name, so that we can communicate about such taboo topics
    One more note, probably relevant: .sis and .sisx apps and games work flawlessly, bot the old ones needing the D-Pad (they get a virtual one) and the new ones, which are correctly recognized as touch-capable. Even some that are reported incompatible by the phone work without a hitch. It really is a pity to see the Java apps fail after everything else is flawless.
    Perhaps, if there is no known solution or a dirty workaround, we can file an official recommentadion/bug report/feature request to the developers in charge? I can wait.
    Thanks to those brave enough to read my wall of text, and thanks in advance to all who reply something useful
    Careful what you wish for... You just might get it.
    Solved!
    Go to Solution.

    McSteel wrote:
    Thanks a million!
    Can't believe I missed that one... You truly are a "Mobile Overlord".
    Although that kinda sounds like there is a Fixed/Immobile Overlord out there
    Anyway. Kudos for this, I suppose there are others who would find this useful as well.
    Thanks again
    Didn't you notice his wings?
    ‡Thank you for hitting the Blue/Green Star button‡
    N8-00 RM 596 V:111.030.0609; E71-1(05) RM 346 V: 500.21.009

  • HT1353 I have an iPod Touch and want to transfer apps and games from my Mac. Is it possible? Thanks

    I have an iPod Touch and want to transfer apps and games from my Mac. Is it possible? Thanks
    thanks again

    You can sync iOS apps from your compute's iTunes library to your iPod. An iPod will only run iOS apps/games. It will not run or even sync computer apps/games.

  • How do I get music and games which I purchased for my daughter through my iTunes account onto her iPad mini  but at the same time set up a separate iTunes account for her iPad?

    My daughter  used to use my old iPod and all the music and games that she wanted went through my e-mail/iTunes account.  She has moved onto an iPad mini but this is still in my account.  I want to set up an e-mail and iTunes account for her so that my iPhone doesnt get jammed up with all her stuff.  If I do this I think that all the stuff which I've bought will be lost to her.  How can I get round this?

    Apple devices can hold protected content from up to five different accounts, however updating apps purchased over more than one account (as far as I'm aware) requires signing in and out of each account. You may be better off continuing to use one account for your family, as I do, but disabling the options on each device for the automatic download of purchases made on the account, and in iTunes, the automatic inclusion of new apps when syncing from the library to the device.
    tt2

  • How can i transfer my music and games from my iphone 4s to my iphone 6?

    i want to know how i can transfer my pictures, music and games from my iphone 4s to my iphone 6

    You should be storing everything on your computer.  Just sync it to the iPhone of your choice from your computer.

  • My ipod nano was synced by itunes and removed all of my music and game files. I am in the process of adding my music back one cd at a time, but there is no history of tetris that I paid for from the itunes store. How can I get this game back for my ipod?

    My ipod nano was synced by itunes and removed all of my music and game files, and replaced my music with my kids music that they have put into the current itunes library. My music is nowhere to be found on my computer, so now  I am in the long, forever process of adding my music back one cd at a time, but there is no history of tetris that I paid for from the itunes store. How can I get this game back for my ipod?

    Contact iTunes support and explain your situation to them.  They may let you redownload it at no cost.
    http://www.apple.com/support/itunes/contact.html
    If they don't, I'm afraid you'll have to purchase it again.  Sorry.
    B-rock

  • My laptop got formatted and so did all my itunes information like music, contacts, and games. So how can I get all that back because if I just plug my iPhone into the laptop all my stuuf that was on my phone will be gone? help please

    My laptop got formatted and so did all my itunes information like music, contacts, and games. So how can I get all that back because if I just plug my iPhone into the laptop all my stuuf that was on my phone will be gone? help please

    http://www.wideanglesoftware.com/touchcopy/index.php

  • ITunes wiped out most of my music, movies, and games when I synced

    I restored the settings on my iPod, downloaded a fresh version of iTunes 7.7, and tried to re-sync at least a half dozen times. No luck. It turns out that somehow my computer had been deauthorized -- I know it wasn't anything I did or didn't do; it happened spontaneously. Once I reauthorized my computer, my iPod starting adding back the songs, movies, and games. Hope this helps some other short-term sufferers from an attack of the iTunes elves.

    I think it may be how all of your items are checked under your ipod in Summary and Music and Videos tabs. If you don't check either to sync (if you manually manage music and videos), it removes it. This is very confusing b/c you would think you only want to "sync" stuff that you haven't downloaded to your ipod. Not the case, though. You have to sync everything you want to keep on your ipod....I think
    Hope this helps.

  • I just got the 4s and my computer broke so I don't have a way to sync my new phone how do I get my contacts and games on it from old iPhone?

    Help how do I sync my new 4s when I have no comPuter inorder to get contacts apps and games onto it

    Find a computer with iTunes 10.5 and create a backup from the old phone and then restore from backup on the 4s.

  • I have lost my iphone 5. The person who has my phone right now is still using my game center id to play one of my game that i have in that phone named "Clash of Clan". Could you guys help me to sign out this icloud's ID and game center's ID from that fone

    i have lost my iphone 5. The person who has my phone right now is still using my game center id to play one of my game that i have in that phone named "Clash of Clan". Could you guys help me to sign out this icloud's ID and game center's ID from that phone for me, or anyone knows how to do this, please mail back to me. Id : "[email protected]" Thanks.

    As far as I know you can't delete the primary email address for an iCloud account.  It's assigned when the account is created.  But your neighbor wouldn't have been able to get into your iCloud account without your Apple ID and password.  Are you sure the account wasn't still on your phone when you gave it to him?
    You could migrate a copy of your data to a new iCloud account but I would still be concerned that someone else was using my old account, which presumably still has your data in it.
    I'm fairly certain that you're going to have to have iCloud support help you sort this one out as they may have the ability to make changes to an existing account that users can't.  Make an appointment with the genius bar at a nearby Apple store and have them take a look at it.  If necessary, they should be able to contact iCloud support for you.

  • HT5114 trying to set my 8 year old up an account so that My music and games do not download to her device and vs versa???

    Trying to set my 8 year old up an itunes account so that my music and games do not load to her device and vs versa...CANNOT figure out how to do this I got her a email and everyhting but itunes tells me she isnt old enough to have acct

    Do you have access to another Mac to see if the disk can be read by it?  If it can't then you're pretty sure it's the disk. If it can then there may be issues with your optical drive which might be cleared up by using a cleaning disk on it, one that uses dry brushes (no liquid).
    If you have access to another Mac and it can read the iWork disk make a disk image of it so you can move the disk image to your iMac and install from the disk image.
    OT

  • Applications and Games look ZOOMED in

    I recently upgraded from an out 8900 Curve to a 9300 curve, and now when I try to run some of the applications and games I brought over (using the desktop manager) they are all zoomed in (or running in an incorrect resolution). 
    Please help!
    Thanks!
    -808s

    Hi, I recently got a nokia 6300 though it had no applications or games on it so I was hoping you would be able to send me the link for the applications and games...I would be extremely gratefuI if you could please send me the link
                                                      ​                                 Thank You
    Moderator note: e-mail address removed. It is unwise to publish personal contact details on the web.
    Message Edited by michaels on 28-May-2009 02:51 PM

  • Leopard, Parallels and Games

    Anybody here running any games by using Parallels? Like COD4? I am so sick and tired of having to reboot into Bootcamp to play games. I wish Mac and game companies could just get along and release the same games on Mac that are on PC....ARGH!!!

    Hi,
    since Parallels and Fusion have only support for DirectX 8 and experimental support for DX9 at the moment, you don't have another possibility than using BootCamp.
    Maybe we see improved gaming capabilities with Parallels and Fusion in the (not so far) future.
    Regards
    Stefan

Maybe you are looking for

  • Help with customization of xinitrc

    Hello guys, I'm trying to include a small snippet X=`xrandr | awk '/VGA/ {print $2}'` if [ "$X" = "connected" ] then xrandr --output TV --off --output LVDS --off --output VGA --mode 1280x1024 --pos 0x0 --rotate normal fi in my xinitrc #!/bin/sh # ~/.

  • Action script objects not displayed

    Hi, I am creating an air application using Flex 4.5 compiler. The problem i am facing currently is that i have extended shape class to my custom class movingObject. in this class i have defined a function "drawcircleObj" in this class and calling thi

  • Cannot drag songs to playlist

    I have updated my iTunes to the version 9 For some reason I cannot drag any songs from my library to any playlist Can anybody help me Gordon

  • Wow thanx apple, itunes 7.1 fixed all my problems

    not!! no difference whatsoever

  • ICloud Calender and Meeting invites

    Hi. I have a mobile me email address which i have migrated to icloud. I receive meeting invites to my @me.com email address which have been generated by others using Microsoft Exchange I use my iphone and PC to move these invites into the icloud cale