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,149 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "socket"
4
+
5
+ module PixelSnake
6
+ # Just enough of the PulseAudio native protocol to play one stream. The
7
+ # desktop's sound server listens on a Unix socket, and PipeWire, which
8
+ # most Linux desktops run now, answers there in the same words, so a
9
+ # socket is all the game needs to be heard.
10
+ #
11
+ # Everything travels in packets: a descriptor of five big-endian words
12
+ # (the length, a channel, two words of offset and the flags), then the
13
+ # payload. Commands go on the control channel as a run of tagged values,
14
+ # each answered by a reply carrying the same tag. Sound goes on the
15
+ # stream's own channel as raw samples, as much as the server has asked
16
+ # for.
17
+ class Pulse
18
+ ERROR = 0
19
+ REPLY = 2
20
+ CREATE_PLAYBACK_STREAM = 3
21
+ AUTH = 8
22
+ SET_CLIENT_NAME = 9
23
+ REQUEST = 61
24
+ PLAYBACK_STREAM_KILLED = 64
25
+
26
+ VERSION = 32
27
+ # The control channel, and "none" or "the default" wherever an index
28
+ # could go.
29
+ NONE = 0xFFFF_FFFF
30
+ FLOAT32LE = 5
31
+ FRONT = [1, 2].freeze
32
+ FRAME = 8
33
+ UNITY = 0x10000
34
+ COOKIE = 256
35
+ ON = "1"
36
+ OFF = "0"
37
+
38
+ # Where the sound server is listening, if it is listening on this
39
+ # machine.
40
+ def self.address(environment = ENV)
41
+ server = environment["PULSE_SERVER"].to_s.split.first.to_s.delete_prefix("unix:")
42
+ runtime = environment["XDG_RUNTIME_DIR"] || "/run/user/#{Process.uid}"
43
+ path = server.empty? ? File.join(runtime, "pulse", "native") : server
44
+ path if File.socket?(path)
45
+ end
46
+
47
+ # The secret a PulseAudio server may ask for. PipeWire does not check
48
+ # it, and without a cookie file zeros do.
49
+ def self.cookie(environment = ENV)
50
+ path = environment["PULSE_COOKIE"] || File.join(Dir.home, ".config", "pulse", "cookie")
51
+ File.binread(path, COOKIE).ljust(COOKIE, "\0")
52
+ rescue SystemCallError, ArgumentError
53
+ "\0" * COOKIE
54
+ end
55
+
56
+ attr_reader :wanted
57
+
58
+ # Connects, says who is calling, and opens a stream of stereo float
59
+ # samples at the given rate, which the server starts asking for at
60
+ # once. The latency is how much sound the server keeps queued.
61
+ def initialize(address, rate:, latency:, sink: nil, cookie: Pulse.cookie)
62
+ @socket = UNIXSocket.new(address)
63
+ @tag = 0
64
+ ask(AUTH, u32(VERSION), arbitrary(cookie))
65
+ ask(SET_CLIENT_NAME, proplist("application.name" => "pixelsnake"))
66
+ @channel, _sink_input, @wanted = ask(CREATE_PLAYBACK_STREAM, stream(rate, latency, sink))
67
+ end
68
+
69
+ def to_io = @socket
70
+
71
+ # Reads what the server has sent, adding up how much more sound it
72
+ # wants. Anything else it says along the way can be let pass.
73
+ def receive
74
+ command, _tag, channel, bytes = read_packet
75
+ @wanted += bytes if command == REQUEST && channel == @channel
76
+ end
77
+
78
+ # Sends sound, a string of float samples, left and right in turn.
79
+ def write(sound)
80
+ @socket.write(packet(@channel, sound))
81
+ @wanted -= sound.bytesize
82
+ end
83
+
84
+ def close
85
+ @socket.close
86
+ end
87
+
88
+ private
89
+
90
+ # Sends a command and waits for the reply to it, giving back the
91
+ # reply's leading words.
92
+ def ask(command, *fields)
93
+ tag = @tag
94
+ @tag += 1
95
+ @socket.write(packet(NONE, [u32(command), u32(tag), *fields].join))
96
+ loop do
97
+ answer, answered, *words = read_packet
98
+ raise IOError, "the sound server refused: error #{words.first}" if answer == ERROR && answered == tag
99
+ return words if answer == REPLY && answered == tag
100
+ end
101
+ end
102
+
103
+ # The tagged numbers a command starts with, the command and its tag
104
+ # first; nothing for sound. Raises once the server drops the stream.
105
+ def read_packet
106
+ length, channel = @socket.read(20)&.unpack("N2")
107
+ raise EOFError, "the sound server hung up" unless length
108
+
109
+ payload = @socket.read(length)
110
+ return [] unless channel == NONE
111
+
112
+ words = payload.unpack("aN" * (length / 5)).each_slice(2).take_while { |tag, _| tag == "L" }.map(&:last)
113
+ raise IOError, "the sound server dropped the stream" if words.first == PLAYBACK_STREAM_KILLED
114
+
115
+ words
116
+ end
117
+
118
+ def packet(channel, payload) = [payload.bytesize, channel, 0, 0, 0].pack("N5") + payload
119
+
120
+ # The stream as the server reads it, field after field. The sound is
121
+ # buffered to the latency and asked for a quarter of that at a time,
122
+ # and every flag is off but one, which lets the server fit the sink's
123
+ # latency to ours.
124
+ def stream(rate, latency, sink)
125
+ target = (rate * latency).round * FRAME
126
+ [
127
+ ["a", FLOAT32LE, FRONT.size, rate].pack("aCCN"), ["m", FRONT.size, *FRONT].pack("aC*"),
128
+ u32(NONE), sink ? "t#{sink}\0" : "N", # the sink, or the default
129
+ u32(NONE), OFF, u32(target), u32(NONE), u32(target / 4), u32(0), # buffer, not corked, no sync
130
+ ["v", FRONT.size, *[UNITY] * FRONT.size].pack("aCN*"),
131
+ OFF * 7, # no remapping or fixed formats
132
+ OFF, ON, proplist("media.name" => "pixelsnake", "media.role" => "game"), # not muted, fit the latency
133
+ OFF * 7, # volume, requests, suspending
134
+ ["B", 0].pack("aC") # no formats but the samples'
135
+ ].join
136
+ end
137
+
138
+ def u32(value) = ["L", value].pack("aN")
139
+
140
+ def arbitrary(bytes) = ["x", bytes.bytesize].pack("aN") + bytes
141
+
142
+ # Properties as a run of name, length and value, ending with an empty
143
+ # name; the server wants text values ending in a zero byte.
144
+ def proplist(properties)
145
+ fields = properties.map { |name, value| "t#{name}\0#{u32(value.bytesize + 1)}#{arbitrary("#{value}\0")}" }
146
+ "P#{fields.join}N"
147
+ end
148
+ end
149
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PixelSnake
4
+ # A song the player can choose, heard wherever there is music: its name,
5
+ # what kind of piece it is, the tune the menus play, and the tune a game
6
+ # runs to. A game's tune may be the menus' own, with the band joining in
7
+ # once the snake moves.
8
+ Song = Data.define(:name, :kind, :calm, :run) do
9
+ def self.named(name) = Song::ALL.find { |song| song.name == name } || Song::ALL.first
10
+
11
+ def in_the_menus = Music.new(tune: calm)
12
+
13
+ def in_a_game(pace:, level:) = Music.new(tune: run, pace:, level:)
14
+ end
15
+
16
+ Song::ALL = [
17
+ Song.new(name: "DUSK", kind: "LULLABY", calm: :dusk, run: :chase),
18
+ Song.new(name: "FIREFLIES", kind: "WALTZ", calm: :fireflies, run: :fireflies),
19
+ Song.new(name: "LANTERNS", kind: "SWING", calm: :lanterns, run: :lanterns),
20
+ Song.new(name: "JADE", kind: "KOTO", calm: :jade, run: :jade)
21
+ ].freeze
22
+ end
@@ -0,0 +1,225 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PixelSnake
4
+ # Every sound in the game, written for the synth's instruments the way
5
+ # the art is written as text grids. They are all in one key, C major
6
+ # pentatonic, so sounds that overlap never clash; notes are counted in
7
+ # steps up that scale from C4, so step 5 is C5 and step 10 is C6.
8
+ #
9
+ # The menus knock on wood. Fruit and gold ring like glass and bells, and
10
+ # a crash is a dull knock, then a boom with the flash. The courtyard's
11
+ # walls give the bigger sounds an echo. Each sound comes in one or more
12
+ # variants: the notes of a rising run, the pitches of a tick.
13
+ module Sounds
14
+ SEED = 11
15
+ SCALE = [0, 2, 4, 7, 9].freeze
16
+
17
+ module_function
18
+
19
+ # Every sound by name, as its variants, each made as loud at its
20
+ # loudest as the number before it, ahead of the player's volume.
21
+ def render(rng = Random.new(SEED))
22
+ {
23
+ move: peak(0.15, knock(12), knock(10)),
24
+ press: peak(0.28, two(8, 11)),
25
+ start: peak(0.32, Synth.echo(run([5, 7, 8, 10], 0.055) { |step| pluck(step) })),
26
+ back: peak(0.22, two(11, 8, damped: 1.6)),
27
+ click: peak(0.2, knock(9, damped: 1.5)),
28
+ tick: peak(0.13, knock(9), knock(10), knock(12)),
29
+ swish: peak(0.14, swish(rng)),
30
+ key: peak(0.15, *[14, 13, 15].map { |step| key(step, rng) }),
31
+ erase: peak(0.14, Synth.strike(pitch(10), Synth::WOOD, bend: 0.25, settle: 0.03, damped: 2.0)),
32
+ refuse: peak(0.24, run([2, 0], 0.085) { |step| reed(step) }),
33
+ sign: peak(0.3, Synth.echo(run([10, 12, 13, 15], 0.05, fade: 0.1) { |step| chime(step) })),
34
+ ask: peak(0.22, run([2, 4], 0.11) { |step| reed(step) }),
35
+ crumble: peak(0.36, crumble(rng)),
36
+ gleam: peak(0.26, Synth.echo(run([*10..17], 0.022, fade: 0.08) { |step| chime(step, damped: 1.5) })),
37
+ jolt: peak(0.38, Synth.layer([0, thud], [0, knock(0)])),
38
+ count: peak(0.28, Synth.layer([0, bell(8, bend: 0.03, damped: 1.6)], [0, knock(8), 0.6])),
39
+ go: peak(0.38, go),
40
+ bite: peak(0.34, *[5, 6, 7, 8, 9].map { |step| bite(step, rng) }),
41
+ plop: peak(0.1, plop(rng)),
42
+ level: peak(0.34, level_up),
43
+ twinkle: peak(0.22, *twinkles(rng)),
44
+ feast: peak(0.42, feast(rng)),
45
+ plum: peak(0.32, plum(rng)),
46
+ pepper: peak(0.36, pepper(rng)),
47
+ pear: peak(0.32, pear(rng)),
48
+ cool: peak(0.2, *cool(rng)),
49
+ fizzle: peak(0.15, Synth.echo(run([17, 15, 13, 12], 0.07, fade: 0.2) { |step| chime(step, damped: 2.0) })),
50
+ crash: peak(0.6, crash(rng)),
51
+ pop: peak(0.15, *[14, 13, 12, 11, 10, 9, 8, 7, 6, 5].map { |step| pop(step, rng) }),
52
+ burst: peak(0.3, Synth.layer([0, pop(15, rng)], [0.012, pop(12, rng)], [0, chime(15, damped: 2.0), 0.4])),
53
+ pause: peak(0.24, two(8, 5, damped: 1.4)),
54
+ resume: peak(0.24, two(5, 8, damped: 1.4)),
55
+ tally: peak(0.12, *[*5..15].map { |step| chime(step, damped: 5.0) }),
56
+ ding: peak(0.3, Synth.echo(Synth.layer([0, bell(10)], [0, bell(13), 0.6]))),
57
+ medal: peak(0.36, medal),
58
+ fanfare: peak(0.45, fanfare)
59
+ }
60
+ end
61
+
62
+ # The frequency of a step up the scale from C4.
63
+ def pitch(step)
64
+ octave, degree = step.divmod(SCALE.size)
65
+ 440.0 * 2**((60 + 12 * octave + SCALE[degree] - 69) / 12.0)
66
+ end
67
+
68
+ def peak(level, *sounds) = sounds.map { |sound| Synth.finish(sound, level) }
69
+
70
+ def knock(step, damped: 2.0) = Synth.strike(pitch(step), Synth::WOOD, damped:)
71
+
72
+ def chime(step, damped: 1.0) = Synth.strike(pitch(step), Synth::GLASS, damped:)
73
+
74
+ def bell(step, bend: 0.0, damped: 1.0) = Synth.strike(pitch(step), Synth::BELL, bend:, settle: 0.008, damped:)
75
+
76
+ def reed(step) = Synth.strike(pitch(step), Synth::REED, damped: 1.5)
77
+
78
+ # Wood for the strike and a bell under it for the ring.
79
+ def pluck(step, damped: 1.0)
80
+ Synth.layer([0, Synth.strike(pitch(step), Synth::WOOD, damped:)],
81
+ [0, Synth.strike(pitch(step), Synth::BELL, damped: damped * 2.5), 0.5])
82
+ end
83
+
84
+ # Two plucks close together, rising or falling.
85
+ def two(first, second, damped: 1.0) = Synth.layer([0, pluck(first, damped:)], [0.05, pluck(second, damped:)])
86
+
87
+ # Notes one after another, each a little quieter by the fade.
88
+ def run(steps, gap, fade: 0.0)
89
+ Synth.layer(*steps.each_with_index.map { |step, index| [index * gap, yield(step), 1 - index * fade] })
90
+ end
91
+
92
+ # Low and falling, for a jolt and the boom of a crash.
93
+ def thud
94
+ Synth.layer([0, Synth.strike(70, [[1.0, 1.0, 0.09]], bend: 1.6, settle: 0.035)],
95
+ [0, Synth.strike(140, [[1.0, 0.4, 0.04]], bend: 1.2, settle: 0.02)])
96
+ end
97
+
98
+ def key(step, rng)
99
+ Synth.layer([0, knock(step, damped: 3.0)], [0, Synth.noise(rng, decay: 0.004, low: 2000.0), 0.3])
100
+ end
101
+
102
+ def swish(rng)
103
+ hiss = Synth.swell(Synth.noise(rng, decay: 0.05, low: 700.0, high: 5000.0), 0.04)
104
+ Synth.layer([0, hiss], [0.05, knock(12), 0.4])
105
+ end
106
+
107
+ # Teeth into a fruit: a bloop rising into the note, with a little
108
+ # crunch, and the walls answering.
109
+ def bite(step, rng)
110
+ bloop = Synth.strike(pitch(step), Synth::WOOD, bend: -0.3, settle: 0.012)
111
+ ring = Synth.strike(pitch(step), Synth::BELL, bend: -0.3, settle: 0.012, damped: 2.0)
112
+ crunch = Synth.noise(rng, decay: 0.012, low: 1800.0, high: 9000.0)
113
+ Synth.echo(Synth.layer([0, bloop], [0, ring, 0.5], [0, crunch, 0.35]), feedback: 0.22)
114
+ end
115
+
116
+ # GO!: three bells at once, the top two an octave apart.
117
+ def go
118
+ Synth.echo(Synth.layer([0, bell(8)], [0, bell(11), 0.8], [0, bell(13), 0.6], [0, knock(13), 0.5]))
119
+ end
120
+
121
+ # The multiplier rising: a run of four bells with glass above them.
122
+ def level_up
123
+ Synth.echo(Synth.layer([0, run([10, 12, 13, 15], 0.06) { |step| bell(step) }], [0.2, chime(17), 0.4]))
124
+ end
125
+
126
+ # A new fruit landing on the stones.
127
+ def plop(rng)
128
+ Synth.layer([0, Synth.strike(pitch(3), Synth::WOOD, bend: -0.35, settle: 0.01, damped: 1.5)],
129
+ [0, Synth.noise(rng, decay: 0.01, high: 700.0), 0.5])
130
+ end
131
+
132
+ # A rare fruit coming out, in the order the game names them: the gold
133
+ # a rising run of glass, the plum warmer and lower on bells, the pepper
134
+ # a crackle and a quick climb, the pear high and cool, falling slowly.
135
+ def twinkles(rng)
136
+ [Synth.echo(run([13, 16, 18], 0.07, fade: 0.25) { |step| chime(step) }),
137
+ Synth.echo(run([8, 10, 12], 0.08, fade: 0.2) { |step| bell(step, damped: 1.3) }),
138
+ Synth.echo(Synth.layer([0, run([12, 14, 16], 0.045, fade: 0.2) { |step| chime(step, damped: 1.6) }], [0, crackle(rng), 0.6])),
139
+ Synth.echo(run([18, 17, 15], 0.1, fade: 0.25) { |step| chime(step, damped: 0.7) }, delay: 0.14, feedback: 0.35)]
140
+ end
141
+
142
+ # Fire taking: a few dry ticks, close together.
143
+ def crackle(rng)
144
+ Synth.layer(*Array.new(5) { |index| [index * 0.023 + rng.rand * 0.01, Synth.noise(rng, decay: 0.002, low: 1500.0), 1 - index * 0.15] })
145
+ end
146
+
147
+ # A golden fruit: the bite, then a cascade of glass over two bells.
148
+ def feast(rng)
149
+ cascade = run([10, 12, 13, 15, 17, 18], 0.035, fade: 0.08) { |step| chime(step) }
150
+ Synth.echo(Synth.layer([0, bite(10, rng), 0.6], [0.02, cascade], [0.02, bell(10), 0.5], [0.02, bell(13), 0.4]),
151
+ delay: 0.12, feedback: 0.32)
152
+ end
153
+
154
+ # A plum: the bite, then three soft pops falling as the tail lets go.
155
+ def plum(rng)
156
+ shed = run([7, 5, 3], 0.06) { |step| pop(step, rng) }
157
+ Synth.echo(Synth.layer([0, bite(8, rng), 0.7], [0.08, shed], [0.02, bell(8, damped: 1.5), 0.35]), feedback: 0.25)
158
+ end
159
+
160
+ # An ember pepper: the bite, a sizzle, and the heat running up the
161
+ # scale.
162
+ def pepper(rng)
163
+ sizzle = Synth.swell(Synth.noise(rng, decay: 0.12, low: 2500.0, high: 9000.0), 0.03)
164
+ climb = run([10, 12, 13, 15, 17], 0.03) { |step| pluck(step) }
165
+ Synth.echo(Synth.layer([0, bite(10, rng), 0.6], [0.02, sizzle, 0.45], [0.04, climb]), feedback: 0.25)
166
+ end
167
+
168
+ # A silver pear: the bite, then glass falling slowly, ringing long, as
169
+ # time slows down.
170
+ def pear(rng)
171
+ falling = run([17, 15, 13, 12], 0.11, fade: 0.12) { |step| chime(step, damped: 0.8) }
172
+ Synth.echo(Synth.layer([0, bite(10, rng), 0.6], [0.03, falling]), delay: 0.15, feedback: 0.35)
173
+ end
174
+
175
+ # A pepper or a pear wearing off: the heat going out with a hiss and two
176
+ # notes falling, or time waking up with two rising.
177
+ def cool(rng)
178
+ hiss = Synth.swell(Synth.noise(rng, decay: 0.07, low: 2500.0, high: 9000.0), 0.02)
179
+ [Synth.layer([0, hiss, 0.35], [0.03, two(10, 7, damped: 1.3)]), two(7, 10, damped: 1.3)]
180
+ end
181
+
182
+ # The head meets the wall with a dull knock, and the boom comes with
183
+ # the flash, after the beat of stillness the death begins with.
184
+ def crash(rng)
185
+ knock = Synth.strike(pitch(0), Synth::WOOD, bend: 0.3, settle: 0.01)
186
+ rumble = Synth.noise(rng, decay: 0.09, low: 40.0, high: 1200.0)
187
+ Synth.echo(Synth.layer([0, knock, 0.7], [Death::STILL, thud], [Death::STILL, rumble, 0.6]),
188
+ delay: 0.13, feedback: 0.25)
189
+ end
190
+
191
+ # A piece of the snake bursting: a quick flick up and a tick.
192
+ def pop(step, rng)
193
+ flick = Synth.strike(pitch(step), [[1.0, 1.0, 0.025], [2.0, 0.2, 0.01]], bend: -0.45, settle: 0.006)
194
+ Synth.layer([0, flick], [0, Synth.noise(rng, decay: 0.003, low: 3000.0), 0.25])
195
+ end
196
+
197
+ # Stone crumbling: a thud, then grains falling ever more sparsely.
198
+ def crumble(rng)
199
+ grains = Array.new(26) do |index|
200
+ share = index.fdiv(26)
201
+ grain = Synth.noise(rng, decay: 0.004 + rng.rand * 0.008, low: 200.0, high: 2500.0)
202
+ [share**1.6 * 0.5 + rng.rand * 0.02, grain, 1 - share * 0.85]
203
+ end
204
+ Synth.layer([0, thud, 0.6], *grains)
205
+ end
206
+
207
+ # A run up to the top, and a chord that rings out with sparkles.
208
+ # A medal landing in the band: it clinks on its ring, two bells ring
209
+ # out together and two more answer above them, and a little glitter
210
+ # hangs at the top.
211
+ def medal
212
+ clink = Synth.layer([0, Synth.strike(pitch(15), Synth::GLASS, damped: 3.0)], [0.006, knock(13), 0.5])
213
+ chords = [[0.05, bell(10)], [0.05, bell(13), 0.7], [0.2, bell(12), 0.8], [0.2, bell(15), 0.6]]
214
+ glitter = [[0.34, chime(17), 0.35], [0.4, chime(18), 0.3], [0.46, chime(20), 0.25]]
215
+ Synth.echo(Synth.layer([0, clink, 0.45], *chords, *glitter), delay: 0.13, feedback: 0.3)
216
+ end
217
+
218
+ def fanfare
219
+ melody = run([8, 10, 12, 13], 0.09) { |step| pluck(step) }
220
+ chord = [15, 13, 12].map { |step| [0.4, bell(step), 0.7] }
221
+ sparkle = [[0.44, chime(17), 0.35], [0.52, chime(18), 0.3], [0.6, chime(20), 0.25]]
222
+ Synth.echo(Synth.layer([0, melody], *chord, *sparkle), delay: 0.13, feedback: 0.3)
223
+ end
224
+ end
225
+ end
@@ -0,0 +1,199 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PixelSnake
4
+ # The game's voice. Its sounds and music are made and mixed by a second
5
+ # process, forked from the game as it starts, so the game never waits on
6
+ # sound and sound never waits on a busy frame. That process makes every
7
+ # sound in the book, opens a stream to the desktop's sound server and
8
+ # keeps it fed, mixing in whatever the game asks for. The game asks with
9
+ # a line down a pipe for each sound: its name, its variant, and how loud
10
+ # it is on the left and on the right; and with a line for the music
11
+ # whenever what it wants heard changes. When the game closes the pipe,
12
+ # the process ends.
13
+ #
14
+ # The music's notes take longer to make than all the sounds together, so
15
+ # a third process makes them alongside and hands each to the band as it
16
+ # is done: the menus are heard as soon as ever, and the music starts as
17
+ # soon as its instruments are ready.
18
+ #
19
+ # Without a sound server, or without fork, nothing is heard and nothing
20
+ # else changes.
21
+ class Speaker
22
+ # How loud each volume setting plays, about five decibels apart.
23
+ VOLUMES = { off: 0.0, low: 0.35, medium: 0.6, high: 1.0 }.freeze
24
+ # A sound at the edge of the screen leans this far toward that side.
25
+ SPREAD = 0.5
26
+ # How much sound the server keeps queued: enough to ride out a busy
27
+ # moment in the sound process, little enough to feel instant.
28
+ LATENCY = 0.04
29
+
30
+ # For what should not be heard: the attract demo, the tests, the tools.
31
+ class Silent
32
+ def play(*) = nil
33
+
34
+ def music(*) = nil
35
+ end
36
+
37
+ SILENT = Silent.new
38
+
39
+ def self.open(preferences, environment = ENV)
40
+ speaker = new(preferences, *start(environment, preferences.song))
41
+ yield speaker
42
+ ensure
43
+ speaker&.close
44
+ end
45
+
46
+ # Forks the sound process, if there is a sound server to play to, and
47
+ # gives back the pipe to it and its process id. The song the player
48
+ # chose has its notes made first. A system with no room for another
49
+ # process or pipe leaves the game as silent as one that cannot fork.
50
+ def self.start(environment, song)
51
+ address = Pulse.address(environment)
52
+ return [] unless address && Process.respond_to?(:fork)
53
+
54
+ requests, pipe = IO.pipe
55
+ process = fork do
56
+ pipe.close
57
+ quiet_down
58
+ notes = make_notes(requests, song)
59
+ book = Sounds.render
60
+ pulse = Pulse.new(address, rate: Synth::RATE, latency: LATENCY, sink: environment["PULSE_SINK"])
61
+ serve(requests, pulse, book, Band.new(Tunes.all), notes)
62
+ ensure
63
+ exit!
64
+ end
65
+ requests.close
66
+ [pipe, process]
67
+ rescue SystemCallError
68
+ [requests, pipe].each { |io| io&.close }
69
+ []
70
+ end
71
+
72
+ # Forks the process that makes the music's notes, and gives back the
73
+ # pipe they come down: the song's first, so it starts as soon as it
74
+ # can, then every other song's, for when another is chosen. The maker
75
+ # stands back for the game and the sounds. If the sound process goes
76
+ # first, the next note has nowhere to go and the maker goes too.
77
+ def self.make_notes(requests, song)
78
+ notes, sending = IO.pipe
79
+ maker = fork do
80
+ notes.close
81
+ requests.close
82
+ Process.setproctitle("pixelsnake notes")
83
+ Process.setpriority(Process::PRIO_PROCESS, 0, 10)
84
+ tunes = Tunes.all.values_at(song.calm, song.run) | Tunes.all.values
85
+ Tunes.each_note(tunes) { |instrument, pitch, samples| sending.write(Band.pack(instrument, pitch, samples)) }
86
+ rescue Errno::EPIPE
87
+ nil
88
+ ensure
89
+ exit!
90
+ end
91
+ sending.close
92
+ Process.detach(maker)
93
+ notes
94
+ end
95
+
96
+ # The volume a saved name stands for, or medium for anything else.
97
+ def self.volume_named(name) = VOLUMES.keys.find { |volume| volume.to_s == name } || :medium
98
+
99
+ # The sound process's work: whenever the server wants more, it mixes
100
+ # what it has been asked to play, until the pipe closes, and the band
101
+ # learns its notes as they come. The sounds the game asked for while
102
+ # the book was being made are too late to play, so they are let go,
103
+ # but the music it last asked for is still wanted.
104
+ def self.serve(requests, pulse, book, band = nil, notes = nil)
105
+ mixer = Mixer.new(band)
106
+ late = requests.read_nonblock(1 << 16, exception: false)
107
+ asked = late.is_a?(String) ? late.lines.grep(/\Amusic /).last.to_s.dup : +""
108
+ loop do
109
+ while (line = asked.slice!(/.*\n/))
110
+ hear(line, mixer, band, book)
111
+ end
112
+ pulse.write(mixer.mix(pulse.wanted / Pulse::FRAME)) if pulse.wanted.positive?
113
+ ready, = IO.select([requests, pulse, notes].compact)
114
+ pulse.receive if ready.include?(pulse)
115
+ notes = band.learn(notes) if notes && ready.include?(notes)
116
+ asked << requests.readpartial(1 << 12) if ready.include?(requests)
117
+ end
118
+ rescue EOFError
119
+ pulse.close
120
+ end
121
+
122
+ # A sound to mix in, or the music the game now wants.
123
+ def self.hear(line, mixer, band, book)
124
+ name, *details = line.split
125
+ if name == "music"
126
+ tune, pace, level, muffled, volume = details
127
+ band&.ask(tune.to_sym, pace.to_f, level.to_i, muffled == "1", volume.to_f)
128
+ else
129
+ variant, left, right = details
130
+ mixer.add(book.fetch(name.to_sym)[variant.to_i], left.to_f, right.to_f)
131
+ end
132
+ end
133
+
134
+ # The sound process keeps away from the terminal, which belongs to the
135
+ # game, and goes by its own name in a process list.
136
+ def self.quiet_down
137
+ $stdin.reopen(File::NULL, "r")
138
+ $stdout.reopen(File::NULL, "w")
139
+ $stderr.reopen(File::NULL, "w")
140
+ Process.setproctitle("pixelsnake sound")
141
+ end
142
+
143
+ private_class_method :start, :make_notes, :hear, :quiet_down
144
+
145
+ def initialize(preferences, pipe = nil, process = nil)
146
+ @preferences = preferences
147
+ @pipe = pipe
148
+ @process = process
149
+ @music = nil
150
+ @loudness = nil
151
+ end
152
+
153
+ # Plays a sound, or one of its variants, leaning toward a point across
154
+ # the screen when given one. If the sound process has gone, the game
155
+ # plays on in silence.
156
+ def play(name, variant = 0, at: nil)
157
+ volume = VOLUMES.fetch(@preferences.volume)
158
+ return if @pipe.nil? || volume.zero?
159
+
160
+ lean = at ? (at.fdiv(App::WIDTH) * 2 - 1) * SPREAD : 0.0
161
+ left = volume * (1 - [lean, 0].max)
162
+ right = volume * (1 + [lean, 0].min)
163
+ tell(format("%s %d %.3f %.3f\n", name, variant, left, right))
164
+ end
165
+
166
+ # Asks for the music a scene wants heard, at the music's own volume,
167
+ # whenever either changes; until the pipe takes the asking, it is asked
168
+ # again.
169
+ def music(music)
170
+ volume = VOLUMES.fetch(@preferences.music)
171
+ return if @pipe.nil? || (music == @music && volume == @loudness)
172
+
173
+ line = format("music %s %.3f %d %d %.3f\n", music.tune, music.pace, music.level, music.muffled ? 1 : 0, volume)
174
+ return unless tell(line).is_a?(Integer)
175
+
176
+ @music = music
177
+ @loudness = volume
178
+ end
179
+
180
+ def close
181
+ @pipe&.close
182
+ return unless @process
183
+
184
+ Process.kill(:TERM, @process)
185
+ Process.wait(@process)
186
+ rescue SystemCallError
187
+ nil
188
+ end
189
+
190
+ private
191
+
192
+ def tell(line)
193
+ @pipe.write_nonblock(line, exception: false)
194
+ rescue Errno::EPIPE
195
+ @pipe.close
196
+ @pipe = nil
197
+ end
198
+ end
199
+ end