@echo off
chcp 65001 >nul
setlocal enabledelayedexpansion
mode con: cols=130 lines=50
color 0e
:: 參數
set rows=23
set baseIndent=64
:: 主迴圈:逐行產生楊輝三角
set "line=1"
for /l %%r in (1,1,%rows%) do (
set "num=0"
set "newLine="
for %%v in (!line!) do (
set /a num+=1
if !num!==1 set "newLine="
set /a val=%%v+!num2!
set "newLine=!newLine! !val!"
set num2=%%v
)
call :printLine "!newLine:~1!"
set "line=!newLine! 0"
)
:: 倒金字塔
for /l %%r in (%rows% -1 1) do (
if defined name%%r echo !name%%r!
)
:: 彩色呼吸燈
for /l %%i in (1,1,3) do (
for %%c in (a b c d e f) do (
color 0%%c
ping -n 2 127.1 >nul
)
)
exit /b
:printLine
set "str=%~1"
set "len=0"
for /l %%i in (0,1,300) do if not "!str:~%%i,1!"=="" set /a len+=1
set /a pad=%baseIndent% - %len%/2
set "spaces="
for /l %%i in (1,1,!pad!) do set "spaces= !spaces!"
echo !spaces!%~1
set "name%rows%=!spaces!%~1"
set /a rows-=1
goto :eof
| 技巧 | 說明 |
|---|---|
setlocal enabledelayedexpansion | 啟用 `!var!` 即時展開,支援迴圈內變數更新 |
| 字串模擬陣列 | 用空格分隔字串 `1 3 3 1` 當作陣列,`for %%v in (!line!)` 遍歷 |
| 邊界補 0 | 每行結尾加 `0`,下一輪 `%%v+num2` 自然產生邊界 1 |
| 置中對齊 | 計算字串長度 → 算左邊空格數 → `echo spaces+content` |
| 變數名動態 | `set name%rows%=...` 儲存每行,倒序輸出時 `!name%%r!` 取用 |
color 0a~0f | 背景黑(0) + 前景亮色(a-f) 循環 |
ping -n 2 127.1 | 約 1 秒延遲 (比 `timeout` 相容性好) |
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
... (至第 23 行)
... 倒序輸出倒金字塔
★ 彩色呼吸燈動畫
def pascal(n):
row = [1]
for _ in range(n):
print(' '.join(map(str, row)).center(80))
row = [1] + [row[i]+row[i+1] for i in range(len(row)-1)] + [1]
if __name__ == '__main__':
pascal(23)
Python 版本無行數限制、支援大整數、跨平台、可輕易加入 ANSI 彩色 (colorama)。