Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 9 of 9

Thread: how to enforce loop to wait

  1. #1
    Junior Member
    Join Date
    Nov 2013
    Posts
    16
    Thanks
    3
    Thanked 1 Time in 1 Post

    Default how to enforce loop to wait

    I am stuck from last 1 month and i didnot find any solution. my problem is i am writing a game of four players. three are computers and one human.

    so there are a play() funtion for computers and one Overridden play() function for human. here is the function which human player will use

    @Override
    public void play(){
    for(int i=0 ; i <13;i++){
    getJLabels()[i].addMouseListener(new MouseAdapter()
    {
    public void mouseClicked(MouseEvent evt)
    {
    int Index = getIndex(getJLabels(), (JLabel)evt.getSource());
    getJLabels()[Index].setIcon(getHand()[Index].getBackSide());
    getPlayerJLabel().setIcon(getHand()[Index].getCardImage());
    setObjectForPlay(getHand()[Index]);
    }
    });
    }
    temp = getObjectForPlay();
    return temp;
    }
    Other three players use play() and return an object automatically. i mean the mouselistener is only for this human.play() funtion

    i am running these functions from nested loop. when a round of loop complete every player complete his play() turn and then next loop start. and so on.

    Problem is computers play() functions are not waiting for human to click. I want that when loop play the human Play() then wait for human to click and return object. when human play() end with click then next computer play() call


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    4,399
    My Mood
    Mellow
    Thanks
    143
    Thanked 600 Times in 587 Posts

    Default Re: how to enforce loop to wait

    i am running these functions from nested loop. when a round of loop complete every player complete his play() turn and then next loop start. and so on.
    Can you show this code? Please post it in code tags. If you're unsure how to do that, read this first.

  3. #3
    Junior Member
    Join Date
    Nov 2013
    Posts
    16
    Thanks
    3
    Thanked 1 Time in 1 Post

    Default Re: how to enforce loop to wait

    public static void startGame(){
          Deck dock = new Deck();
            for(int j=0;j<13;j++)
             for(int i=0;i<4;i++)
                 deckArray[i] = Player[i].play(); //here deckArray will obtain the return object of each player
     
     
         }


    --- Update ---

    here player[2].play() is human who will send card object to this array through mouse click. i want the loop will wait until i clicked.

  4. #4
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    4,399
    My Mood
    Mellow
    Thanks
    143
    Thanked 600 Times in 587 Posts

    Default Re: how to enforce loop to wait

    I think you can make this approach work. An idle loop comes to mind. As long as the human player's thread is executing on a separate thread, the loop wouldn't exit until a flag from the player[i] object is received to indicate that a move has been made.

    However, since graphical programs, including graphical games, are event driven, I would rewrite this game's control loop to be event driven rather than a realtime loop that executes without regard for the game's state. You can learn a lot more about game loops by searching with your favorite search engine.

    I may try to write a simple example, because it's interesting, but don't wait for me. Keep studying.

  5. #5
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    4,399
    My Mood
    Mellow
    Thanks
    143
    Thanked 600 Times in 587 Posts

    Default Re: how to enforce loop to wait

    This demonstration is purely event driven, each new event in the simulated game's progress is driven by the end of the last event. It doesn't end, by the way. You'll have to manually break out of it. This demo is done in a single thread, because there was no reason for more than that. I hope it helps. Let me know if you have any questions.
    /**
     * A class to simulate control of a multi-player game
     * @author GregBrannon Nov 10, 2013
     */
    public class GameControl
    {
        Player[] players;
        Player currentPlayer;
        boolean moveMade;
        int numberOfPlayers;
        int playersTurn;
     
        // a constructor that sets the number of players, creates them, and
        // then waits for control to be passed to playTheGame()
        public GameControl( int numberOfPlayers )
        {
            // initialize instance variables
            moveMade = false;
            this.numberOfPlayers = numberOfPlayers;
            playersTurn = 0;
     
            players = new Player[numberOfPlayers];
     
            // fill the players[] array with Player objects
            for ( int i = 0 ; i < players.length ; i++ )
            {
                players[i] = new Player( this );
            }
     
        } // end default constructor
     
        // the method that starts game play and then waits for a player
        // to make a move
        public void playTheGame()
        {
            // telling the first player to take a turn
            // (subsequent players are told to move after a move is made)
            System.out.println( "GC: Telling " + players[playersTurn].getName() +
                    " to take a turn." );
            players[playersTurn].makeAMove();
     
            System.out.println( "GC: Waiting for a player to make a move." );
     
        } // end method playTheGame()
     
        // method setMoveMade() is used by the Player objects to indicate
        // to GameControl that move has been made
        public void setMoveMade( Player player )
        {
            currentPlayer = player;
     
            System.out.println( "GC: " + player.getName() + " made a move." );
     
            // process the player's move
            makeTheMove();
     
            // tell the next player to move - could be a separate method
            playersTurn = ( playersTurn + 1 ) % numberOfPlayers;
            System.out.println( "GC: Telling " + players[playersTurn].getName() +
                    " to take a turn." );
            players[playersTurn].makeAMove();
     
        } // end method setMoveMade()
     
        private void makeTheMove()
        {
            System.out.println( "GC: Applying the move that was made" );
     
            // get the player's move
            int[] playersMove = currentPlayer.getMyMove();
     
            // print the player and the move
            System.out.print( currentPlayer.getName() + " move is : " );
            System.out.println( playersMove[0] + " , " + playersMove[1] );
            System.out.println();
     
        } // end method makeTheMove()
     
        // a simple main() method to create an instance of GameControl
        // that is used to start the game
        public static void main( String[] args )
        {
            GameControl gameControl = new GameControl( 4 );
            gameControl.playTheGame();
        }
     
    } // end class GameControl
     
    /**
     * A Player class to simulate a player making a move in a game
     * @author GregBrannon Nov 10, 2013
     */
    class Player
    {
        // class fields - just one to build the player number for
        // each instance's name
        public static int playerNumber;
     
        // a reference to the GameControl object
        GameControl gameControl;
        // a flag to indicate when its this player's turn
        boolean myTurn;
        // the player's move
        int[] myMove;
        // the player's name
        String name;
     
        // the delay
        long PLAY_DELAY = 5000L;
     
        // a default constructor that takes a parameter GameControl 
        public Player( GameControl gameControl )
        {
            // set the thread's name
            name = "Player " + playerNumber++;
     
            // initialize instance variables
            this.gameControl = gameControl;
            myMove = new int[2];
     
        } // end constructor
     
     
        // method makeAMove() simulates a player making a move after a 5-second
        // delay. the move is completed by informing the GameControl object
        // that a move has been made and placing the move in 
        public void makeAMove()
        {
            System.out.println( "Player: " + this.getName() +
                    " is thinking . . . ." );
     
            // a delay to simulate a player thinking
            try
            {
                Thread.sleep( PLAY_DELAY );
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
     
            // done thinking
            System.out.println( "Player: " + this.getName() +
                    " is making a move." );
     
            // simulate a move
            myMove[0] += 2;
            myMove[1] += 3;
     
            // inform the GameControl object that a move has been made
            gameControl.setMoveMade( this );
     
            System.out.println( "Player: " + this.getName() +
                    " is done making a move." );
     
        } // end method makeAMove()
     
        // method getMove() returns the player's move
        public int[] getMyMove()
        {
            return myMove;
        }
     
        // method getName() returns the current instance's name
        public String getName()
        {
            return name;
     
        } // end method getName()
     
    } // end class Player

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,067
    Thanks
    47
    Thanked 2,146 Times in 2,119 Posts

    Default Re: how to enforce loop to wait

    @Greg
    I tried executing the code with delay of 100 vs 5000.
    I never saw that this statement was executed:
            System.out.println( "mAM Player: " + this.getName() +" is done making a move." );
    The code appears to be doing recursive calls and never gets past the call before the above statement.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    4,399
    My Mood
    Mellow
    Thanks
    143
    Thanked 600 Times in 587 Posts

    Default Re: how to enforce loop to wait

    I tried a 100ms on a mediocre laptop with Win 7, and it doesn't break, but I imagine there could be a speed of execution at which a call to System.print() might not complete before the next event is sent and then gets dropped. The code was provided as a demonstration of how external events can be used to step the execution of a program (or an object) that is in a wait state. More print() statements - several redundant - were included to show the flow than would be required. An actual application that might not have any.

    I'll add a disclaimer next time that says something like, "This code is written for the expressed purpose described herein and is not guaranteed to not break or be suitable for all possible uses, environmental conditions, operating systems, etc., that the user may subject it to. You may use my code by agreeing that you will not sue me or seek damages for any reason with the understanding that you'll be sorely disappointed if you do."

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,067
    Thanks
    47
    Thanked 2,146 Times in 2,119 Posts

    Default Re: how to enforce loop to wait

    It wasn't an issue of missed println() output. I put some debug code after the println in question and it was never executed. I didn't see that the setMadeMove() method ever returned.
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    4,399
    My Mood
    Mellow
    Thanks
    143
    Thanked 600 Times in 587 Posts

    Default Re: how to enforce loop to wait

    Ahh. An interesting point with worthwhile lessons learned. The first lesson might be to use a profiler or debugger more often. Thanks for pointing out the value of those tools. The second is detailed below:

    While there is not explicit recursion, there is recursion-like behavior in that Object1 calls Object2 and then waits for Object2 to notify Object1 that it's done, a ping-pong like behavior, but the entry or return point to Object1 is different than the exit point. In an effort to show the action between the two classes with print statements, I left loose ends that will probably come back as errors, probably StackOverflow errors, but I never ran it long enough to confirm.

    The code as posted includes at least two print statements AFTER the call from objectX to objectY. As in recursion, I expect the return to those print statements are pushed to the stack to be executed someday, but in this program that someday never comes. There's no return, no unwinding as there would be in properly coded recursion. The solution that rids the code of this nuisance is to simply move all print statements to occur before the call to the next object.

    Again, thanks for the lesson.

Similar Threads

  1. wait(); and notify();
    By tenacious23cb in forum What's Wrong With My Code?
    Replies: 1
    Last Post: August 14th, 2013, 04:36 PM
  2. Help wanted using wait() and notify()
    By sandramo in forum Java Theory & Questions
    Replies: 7
    Last Post: March 29th, 2013, 12:19 PM
  3. wait(), sleep() and notify()
    By evthim in forum Threads
    Replies: 3
    Last Post: October 30th, 2012, 11:37 AM
  4. let first thread through, the rest has to wait
    By hamsterofdeath in forum Threads
    Replies: 0
    Last Post: November 19th, 2010, 12:32 PM
  5. Enforce DTD on DomParser - Make Parser fall over if error detected
    By toriacht in forum What's Wrong With My Code?
    Replies: 0
    Last Post: March 18th, 2010, 05:28 PM