import java.util.*;
public class Bagels {
private static final int NUM_DIGITS = 3;
private static final int MAX_GUESSES = 10;
/**
* 返回由NUM_DIGITS唯一随机数字组成的字符串。
*
* @return
*/
public static String getSecretNum(){
//设置数组
int[] number = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
//将数组放进列表中
List<Integer> list = new ArrayList<Integer>();
for (int i : number) {
list.add(i);
}
//打乱列表
Collections.shuffle(list);
//将打乱的列表重新存放到数组中
int[] shuffledArray = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
shuffledArray[i] = list.get(i);
}
//定义秘密数字
String secretNum = "";
for(int i=1;i<=NUM_DIGITS;i++){
secretNum += shuffledArray[i];
}
return secretNum;
}
private static String getClues(String guess, String secretNum) {
//判断猜的数字和秘密数字是否相等
if (guess.equals(secretNum) ){
return "你猜对了!";
}
String clues = "";
for (int i = 0; i < guess.length(); i++){
//判断猜的数字的每个字符和秘密数字的每个字符是否相等
if (guess.charAt(i)==secretNum.charAt(i)){
clues+="Fermi";
//判断秘密字符中是否包含猜的数字的字符
}else if (secretNum.contains(String.valueOf(guess.charAt(i)))){
clues+="Pico";
}
}
if (clues.length()==0){
return "Bagels";
}else {
return clues;
}
}
public static void main(String[] args) {
//打印游戏说明
System.out.printf(
"Bagels,一个演绎逻辑游戏。\n"+
"我想到的是一个没有重复数字的%d位数字。\n"+
"当我说: 这意味着:\n" +
"Pico 一个数字是正确的,但位置不对。\n"+
"Fermi 一个数字是正确的,在正确的位置。\n"+
"Bagels 没有数字是正确的。\n"+
"例如:如果秘密号码是248,而您的猜测是843,则线索将是Fermi Pico。\n",NUM_DIGITS
);
while (true){
//获得秘密数字
String secretNum = getSecretNum();
System.out.printf("我想到了一个数字\n"+
"您有%d个猜测可以得到它\n",MAX_GUESSES);
//记录猜测次数
int numGuesses = 1;
//如果猜测次数大于最大猜测次数停止循环
while (numGuesses <= MAX_GUESSES){
//定义猜测数字
String guess = "";
//判断输入的猜测数字是否等于秘密数字的长度,和判断是否是数字
while (guess.length() != NUM_DIGITS || !guess.matches("\\d+")){
System.out.printf("第%d轮", numGuesses);
Scanner scanner = new Scanner(System.in);
System.out.println("请输入你的猜的数字:");
guess = scanner.nextLine();
}
//判断输入的数字位置和数字的准确
String clues = getClues(guess, secretNum);
System.out.println(clues);
//猜测数量加一
numGuesses += 1;
//猜的数字等于秘密数字推出循环
if (guess.equals(secretNum)) {
break;
}
//猜的次数大于最大次数公布答案
if (numGuesses > MAX_GUESSES) {
System.out.println("你的猜测已经用完了。");
System.out.printf("答案是%s。", secretNum);
}
}
//是否要在来一次
Scanner scanner = new Scanner(System.in);
System.out.println("再来一次?(yes/no)");
if (!scanner.nextLine().startsWith("y")){
break;
}
}
System.out.println("谢谢您的游玩");
}
}
Bagels
最新推荐文章于 2024-05-21 22:13:42 发布