Tetris extends JFrame:主窗口、菜單欄、啟動入口。TetrisPanel extends JPanel:遊戲邏輯、繪製、定時器、鍵盤監聽。TimerKeyListener:實現 ActionListener(定時下落) + KeyAdapter(鍵盤)。int[][][] shapes = {
// I
{{0,0,0,0, 1,1,1,1, 0,0,0,0, 0,0,0,0},
{0,1,0,0, 0,1,0,0, 0,1,0,0, 0,1,0,0},
{0,0,0,0, 1,1,1,1, 0,0,0,0, 0,0,0,0},
{0,1,0,0, 0,1,0,0, 0,1,0,0, 0,1,0,0}},
// S, Z, J, O, L, T ...
};
private int crash(int x, int y, int type, int state) {
for (int a=0;a<4;a++) for (int b=0;b<4;b++)
if ((shapes[type][state][a*4+b] & map[x+b+1][y+a]) == 1) return 0; // 撞牆/塊
return 1; // 可移動
}
private void tryDelLine() {
for (int row=0; row<21; row++) {
int full = 1;
for (int col=0; col<12; col++) full &= map[col][row];
if (full == 1) {
// 上方所有行下移一行
for (int r=row; r>0; r--)
for (int c=0; c<11; c++) map[c][r] = map[c][r-1];
score += 100;
delay /= 1.05; // 加速
timer.setDelay(delay);
}
}
}
cn/hncu/Tetris.java。java cn.hncu.Tetris。約 300 行代碼實現完整俄羅斯方塊,展示了 Swing 定時器驅動、矩陣碰撞檢測、雙緩衝繪製核心遊戲循環思想。