JFrame,負責視窗初始化、居中顯示、載入棋盤面板 OperatorPane。JPanel 並實現 MouseListener, Runnable,處理繪圖、落子邏輯、勝負判定、計時器、UI 交互(按鈕區域)。
public void paint(Graphics g) {
BufferedImage buf = new BufferedImage(495, 475, BufferedImage.TYPE_INT_ARGB);
Graphics g2 = buf.createGraphics();
// 1. 繪製背景圖
g2.drawImage(imageBackground, 0, 0, 495, 475, null);
// 2. 繪製網格線(18×18,格距 20px)
g2.setColor(Color.BLACK);
for (int i = 0; i <= 18; i++) {
g2.drawLine(10, 50 + 20*i, 10+360, 50+20*i); // 橫線
g2.drawLine(10+20*i, 50, 10+20*i, 50+360); // 直線
}
// 3. 繪製星位(五個黑點)與天元
g2.fillOval(67, 107, 6, 6); // 等 5 個位置
g2.fillOval(187, 227, 6, 6); // 天元
// 4. 繪製所有棋子
for (int i = 0; i <= 18; i++)
for (int j = 0; j <= 18; j++)
if (allchess[i][j] == 1) drawBlack(g2, i, j);
else if (allchess[i][j] == 2) drawWhite(g2, i, j);
// 5. 繪製狀態文字(回合、計時)
g2.drawString("遊戲信息:" + message, 130, 40);
g2.drawString("黑方時間:" + blackMessage, 25, 445);
g2.drawString("白方時間:" + whiteMessage, 245, 445);
// 6. 輸出到屏幕
g.drawImage(buf, 0, 0, this);
}
// 滑鼠像素座標 -> 棋盤邏輯座標 (0~18) x = (e.getX() - 10) / 20; y = (e.getY() - 50 - 20) / 20;
private boolean checkWin() {
int color = allchess[x][y];
// 四個方向:橫(1,0)、豎(0,1)、斜/(1,1)、斜\(1,-1)
return checkCount(1,0,color) >= 5 ||
checkCount(0,1,color) >= 5 ||
checkCount(1,1,color) >= 5 ||
checkCount(1,-1,color) >= 5;
}
private int checkCount(int dx, int dy, int color) {
int cnt = 1;
// 正向
for (int i = 1; color == allchess[x + i*dx][y + i*dy]; i++) cnt++;
// 反向
for (int i = 1; color == allchess[x - i*dx][y - i*dy]; i++) cnt++;
return cnt;
}
public void run() {
if (maxTime > 0) {
while (true) {
if (isBlack) { blackTime--; if (blackTime == 0) timeout("黑方"); }
else { whiteTime--; if (whiteTime == 0) timeout("白方"); }
updateTimeStrings();
repaint();
Thread.sleep(1000);
}
}
}
在 mouseClicked 中通過座標範圍判斷點擊了哪個功能按鈕:
System.exit(0)。
public class OperatorPane extends JPanel implements MouseListener, Runnable {
Image imageBackground;
int boardrows=18, boardcols=18, boardsize=20;
int x=0, y=0;
int allchess[][] = new int[19][19];
boolean isBlack = true, canPlay = true;
String message = "黑方先行";
int maxTime = 0, blackTime = 0, whiteTime = 0;
String blackMessage = "無限制", whiteMessage = "無限制";
Thread t = new Thread(this);
@SuppressWarnings("deprecation")
public OperatorPane() {
t.start(); t.suspend();
imageBackground = new ImageIcon("image/background.jpg").getImage();
}
// paint(), checkWin(), checkCount(), mouseClicked(), run() 等方法見上文
// 其餘 MouseListener 方法留空
}
專案目錄需包含 image/background.jpg 作為棋盤背景。若無圖片,可在 paint 中改用純色填充:g2.setColor(new Color(220,179,92)); g2.fillRect(0,0,495,475);。