当前位置: 移动互联网学院 > Java培训 > JAVA开发 > Java猜数字游戏代码实现
Java猜数字游戏代码实现 时间:2017-09-15     来源:华清远见JAVA学院

很多人都玩过猜数字游戏,但你知道如何用代码编写一款猜数字游戏吗?今天华清Java学院小编就和大家分享一下Java猜数字游戏代码实现

Java猜数字游戏如何实现

Java猜数字游戏代码具体如下:

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 游戏一结束");

}

}

X