2048 是款風靡全球的數字合併遊戲。本文提供完整可編譯的 C 原始碼,在標準終端機(Windows conio.h、Linux ncurses 皆可移植)上運行,支援 WASD 方向鍵控制、分數統計、遊戲結束判定。
int board[4][4] = {0}; // 4×4 棋盤,0 代表空格
int temp[5]; // 暫存單行/單列資料(含哨兵)
int score = 0; // 累計分數
int moves = 0; // 移動步數
add()將一行/列壓縮至 temp[4],temp[4]=0 作哨兵:
int add(void) {
int changed = 0, t = 0;
// 階段 1:去零
do {
for (int i=0;i<4;++i) if (temp[i]==0 && temp[i]!=temp[i+1]) {
temp[i]=temp[i+1]; temp[i+1]=0; changed=1;
}
} while (++t < 4);
// 階段 2:合併
for (int i=1;i<4;++i) if (temp[i]==temp[i-1] && temp[i]!=0) {
temp[i-1]*=2; score+=temp[i-1]; temp[i]=0; changed=1;
}
// 階段 3:再去零(同上)
t=0;
do {
for (int i=0;i<4;++i) if (temp[i]==0 && temp[i]!=temp[i+1]) {
temp[i]=temp[i+1]; temp[i+1]=0; changed=1;
}
} while (++t < 4);
return changed;
}
透過索引映射將「上、下、左、右」統一轉為「左向」邏輯:
temp[i]=board[i][col] → add() → 寫回temp[i]=board[3-i][col] 反序取出 → add() → 反序寫回temp[j]=board[row][j] → add() → 寫回temp[j]=board[row][3-j] 反序 → add() → 反序寫回while (!gameover) {
if (changed) { // 僅在棋盤變化時生成新數
do { r=rand()%4; c=rand()%4; } while (board[r][c]);
board[r][c] = (rand()%4==0) ? 4 : 2; // 25% 機率生成 4
moves++;
}
print_board();
switch (getch()) {
case 'w': case 'W': slide_up(); break;
case 's': case 'S': slide_down(); break;
case 'a': case 'A': slide_left(); break;
case 'd': case 'D': slide_right(); break;
case '0': exit(0);
}
// 檢查是否全滿且無法合併
gameover = 1;
for (int i=0;i<4;++i) for (int j=0;j<4;++j) if (!board[i][j]) gameover=0;
}
printf("Game Over! 分數:%d 步數:%d\n", score, moves);
conio.h、system("cls")getch() 改用 ncurses 或 termios 非緩衝輸入;system("clear") 替換 cls完整原始碼約 150 行,結構清晰,適合 C 語言初學者研讀陣列操作、隨機數、終端機控制等核心技巧。