package arraylist.guessgame;
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* 完成游戏的输入输出功能
*
*/
public class GuessGameUI {
Scanner scanner = new Scanner(System.in);
public void GameStart() {
System.out.println("猜一个四个不重复数字,游戏开始:");
}
public ArrayList<Integer> GameIn() {
ArrayList<Integer> set = new ArrayList<Integer>();
while (true) {
System.out.print("请输入答案:");
char[] ch = scanner.nextLine().toCharArray();
for (int i = 0; i < ch.length; i++) {
set.add(ch[i] - '0');
}
if (set.size() == 4) {
break;
}
}
return set;
}
public void outAB(int a, int b) {
System.out.println(a + "A" + b + "B");
}
public void OutRight(int n) {
System.out.print("恭喜您猜对了,你用了" + n + "次");
if (n <= 5) {
System.out.println("你真是个天才!");
} else if (n <= 10) {
System.out.println("你还挺聪明!");
} else if (n <= 15) {
System.out.println("你还不错!");
} else {
System.out.println("你太笨了!");
}
}
public void OutWrong() {
System.out.println("笨蛋,game over");
}
}
package arraylist.guessgame;
import java.util.ArrayList;
import java.util.Random;
/**
* 完成随机出一个不重复的数组
*
*/
public class GuessRandom {
private ArrayList<Integer> result = new ArrayList<Integer>();
public ArrayList<Integer> numberRandom(int n) {
Random r = new Random();
int i = 0;
while (result.size() < n) {
i = r.nextInt(10);
// System.out.println(i);
if (result.contains(i)) {
continue;
} else {
result.add(i);
// System.out.print(i);
}
}
return result;
}
}
package arraylist.guessgame;
import java.util.ArrayList;
/**
* 完成比较功能
*/
public class GuessComparator {
public boolean isequal(ArrayList<Integer> set, ArrayList<Integer> answer){
if(set.equals(answer))
return true;
return false;
}
public int first(ArrayList<Integer> set, ArrayList<Integer> answer){
int num = 0;
for(int i = 0; i < set.size(); i++){
if(set.get(i) == answer.get(i)){
num++;
}
}
return num;
}
public int second(ArrayList<Integer> set, ArrayList<Integer> answer){
int num = 0;
for(int i = 0; i < set.size(); i++){
if(set.contains(answer.get(i)) && set.get(i)!=answer.get(i)){
num++;
}
}
return num;
}
}
package arraylist.guessgame;
import java.util.ArrayList;
/**
*
* 游戏主逻辑程序
*
*/
public class GuessGame {
public void run() {
int n = 0;
GuessRandom gr = new GuessRandom();
ArrayList<Integer> set = gr.numberRandom(4);
// System.out.println(set);
GuessGameUI ui = new GuessGameUI();
while (true) {
n++;
ArrayList<Integer> answer = ui.GameIn();
// System.out.println(answer);
GuessComparator gc = new GuessComparator();
int first = gc.first(set, answer);
int second = gc.second(set, answer);
ui.outAB(first, second);
if (gc.isequal(set, answer)) {
ui.OutRight(n);
// System.out.println("恭喜你答对了,正确答案是:" + set);
break;
}
if(n==20){
ui.OutWrong();
System.out.println("已经20次了,回去再练练吧!");
break;
}
}
}
}
package arraylist.guessgame;
/**
* 游戏主入口程序
* 创建GuessGame 对象,调用run()方法
*/
public class GuessGameMain {
public static void main(String[] args) {
GuessGame game = new GuessGame();
game.run();
}
}