3×3 棋盤,雙方輪流落子(o/x),顯示局面,檢查勝利條件(行/列/對角線三連),平局判斷。
MyChess:char[][] data 棋盤,boolean side 當前方show():打印棋盤,空位顯示 '_'judge():檢查 8 條勝負線,返回 1(o勝)/2(x勝)/0(未分勝負)isEnd():有勝負或棋盤滿返回 trueplay():讀入 "行,列",合法性檢查,落子切換方import java.util.*;
class MyChess {
private char[][] data = new char[3][3];
private boolean side = true; // true:o, false:x
private static Scanner scan = new Scanner(System.in);
public void show() {
for (int i=0;i<3;i++) {
for (int j=0;j<3;j++) System.out.print((data[i][j]==0?'_':data[i][j])+" ");
System.out.println();
}
}
private int judge() {
for (int k=0;k<3;k++) // 行
if (data[k][0]==data[k][1]&&data[k][0]==data[k][2])
return data[k][0]=='o'?1:2;
for (int k=0;k<3;k++) // 列
if (data[0][k]==data[1][k]&&data[0][k]==data[2][k])
return data[0][k]=='o'?1:2;
if (data[0][0]==data[1][1]&&data[0][0]==data[2][2]) // 主對角
return data[0][0]=='o'?1:2;
if (data[0][2]==data[1][1]&&data[0][2]==data[2][0]) // 副對角
return data[0][2]=='o'?1:2;
return 0;
}
public boolean isEnd() { if (judge()>0) return true; for(char[] r:data) for(char c:r) if(c==0) return false; return true; }
public void showResult() { switch(judge()){case 0:System.out.println("平局!");break;case 1:System.out.println("o方勝利!");break;case 2:System.out.println("x方勝利!");break;} }
public void play() {
for(;;) {
char c = side?'o':'x';
System.out.print(" "+c+" 請輸入棋子位置(行,列):");
String s=scan.nextLine();
try {
String[] ss=s.split(","); int r=Integer.parseInt(ss[0])-1, col=Integer.parseInt(ss[1])-1;
if (data[r][col]!=0) continue;
data[r][col]=c; side=!side; break;
} catch(Exception e) {}
}
}
}
public class MyTest {
public static void main(String[] args) {
MyChess a=new MyChess();
for(;;) { a.show(); if(a.isEnd()){a.showResult();break;} a.play(); }
}
}
_ _ _ _ _ _ _ _ _ o 請輸入棋子位置(行,列):1,1 o _ _ _ _ _ _ _ _ x 請輸入棋子位置(行,列):2,2 o _ _ _ x _ _ _ _ ...
自底向上風格:先實現底層邏輯(判勝、顯示),再組裝遊戲循環。