開發連連看遊戲時,不應直接操作 PictureBox 控制項指標來判斷連通與消除,而應建立邏輯資料結構(二維陣列/圖模型)對應棋盤狀態,UI 僅負責渲染。
// 邏輯層
class LinkGame {
int rows, cols;
int[,] board; // 0=空, >0=圖片ID
PictureBox[,] uiBoxes; // 對應 UI 控制項,僅供渲染用
public LinkGame(int r, int c, PictureBox[,] boxes) {
rows = r; cols = c; uiBoxes = boxes;
board = new int[rows, cols];
InitBoard();
}
void InitBoard() {
// 隨機配對填充 board,確保可解
// ...
Render();
}
bool CanLink(Point p1, Point p2) {
// 判斷兩格是否可用 ≤3 段直線連通(經典規則)
// 可用 BFS/DFS 尋路,或針對直線/一折/兩折專門判斷
return true; // 簡化
}
void OnBoxClick(Point p) {
if (firstClick == null) { firstClick = p; Highlight(p); }
else {
if (CanLink(firstClick.Value, p)) {
ClearBoxes(firstClick.Value, p);
board[firstClick.Value.X, firstClick.Value.Y] = 0;
board[p.X, p.Y] = 0;
Render();
CheckWin();
}
firstClick = null; ClearHighlight();
}
}
void ClearBoxes(Point a, Point b) {
// 僅操作 UI 控制項隱藏/清空圖片
uiBoxes[a.X, a.Y].Visible = false; // 或 Image = null
uiBoxes[b.X, b.Y].Visible = false;
}
void Render() {
for (int i=0;i 0) uiBoxes[i,j].Image = images[board[i,j]];
else uiBoxes[i,j].Image = null;
}
}
}
Invoke,易死結。PictureBox 繪製整個棋盤(OnPaint 畫格子),效能遠優於成百上千個控制項。Bitmap 雙緩衝繪製,實現流暢動畫。「資料驅動 UI」是圖形遊戲開發的核心原則,連連看正是絕佳練習案例。