1. 程式人生 > >五子棋輸贏判定算法

五子棋輸贏判定算法

owin system void turn 行數 sys [] 數據 oar

public void whoWin(int row, int col, char ch) {  // row是傳入的棋子行地址,col為列地址,ch代表棋子,"黑"或“白”

  int i;
  int j;
  int k;
  char[] line = new char[getColOfBoard()]; //存儲斜行數據
  int chNum = 0; //若chNum >= 5,則贏

  //從行判斷輸贏
  for(i = 0; i < getColOfBoard(); i++) {
    if(cheboard[row][i] == ch) {
      chNum++;
      if(chNum >= 5) {
        System.out.println(ch + "獲勝!遊戲結束!");
        return;
      }
    } else {
      chNum = 0;
    }
   }

  //從列判斷輸贏
  chNum = 0;
  for(i = 0; i < getRowOfBoard(); i++) {

    if(cheboard[i][col] == ch) {

      chNum++;
      if(chNum >= 5) {
        System.out.println(ch + "獲勝!遊戲結束!");
        return;
      }
     } else {
      chNum = 0;
    }
  }

  //從右下斜行判斷
  chNum = 0;
  k = 0;
  for(i = 0; i < getColOfBoard(); i++) { //將line數組清零
    line[i] = ‘0‘;
  }
  i = row + 1;
  j = col + 1;
  while(i > 0 && j > 0) {
    i--;
    j--;
  }
  while(i < getRowOfBoard() && j < getColOfBoard()) {
    line[k++] = cheboard[i][j];
    i++;
    j++;
  }
  for(i = 0; i < line.length; i++) {
    if(line[i] == ch) {
      chNum++;
      if(chNum >= 5) {
        System.out.println(ch + "獲勝!遊戲結束!");
        return;
      }
    } else {
      chNum = 0;
    }
  }

  //從右上斜行判斷
  chNum = 0;
  k = 0;
  for(i = 0; i < getColOfBoard(); i++) { //將line數組清零
    line[i] = ‘0‘;
  }
  i = row;
  j = col;
  while(i < getRowOfBoard() - 1 && j > 0) {
    i++;
    j--;
  }
  while(i >= 0 && j < getColOfBoard()) {
    line[k++] = cheboard[i][j];
    i--;
    j++;
  }
  for(i = 0; i < line.length; i++) {
    if(line[i] == ch) {
      chNum++;
      if(chNum >= 5) {
        System.out.println(ch + "獲勝!遊戲結束!");
        return;
      }
    } else {
      chNum = 0;
    }
  }
}

五子棋輸贏判定算法