Pausing execution in a program.

I'm developing a GUI for a game called Pig, where players take turns rolling the dice and accumulating points. I have made the computer players automatically keep rolling until they can no longer roll (if they happen to roll a 1 or have 20 more points than a human player). Here is my code for the computer:
if (comp) {
     while (!pass) {
          if (computerScore+roundScore>=humanScores+TURNOVER) {
               status = name+" has turned over the dice by default.";
               update();
               JOptionPane.showMessageDialog(null, status);
               status = " ";
               pass=true;
          } else {
               rollDice();
               update();
               /*try {
                    Thread.sleep(1000);
               catch (InterruptedException e) {
                    e.printStackTrace();
               //I want to use a Timer here, instead of JOptionPane.
               JOptionPane.showMessageDialog(null, name+" has rolled: "+toString());
               if (losePoints()) {
                    JOptionPane.showMessageDialog(null, name+" got too ambitious and rolled snake eyes!\n"+name+" lost all points.");
               } else
                    if (loseRound()) {
                         JOptionPane.showMessageDialog(null, name+" got too ambitious and rolled a one!\n"+name+" lost all points for this round.");
                    } else
                         roundScore += points;
               if (computerScore+roundScore>=GOAL) {
                    computerScore += roundScore;
                    status = name+" has won the game!";
                    pass=true;
                    end=true;
               update();
}As you can see, I've already tried pausing with a Thread.sleep(delay) function. I have found that the only thing that works is using a JOptionPane to stop execution. The problem with the Thread.sleep() is that the drawing of the GUI stops working while the computer never stops (I want it to pause between each time it rolls the dice) taking turns to roll its dice (until it passes).
Everything works perfectly with a JOptionPane, but I don't want to display what the computer rolls each time (because the update() method takes care of that already). Here is the code for my update() method:
public void update() {
     turnLabel.setText("Player: "+name);
     roundScoreLabel.setText("Score for this round: "+roundScore);
     statusLabel.setText(status);
     remove(dice);
     add(dice, BorderLayout.SOUTH);
     statusPanel.setBackground(Color.gray);
     revalidate();
     repaint();
}Any suggestions on how to pause while still redrawing the GUI components?

I don't think this can be that short because my code is in its draft state, since I'm commenting all the possible ways to pause the execution; however, I will give you a summary of my PigPlayer class (the main method is totally irrelevant in this case):
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
public class PigPlayer extends JPanel {
     private Dice dice;
     private int points, humanScore, computerScore, roundScore;
     private boolean comp, endTurn, time;
     public static boolean end, pass;
     private String name, info;
     private static String status;
     private static final int GOAL=100, TURNOVER=20;
     public static int humanScores;
     private JLabel roundScoreLabel, turnLabel, infoLabel, statusLabel;
     private JPanel turnPanel, statusPanel, musicPanel, centerPanel;
     private Timer timer;
     public PigPlayer() {
     public PigPlayer(String name, boolean comp) {
          //  Sets up a PigPlayer's JPanel with the specified information.
     public void update() {
          //  Updates the JLabels and the Dice pictures that were added to the JPanel above.
        //  I leave the go() method, for this is the part being worked on.
     public void go() {
          if (!end) {
               if (!comp) {
                    rollDice();
                    if (losePoints()) {
                         JOptionPane.showMessageDialog(null, name+" got too ambitious and rolled snake eyes!\n"+name+" lost all points.");
                    } else
                         if (loseRound()) {
                              JOptionPane.showMessageDialog(null, name+" got too ambitious and rolled a one!\n"+name+" lost all points for this round.");
                         } else
                              roundScore += points;
                    if (humanScore+roundScore>=GOAL) {
                         humanScore += roundScore;
                         status = name+" has won the game!";
                         end=true;
                    update();
               if (comp) {
                    while (!pass) {
                         /*timer = new Timer(1000, new ActionListener () {
                              public void actionPerformed(ActionEvent e) {
                                   time = true;
                         timer.start();*/
                         if (time) {
                              if (computerScore+roundScore>=humanScores+TURNOVER) {
                                   status = name+" has turned over the dice by default.";
                                   update();
                                   JOptionPane.showMessageDialog(null, status);
                                   status = " ";
                                   pass=true;
                              } else {
                                   rollDice();
                                   update();
                                   /*try {
                                        Thread.sleep(1000);
                                   catch (InterruptedException e) {
                                        e.printStackTrace();
                                   //I want to use a Timer here, instead of JOptionPane.
                                   //JOptionPane.showMessageDialog(null, name+" has rolled: "+toString());
                                   if (losePoints()) {
                                        JOptionPane.showMessageDialog(null, name+" got too ambitious and rolled snake eyes!\n"+name+" lost all points.");
                                   } else
                                        if (loseRound()) {
                                             JOptionPane.showMessageDialog(null, name+" got too ambitious and rolled a one!\n"+name+" lost all points for this round.");
                                        } else
                                             roundScore += points;
                                   if (computerScore+roundScore>=GOAL) {
                                        computerScore += roundScore;
                                        status = name+" has won the game!";
                                        pass=true;
                                        end=true;
                                   update();
                                       time = false;
                    //timer.stop();
        // Some code executed OUTSIDE of PigPlayer when this PigPlayer is finished with its turn.
     public void pass() {
          if (!comp) {
               humanScore += roundScore;
               roundScore=0;
               if (humanScore>=humanScores)
                    humanScores = humanScore;
          else {
               computerScore += roundScore;
               roundScore=0;
          update();
        //  This PigPlayer rolls its set of Dice.
     public void rollDice() {
          dice.roll();
          points = dice.getValue();
       //  When this PigPlayer loses a round or all of its points.
     public boolean loseRound() {
          if (dice.firstDie()==1 || dice.secondDie()==1) {
               roundScore = 0;
               pass=true;
               update();
               return true;
          else
               return false;
     public boolean losePoints() {
          if (dice.firstDie()==1 && dice.secondDie()==1) {
               humanScore = 0;
               computerScore = 0;
               roundScore = 0;
               pass=true;
               update();
               return true;
          else
               return false;
}I left out most of the methods, for they don't even apply to this class or are commented parts that are simply methods using Thread.sleep(int delay) or other.
Does this help at all, or did you want something different?

Similar Messages

  • Pause execution

    Hello!! I want to pause my execution after a message ("display message to the user" function) and enter some data (in many fields) on the front panel. After that i need some other messages to be displayed. How can i pause,enter that data (with paused execution) between these messages;; Thanks a lot!!!

    Here is a simple Dialog vi that takes in the instructions and displays it in the Title box on the front panel.  The user then enters information in the string box.  Then the user clicks OK.  If you put this vi into your code, it will pause the program until the OK button is pressed.  The Dialog VI will pop up, then go away once the OK is pressed, then your code will continue.  Actually, you should add error in and out to the Dialog VI so that you could cause the proper execution flow.
    Modify it to your needs.  Instead of a string, put in whatever data type you need.  You can set the key focus to the box where the user will start typing, then he won't have to click in the box first.  I've made this VI very crude so that you can practice making it better.  Change the icon to something more suitable.
    - tbob
    Inventor of the WORM Global
    Attachments:
    Dialog.vi ‏8 KB

  • Program for the last execution of a program or a TC

    Hello,
    DO you know a program or a TC (Transaction) to edit the date and the hour of the last execution of a program or a TC.
    Thank you for the help
    Denis Corminboeuf

    Hi Denis,
    I attached below parts of a program I created a couple of years ago to get use statistics on (customer) reports and transactions.
    Maybe you can reuse parts of it for your needs.
    Regards
    Ferdi
    <pre>
    internal tables for use counter
    data: begin of list occurs 5.
            include structure sapwlserv.
    data: end of list.
    data: begin of applicat occurs 0.
            include structure sapwlustcx.
    data: end of applicat.
    data: begin of applica_ occurs 0.
            include structure sapwlustcx.
    data: end of applica_.
    data: begin of applicau occurs 0,
            entry_id like sapwlustcx-entry_id,
            account  like sapwlustcx-account,
            count    like sapwlustcx-count,
        : end of applicau.
    data: wa_applicau like applicau.
    *&      Form  MONI
    form moni.
      data: l_host like  sapwlserv-hostshort.
      m_start = p_usedt.
    get server
      call function 'SAPWL_SERVLIST_GET_LIST'
           tables
                list = list.
      do.
        loop at list.
    loop on server
          check not list-instshort is initial.
          l_host = list-instshort.
    get statistics per month and server
          perform workload using m_start l_host.
        endloop.
        add 31 to m_start.
        if m_start > sy-datum.
          exit.
        endif.
      enddo.
      sort applica_ by entry_id.
      sort applicau by entry_id count descending.
    endform.                               " MONI
    *&      Form  WORKLOAD
    form workload using    p_start like sy-datum
                             p_host  like  sapwlserv-hostshort.
      refresh: applica_.
    read application statistic from MONI
      call function 'SAPWL_WORKLOAD_GET_STATISTIC'
           exporting
                periodtype                 = 'M'
                hostid                     = p_host
                startdate                  = p_start
                only_application_statistic = 'X'
           tables
                application_statistic      = applica_
           exceptions
                unknown_periodtype         = 1
                no_data_found              = 2
                others                     = 3.
      sort applica_ by entry_id account.
      loop at applica_  where entry_id(1) ge 'Y'.             "#EC PORTABLE
        clear wa_applicau-entry_id.
        wa_applicau-entry_id(25) = applica_-entry_id.
        wa_applicau-account      = applica_-account.
        wa_applicau-count        = applica_-count.
        collect wa_applicau into applicau.
      endloop.
      sort applicau by entry_id count descending.
      applica_-ttype    = space.
      applica_-account  = space.
      modify applica_ transporting ttype account
             where ttype ne space.
    collect only enhancements statistic
      if p_temp = 'X'.
        loop at applica_.
          applica_-entry_id+25(48) = space.
          collect applica_ into applicat.
        endloop.
      else.
        loop at applica_ where entry_id(1) ge 'Y'.            "#EC PORTABLE
          applica_-entry_id+25(48) = space.
          collect applica_ into applicat.
        endloop.
      endif.
    endform.                               " WORKLOAD
    </pre>

  • The system variables in java, NEEDED ONLY at CLI execution of java programs

    The system variables in java, NEEDED ONLY at CLI execution of java programs, and NOT needed at all[essentially] if I install bundle(14+6.7)?
    if I install bundle(14+6.7) to run-test a web app with netbeans 6.7 what I must press, then opens the default browser? I have to be online,...? How I test browse my project?

    Probably a complete tutorial on all possible environment variables in addition to a tutorial on netbeans configuration.

  • Safari 4.0.3 Breakpoint in gutter doesn't pause execution

    Hi All,
    I have a slight issue using the scripts section of the web inspector, namely it doesn't pause execution on setting a breakpoint on a line number in the gutter.
    Can someone suggest a fix?
    Thanks
    Craig

    HI Craig,
    See if anything here helps. http://www.qtweb.net/pages/ibr9600.html
    Carolyn

  • How to stop the execution of a program

    greets folks
    i want to know if its possible to stop or let in stand by the execution (run) of a program while HttpService responds the request??

    No. All remote requests in Flex are asynchronous.It's part of how Flash Player works and you can't change that. You need to react to the event when the call completes. What are you trying to achieve?

  • Oracle execution in C program exits immediately when CNTR-C is hitted

    Hi,
    I have a pro c program that connects to oracle and executes a stored procedure. This is done in a while loop. An intrrupt signal function is done(catches CNTRL-C signal), which makes the varibale in while loop false and exits normally in coming loop. But when i hit CNTRL-C , the oracle execution breaks immedietly with errors such as
    *"ora-01013 user requested cancel of current operation".*
    I dont want this to happen. I want the oracle procedure execution completes and in next while loop the program should exit. Is there any way to accomplish this?

    You probably want to capture the exceptions and handle them.
    Refer to [PL/SQL 101 : Exception Handling|http://forums.oracle.com/forums/thread.jspa?threadID=697262&tstart=50]

  • How to restrict simultaneous execution of two programs?

    Hi Experts,
    Need inputs for the situation described below:
    We have two programs prog A and prog B. These are independent executable programs and have no dependency on each other. I want to restrict execution of prog B if prog A is running in any session by any user. Is there any system/basis table which stores runtime status of all the programs? There should be some table where all the currently executing programs get stored and once program is completed, entry is cleared from the table.
    One way can be:
    When prog A has started execution, add an entry in any Z table and at the time of finishing delete the particular entry. In prog B check that the table has any entry for prog A. If yes that means prog A is still running.
    Issue with this approach is, if program A has some error or cancelled while execution, it will not delete its own entry and hence even if prog A is finished, prog B will find entry in Ztable. 
    Any other way to achieve this functionality?
    This is very urgent.Please help!
    TIA
    Abhishek

    Hi,
    Although I don't understand why you need to serialized two programs
    that have no dependency on each other, maybe the following code can help provided the programs are executed using specific tcodes.
      DATA: BEGIN OF USR_TABL OCCURS 10.
              INCLUDE STRUCTURE UINFO.
      DATA: END OF USR_TABL.
    CONSTANTS: OPCODE_LIST LIKE TH_OPCODE VALUE 2.
      refresh USR_TABL.
      CALL 'ThUsrInfo' ID 'OPCODE' field OPCODE_LIST
        ID 'TAB' FIELD USR_TABL-SYS.
      sort usr_tabl by mandt bname.
    You can check wheter the other program(tcode) is being run from itab USR_TABL, good luck.
    Jeffrey Satriadi

  • Pause execution of SQL file on error

    I have a build file where I am calling the create scripts of my DB objects. Eg:
    @@COUNTRY_MASTER.sql
    @@COUNTRY_MASTER_AUDIT.sql
    @@COUNTRY_MASTER_TEMPTABLE.sql
    @@COUNTRY_MASTER_WORKTABLE.sql
    I want to pause or exit the execution of this script in case any script fails. Also in case of failure I want to know where the script failed (which line and file name).

    You can exit sqlplus when an error occurs using the WHENEVER command macro:
    WHENEVER OSERROR
    Performs the specified action (exits SQL*Plus by default) if an
    operating system error occurs (such as a file writing error).
    In iSQL*Plus, performs the specified action (stops the current
    script by default) and returns focus to the Workspace if an
    operating system error occurs.
    WHENEVER OSERROR {EXIT [SUCCESS|FAILURE|n|variable|:BindVariable]
                       [COMMIT|ROLLBACK] | CONTINUE [COMMIT|ROLLBACK|NONE]}
    WHENEVER SQLERROR
    Performs the specified action (exits SQL*Plus by default) if a
    SQL command or PL/SQL block generates an error.
    In iSQL*Plus, performs the specified action (stops the current
    script by default) and returns focus to the Workspace if a SQL
    command or PL/SQL block generates an error.
    WHENEVER SQLERROR {EXIT [SUCCESS|FAILURE|WARNING|n|variable|:BindVariable]
                        [COMMIT|ROLLBACK] | CONTINUE [COMMIT|ROLLBACK|NONE]}There is no command for pausing processing when an error occurs. The command language of sqlplus is very primitive. There is no easy way to do conditional processing. And user interaction is limited to prompting for substitution variable values.

  • How do I pause C command-line program?

    Hello. I'm writing a little command-line game app in C and I'm curious about how I can pause the program to wait for the user to hit return. I want the user to need to hit return (or having to hit any key would work too) to make the program continue, and I would like the key that was hit not to appear on the screen -- just a simple sort of "hit any key to continue" type thing. In C++ I think we used something like system("Pause") or something like that -- don't really remember, but any help here will be greatly appreciated. Thanks!

    Something like this will print a prompt, then wait for a keystroke:
    printf("Hit any key to continue> ");
    getchar();
    However in a console application, it's not so easy to prevent the user's keystrokes from being echoed. There are ways to turn the echo off for the keystroke then restore it, but those can depend on the environment. I'd need to know whether you're running your program in an Xcode console window, a Terminal window, or elsewhere. In short, don't go there unless it's quite important to you. The above prompt will show any chars that are keyed-in as text after the arrow, which is what a user would expect.
    Hope that helps!
    - Ray

  • Pausing execution of a VI

    Hello, I am fairly new to LabView.  For the VI I am writing, I would like it to pause at a certain point, wait for the user to click a button (which is wired to a case structure), and then continue execution based on the case that was selected.  I'm not sure how to do this.  Does anyone have any advice? 
    Thanks!
    Solved!
    Go to Solution.

    Everything is do-able... 
    Have a look at the attached example for a sample solution using radio buttons. 
    There are many ways of creating a solution.  You need to define more what you want.
    R
    Attachments:
    SelectTrueFalse.vi ‏24 KB

  • Compilation and Execution of SQLJ Programs

    Hai,
    I want to execute the SQLJ demo programs along with the Oracle8.1.5.0.0 NT platform.
    I am having jdk 1.2.2 on my system. After translation of the Java File. I try to execute to the program. It gives me an error. Unable to find slzsetevar an entry mismatch oracore.dll.
    My concern is do we need to have only JDK1.1 for the execution. I am being misled from the Readme.Txt in the SQLJ/DEMO/README.TXT .
    Kindly guide me. I have to provide a solution to my clients.
    -Regards
    [email protected]

    Hello,
    I have executed some sqlj programs. The platform i have used are 8.1.5 and jdk 1.2.2
    I had no problem in executing the demos. Kindly check your path/classpath and try the same thing with the latest jdbc drivers. Any more doubts regarding this check out the sqlj documentation or u can feel free to mail me at [email protected]
    Regards,
    shravan
    null

  • Issue with Background execution of a Program

    Hi,
    I have developed a simple Report.
    If i execute the report in foreground, the execution will be perfect as per logic maintained in the code.
    If i execute the report in background, a particular IF condition is getting failed in the program.
    I tried to debug the code (maintaining sy-batch = 'X' while debug). The same IF condition which gets failed in background, will get satisfied now in debug mode with sy-batch = 'X'.
    I believe sy-batch = 'X' means the program running in background.
    But when i run the program in background (pressing F9 without any debug), again the particular IF condition in the code gets fails.
    Any idea to resolve this kind of issues...??
    Regards
    Pavan

    What is "getting failed"? Result not true, so not going to the code inside IF/ENDIF? What is your expected result?
    Please post the code part here (using code tags, only the relevant part, please watch the formatting).
    Thomas

  • Execution speed onboard programs

    Hi all
    I am tying store the value of analog input channels of PCI-7352 on buffer, from onboard program.
    The program run fine, but I don´t know how measure the total acquisition time in the program.
    In an example in LabView ( adc-gpbuffer.vi ), use 'flex_load_delay' function to establish an interval in
    the acquisition. But the real interval between readings not is calculated.
    Another question, How I can know the execution speed of onboard program ?.  The documentation does not
    show information.
             Thank´s
             Javier
    Attachments:
    adc-gpbuffer.vi ‏165 KB

    Javier,
    there is no easy way to measure the execution timing of onboard programs. One thing that you could do is to toggle a digital line in your onboard program and measure the timing with an oscilloscope.
    Please be aware that the timing of onboard programs doesn't work deterministicallly as onboard programs don't run with time critical priority on the board's CPU so you will probably see a fair amount of jitter.
    The main purpose of the analog inputs on the 7352 is analog feedback. You can use them for single point measurements, too but if you need to acquire data with an accurate timing you better should use an additional M-Series board like the PCI-6220 which provide a much better measurement and timing accuracy and as true measurement devices they provide a whole set of additional useful features.
    Best regards,
    Jochen Klier
    National Instruments Germany

  • How pausing execution of media player when this Vi closes

    Hi,
    I would like to use a subvi that executes 20 seconds of playing movie with media player and then pauses. For this I succeed writing it.
    Next, I would like the vi closes and when the main vi recall the subvi, I want that the movie plays in the state it finished before.
    Is it possible to do this?
    Thanks in advance.  

    Hi nousome,
    this could be done by setting in the "VI Properties"- dialog the options "Show Front Panel when called" & "Close afterwards..." in the section "window appearance". Then let the video play for 20 seconds, when the VI finishes it closes by itself. After this, all local variables (controls & indicators) which are not connected to the connector pane keep their state until you unload them from memory (close LabView). So you can store the current video position inside the VI and start the video at this point with the next VI- call.
    Another good solution to save values inside a sub-VI between VI- calls is an uninitialized shift register. If you have difficulties implementing this lok at the example "Single Execution Uninitialized Shift Registers.vi". I found this in my LV 7.1 but older versions should have this example too.
    Hope this helps,
    Dave
    Greets, Dave

Maybe you are looking for

  • A suggestion for pacman

    Right now if you want to use "makepkg" effectively, you have to install and setup "sudo" just to be able to get the dependencies for a build (makepkg -s). My suggestion is for pacman to have a new parameter, like "pacman -P" for example, that would r

  • Tiger on Mac Pro 3.1

    Can i install Mac OS X Tiger on my Mac Pro?

  • Do I still need to calibrate the battery every few months?

    Hi, I recently bought the MBP 13" i5 and I read on a forum that MBPs made mid-2010 or later come precalibrated and "do not require the calibration procedure outlined in this article." http://support.apple.com/kb/ht1490 Should I still calibrate the bu

  • How do I download my software purchases with Snow Leopard

    I had a virus on my iMac desktop.  I erased entire hard drive after I did a backup.  I installed my original software that came with my computer (Snow Leopard).  Now I cannot download Yosemite which I have already purchased.

  • Renaming Photo on Import and Folder Destination LR4

    Sometime back I moved away from Lightroom for two specific reasons. I'm interested in possibly returning to the LR workflow but I've reviewed the new LR4 and can not decipher if it is possible to do the two specific things that made me leave it behin