pixelsnake 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +5 -0
  3. data/LICENSE +21 -0
  4. data/README.md +122 -0
  5. data/bin/pixelsnake +8 -0
  6. data/lib/pixelsnake/abacus.rb +102 -0
  7. data/lib/pixelsnake/app.rb +130 -0
  8. data/lib/pixelsnake/art/big_font.rb +196 -0
  9. data/lib/pixelsnake/art/heads.rb +68 -0
  10. data/lib/pixelsnake/art/small_font.rb +73 -0
  11. data/lib/pixelsnake/autopilot.rb +34 -0
  12. data/lib/pixelsnake/award.rb +67 -0
  13. data/lib/pixelsnake/board.rb +36 -0
  14. data/lib/pixelsnake/canvas.rb +189 -0
  15. data/lib/pixelsnake/choice.rb +92 -0
  16. data/lib/pixelsnake/clockwork.rb +169 -0
  17. data/lib/pixelsnake/controls.rb +26 -0
  18. data/lib/pixelsnake/countdown.rb +80 -0
  19. data/lib/pixelsnake/courtyard.rb +306 -0
  20. data/lib/pixelsnake/day.rb +23 -0
  21. data/lib/pixelsnake/death.rb +115 -0
  22. data/lib/pixelsnake/debug_overlay.rb +53 -0
  23. data/lib/pixelsnake/demo.rb +85 -0
  24. data/lib/pixelsnake/density.rb +47 -0
  25. data/lib/pixelsnake/ease.rb +27 -0
  26. data/lib/pixelsnake/fade.rb +30 -0
  27. data/lib/pixelsnake/feats.rb +86 -0
  28. data/lib/pixelsnake/fine.rb +78 -0
  29. data/lib/pixelsnake/fireflies.rb +63 -0
  30. data/lib/pixelsnake/floating_text.rb +36 -0
  31. data/lib/pixelsnake/font.rb +62 -0
  32. data/lib/pixelsnake/fruit.rb +149 -0
  33. data/lib/pixelsnake/game.rb +294 -0
  34. data/lib/pixelsnake/gear.rb +132 -0
  35. data/lib/pixelsnake/high_scores.rb +91 -0
  36. data/lib/pixelsnake/hud.rb +217 -0
  37. data/lib/pixelsnake/iris.rb +76 -0
  38. data/lib/pixelsnake/jukebox.rb +143 -0
  39. data/lib/pixelsnake/keyboard.rb +96 -0
  40. data/lib/pixelsnake/laurel.rb +76 -0
  41. data/lib/pixelsnake/leaf.rb +73 -0
  42. data/lib/pixelsnake/lettering.rb +111 -0
  43. data/lib/pixelsnake/medal.rb +29 -0
  44. data/lib/pixelsnake/medal_view.rb +428 -0
  45. data/lib/pixelsnake/menu.rb +213 -0
  46. data/lib/pixelsnake/meter.rb +108 -0
  47. data/lib/pixelsnake/metronome.rb +24 -0
  48. data/lib/pixelsnake/name.rb +22 -0
  49. data/lib/pixelsnake/name_field.rb +156 -0
  50. data/lib/pixelsnake/odometer.rb +76 -0
  51. data/lib/pixelsnake/palette.rb +64 -0
  52. data/lib/pixelsnake/panel.rb +45 -0
  53. data/lib/pixelsnake/particles.rb +188 -0
  54. data/lib/pixelsnake/piece.rb +82 -0
  55. data/lib/pixelsnake/playback.rb +22 -0
  56. data/lib/pixelsnake/preferences.rb +96 -0
  57. data/lib/pixelsnake/rare_fruit.rb +268 -0
  58. data/lib/pixelsnake/recording.rb +44 -0
  59. data/lib/pixelsnake/ribbon.rb +110 -0
  60. data/lib/pixelsnake/save_file.rb +51 -0
  61. data/lib/pixelsnake/scenes/game_over.rb +249 -0
  62. data/lib/pixelsnake/scenes/medal_case.rb +268 -0
  63. data/lib/pixelsnake/scenes/pause.rb +171 -0
  64. data/lib/pixelsnake/scenes/play.rb +326 -0
  65. data/lib/pixelsnake/scenes/scores.rb +420 -0
  66. data/lib/pixelsnake/scenes/settings.rb +344 -0
  67. data/lib/pixelsnake/scenes/size_notice.rb +38 -0
  68. data/lib/pixelsnake/scenes/statistics.rb +420 -0
  69. data/lib/pixelsnake/scenes/title.rb +152 -0
  70. data/lib/pixelsnake/screen.rb +163 -0
  71. data/lib/pixelsnake/shed.rb +40 -0
  72. data/lib/pixelsnake/skin.rb +36 -0
  73. data/lib/pixelsnake/snake.rb +53 -0
  74. data/lib/pixelsnake/snake_view.rb +393 -0
  75. data/lib/pixelsnake/sound/band.rb +354 -0
  76. data/lib/pixelsnake/sound/instruments.rb +143 -0
  77. data/lib/pixelsnake/sound/mixer.rb +60 -0
  78. data/lib/pixelsnake/sound/music.rb +15 -0
  79. data/lib/pixelsnake/sound/pulse.rb +149 -0
  80. data/lib/pixelsnake/sound/song.rb +22 -0
  81. data/lib/pixelsnake/sound/sounds.rb +225 -0
  82. data/lib/pixelsnake/sound/speaker.rb +199 -0
  83. data/lib/pixelsnake/sound/synth.rb +277 -0
  84. data/lib/pixelsnake/sound/tune.rb +145 -0
  85. data/lib/pixelsnake/sound/tunes/dusk.rb +154 -0
  86. data/lib/pixelsnake/sound/tunes/fireflies.rb +106 -0
  87. data/lib/pixelsnake/sound/tunes/jade.rb +100 -0
  88. data/lib/pixelsnake/sound/tunes/lanterns.rb +126 -0
  89. data/lib/pixelsnake/sound/tunes.rb +40 -0
  90. data/lib/pixelsnake/sprite.rb +58 -0
  91. data/lib/pixelsnake/stage.rb +95 -0
  92. data/lib/pixelsnake/stats.rb +131 -0
  93. data/lib/pixelsnake/terminal.rb +84 -0
  94. data/lib/pixelsnake/terrarium.rb +206 -0
  95. data/lib/pixelsnake/tile.rb +32 -0
  96. data/lib/pixelsnake/toolbox.rb +251 -0
  97. data/lib/pixelsnake/trophy.rb +99 -0
  98. data/lib/pixelsnake/tuft.rb +55 -0
  99. data/lib/pixelsnake/upscale.rb +60 -0
  100. data/lib/pixelsnake/version.rb +5 -0
  101. data/lib/pixelsnake.rb +143 -0
  102. metadata +146 -0
@@ -0,0 +1,163 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PixelSnake
4
+ # Puts canvases on the terminal. Each terminal cell shows two pixels, the
5
+ # top one as the foreground of an upper half block and the bottom one as
6
+ # its background. Only cells that changed since the last frame are sent,
7
+ # colors are sent only when they differ from the terminal's current ones,
8
+ # and each frame goes out in one write inside synchronized output.
9
+ class Screen
10
+ UPPER = "▀"
11
+ LOWER = "▄"
12
+ FULL = "█"
13
+ BLANK = " "
14
+ BEGIN_FRAME = "\e[?2026h"
15
+ END_FRAME = "\e[?2026l"
16
+
17
+ attr_reader :bytes
18
+
19
+ def initialize(output)
20
+ @output = output
21
+ @frame = String.new(capacity: 1 << 20, encoding: Encoding::UTF_8)
22
+ @numbers = []
23
+ @foregrounds = Array.new(Palette::SIZE) { |index| "\e[38;2;#{Palette.rgb(index).join(";")}m".freeze }
24
+ @backgrounds = Array.new(Palette::SIZE) { |index| "\e[48;2;#{Palette.rgb(index).join(";")}m".freeze }
25
+ @both = Array.new(Palette::SIZE) do |top|
26
+ Array.new(Palette::SIZE) do |bottom|
27
+ "\e[38;2;#{Palette.rgb(top).join(";")};48;2;#{Palette.rgb(bottom).join(";")}m".freeze
28
+ end
29
+ end
30
+ @bytes = 0
31
+ resize(0, 0)
32
+ end
33
+
34
+ # The terminal changed size: everything will be cleared and redrawn,
35
+ # centered in the new space.
36
+ def resize(columns, lines)
37
+ @columns = columns
38
+ @lines = lines
39
+ @previous = nil
40
+ number_to([columns, lines].max)
41
+ end
42
+
43
+ def present(canvas)
44
+ frame = @frame.clear << BEGIN_FRAME
45
+ start_over(canvas, frame) unless same_size?(canvas)
46
+ @cursor_x = @cursor_y = -1
47
+ rows = canvas.rows
48
+ width = canvas.width
49
+ y = 0
50
+ while y < canvas.height / 2
51
+ top = rows[2 * y]
52
+ bottom = rows[2 * y + 1]
53
+ old_top = @previous[2 * y]
54
+ old_bottom = @previous[2 * y + 1]
55
+ unless top == old_top && bottom == old_bottom
56
+ draw_row(frame, y, top, bottom, old_top, old_bottom, width)
57
+ old_top.bytesplice(0, width, top, 0, width)
58
+ old_bottom.bytesplice(0, width, bottom, 0, width)
59
+ end
60
+ y += 1
61
+ end
62
+ return @bytes = 0 if frame.bytesize == BEGIN_FRAME.bytesize
63
+
64
+ @output.write(frame << END_FRAME)
65
+ @bytes = frame.bytesize
66
+ end
67
+
68
+ private
69
+
70
+ # Cursor moves are written with numbers kept ready as text, so that
71
+ # writing one allocates nothing: enough of them for any place on the
72
+ # terminal, counted from one.
73
+ def number_to(highest)
74
+ (@numbers.size..highest + 1).each { |number| @numbers << number.to_s.freeze }
75
+ end
76
+
77
+ def same_size?(canvas)
78
+ @previous && @previous.size == canvas.height && @previous.first.bytesize == canvas.width
79
+ end
80
+
81
+ # Clears the terminal to ink and forgets the last frame, so that every
82
+ # cell of the next one is drawn.
83
+ def start_over(canvas, frame)
84
+ @left = (@columns - canvas.width) / 2
85
+ @top = (@lines - canvas.height / 2) / 2
86
+ @previous = Array.new(canvas.height) { (Sprite::CLEAR.chr * canvas.width).b }
87
+ frame << "\e[0m" << @backgrounds[0] << "\e[2J"
88
+ @foreground = -1
89
+ @background = 0
90
+ end
91
+
92
+ def draw_row(frame, y, top, bottom, old_top, old_bottom, width)
93
+ x = 0
94
+ while x < width
95
+ upper = top.getbyte(x)
96
+ lower = bottom.getbyte(x)
97
+ if upper != old_top.getbyte(x) || lower != old_bottom.getbyte(x)
98
+ move(frame, x, y)
99
+ if upper == lower
100
+ draw_solid(frame, upper)
101
+ else
102
+ draw_split(frame, upper, lower)
103
+ end
104
+ @cursor_x = x + 1
105
+ end
106
+ x += 1
107
+ end
108
+ end
109
+
110
+ def move(frame, x, y)
111
+ return if @cursor_y == y && @cursor_x == x
112
+
113
+ if @cursor_y == y && x - @cursor_x == 1
114
+ frame << "\e[C"
115
+ elsif @cursor_y == y && x > @cursor_x
116
+ frame << "\e[" << @numbers[x - @cursor_x] << "C"
117
+ else
118
+ frame << "\e[" << @numbers[@top + y + 1] << ";" << @numbers[@left + x + 1] << "H"
119
+ @cursor_y = y
120
+ end
121
+ end
122
+
123
+ # A cell of one color needs only a space on that background or a full
124
+ # block in that foreground, whichever the terminal already has.
125
+ def draw_solid(frame, color)
126
+ if @background == color
127
+ frame << BLANK
128
+ elsif @foreground == color
129
+ frame << FULL
130
+ else
131
+ frame << @backgrounds[color]
132
+ @background = color
133
+ frame << BLANK
134
+ end
135
+ end
136
+
137
+ # A cell of two colors can be an upper half block or a lower one with
138
+ # the colors swapped; pick whichever changes fewer colors.
139
+ def draw_split(frame, upper, lower)
140
+ if @foreground == upper && @background == lower
141
+ frame << UPPER
142
+ elsif @foreground == lower && @background == upper
143
+ frame << LOWER
144
+ elsif @foreground == upper
145
+ frame << @backgrounds[lower] << UPPER
146
+ @background = lower
147
+ elsif @background == lower
148
+ frame << @foregrounds[upper] << UPPER
149
+ @foreground = upper
150
+ elsif @foreground == lower
151
+ frame << @backgrounds[upper] << LOWER
152
+ @background = upper
153
+ elsif @background == upper
154
+ frame << @foregrounds[lower] << LOWER
155
+ @foreground = lower
156
+ else
157
+ frame << @both[upper][lower] << UPPER
158
+ @foreground = upper
159
+ @background = lower
160
+ end
161
+ end
162
+ end
163
+ end
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PixelSnake
4
+ # The end of the tail a plum takes, going in puffs of the skin's scales
5
+ # with a little of the plum's bloom in each: from the tile nearest the
6
+ # snake out to the tip, a beat apart, so a long shed runs out along where
7
+ # the tail lay. However long it is, it is over in under half a second.
8
+ class Shed
9
+ EACH = 0.03
10
+ WHOLE = 0.4
11
+
12
+ def initialize(courtyard, particles, skin)
13
+ @courtyard = courtyard
14
+ @particles = particles
15
+ @scales = skin.flakes.first(5)
16
+ @waiting = []
17
+ @time = 0.0
18
+ end
19
+
20
+ # The tiles a plum took, farthest first, as the game gives them.
21
+ def add(tiles)
22
+ each = [EACH, WHOLE / tiles.size].min
23
+ tiles.reverse.each_with_index { |tile, index| @waiting << [tile, @time + index * each] }
24
+ end
25
+
26
+ def update(dt)
27
+ @time += dt
28
+ due, @waiting = @waiting.partition { |_, at| at <= @time }
29
+ due.each { |tile, _| puff(tile) }
30
+ end
31
+
32
+ private
33
+
34
+ def puff(tile)
35
+ x, y = @courtyard.corner(tile.column, tile.row)
36
+ @particles.burst(x + 4, y + 4, @scales, count: 6, speed: 38)
37
+ @particles.burst(x + 4, y + 4, %i[blush orchid], count: 2, speed: 20, gravity: -20.0)
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PixelSnake
4
+ # The colors a snake wears. Every snake is painted in jade; a skin is the
5
+ # map that recolors it on the way to the screen, its six scales from dark
6
+ # to light for jade's six and its own eyes for the gold ones.
7
+ class Skin
8
+ JADE = %i[deep pine jade fern leaf lime].freeze
9
+ GOLD_EYES = %i[amber gold].freeze
10
+
11
+ attr_reader :name, :scales, :eyes, :map
12
+
13
+ def initialize(name, scales, eyes = GOLD_EYES)
14
+ @name = name
15
+ @scales = scales
16
+ @eyes = eyes
17
+ worn = (JADE + GOLD_EYES).zip(scales + eyes).to_h { |from, to| [Palette[from], Palette[to]] }
18
+ @map = Palette.map { |index| worn.fetch(index, index) }
19
+ end
20
+
21
+ # The scales from light to dark: a bit flung off the snake starts bright
22
+ # and darkens as it flies.
23
+ def flakes = scales.reverse
24
+
25
+ # The red snake looks out of green eyes, and the pale one out of red.
26
+ ALL = [
27
+ new("JADE", JADE),
28
+ new("EMBER", %i[wine crimson red orange amber gold], %i[leaf lime]),
29
+ new("IVORY", %i[slate steel ash sand cream white], %i[red orange]),
30
+ new("LAGOON", %i[deep tide teal lagoon foam white]),
31
+ new("ORCHID", %i[wine plum mauve orchid blush cream])
32
+ ].freeze
33
+
34
+ def self.named(name) = ALL.find { |skin| skin.name == name } || ALL.first
35
+ end
36
+ end
@@ -0,0 +1,53 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PixelSnake
4
+ # The snake as the rules see it: the tiles it covers, head first, and the
5
+ # way it is heading.
6
+ class Snake
7
+ attr_reader :body, :heading, :previous_tail
8
+
9
+ def self.lying(head, heading, length)
10
+ new(Array.new(length) { |index| Tile.new(head.column - heading.dx * index, head.row - heading.dy * index) }, heading)
11
+ end
12
+
13
+ def initialize(body, heading)
14
+ @body = body
15
+ @heading = heading
16
+ @previous_tail = nil
17
+ end
18
+
19
+ def head = body.first
20
+
21
+ def length = body.size
22
+
23
+ def ahead = head + heading
24
+
25
+ def turn(direction)
26
+ @heading = direction
27
+ end
28
+
29
+ # Moves one tile along the heading. When it grows, the tail stays where
30
+ # it is and the snake is one tile longer.
31
+ def advance(grow: false)
32
+ body.unshift(ahead)
33
+ @previous_tail = grow ? nil : body.pop
34
+ end
35
+
36
+ # Lets go of tiles from the tail end, as a plum makes it, and gives back
37
+ # the tiles it left this move, farthest first. The tail moves on from
38
+ # the nearest of them, as it does from any tile it leaves.
39
+ def shed(count)
40
+ return [] if count.zero?
41
+
42
+ cut = body.pop(count)
43
+ gone = [*cut.drop(1), previous_tail].reverse
44
+ @previous_tail = cut.first
45
+ gone
46
+ end
47
+
48
+ # Whether the body is in the way of a head moving into the tile. The
49
+ # tail never is: it moves on as the head moves in, because the snake only
50
+ # grows by eating and food is never under the tail.
51
+ def blocks?(tile) = body[0...-1].include?(tile)
52
+ end
53
+ end
@@ -0,0 +1,393 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PixelSnake
4
+ # Draws the snake as one creature: a tube of jade scales that follows the
5
+ # body tile by tile, lit from the upper left, with a hand-drawn head in
6
+ # front. Between ticks the head glides into its new tile and the tail
7
+ # glides out of its old one, while the body between them stays put and
8
+ # its pattern slides along it like skin.
9
+ #
10
+ # It also keeps the snake's small life: blinking, glancing at the food,
11
+ # flicking its tongue (more often near food), the bulge of each meal
12
+ # working down the body, and a sheen that runs along the scales now and
13
+ # then, and at once when the snake changes skin.
14
+ #
15
+ # The snake is painted in jade and drawn through its skin's map, its
16
+ # tiles counted from the point at the corner of the first. On the fine
17
+ # canvas it is painted in tiles of twelve pixels, its body fuller and its
18
+ # pattern finer, and its head is drawn again with room for eyes that look
19
+ # round and catch the light.
20
+ #
21
+ # Distance along the body is measured in points from the head's center:
22
+ # tile i (the head's tile is 0) has its center at TILE * (progress + i - 1).
23
+ class SnakeView
24
+ TILE = Courtyard::TILE
25
+ HALF_WIDTH = 3.0
26
+ TAPER = 12.0
27
+ BLINK = 0.14
28
+ TONGUE = 0.16
29
+ BULGE_SPEED = 75.0
30
+ BULGE = 4.0
31
+ SHEEN_SPEED = 170.0
32
+ SHEEN_EVERY = 5.5
33
+ SHEEN = 3.0
34
+ LONGEST = Courtyard::WIDE * Courtyard::ROWS * TILE
35
+
36
+ # The one light: from the upper left and a little in front.
37
+ LIGHT = [-1.0, -1.0, 1.7].freeze
38
+ LIGHT_X, LIGHT_Y, LIGHT_Z = LIGHT.map { |part| part / Math.sqrt(LIGHT.sum { |each| each * each }) }
39
+
40
+ # Interior scales from light to dark, with the brightness each needs.
41
+ # Lime and deep are only reached through the pattern or the sheen.
42
+ SCALES = [[2.0, :lime], [0.86, :leaf], [0.6, :fern], [0.38, :jade], [-2.0, :pine], [-2.0, :deep]].freeze
43
+ RAMP = SCALES.map { |_, color| Palette[color] }.freeze
44
+ LIT_EDGE = Palette[:pine]
45
+ DARK_EDGE = Palette[:deep]
46
+
47
+ # How the snake is drawn at a density: its tile, how many pixels a
48
+ # point is, its body's half width and how far that narrows to the tail
49
+ # and swells round a meal, its pattern, its heads and tongues, and how
50
+ # many rows at the back of the head a bend may trim.
51
+ Build = Data.define(:tile, :scale, :half_width, :narrowing, :swelling, :pattern, :heads, :tongues, :behind)
52
+
53
+ def initialize(rng, origin:, skin: Skin::ALL.first)
54
+ @rng = rng
55
+ @skin = skin
56
+ @left, @top = origin
57
+ @time = 0.0
58
+ @plain = {}
59
+ @next_blink = 2.0
60
+ @bulges = []
61
+ @sheen_from = SHEEN_EVERY
62
+ end
63
+
64
+ def update(dt)
65
+ @time += dt
66
+ @next_blink = @time + @rng.rand(2.0..5.0) if @time > @next_blink + BLINK
67
+ @bulges = @bulges.map { |along| along + BULGE_SPEED * dt }.reject { |along| along > LONGEST }
68
+ end
69
+
70
+ # A meal starts down the body from just behind the head.
71
+ def swallow
72
+ @bulges << TILE / 2.0
73
+ end
74
+
75
+ # A new skin catches the light from the head down.
76
+ def wear(skin)
77
+ @skin = skin
78
+ @sheen_from = @time
79
+ end
80
+
81
+ # Popped counts the tiles, from the head back, that have already burst
82
+ # at the end of a run; a stunned snake has its eyes shut.
83
+ def draw(canvas, snake, progress, food = nil, popped: 0, stunned: false)
84
+ density = canvas.density
85
+ build = SnakeView.build(density)
86
+ tiles = snake.previous_tail ? snake.body + [snake.previous_tail] : snake.body
87
+ tail_end = TILE * (snake.previous_tail ? snake.length - 1 : progress + snake.length - 2)
88
+ tiles.each_with_index do |tile, index|
89
+ next if index < popped
90
+
91
+ front = index.zero? ? snake.heading : tile.toward(tiles[index - 1])
92
+ back = index == tiles.size - 1 ? front.reverse : tile.toward(tiles[index + 1])
93
+ start = TILE * (progress + index - 1) - TILE / 2
94
+ draw_piece(canvas, build, tile, Piece.between(front, back, build.tile), start, tail_end)
95
+ end
96
+ draw_head(canvas, build, snake, progress, food, stunned) if popped.zero?
97
+ end
98
+
99
+ def self.build(density) = density.fine? ? FINE : STANDARD
100
+
101
+ # The head facing one way at a pixel of a canvas of pixels, eyes open
102
+ # or shut mid-blink. Each eye is gold with a dark pupil in the corner it
103
+ # looks toward; the fine eye catches the light too. While the head is
104
+ # still in the tile where the body turned, the bend (that tile's piece
105
+ # and its corner pixel) trims the back of the head to the curve, so the
106
+ # neck follows the body round the corner. A skin's map recolors it all.
107
+ def self.draw_head(canvas, direction, x, y, build: STANDARD, blink: false, look: [1, 1], bend: nil,
108
+ map: Palette::IDENTITY)
109
+ head = build.heads.fetch(direction)
110
+ if bend
111
+ draw_bent(canvas, build, head.sprite, direction, x, y, *bend, map)
112
+ else
113
+ canvas.draw(head.sprite, x, y, map)
114
+ end
115
+ worn = ->(name) { map.getbyte(Palette[name]) }
116
+ head.eyes.each do |eye_x, eye_y|
117
+ build == FINE ? draw_fine_eye(canvas, x + eye_x, y + eye_y, blink, look, worn) : draw_eye(canvas, x + eye_x, y + eye_y, blink, look, worn)
118
+ end
119
+ end
120
+
121
+ def self.draw_eye(canvas, x, y, blink, look, worn)
122
+ if blink
123
+ canvas.fill(x, y, 2, 1, worn[:jade])
124
+ canvas.fill(x, y + 1, 2, 1, worn[:pine])
125
+ else
126
+ canvas.fill(x, y, 2, 2, worn[:amber])
127
+ canvas.plot(x, y, worn[:gold])
128
+ canvas.plot(x + look[0], y + look[1], Palette[:ink])
129
+ end
130
+ end
131
+
132
+ # Three pixels square: the lid's two shades when shut; open, the iris
133
+ # lit toward its top left, a slit of a pupil two pixels tall turned
134
+ # where it looks, and a speck of light in the corner toward the light.
135
+ def self.draw_fine_eye(canvas, x, y, blink, look, worn)
136
+ if blink
137
+ canvas.fill(x, y, 3, 2, worn[:fern])
138
+ canvas.fill(x, y + 2, 3, 1, worn[:pine])
139
+ else
140
+ canvas.fill(x, y, 3, 3, worn[:amber])
141
+ canvas.plot(x + 1, y, worn[:gold])
142
+ canvas.plot(x, y + 1, worn[:gold])
143
+ canvas.fill(x + 1 + look[0], y + look[1], 1, 2, Palette[:ink])
144
+ canvas.plot(x, y, Palette[:white])
145
+ end
146
+ end
147
+
148
+ def self.draw_bent(canvas, build, sprite, direction, x, y, piece, tile_x, tile_y, map)
149
+ sprite.rows.each_with_index do |row, sy|
150
+ row.each_byte.with_index do |color, sx|
151
+ next if color == Sprite::CLEAR
152
+ next if behind?(build, direction, sx, sy) && !piece.covers?(x + sx - tile_x, y + sy - tile_y, build.half_width)
153
+
154
+ canvas.plot(x + sx, y + sy, map.getbyte(color))
155
+ end
156
+ end
157
+ end
158
+
159
+ # The rows of a head farthest from its snout.
160
+ def self.behind?(build, direction, x, y)
161
+ along = direction.dx.zero? ? y : x
162
+ along = build.tile - 1 - along if direction.dx.negative? || direction.dy.negative?
163
+ along < build.behind
164
+ end
165
+
166
+ private_class_method :draw_eye, :draw_fine_eye, :draw_bent, :behind?
167
+
168
+ private
169
+
170
+ # A piece with nothing special about it comes from a cache, one for each
171
+ # shape and each place the pattern can be in; pieces at the tail, under
172
+ # a meal or in the sheen are painted fresh. Distances are in points
173
+ # until a piece is painted in the pixels of its density.
174
+ def draw_piece(canvas, build, tile, piece, start, tail_end)
175
+ density = canvas.density
176
+ x, y = corner(tile)
177
+ at_x = density.at(x)
178
+ at_y = density.at(y)
179
+ scale = build.scale
180
+ if plain?(start, tail_end)
181
+ phase = (start * scale).round % build.pattern.first.size
182
+ sprite = @plain[[piece, phase]] ||= paint(build, piece, phase, Float::INFINITY, plain: true)
183
+ else
184
+ sprite = paint(build, piece, start * scale, tail_end * scale)
185
+ end
186
+ canvas.pixels.draw(sprite, at_x, at_y, @skin.map)
187
+ end
188
+
189
+ def corner(tile) = [@left + tile.column * TILE, @top + tile.row * TILE]
190
+
191
+ def plain?(start, tail_end)
192
+ finish = start + TILE
193
+ start >= 0 && finish <= tail_end - TAPER &&
194
+ @bulges.none? { |along| along + BULGE > start && along - BULGE < finish } &&
195
+ !(sheen && sheen + SHEEN > start && sheen - SHEEN < finish)
196
+ end
197
+
198
+ # Where the sheen is along the body, in points, if it is running now.
199
+ def sheen
200
+ since = @time - @sheen_from
201
+ since % SHEEN_EVERY * SHEEN_SPEED unless since.negative?
202
+ end
203
+
204
+ # Paints one piece of body as a sprite: which pixels are inside depends
205
+ # on the width there, the outline is wherever the inside meets the
206
+ # outside, and the rest is shaded by the light, the pattern and the
207
+ # sheen. A plain piece is painted with no meal or sheen anywhere near.
208
+ def paint(build, piece, start, tail_end, plain: false)
209
+ inside = {}
210
+ piece.spots.each do |spot|
211
+ along = start + spot.along
212
+ next if along.negative? || along > tail_end
213
+
214
+ width = half_width(build, along, tail_end, plain)
215
+ inside[[spot.x, spot.y]] = [spot, along, width] if spot.across.abs < width
216
+ end
217
+ rows = Array.new(build.tile) { (Sprite::CLEAR.chr * build.tile).b }
218
+ inside.each_value do |spot, along, width|
219
+ color =
220
+ if edge?(build, piece, spot, inside) then edge_color(spot)
221
+ else scale_color(build, spot, start.round + spot.along, width, !plain && lit?(build, along))
222
+ end
223
+ rows[spot.y].setbyte(spot.x, color)
224
+ end
225
+ Sprite.new(rows)
226
+ end
227
+
228
+ # The body narrows over its last few tiles to a point, and swells where
229
+ # a meal is passing.
230
+ def half_width(build, along, tail_end, plain)
231
+ taper = TAPER * build.scale
232
+ width = build.half_width - build.narrowing * ((along - (tail_end - taper)) / taper).clamp(0.0, 1.0)
233
+ !plain && swollen?(build, along) ? width + build.swelling : width
234
+ end
235
+
236
+ def swollen?(build, along) = @bulges.any? { |bulge| (along - bulge * build.scale).abs < BULGE * build.scale }
237
+
238
+ # Scales catch more light where the sheen passes or the skin is
239
+ # stretched over a meal.
240
+ def lit?(build, along)
241
+ swollen?(build, along) || (sheen && (along - sheen * build.scale).abs < SHEEN * build.scale)
242
+ end
243
+
244
+ def edge?(build, piece, spot, inside)
245
+ [[1, 0], [-1, 0], [0, 1], [0, -1]].any? do |dx, dy|
246
+ x = spot.x + dx
247
+ y = spot.y + dy
248
+ if x.between?(0, build.tile - 1) && y.between?(0, build.tile - 1)
249
+ !inside.key?([x, y])
250
+ else
251
+ !piece.open_toward?(Direction.new(dx, dy))
252
+ end
253
+ end
254
+ end
255
+
256
+ # The outline is a shade lighter on the side that faces the light.
257
+ def edge_color(spot) = spot.facing_x * LIGHT_X + spot.facing_y * LIGHT_Y > 0 ? LIT_EDGE : DARK_EDGE
258
+
259
+ def scale_color(build, spot, along, width, lit)
260
+ across = spot.across.abs / width
261
+ brightness = (spot.facing_x * LIGHT_X + spot.facing_y * LIGHT_Y) * across + LIGHT_Z * Math.sqrt(1 - across * across)
262
+ level = SCALES.index { |threshold, _| brightness > threshold }
263
+ pattern = build.pattern
264
+ row = pattern[(spot.across + pattern.size / 2).floor.clamp(0, pattern.size - 1)]
265
+ RAMP[(level + row[along.floor % row.size] - (lit ? 1 : 0)).clamp(0, RAMP.size - 1)]
266
+ end
267
+
268
+ # The head glides between its last tile and its new one, a pixel at a
269
+ # time in the density's own pixels.
270
+ def draw_head(canvas, build, snake, progress, food, stunned)
271
+ density = canvas.density
272
+ from_x, from_y = corner(snake.body[1]).map { |point| density.at(point) }
273
+ to_x, to_y = corner(snake.head).map { |point| density.at(point) }
274
+ x = (from_x + (to_x - from_x) * progress).round
275
+ y = (from_y + (to_y - from_y) * progress).round
276
+ look = food ? [food.column > snake.head.column ? 1 : 0, food.row > snake.head.row ? 1 : 0] : [1, 1]
277
+ shut = stunned || @time.between?(@next_blink, @next_blink + BLINK)
278
+ SnakeView.draw_head(canvas.pixels, snake.heading, x, y, build:, blink: shut, look:,
279
+ bend: bend(density, build, snake, progress), map: @skin.map)
280
+ flick(canvas.pixels, build, snake.heading, x, y, food && food.distance(snake.head) <= 3) unless stunned
281
+ end
282
+
283
+ # The corner piece the head has just turned out of and that tile's top
284
+ # left pixel, while the head is still inside it.
285
+ def bend(density, build, snake, progress)
286
+ return if progress >= 0.5
287
+
288
+ turned_at = snake.body[1]
289
+ piece = Piece.between(snake.heading, turned_at.toward(snake.body[2]), build.tile)
290
+ [piece, *corner(turned_at).map { |point| density.at(point) }] unless piece.straight?
291
+ end
292
+
293
+ # Now and then the tongue tastes the air; with food close by, it does
294
+ # so three times as often.
295
+ def flick(canvas, build, direction, x, y, near_food)
296
+ return unless @time % (near_food ? 0.85 : 2.6) < TONGUE
297
+
298
+ sprite, dx, dy = build.tongues.fetch(direction)
299
+ canvas.draw(sprite, x + dx, y + dy)
300
+ end
301
+
302
+ Head = Data.define(:sprite, :eyes) do
303
+ def self.parse(art)
304
+ eyes = art.lines.each_with_index.flat_map do |line, y|
305
+ line.chars.each_index.select { |x| line[x] == "E" }.map { |x| [x, y] }
306
+ end
307
+ new(Sprite.parse(art, Heads::LEGEND), eyes)
308
+ end
309
+
310
+ def transpose = Head.new(sprite.transpose, eyes.map(&:reverse))
311
+ end
312
+
313
+ def self.heads(right, left)
314
+ right = Head.parse(right)
315
+ left = Head.parse(left)
316
+ { Direction::RIGHT => right, Direction::LEFT => left, Direction::DOWN => right.transpose,
317
+ Direction::UP => left.transpose }.freeze
318
+ end
319
+
320
+ def self.tongues(right, left, tile, reach, middle)
321
+ { Direction::RIGHT => [right, tile, middle], Direction::LEFT => [left, -reach, middle],
322
+ Direction::DOWN => [right.transpose, middle, tile], Direction::UP => [left.transpose, middle, -reach] }.freeze
323
+ end
324
+
325
+ private_class_method :heads, :tongues
326
+
327
+ TONGUE_COLORS = { "r" => :red, "c" => :crimson }.freeze
328
+ FORK_RIGHT = Sprite.parse(<<~ART, TONGUE_COLORS)
329
+ ..r
330
+ rc.
331
+ ..r
332
+ ART
333
+ FORK_LEFT = Sprite.parse(<<~ART, TONGUE_COLORS)
334
+ r..
335
+ .cr
336
+ r..
337
+ ART
338
+ FINE_FORK_RIGHT = Sprite.parse(<<~ART, TONGUE_COLORS)
339
+ ...r
340
+ ..r.
341
+ rcc.
342
+ ..r.
343
+ ...r
344
+ ART
345
+ FINE_FORK_LEFT = Sprite.parse(<<~ART, TONGUE_COLORS)
346
+ r...
347
+ .r..
348
+ .ccr
349
+ .r..
350
+ r...
351
+ ART
352
+
353
+ # A broken pale stripe down the spine with dark flecks on the flanks,
354
+ # repeating every 12 pixels so it never lines up with the tiles. Rows run
355
+ # across the body, columns along it from the head. "+" and "*" lighten a
356
+ # scale by one and two steps, "-" darkens it by one.
357
+ STEPS = { "." => 0, "+" => -1, "*" => -2, "-" => 1 }.freeze
358
+ PATTERN = <<~GRID.lines(chomp: true).map { |line| line.chars.map { |char| STEPS.fetch(char) } }.freeze
359
+ ............
360
+ ............
361
+ ..-......-..
362
+ .+**+...+*+.
363
+ ..+*+....+..
364
+ ....-....-..
365
+ ............
366
+ ............
367
+ GRID
368
+
369
+ # The same marks at half as fine again, repeating every 18 pixels, with
370
+ # a scale or two catching the light on the lower flank.
371
+ FINE_PATTERN = <<~GRID.lines(chomp: true).map { |line| line.chars.map { |char| STEPS.fetch(char) } }.freeze
372
+ ..................
373
+ ..................
374
+ ..................
375
+ ...-.........-....
376
+ ..+**+......+*+...
377
+ .+****+....+**+...
378
+ ..+**+......+*+...
379
+ ...-.-.......-....
380
+ ......+.........+.
381
+ ..................
382
+ ..................
383
+ ..................
384
+ GRID
385
+
386
+ STANDARD = Build.new(tile: TILE, scale: 1, half_width: HALF_WIDTH, narrowing: 2.0, swelling: 1.0, pattern: PATTERN,
387
+ heads: heads(Heads::RIGHT, Heads::LEFT), tongues: tongues(FORK_RIGHT, FORK_LEFT, TILE, 3, 2),
388
+ behind: 3)
389
+ FINE = Build.new(tile: 12, scale: 1.5, half_width: 5.0, narrowing: 3.5, swelling: 1.5, pattern: FINE_PATTERN,
390
+ heads: heads(Heads::FINE_RIGHT, Heads::FINE_LEFT),
391
+ tongues: tongues(FINE_FORK_RIGHT, FINE_FORK_LEFT, 12, 4, 4), behind: 5)
392
+ end
393
+ end