1. 程式人生 > >JAVA 五子棋 判斷輸贏的程式碼實現

JAVA 五子棋 判斷輸贏的程式碼實現

	<pre name="code" class="java">//定義棋盤大小,寬w,高h
	int w = 11;
	int h = w;
	//用一個二維陣列儲存棋盤資料,1代表紅棋,2代表黑棋
	int[][] chess = new int[h][w];
	//定義控制迴圈的布林變數
	boolean game_over = false;
	boolean win_red = false;
	boolean win_black = false;

//判斷輸贏的函式,傳入當前點位置座標
		public void judge(int y3, int x3) {
			//建立4個StringBuffer物件分別儲存橫向,縱向,兩個斜向棋盤資料
			StringBuffer buf21 = new StringBuffer();
			StringBuffer buf14 = new StringBuffer();
			StringBuffer buf13 = new StringBuffer();
			StringBuffer buf24 = new StringBuffer();
			// 橫向資料流
			for (int y = y3, x = 0; x < w; x++) {
				buf21.append(chess[y][x]);
			}
			//System.out.println(buf21);
			
			// 縱向資料流
			for (int y = 0, x = x3; y < h; y++) {
				buf14.append(chess[y][x]);
			}
			//System.out.println(buf14);
			
			// 二四象限資料流
			if (y3 >= x3) {
				for (int y = y3 - x3, x = 0; y < h; y++, x++) {
					buf24.append(chess[y][x]);
				}
			} else {
				for (int y = 0, x = x3 - y3; x < w; y++, x++) {
					buf24.append(chess[y][x]);
				}
			}
			//System.out.println(buf24);

			// 一三象限資料流
			if ((x3 + y3) < h) {
				for (int x = x3 + y3, y = 0; y <= x3 + y3; y++, x--) {
					buf13.append(chess[y][x]);
				}
			} else {
				for (int x = h - 1, y = x3 + y3 - (h - 1); y < h; y++, x--) {
					buf13.append(chess[y][x]);
				}
			}
			//System.out.println(buf13);

			//使用正則表示式匹配資料判斷輸贏,連續5個1表示紅棋贏,連續5個二表示黑棋贏
			if (buf21.toString().matches("\\d*1{5}\\d*")
					|| buf14.toString().matches("\\d*1{5}\\d*")
					|| buf13.toString().matches("\\d*1{5}\\d*")
					|| buf24.toString().matches("\\d*1{5}\\d*")) {
				win_red =true;
			}
			
			if (buf21.toString().matches("\\d*2{5}\\d*")
					|| buf14.toString().matches("\\d*2{5}\\d*")
					|| buf13.toString().matches("\\d*2{5}\\d*")
					|| buf24.toString().matches("\\d*2{5}\\d*")) {
				win_black =true;
			}
			
			if (win_red) {
				JOptionPane.showMessageDialog(null, "紅棋贏!");
			} else if (win_black) {
				JOptionPane.showMessageDialog(null, "黑棋贏!");
			}
		}