Skip to content

Instantly share code, notes, and snippets.

@horimislime
Created April 25, 2012 03:29
Show Gist options
  • Save horimislime/2486000 to your computer and use it in GitHub Desktop.
Save horimislime/2486000 to your computer and use it in GitHub Desktop.
HitAndBlow
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
public class HitAndBlow{
private List<Integer> hiddenNumber;
private int length;
private int tryCount;
/**
*ゲームに使う桁数を指定する
*
*/
public HitAndBlow(int length){
this.length=length;
this.tryCount=0;
hiddenNumber=new ArrayList<Integer>();
//ArrayListに0~9の数を代入
ArrayList<Integer> source=new ArrayList<Integer>();
for(int i=0;i<10;i++){
source.add(i);
}
//中身をシャッフル
do{
Collections.shuffle(source);
while(source.get(0)==0);
for(int i=0;i<length;i++){
hiddenNumber.add(source.get(i));
}
}
private int[] parseArgument(String arg)
throws Exception{
//入力された文字列を数値に変換する。数値でない場合はExceptionを投げる
int number=Integer.parseInt(arg);
//桁チェック
if(arg.length()!=this.length){
System.err.println("4桁で入力してください。");
throw new Exception();
}
int[] array=integerToArray(number);
for(int i=0;i<array.length-1;i++){
for(int j=i+1;j<array.length;j++){
if(array[i]==array[j]){
System.err.println(this.length+"桁の各数字は重複なし!");
throw new Exception();
}
}
}
return array;
}
private List<Integer> integerToArray(int number){
int length=String.valueOf(number).length();
List<Integer> array=new ArrayList<Integer>();
for(int i=0;i<length;i++){
array.add(number/(int)Math.pow(10,3-i));
number%=Math.pow(10,3-i);
}
return array;
}
private boolean checkNumbers(List<Integer> userNumber){
int hit=0,blow=0;
for(int i=0;i<userNumber.size();i++){
for(int j=0;j<this.hiddenNumber.size();j++){
if(userNumber.get(i)==this.hiddenNumber.get(i) && i==j){
hit++;
}
else if(userNumber.get(i)==this.hiddenNumber.get(j) && i!=j){
blow++;
}
}
}
if(hit==this.length){
System.out.println("ゲームクリア!試行回数="+tryCount);
return true;
}
System.out.println("hit="+hit+"blow="+blow);
return false;
}
public void play(){
try{
BufferedReader reader=new BufferedReader(
new InputStreamReader(System.in));
String line=null;
int[] userArray;
while(true){
this.tryCount++;
System.out.println("数値を入力してください("+this.tryCount+"回目)");
line=reader.readLine();
try{
userArray=parseArgument(line);
if(checkNumbers(userArray)){
break;
}
}catch(Exception e){
System.err.println("数値フォーマットエラー.");
}
}
}catch(IOException e){
e.printStackTrace();
}
}
public static void main(String[] args){
//4桁の整数でプレイする
HitAndBlow game=new HitAndBlow(4);
game.play();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment