随手写了一个,没有对用户输入数据是否与上一次回答数目是否连续进行验证~~
ai部分只是把取胜的部分列了出来而已,你可以自己写一个通用的。提示,以这个题目为例,无论是哪一方,只需要最后一个数字说的是16,那么这一方就稳赢了。这里16和19都是稳赢的关键点,那么往前推10和13也是类似,因为只要你能抓住这两个点的话就很容易能说到16这个数了~~^_^
import java.util.Scanner;
import java.io.*;
public class Game
{
public static void main(String[] args)
throws IOException
{
System.out.println("Input your code below:");
String line = null;
Scanner scanner = new Scanner(System.in);
Game game = new Game();
while(true)
{
line = scanner.nextLine(); //获取用户输入
try
{
int[] userInput = game.parseInput(line); // String2int
if(userInput[userInput.length-1]>=20)
{
System.out.println("You lose");
break;
}
int[] answer = game.answer(userInput);
for(int i=0;i<answer.length;i++)
{
System.out.print(answer[i]+",");
}
if(answer[answer.length-1]>=20)
{
System.out.println("You win");
break;
} else if(answer[answer.length-1]==19)
{
System.out.println("You lose");
break;
} else
{
System.out.println("\010 ");
}
}catch (IllegalArgumentException e)
{
System.out.println("Bad format input data.");
continue;
}
}
}
private int[] parseInput(String line)
throws IllegalArgumentException
{
String[] tmps = line.split(",");
if(tmps.length>=2)
throw new IllegalArgumentException();
int[] result = new int[tmps.length];
for(int i=0;i<result.length;i++)
{
result[i] = Integer.parseInt(tmps[i]);
}
return result;
}
private int[] answer(int[] ui)
{
int umax = ui[ui.length-1]; // 获取用户输入的最后一个数字
int[] result;
final int[] winpoint = {4,7,10,13,16,19}; // winpoint
boolean checked = false; // 是否与WinPoint相关
boolean answerTwoNum = false; // 下一次应该回答的数字数目,如回答一个数即false,两个数即为true
for(int i=0;i<winpoint.length;i++)
{
if(winpoint[i]-umax==2) // 与winpoint相差2时便回答2个数以抢到point
{
answerTwoNum = true;
checked = true;
}
if(winpoint[i]==umax || winpoint[i]-umax==1) // 相差1时就回答一个数。若对方抢到winpoint也只回答一个数(这样后面抢到winpoint的几率貌似更高)
{
checked = true;
}
}
if(checked)
{
if(answerTwoNum)
result = new int[]{umax+1,umax+2};
else
{
result = new int[]{umax+1};
}
}else // 余下的部分随机回答,因为20的上限比较小貌似也没多大用=_=
{
if(Math.random()>0.5)
result = new int[]{umax+1,umax+2};
else
result = new int[]{umax+1};
}
return result;
}
}