import java.net.URL; |
import javax.swing.ImageIcon; |
import javax.swing.JOptionPane; |
public class GameNumberDemo { |
|
public static Object[] chooseNumber = { 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 }; |
public static int myNumber; |
public static int random_Number ; |
|
public static void main(String[] args) { |
new GameNumberDemo(); |
} |
|
public GameNumberDemo(){ |
//选择是--继续游戏---退出游戏 |
int Y_N = JOptionPane.showConfirmDialog( null , "是否继续游戏" , "猜数字游戏" , |
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); |
|
//如果是----继续游戏 |
if (Y_N == JOptionPane.YES_OPTION){ |
System.out.println( "yes" ); |
|
JOptionPane.showMessageDialog( null , "游戏提示: \n 你有4次机会" , "猜数字游戏" , |
JOptionPane.INFORMATION_MESSAGE, null ); |
|
//随机生成一个数字 |
random_Number = ( int ) (Math.random()* 10 ); |
|
selectNumber(); |
|
|
//如果是----退出游戏 |
} else if (Y_N == JOptionPane.NO_OPTION){ |
System.exit( 0 ); |
} |
} |
|
/** |
* 选择你所猜的数值 |
*/ |
public void selectNumber(){ |
for ( int i= 0 ; i< 4 ; i++){ |
/*选择数字的方式一*/ |
Object num = JOptionPane.showInputDialog( null , "选择数字" , "猜数字游戏" , |
JOptionPane.QUESTION_MESSAGE, null , chooseNumber, chooseNumber[ 0 ]); |
|
/*选择数字的方式二*/ |
// Object num = JOptionPane.showOptionDialog(null, "选择数字", "猜数字游戏", |
// JOptionPane.CLOSED_OPTION, JOptionPane.QUESTION_MESSAGE, null, chooseNumber, chooseNumber[0]); |
|
myNumber = ( int ) num; |
System.out.println(myNumber); |
|
//偏小 |
if (random_Number > myNumber){ |
JOptionPane.showMessageDialog( null , "第" +(i+ 1 ) + "次\n 猜小了" ); |
|
//偏大 |
} else if (random_Number < myNumber){ |
JOptionPane.showMessageDialog( null , "第" +(i+ 1 ) + "次\n 猜大了" ); |
|
//相等 |
} else { |
URL resource = GameNumber. class .getResource( "image.jpg" ); |
ImageIcon imageIcon = new ImageIcon(resource); |
JOptionPane.showMessageDialog( null , "猜对了" , "" , JOptionPane.PLAIN_MESSAGE, imageIcon); |
return ; |
} |
} |
|
JOptionPane.showMessageDialog( null , "你没有猜出数字 \n 游戏一结束" ); |
} |
} |
中级程序员
by: 陆痴 发表于:2017-05-02 14:08:26 顶(1) | 踩(0) 回复
运行时的状态图:

回复评论