Topic: 和计算机之间的游戏

  Print this page

1.和计算机之间的游戏 Copy to clipboard
Posted by: stream
Posted on: 2007-10-19 11:34

用JAVA编一个小游戏,这个游戏的规则是这样的1--20之间的数,你和计算机玩如果你说1,那计算机就说2OR2,3,但是每次最多可以说两个数字,最后谁数到20这个数字,谁就算输。

2.Re:和计算机之间的游戏 [Re: stream] Copy to clipboard
Posted by: Cappuccino
Posted on: 2007-10-19 14:54

随手写了一个,没有对用户输入数据是否与上一次回答数目是否连续进行验证~~

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;
}
}

3.Re:和计算机之间的游戏 [Re: stream] Copy to clipboard
Posted by: JiafanZhou
Posted on: 2007-10-19 21:04

Good one, it can fulfill the user needs here.


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923