Java Writing dice Game _java

Source: Internet
Author: User
Tags gettext thread class

Don't say much nonsense, direct Ben theme.

* * Multithreading && Observer mode

Title Requirements: "Roll dice" form games, in the game, the player initially has 1000 of the money, each input bet large or small, as well as betting amount, random 3 dice points, if the total number of 3 dice is less than 9, then open small, or open large, and then determine whether the player is betting on the right, If not, the amount of bets is deducted, and if a bet is paid the same amount of money as the player bets.

Analysis: This topic requires flexible use of multithreading related knowledge, to hit the Start button, there are 3 threads to start, control the rotation of 3 dice, 3 dice all turn over, back to the main route to calculate the game results.

 A thread control dice thread
 t = new thread ();
 Thread t = new thread ();
 Thread t = new thread ();
 Start a thread
 t.start ();
 T.start ();
 T.start ();
 Adding threads to the main thread
 t.join ();
 T.join ();
 T.join ();

But,,, after writing the code, it is found that this will ensure that the game will work correctly, but when I click on the Start button, since 3 dice threads are directly on the main thread, click the Start button, the button is sinking, the child thread has been running in the background, my form will not change the picture at all, But the direct display of the final result, meaning that the dice has been in the background rotation, not in the foreground of the form in time to update the display. After searching the internet, the great gods said that if you want to update the Jlabel/jtextfeild and other components in the form by clicking JButton, you can directly create the anonymous thread directly inside the JButton implementation of the listener event. That is, you can modify the code directly in the Actionperformed () method to ensure that the content of your components in a timely manner to achieve a very cool effect.

The code is as follows:

public void actionperformed (ActionEvent e) {
 new Thread (new Runnable () {
  @Override public
  void Run () {
   / /Transfer external thread class to form internal
  }
 }. Start ();

But,,, But,,, Although very cool, can realize the timely update of the picture, the game result is wrong, every time my dice is still rotating, my game results are early out.

Cause: 3 Dice threads belong to child threads, the problem with the form thread being the main thread is that the child thread is able to maintain the same life as the main thread by becoming a wizard thread, but the main thread is unable to control when the child thread dies, only to wait for the child thread to execute its own run () method and then to know it.

Workaround: Open 3 Child Threads (T1,T2,T3) in the main thread (main), and then open a child thread (T11,T21,T31) on each child thread.

T1,T2,T3 only once, responsible for creating child threads, t11,t21,t31 each thread to run multiple times, responsible for controlling the icons in the form to be updated in a timely manner.

The main thread is not affected by the child thread and the Start button does not return a sinking condition.

But also use the Join method here is also hold thread, after all, T1,T2,T3 only run once, join for them does not work, want to control the T11,T21,T31, the easiest way to understand is to use the Observer mode.

The form is viewed as the observer, and the child thread as the observed. When the child thread finishes running, notify the Observer that I am already running, and then start the next step when the observer observes that the child threads are all running.

All code:

1. Form

 Package com.sxt.dice;
 Import Java.awt.Color; public class Diceframe extends JFrame implements ActionListener, Observer {/** * "dice" console games, in which the player initially owns the money, each time the input is large or
  Bet Small, * and the amount of betting, random dice, if the total number of dice is less than equal, then open small, otherwise open large, * and then determine whether the player is on the right, if not a bet on the deduction of the amount of bets, if the bet on the reward and players bet the same amount of money. * * Using the Observer mode child thread to control the dice separately, when all is over, notify the Observer form, the form observes that all child threads are finished, calculate the game result * */private static final long Serialversionuid = L
  ;
  Private JTextField Txtput;
  Private JButton btnstart;
  Private JLabel Labresult;
  Private jcombobox<string> ComboBox;
  Private JLabel Labbigorsmall;
  Private JLabel Labput;
  Private JLabel Labsummoney;
  Private JLabel Labdice;
  Private JLabel Labdice;
  Private JLabel Labdice;
  Private JLabel labsum;
  Private JLabel labmes;
  private static list<icon> IMGs = new arraylist<icon> ();
  public static void Main (string[] args) {new diceframe ();
   Public Diceframe () {this.setlocationrelativeto (null);
   This.setbounds (,,,); This.setdefaultcloseoperation (JframE.dispose_on_close);
   Getcontentpane (). setlayout (NULL);
   This.setresizable (FALSE);
   Labdice = new JLabel ("");
   Labdice.seticon (New ImageIcon ("img/dices.jpg"));
   Labdice.setbounds (,,,);
   Getcontentpane (). Add (Labdice);
   Labsum = new JLabel ("\u\uf\ud\ud\uffa");
   Labsum.setbounds (,,,);
   Getcontentpane (). Add (Labsum);
   Labdice = new JLabel ("");
   Labdice.seticon (New ImageIcon ("img/dices.jpg"));
   Labdice.setbounds (,,,);
   Getcontentpane (). Add (Labdice);
   Labdice = new JLabel ("");
   Labdice.seticon (New ImageIcon ("img/dices.jpg"));
   Labdice.setbounds (,,,);
   Getcontentpane (). Add (Labdice);
   Labsummoney = new JLabel ("");
   Labsummoney.setforeground (color.red);
   Labsummoney.setbounds (,,,);
   Getcontentpane (). Add (Labsummoney);
   Labput = new JLabel ("\uc\ub\ueb\uce\uffa");
   Labput.settooltiptext (".");
   Labput.setbounds (,,,);
   Getcontentpane (). Add (Labput);
   Txtput = new JTextField ();
   Txtput.setbounds (,,,); Getcontentpane (). Add (TXTPut);
   Txtput.setcolumns ();
   Labbigorsmall = new JLabel ("\ubc\uffa");
   Labbigorsmall.setbounds (,,,);
   Getcontentpane (). Add (Labbigorsmall);
   ComboBox = new jcombobox<string> ();
   Combobox.setbounds (,,,);
   Getcontentpane (). Add (ComboBox);
   Combobox.additem ("big");
   Combobox.additem ("small");
   Labresult = new JLabel ("");
   Labresult.setbounds (,,,);
   Getcontentpane (). Add (Labresult);
   btnstart = new JButton ("START");
   Btnstart.setbounds (,,,);
   Getcontentpane (). Add (Btnstart);
   Labmes = new JLabel (" 

2. Thread

 Package com.sxt.dice;
 Import java.util.List;
 Import java.util.Observable;
 Import Java.util.Random;
 Import Javax.swing.Icon;
 Import Javax.swing.JLabel;
 The public class Iconthread extends observable implements Runnable {
  /**
  * uses the Observer mode to use the child thread as the observed object, and once the child thread has run out, it notifies the Observer
  */
  JLabel Lab;
  Random Random = new Random ();
  List<icon> IMGs;
  Public Iconthread (JLabel Lab, list<icon> IMGs) {
   This.lab = Lab;
   This.imgs = IMGs;
  }
  @Override public
  Void Run () {
   //Set every dice to rotate
   int count =;
   while (Count >) {
    //get a random number [~]
    int index = Random.nextint ();
    Take the corresponding picture from the IMGs collection into Lab
    Lab.seticon (Imgs.get (index));
    count--;
    try {
     thread.sleep ();
    } catch (Interruptedexception e) {
     //TODO auto-generated catch
     block E.printstacktrace ();
    }
   This.setchanged ()///child thread runs out, changes
   this.notifyobservers ()/notifies observer
  }
 }

The above is all about Java writing dice game, I hope you like it.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.