五子棋判斷五子相連




//主要看getLInkedCount方法怎麼實現的就行,你可以自己運行一下看看結果。親測
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;


public class test {


private static final int xBound = 10;
private static final int yBound = 10;
private static int  a[][] = new int[10][10];
private static ArrayList<Integer> xTrack;
private static ArrayList<Integer> yTrack;



/**
* @param args
* @throws IOException 
* @throws ClassNotFoundException 
*/
public static void main(String[] args) {


printFSameColor();
}



public static void printFSameColor(){
Random random = new Random();

for(int i=0; i<10; i++){
for(int j=0; j<10; j++){
a[i][j] = random.nextInt(100)%4;
System.out.print(a[i][j] + " ");
}
System.out.println();
}
System.out.println("****************************************************");



for(int i=0; i<10; i++){
for(int j=0; j<10; j++){



for(int k=0; k<4; k++){
for(int h=0; h<4; h++){
xTrack  = new ArrayList<Integer>();
yTrack  = new ArrayList<Integer>();
int temp1 = getLinkedCount(i,j,k,1,h);
if(temp1>=5){
print();
}
}

}




}
System.out.println();
}

}


public static void print(){


int index = 0;
while(!xTrack.isEmpty()){
int x =  xTrack.remove(index);
int y =  yTrack.remove(index);
System.out.println("x = " + x + " y=" + y);
System.out.println(a[x][y] + " ");
}
System.out.println();
}




/**
 * 然後從落子的地方開始判斷4個方向是否是同顏色的。分別是-,/,|,\,分別以數字0,1,2,3爲參數,往前查找時帶參數-1,每找到一個就把返回值-1,往後查找時帶參數1,每找到一個將返回值加1。方法聲明爲:
 * 如果沒有找到相連的子,返回0,否則返回相連子的個數(和forward符號相同)
 * @xpos : 當前子位置x
 * @ypos : 
 * @direction : 當前方向
 * @forward : -1表示向前,1表示向後(往前表示X值增加)
 * @color : 表示己方的顏色是否爲黑子
 */
private static int getLinkedCount(int xpos, int ypos, int direction, int forward, int color) {
    // | 時x值不變
    int tXpos = (direction == 0) ? xpos : xpos + forward;
    // -時y值不變, /時y值減少
    int tYpos = (direction == 2) ? ypos : ypos + ((direction == 1) ? -forward : forward);
    
    // 超出了邊界
    if (tXpos < 0 || tYpos < 0 || tXpos > xBound || tYpos > yBound) {
        return 0;
    }
    // 取得顏色
    int tColor = a[xpos][ypos];
    if (tColor == color) {
        // 顏色相等時,遞歸取得相連的個數


    xTrack.add(xpos);
    yTrack.add(ypos);
        return 1 + getLinkedCount(tXpos, tYpos, direction, forward, color);
    }
    return 0;
}




}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章