萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

批次檔實作彩色楊輝三角:CMD 字符圖形動畫

效果預覽

  • CMD 視窗顯示彩色楊輝三角 (23 行)
  • 完成後倒序輸出倒金字塔
  • RGB 循環變色動畫 (color 0a~0f)

完整批次碼 (bat)

@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 行)
                  ... 倒序輸出倒金字塔
                  ★ 彩色呼吸燈動畫

限制與改進

  • **行數上限** ~35 行 (CMD 視窗寬度/字串長度限制)
  • **數值溢位**:第 30+ 行數值超過 32 位整數範圍 → 需改用 Python/JS 大整數
  • **顏色閃爍**:`color` 指令重繪整個緩衝區,大量輸出會閃爍
  • **跨平台**:僅限 Windows CMD;PowerShell/Linux 需改寫

現代化重寫建議 (Python)

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)。

copyright © 萬盛學電腦網 all rights reserved