diff options
Diffstat (limited to 'examples/spiral_snake.lua')
-rw-r--r-- | examples/spiral_snake.lua | 72 |
1 files changed, 72 insertions, 0 deletions
diff --git a/examples/spiral_snake.lua b/examples/spiral_snake.lua new file mode 100644 index 0000000..84a2040 --- /dev/null +++ b/examples/spiral_snake.lua | |||
@@ -0,0 +1,72 @@ | |||
1 | local sys = require "system" | ||
2 | |||
3 | print [[ | ||
4 | |||
5 | This example will draw a snake like spiral on the screen. Showing ANSI escape | ||
6 | codes for moving the cursor around. | ||
7 | |||
8 | ]] | ||
9 | |||
10 | -- backup term settings with auto-restore on exit | ||
11 | sys.autotermrestore() | ||
12 | |||
13 | -- setup Windows console to handle ANSI processing | ||
14 | sys.setconsoleflags(io.stdout, sys.getconsoleflags(io.stdout) + sys.COF_VIRTUAL_TERMINAL_PROCESSING) | ||
15 | |||
16 | -- start drawing the spiral. | ||
17 | -- start from current pos, then right, then up, then left, then down, and again. | ||
18 | local x, y = 1, 1 -- current position | ||
19 | local dx, dy = 1, 0 -- direction after each step | ||
20 | local wx, wy = 30, 30 -- width and height of the room | ||
21 | local mx, my = 1, 1 -- margin | ||
22 | |||
23 | -- commands to move the cursor | ||
24 | local move_left = "\27[1D" | ||
25 | local move_right = "\27[1C" | ||
26 | local move_up = "\27[1A" | ||
27 | local move_down = "\27[1B" | ||
28 | |||
29 | -- create room: 30 empty lines | ||
30 | print(("\n"):rep(wy)) | ||
31 | local move = move_right | ||
32 | |||
33 | while wx > 0 and wy > 0 do | ||
34 | sys.sleep(0.01) -- slow down the drawing a little | ||
35 | io.write("*" .. move_left .. move ) | ||
36 | io.flush() | ||
37 | x = x + dx | ||
38 | y = y + dy | ||
39 | |||
40 | if x > wx and move == move_right then | ||
41 | -- end of move right | ||
42 | dx = 0 | ||
43 | dy = 1 | ||
44 | move = move_up | ||
45 | wy = wy - 1 | ||
46 | my = my + 1 | ||
47 | elseif y > wy and move == move_up then | ||
48 | -- end of move up | ||
49 | dx = -1 | ||
50 | dy = 0 | ||
51 | move = move_left | ||
52 | wx = wx - 1 | ||
53 | mx = mx + 1 | ||
54 | elseif x < mx and move == move_left then | ||
55 | -- end of move left | ||
56 | dx = 0 | ||
57 | dy = -1 | ||
58 | move = move_down | ||
59 | wy = wy - 1 | ||
60 | my = my + 1 | ||
61 | elseif y < my and move == move_down then | ||
62 | -- end of move down | ||
63 | dx = 1 | ||
64 | dy = 0 | ||
65 | move = move_right | ||
66 | wx = wx - 1 | ||
67 | mx = mx + 1 | ||
68 | end | ||
69 | end | ||
70 | |||
71 | io.write(move_down:rep(15)) | ||
72 | print("\nDone!") | ||