用 PowerShell 显示 黑客帝国数码雨动画

请在 PowerShell 控制台中执行本脚本

今天在群里看到一个数码雨的课题,试着实现了一下:

【话痨】powershell传教士(1328486072) 12:58:11
话说有人用bat写出了数码雨,谁也用powershell写一个,我用powershell写了几个,总感觉不对。
【话痨】powershell传教士(1328486072) 12:58:52
有人对命令行数码雨,感兴趣么?

根据传教士的提示,改了一下,避免了闪烁。

实现效果

Matrix

源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
## Prepare the screen
$host.UI.RawUI.BackgroundColor = "Black"
$host.UI.RawUI.ForegroundColor = "Green"

$charSet = '0123456789'.ToCharArray()

$width = 75
$height = [Console]::WindowHeight
$maxStringLength = 7
$minStringLength = 2
$maxSpaceLength = 20
$minSpaceLength = 6

$lines = New-Object System.Collections.ArrayList
$symbols = @()

for ($i = 0; $i -lt $width; $i++) {
$symbols += ''
}

function AddLine([string]$line) {
$lines.insert(0, $line)
if ($lines.Count -eq $height) {
$lines.RemoveAt($lines.Count - 1)
}
}

function ShowFrame() {
Write-Host ($lines.ToArray() -join "`n")
}

function TryGenerateSymbol() {
for ($i = 0; $i -lt $width; $i++) {
$column = $symbols[$i]
if ($column -eq '') {
# initial state, generate spaces
$symbols[$i] = New-Object String ' ', (Get-Random -Minimum $minSpaceLength -Maximum $maxSpaceLength)
} elseif ($column -eq ' ') {
# last space
$randomCount = Get-Random -Minimum $minStringLength -Maximum $maxStringLength
$chars = Get-Random -InputObject $charSet -Count $randomCount
$symbols[$i] = $column + ($chars -join '')
} elseif ($column.Length -eq 1) {
# last char
$symbols[$i] = $column + (New-Object String ' ', (Get-Random -Minimum $minSpaceLength -Maximum $maxSpaceLength))
}
}
}

function UpdateFrame() {
TryGenerateSymbol

$line = @()
for ($i = 0; $i -lt $width; $i++) {
$column = $symbols[$i]
$line += $column[0]
$symbols[$i] = $column.Substring(1, $column.Length - 1)
}
$line = $line -join ''
AddLine $line
}

try
{
$host.UI.RawUI.WindowSize = New-Object System.Management.Automation.Host.Size $width + 1, $height + 1
}
catch {}

try
{
$host.UI.RawUI.BufferSize = New-Object System.Management.Automation.Host.Size $width + 1, $height + 1
} catch {}

try
{
while($true)
{
if([Console]::KeyAvailable)
{
$key = [Console]::ReadKey()
if(($key.Key -eq 'Escape') -or
($key.Key -eq 'Q') -or
($key.Key -eq 'C'))
{
break
}
}

# Clear-Host

$host.UI.RawUI.CursorPosition = New-Object System.Management.Automation.Host.Coordinates 0,0

UpdateFrame
ShowFrame

$host.UI.RawUI.CursorPosition = New-Object System.Management.Automation.Host.Coordinates `
0,([Console]::WindowHeight - 1)
Write-Host -NoNewLine 'Q or ESC to Quit'

Start-Sleep -m 100
}
}
finally
{
## Clean up, display exit screen
Clear-Host
"`n"
" Happy Scripting from PowerShell..."
" by Victor.Woo!"
"`n`n`n"
}

您也可以在这里下载 Matrix.ps1