开发者

java guess the number game

import java.awt.*;
import java.awt.event.*; 
import javax.swing.*;

public class guess extends JFrame implements ActionListener
{
    JLabel title = new JLabel ("SAMPLE 1");
    JTextField txt1 = new JTextField (10);
    JLabel direction = new JLabel ("GUESS A NUMBER BETWEEN 1 AND 100");
    JLabel status = new JLabel ();
    JPanel pnl1 = new JPanel ();
    JPanel pnl2 = new JPanel ();
    JPanel pnl3 = new JPanel ();

    public guess()
    {
        super ("guess the number");
        Container c = getContentPane();
        c.setLayout (new BorderLayout());
        txt1.addActionListener(this);
        pnl2.setLayout (new BorderLayout());
        c.add(pnl1, BorderLayout.NORTH);
        c.add(pnl2, BorderLayout.CENTER);
        pnl1.add(title);
        pnl2.add(direction, BorderLayout.NORTH);
        pnl2.add(txt1, BorderLayout.CENTER);
        pnl2.add(status, BorderLayout.SOUTH);       

        setVisible(tru开发者_开发问答e);
        setSize(350,450);
    }


public void guess(int i)
{
    super ("guess the number");
    Container c = getContentPane();
    c.setLayout (new BorderLayout());
    txt1.addActionListener(this);
    pnl2.setLayout (new BorderLayout());
    c.add(pnl1, BorderLayout.NORTH);
    c.add(pnl2, BorderLayout.CENTER);
    pnl1.add(title);
    pnl2.add(direction, BorderLayout.NORTH);
    pnl2.add(txt1, BorderLayout.CENTER);
    pnl2.add(status, BorderLayout.SOUTH);       

    setVisible(true);
    setSize(350,450);
}

public static void main(String args[])
{
    guess start = new guess();
    start.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public void actionPerformed(ActionEvent e)
{
    int counter = 1;
    int num = (int)(Math.random() * 100);
    if (e.getSource()==txt1)
    {
        int a = Integer.parseInt(txt1.getText());
        while(a != num)
        {
            if(a < num)
                int x = num - 10;
                if(a >= x)
                {

                }
        }
    }
}   
}

here's my code but my problem for me is in the actionPerformed, i don't know when to put the int num = (int)(Math.random() * 100); cause if i put it outside the if(e.getSource) then it will always generate a random number i think, but if inside my new problem is what if i reset the entered a new value for my guess will the int num = (int)(Math.random() * 100); get a new value?


You should add a start button, and make the input text field disabled by default.
When the start button is clicked, the input text field can become enabled, and a random number is generated for that round of the game.
You can also disable the start button while the game is being played.
You may want to limit the number of guesses, after which the player loses the game, and the start button is enabled and the input text field is disabled, until a new game is started.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜