-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsl
More file actions
executable file
·343 lines (290 loc) · 12.2 KB
/
sl
File metadata and controls
executable file
·343 lines (290 loc) · 12.2 KB
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
#!/usr/bin/env python3
"""
sl - Steam Locomotive
A joke command that displays an animated train when you type 'sl' instead of 'ls'
Author: Reverend Steven Milanese
License: MIT
"""
import os
import sys
import time
import random
import signal
import argparse
from typing import List, Tuple
# Version
__version__ = "2.0.0"
# ANSI escape codes for colors and cursor control
class ANSI:
# Colors
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
MAGENTA = '\033[95m'
CYAN = '\033[96m'
WHITE = '\033[97m'
RESET = '\033[0m'
# Cursor control
HIDE_CURSOR = '\033[?25l'
SHOW_CURSOR = '\033[?25h'
CLEAR_SCREEN = '\033[2J\033[H'
CLEAR_LINE = '\033[2K'
@staticmethod
def move_cursor(x: int, y: int) -> str:
"""Move cursor to position."""
return f'\033[{y};{x}H'
class Train:
"""Represents the ASCII art train with different styles."""
# Classic steam locomotive
CLASSIC = [
" ==== ________ ___________",
" _D _| |_______/ \\__I_I_____===__|_________|",
" |(_)--- | H\\________/ | | =|___ ___| ",
" / | | H | | | | ||_| |_|| ",
" | | | H |__--------------------| [___] | ",
" | ________|___H__/__|_____/[][]~\\_______| | ",
" |/ | |-----------I_____I [][] [] D |=======|__",
"__/ =| o |=-~~\\ /~~\\ /~~\\ /~~\\ ____Y___________|__",
" |/-=|___|= || || || |_____/~\\___/ ",
" \\_/ \\O=====O=====O=====O_/ \\_/ "
]
# Small locomotive for faster animation
SMALL = [
" ++ +------ ",
" || |+-+ | ",
" /---------|| | | ",
" + ======== +-+ | ",
" _|--O========O~\\-+ ",
"//// \\_/ \\_/ "
]
# D51 locomotive (Japanese style)
D51 = [
" ==== ________ ___________ ",
" _D _| |_______/ \\__I_I_____===__|_________|",
" |(_)--- | H\\________/ | | =|___ ___| ",
" / | | H | | | | ||_| |_|| ",
" | | | H |__--------------------| [___] | ",
" | ________|___H__/__|_____/[][]~\\_______| | ",
" |/ | |-----------I_____I [][] [] D |=======|__",
"__/ =| o |=-O=====O=====O=====O \\ ____Y___________|__",
" |/-=|___|= || || || |_____/~\\___/ ",
" \\_/ \\__/ \\__/ \\__/ \\__/ \\_/ "
]
# C51 locomotive
C51 = [
" ___ ",
" _|_|_ _ __ __ ___________",
" D__/ \\_(_)___| |__H__| |_____I_Ii_()|_________|",
" | `---' |:: `--' H `--' | |___ ___| ",
" +|~~~~~~~~++::~~~~~~~H~~+=====+~~~~~~|~~||_| |_|| ",
" || | :: H +=====+ | |:: ...| ",
"| | _______|_::-----------------[][]-----| | ",
"| /~~ || |-----/~~~~\\ /[I_____I][][] --|||_______|__",
"------'|oOo|===[]- || || | ||=======_|__",
"/~\\____|___|/~\\_| O=======O=======O |__|\\ / ",
"\\_/ \\_/ \\____/ \\____/ \\____/ \\_____/ "
]
@staticmethod
def get_train(style: str = "classic") -> List[str]:
"""Get train ASCII art by style."""
trains = {
"classic": Train.CLASSIC,
"small": Train.SMALL,
"D51": Train.D51,
"C51": Train.C51
}
return trains.get(style, Train.CLASSIC)
class SmokeGenerator:
"""Generates dynamic smoke patterns."""
SMOKE_CHARS = ['@', '*', 'o', 'O', '.', '\'', '"']
@staticmethod
def generate(length: int, density: float = 0.4) -> str:
"""Generate a smoke pattern."""
smoke = []
for _ in range(length):
if random.random() < density:
smoke.append(random.choice(SmokeGenerator.SMOKE_CHARS))
else:
smoke.append(' ')
return ''.join(smoke)
@staticmethod
def get_smoke_lines(width: int, height: int = 4) -> List[str]:
"""Generate multiple lines of smoke."""
lines = []
for i in range(height):
density = 0.4 - (i * 0.1) # Decrease density as smoke rises
lines.append(SmokeGenerator.generate(width, density))
return lines
class SLAnimation:
"""Main animation controller."""
def __init__(self, train_type: str = "classic", speed: float = 1.0,
fly: bool = False, accident: bool = False):
self.train_type = train_type
self.speed = speed
self.fly = fly
self.accident = accident
self.running = True
# Get terminal size
self.update_terminal_size()
# Setup signal handler for window resize
signal.signal(signal.SIGWINCH, self._handle_resize)
signal.signal(signal.SIGINT, self._handle_interrupt)
def update_terminal_size(self):
"""Update terminal dimensions."""
try:
size = os.get_terminal_size()
self.width = size.columns
self.height = size.lines
except:
self.width = 80
self.height = 24
def _handle_resize(self, signum, frame):
"""Handle terminal resize."""
self.update_terminal_size()
def _handle_interrupt(self, signum, frame):
"""Handle Ctrl+C gracefully."""
self.running = False
def clear_screen(self):
"""Clear the terminal screen."""
sys.stdout.write(ANSI.CLEAR_SCREEN)
sys.stdout.flush()
def run(self):
"""Run the animation."""
# Hide cursor
sys.stdout.write(ANSI.HIDE_CURSOR)
sys.stdout.flush()
try:
train_lines = Train.get_train(self.train_type)
train_height = len(train_lines)
train_width = max(len(line) for line in train_lines)
# Calculate vertical position
if self.fly:
y_positions = self._calculate_fly_path(train_height)
else:
y_position = (self.height - train_height) // 2
y_positions = [y_position] * (self.width + train_width + 10)
# Animation loop
frame = 0
while self.running and frame < len(y_positions):
self.clear_screen()
# Calculate horizontal position (right to left)
x_position = self.width - frame
y_position = y_positions[frame]
# Add smoke above train
if not self.fly:
smoke_lines = SmokeGenerator.get_smoke_lines(train_width + 20, 4)
for i, smoke in enumerate(smoke_lines):
smoke_y = y_position - len(smoke_lines) + i
if smoke_y > 0:
sys.stdout.write(ANSI.move_cursor(max(1, x_position - 10), smoke_y))
sys.stdout.write(ANSI.WHITE + smoke + ANSI.RESET)
# Draw train
for i, line in enumerate(train_lines):
if 0 < y_position + i <= self.height:
# Calculate visible portion of line
if x_position < 1:
# Train is partially off-screen (left side)
start = abs(x_position) + 1
if start < len(line):
visible_line = line[start:]
sys.stdout.write(ANSI.move_cursor(1, y_position + i))
sys.stdout.write(self._colorize_line(visible_line))
elif x_position + len(line) > self.width:
# Train is partially off-screen (right side)
visible_line = line[:self.width - x_position]
sys.stdout.write(ANSI.move_cursor(x_position, y_position + i))
sys.stdout.write(self._colorize_line(visible_line))
else:
# Train is fully visible
sys.stdout.write(ANSI.move_cursor(x_position, y_position + i))
sys.stdout.write(self._colorize_line(line))
# Accident mode - show collision
if self.accident and x_position < self.width // 2:
self._show_accident(x_position, y_position, train_height)
break
sys.stdout.flush()
time.sleep(0.05 / self.speed)
frame += 1
# Stop when train is off screen
if x_position + train_width < 0:
break
finally:
# Clean up
self.clear_screen()
sys.stdout.write(ANSI.SHOW_CURSOR)
sys.stdout.flush()
def _colorize_line(self, line: str) -> str:
"""Add colors to train line."""
# Simple coloring based on characters
colored = line
colored = colored.replace('D', ANSI.RED + 'D' + ANSI.RESET)
colored = colored.replace('_', ANSI.YELLOW + '_' + ANSI.RESET)
colored = colored.replace('|', ANSI.BLUE + '|' + ANSI.RESET)
colored = colored.replace('=', ANSI.GREEN + '=' + ANSI.RESET)
colored = colored.replace('O', ANSI.WHITE + 'O' + ANSI.RESET)
colored = colored.replace('o', ANSI.WHITE + 'o' + ANSI.RESET)
colored = colored.replace('~', ANSI.CYAN + '~' + ANSI.RESET)
return colored
def _calculate_fly_path(self, train_height: int) -> List[int]:
"""Calculate flying path for train."""
path = []
total_frames = self.width + 60
for i in range(total_frames):
# Sinusoidal flight path
progress = i / total_frames
y = int((self.height - train_height) * (0.5 + 0.3 *
(progress * progress * progress)))
path.append(max(1, min(self.height - train_height, y)))
return path
def _show_accident(self, x_pos: int, y_pos: int, height: int):
"""Show accident/crash effect."""
crash_art = [
" CRASH! ",
" BOOM! ",
" * * * * * ",
" * BANG!! * ",
" * * * * * "
]
for i, line in enumerate(crash_art):
if 0 < y_pos + i <= self.height:
sys.stdout.write(ANSI.move_cursor(x_pos + 10, y_pos + i))
sys.stdout.write(ANSI.RED + line + ANSI.RESET)
sys.stdout.flush()
time.sleep(2)
def main():
"""Main entry point."""
parser = argparse.ArgumentParser(
description='sl - Display animated steam locomotive',
epilog='A joke command for when you type sl instead of ls'
)
parser.add_argument('-a', '--accident', action='store_true',
help='An accident occurs')
parser.add_argument('-F', '--fly', action='store_true',
help='Make the train fly')
parser.add_argument('-l', '--long', action='store_true',
help='Use a longer train')
parser.add_argument('-c', '--C51', action='store_true',
help='Use C51 train type')
parser.add_argument('-s', '--speed', type=float, default=1.0,
help='Animation speed multiplier (default: 1.0)')
parser.add_argument('-v', '--version', action='version',
version=f'sl version {__version__}')
args = parser.parse_args()
# Determine train type
if args.C51:
train_type = "C51"
elif args.long:
train_type = "D51"
else:
train_type = "classic"
# Run animation
animation = SLAnimation(
train_type=train_type,
speed=args.speed,
fly=args.fly,
accident=args.accident
)
animation.run()
if __name__ == "__main__":
main()