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,294 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PixelSnake
4
+ # The rules of one game of snake. Time and randomness come from outside:
5
+ # the caller decides when to tick, and food is placed with the Random it
6
+ # was given, so a game is deterministic and easy to test.
7
+ #
8
+ # Now and then eating a fruit brings out a rare one, never more than one
9
+ # at a time, and it is gone again after a set number of moves; it only
10
+ # appears where the head can reach it in time. None of them makes the
11
+ # snake longer. A golden fruit is worth five fruit. The others are worth
12
+ # one and do something: a plum takes a quarter of the snake off its tail,
13
+ # a third once it is very long, and comes only to a snake long enough to
14
+ # miss the tiles; an ember pepper makes the snake faster for a while, and
15
+ # every fruit it eats meanwhile counts double; a silver pear makes it
16
+ # slower for a while. No rare fruit comes out while a pepper or a pear is
17
+ # working.
18
+ #
19
+ # A game keeps count of itself as it goes, for the player's stats: its
20
+ # moves, the time those moves took, the longest the snake grew, and each
21
+ # kind of rare fruit it brought out and saw eaten. It keeps every turn
22
+ # the snake made too, so that it can be played again. It ends into the
23
+ # wall, into the snake itself, or won, with the board full.
24
+ #
25
+ # The rules are numbered, and a game can be played under older ones, so
26
+ # a game recorded under them comes out the same when it is played again.
27
+ class Game
28
+ Moved = Data.define
29
+ # A fruit, or a rare one of a kind, and for a plum the tiles the snake
30
+ # let go of, farthest first.
31
+ Ate = Data.define(:tile, :points, :kind, :shed) do
32
+ def initialize(tile:, points:, kind: :fruit, shed: []) = super
33
+ end
34
+ Crashed = Data.define(:tile)
35
+ Rare = Data.define(:kind, :tile)
36
+ # A game told in numbers, the rare fruit as a count for each kind. One
37
+ # given up before it ended has ended :left.
38
+ Run = Data.define(:speed, :score, :length, :longest, :fruit, :rare_eaten, :rare_seen, :moves, :seconds, :ending)
39
+
40
+ START_LENGTH = 4
41
+ QUEUED_TURNS = 2
42
+ SLOWEST = 0.15
43
+ FASTEST = 0.066
44
+ SPEEDUP = 0.95
45
+ FRUIT_PER_LEVEL = 5
46
+ TOP_LEVEL = 9
47
+ # From the third fruit, one eaten in four brings out a rare fruit, of a
48
+ # kind chosen by these shares, which waits so many moves.
49
+ RARE = %i[golden plum pepper pear].freeze
50
+ RARE_FROM = 3
51
+ RARE_ODDS = 4
52
+ RARE_SHARES = { golden: 2, plum: 1, pepper: 1, pear: 1 }.freeze
53
+ RARE_MOVES = 36
54
+ GOLDEN_WORTH = 5
55
+ # The score counts no further: six digits are all the band and the
56
+ # tables have room for.
57
+ HIGHEST_SCORE = 999_999
58
+ PLUM_FROM = 12
59
+ # A plum takes a quarter of the snake, or a third of one this long.
60
+ # Under the first rules it took three tiles whatever the length.
61
+ PLUM_LONG = 68
62
+ FIRST_PLUM = 3
63
+ # How many moves a pepper and a pear work for, and how much longer each
64
+ # move takes meanwhile; however hot the pepper, never faster than this.
65
+ WORKS = { pepper: 40, pear: 32 }.freeze
66
+ PACES = { pepper: 0.72, pear: 1.5 }.freeze
67
+ FASTEST_BURN = 0.05
68
+ # How long each move takes at each speed, against normal.
69
+ SPEEDS = { slow: 4.0 / 3, normal: 1.0, fast: 0.8 }.freeze
70
+ # Raised whenever a change to the rules would make an old game come out
71
+ # differently, with the old rules kept beside the new.
72
+ RULES = 2
73
+
74
+ attr_reader :board, :speed, :rules, :snake, :food, :rare, :rare_left, :effect, :effect_left, :score, :eaten, :moves,
75
+ :ending, :made_turns
76
+
77
+ def initialize(board, rng, speed: :normal, snake: nil, food: nil, rare: nil, rules: RULES)
78
+ @board = board
79
+ @rng = rng
80
+ @speed = speed
81
+ @rules = rules
82
+ @pace = SPEEDS.fetch(speed)
83
+ @snake = snake || Snake.lying(Tile.new(board.columns / 3, board.rows / 2), Direction::RIGHT, START_LENGTH)
84
+ @turns = []
85
+ @score = 0
86
+ @eaten = 0
87
+ @moves = 0
88
+ @seconds = 0.0
89
+ @longest = @snake.length
90
+ @rare_eaten = RARE.to_h { |kind| [kind, 0] }
91
+ @rare_seen = RARE.to_h { |kind| [kind, rare&.kind == kind ? 1 : 0] }
92
+ @ending = nil
93
+ @rare = rare
94
+ @rare_left = rare ? RARE_MOVES : 0
95
+ @effect = nil
96
+ @effect_left = 0
97
+ @made_turns = []
98
+ @food = food || place_food
99
+ end
100
+
101
+ # Queues a turn for the coming ticks. Each turn is judged against the
102
+ # one queued before it, so two quick turns both count and a reversal
103
+ # onto the body never does.
104
+ def steer(direction)
105
+ last = @turns.last || snake.heading
106
+ return if @turns.size == QUEUED_TURNS || direction == last || direction.opposite?(last)
107
+
108
+ @turns << direction
109
+ end
110
+
111
+ # One move. It is made under whatever is working as it starts, which
112
+ # may wear off with it; a pepper or a pear eaten on it works from the
113
+ # next move on.
114
+ def tick
115
+ under = effect
116
+ @seconds += interval
117
+ wear_off
118
+ make_turn unless @turns.empty?
119
+ target = snake.ahead
120
+ return crash(target) if !board.include?(target) || snake.blocks?(target)
121
+
122
+ eating = target == food
123
+ snake.advance(grow: eating)
124
+ @moves += 1
125
+ @longest = [@longest, snake.length].max
126
+ event =
127
+ if eating then eat(target, under)
128
+ elsif target == rare&.tile then savour(target)
129
+ else Moved.new
130
+ end
131
+ age_rare
132
+ bring_rare if eating
133
+ event
134
+ end
135
+
136
+ def over? = !ending.nil?
137
+
138
+ def won? = ending == :won
139
+
140
+ # The game so far, counted up. The time is what its moves took, each at
141
+ # the pace it was made.
142
+ def run
143
+ Run.new(speed: @speed, score:, length: snake.length, longest: @longest, fruit: eaten, rare_eaten: @rare_eaten.dup,
144
+ rare_seen: @rare_seen.dup, moves:, seconds: @seconds, ending: ending || :left)
145
+ end
146
+
147
+ # Seconds per tick after so many fruit, at normal speed. The game starts
148
+ # slow and closes in on its top speed a little with every fruit, so it
149
+ # quickens without ever lurching.
150
+ def self.interval_after(eaten) = FASTEST + (SLOWEST - FASTEST) * SPEEDUP**eaten
151
+
152
+ def self.level_after(eaten) = [1 + eaten / FRUIT_PER_LEVEL, TOP_LEVEL].min
153
+
154
+ # The speed a saved name stands for, or normal for anything else.
155
+ def self.speed_named(name) = SPEEDS.keys.find { |speed| speed.to_s == name } || :normal
156
+
157
+ # Seconds per tick now, at the game's speed and with whatever is working.
158
+ def interval
159
+ plain = Game.interval_after(eaten) * @pace
160
+ case effect
161
+ when :pepper then [plain * PACES[:pepper], FASTEST_BURN].max
162
+ when :pear then plain * PACES[:pear]
163
+ else plain
164
+ end
165
+ end
166
+
167
+ def level = Game.level_after(eaten)
168
+
169
+ # The share of a pepper's or a pear's moves still to come.
170
+ def effect_share = effect ? effect_left.fdiv(WORKS.fetch(effect)) : 0.0
171
+
172
+ private
173
+
174
+ # The next queued turn, kept as the move it was made on and the way.
175
+ def make_turn
176
+ snake.turn(@turns.shift)
177
+ @made_turns << [@moves, snake.heading]
178
+ end
179
+
180
+ def crash(tile)
181
+ @ending = board.include?(tile) ? :itself : :wall
182
+ Crashed.new(tile)
183
+ end
184
+
185
+ # A fruit counts double eaten on a move a pepper was working.
186
+ def eat(tile, under)
187
+ points = 10 * level * (under == :pepper ? 2 : 1)
188
+ @score = [@score + points, HIGHEST_SCORE].min
189
+ @eaten += 1
190
+ @food = place_food || instead_of_rare
191
+ @ending = :won if food.nil?
192
+ Ate.new(tile:, points:)
193
+ end
194
+
195
+ # With nowhere else left for it, the fruit takes a rare fruit's tile,
196
+ # and the game is only won once that is eaten too.
197
+ def instead_of_rare
198
+ tile = rare&.tile
199
+ @rare = nil
200
+ tile
201
+ end
202
+
203
+ def savour(tile)
204
+ kind = rare.kind
205
+ @rare = nil
206
+ @rare_eaten[kind] += 1
207
+ points = 10 * level * (kind == :golden ? GOLDEN_WORTH : 1)
208
+ @score = [@score + points, HIGHEST_SCORE].min
209
+ shed = kind == :plum ? snake.shed(plum_takes) : []
210
+ start(kind) if WORKS.key?(kind)
211
+ Ate.new(tile:, points:, kind:, shed:)
212
+ end
213
+
214
+ # How many tiles a plum takes off the tail, never leaving the snake
215
+ # shorter than it started.
216
+ def plum_takes
217
+ length = snake.length
218
+ takes = if rules == 1 then FIRST_PLUM
219
+ elsif length >= PLUM_LONG then length / 3
220
+ else length / 4
221
+ end
222
+ [takes, length - START_LENGTH].min
223
+ end
224
+
225
+ def start(kind)
226
+ @effect = kind
227
+ @effect_left = WORKS.fetch(kind)
228
+ end
229
+
230
+ def wear_off
231
+ return unless effect
232
+
233
+ @effect_left -= 1
234
+ @effect = nil if @effect_left.zero?
235
+ end
236
+
237
+ # A rare fruit waits a set number of moves, counted from the one after
238
+ # it appears, and then it is gone.
239
+ def age_rare
240
+ return unless rare
241
+
242
+ @rare_left -= 1
243
+ @rare = nil if @rare_left.zero?
244
+ end
245
+
246
+ def bring_rare
247
+ return if over? || rare || effect || eaten < RARE_FROM || !@rng.rand(RARE_ODDS).zero?
248
+
249
+ kind = choose_rare
250
+ tile = place_rare
251
+ return unless tile
252
+
253
+ @rare = Rare.new(kind:, tile:)
254
+ @rare_left = RARE_MOVES
255
+ @rare_seen[kind] += 1
256
+ end
257
+
258
+ # A kind by its share of the chances, leaving out a plum for a snake too
259
+ # short to spare its tiles.
260
+ def choose_rare
261
+ shares = RARE_SHARES.reject { |kind, _| kind == :plum && snake.length < PLUM_FROM }
262
+ ticket = @rng.rand(shares.values.sum)
263
+ shares.find { |_, share| (ticket -= share).negative? }.first
264
+ end
265
+
266
+ # Food goes somewhere fair: not on the snake, not right under its nose,
267
+ # somewhere the head can reach, and not at the end of a dead end. When
268
+ # the board is too crowded for all of that, the rules give way one at a
269
+ # time, nearness first and reachability last.
270
+ def place_food = fair_ground.find(&:any?)&.sample(random: @rng)
271
+
272
+ # A rare fruit is choosier: every rule holds, and it is close enough
273
+ # for the head to get there well before it is gone. Failing that, there
274
+ # is none this time.
275
+ def place_rare
276
+ fair_ground.first.select { |tile| tile.distance(snake.head) <= RARE_MOVES / 2 }.sample(random: @rng)
277
+ end
278
+
279
+ # Free tiles from the fairest to the merely free.
280
+ def fair_ground
281
+ body = snake.body.to_set
282
+ free = board.free_tiles(snake) - [food, rare&.tile]
283
+ reachable = board.reachable(snake.head, body)
284
+ within_reach = free.select { |tile| reachable.include?(tile) }
285
+ roomy = within_reach.select { |tile| roomy?(tile, body) }
286
+ away = roomy.select { |tile| tile.distance(snake.head) > 2 }
287
+ [away, roomy, within_reach, free]
288
+ end
289
+
290
+ def roomy?(tile, body)
291
+ tile.neighbors.count { |neighbor| board.include?(neighbor) && !body.include?(neighbor) } >= 2
292
+ end
293
+ end
294
+ end
@@ -0,0 +1,132 @@
1
+ # frozen_string_literal: true
2
+
3
+ module PixelSnake
4
+ # A cog worked out from what it is rather than drawn by hand, so it can
5
+ # be shown turned to any angle: a disc with a ring of teeth that narrow
6
+ # toward their tips, round holes through it if it is big enough to have
7
+ # them, and an axle of the other metal, lit from the top left like
8
+ # everything else. Each angle is drawn the first time it is needed and
9
+ # kept. A gear for the fine canvas is the same gear worked out at half
10
+ # as big again, so its teeth and holes come out rounder.
11
+ class Gear
12
+ # A metal's lit edges, its body, its shaded edges, the glint where its
13
+ # face turns to the light, and its axle.
14
+ METALS = {
15
+ brass: %i[gold amber orange cream ash],
16
+ silver: %i[sand ash steel cream gold]
17
+ }.freeze
18
+ # A turn is drawn at this many angles, so a slow gear ticks round like
19
+ # clockwork.
20
+ STEPS = 60
21
+ DEPTH = 3.0
22
+ # A tooth's half width, as a share of the space from one tooth to the
23
+ # next, at its root and at its tip.
24
+ ROOT = 0.3
25
+ TIP = 0.19
26
+ AXLE = 1.6
27
+ # Holes sit this far out, as a share of the way to the teeth.
28
+ HOLES_OUT = 0.52
29
+ HOLE = 1.6
30
+ # Each pixel is sampled at four points and is solid where half are.
31
+ SAMPLES = [-0.25, 0.25].product([-0.25, 0.25]).freeze
32
+
33
+ attr_reader :teeth, :radius
34
+
35
+ def initialize(teeth:, radius:, metal:, holes: 0, scale: 1)
36
+ @teeth = teeth
37
+ @radius = radius
38
+ @holes = holes
39
+ @scale = scale
40
+ @depth = DEPTH * scale
41
+ @lit, @body, @shade, @glint, @axle = METALS.fetch(metal).map { |name| Palette[name] }
42
+ @hole_out = (radius - @depth) * HOLES_OUT
43
+ @points = points
44
+ @drawn = {}
45
+ end
46
+
47
+ # The angle from one tooth to the next.
48
+ def pitch = Math::PI * 2 / teeth
49
+
50
+ # Where the teeth of two gears meet, halfway up the teeth.
51
+ def pitch_radius = radius - @depth / 2
52
+
53
+ def size = radius * 2 + 1
54
+
55
+ # The gear turned clockwise by an angle, drawn around its middle pixel.
56
+ # It looks the same again once its teeth, and its holes if it has any,
57
+ # are back where they started, so only the angles before that are ever
58
+ # drawn.
59
+ def sprite(angle)
60
+ repeat = Math::PI * 2 / (@holes.positive? ? @holes.gcd(teeth) : teeth)
61
+ steps = (repeat / (Math::PI * 2) * STEPS).round
62
+ step = (angle / (Math::PI * 2) * STEPS).round % steps
63
+ @drawn[step] ||= draw(step * Math::PI * 2 / STEPS)
64
+ end
65
+
66
+ private
67
+
68
+ # Every sample point of every pixel, as how far it is from the middle and
69
+ # which way, worked out once; turning the gear only changes the way.
70
+ def points
71
+ Array.new(size) do |y|
72
+ Array.new(size) do |x|
73
+ SAMPLES.map do |dx, dy|
74
+ across = x - radius + dx
75
+ down = y - radius + dy
76
+ [Math.hypot(across, down), Math.atan2(down, across)]
77
+ end
78
+ end
79
+ end
80
+ end
81
+
82
+ def draw(angle)
83
+ solid = @points.map { |row| row.map { |samples| samples.count { |reach, way| metal?(reach, way - angle) } >= 2 } }
84
+ Sprite.new(Array.new(size) do |y|
85
+ Array.new(size) { |x| solid[y][x] ? color(solid, x, y) : Sprite::CLEAR }.pack("C*")
86
+ end)
87
+ end
88
+
89
+ # Whether a point is metal, given how far it is from the middle and
90
+ # which way it lies from the gear's first tooth and hole.
91
+ def metal?(reach, way)
92
+ return false if reach > radius
93
+ return !hole?(reach, way) if reach <= radius - @depth
94
+
95
+ across = (way / pitch) % 1 - 0.5
96
+ across.abs <= ROOT - (ROOT - TIP) * (reach - radius + @depth) / @depth
97
+ end
98
+
99
+ # Within a hole's reach of the nearest one, by the law of cosines.
100
+ def hole?(reach, way)
101
+ hole = HOLE * @scale
102
+ return false if @holes.zero? || (reach - @hole_out).abs > hole
103
+
104
+ between = Math::PI * 2 / @holes
105
+ off = way % between
106
+ apart = [off, between - off].min
107
+ reach * reach + @hole_out * @hole_out - 2 * reach * @hole_out * Math.cos(apart) <= hole * hole
108
+ end
109
+
110
+ # Lit where the edge faces up or left, toward the light, shaded where it
111
+ # faces down or right, and the axle in the other metal.
112
+ def color(solid, x, y)
113
+ reach = Math.hypot(x - radius, y - radius)
114
+ return @axle if reach <= AXLE * @scale
115
+
116
+ lit = !solid?(solid, x, y - 1) || !solid?(solid, x - 1, y)
117
+ shaded = !solid?(solid, x, y + 1) || !solid?(solid, x + 1, y)
118
+ if lit && !shaded then @lit
119
+ elsif shaded && !lit then @shade
120
+ elsif glint?(x - radius, y - radius, reach) then @glint
121
+ else @body
122
+ end
123
+ end
124
+
125
+ # A short arc of the face toward the top left, just inside the teeth.
126
+ def glint?(x, y, reach)
127
+ reach.between?(radius - @depth - 2.6 * @scale, radius - @depth - 0.8 * @scale) && Math.atan2(y, x).between?(-2.8, -1.9)
128
+ end
129
+
130
+ def solid?(solid, x, y) = x.between?(0, size - 1) && y.between?(0, size - 1) && solid[y][x]
131
+ end
132
+ end
@@ -0,0 +1,91 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "date"
4
+
5
+ module PixelSnake
6
+ # The hundred best games at each speed, signed with the player's name and
7
+ # kept in a file between runs, each with its recording so it can be
8
+ # watched again. Games saved before there were names and speeds read as
9
+ # unsigned games at normal speed, and those from before there were
10
+ # recordings have none. Whatever in the file is not a game, with a score,
11
+ # a length and a day, is left out, and the games are put best first.
12
+ class HighScores
13
+ Entry = Data.define(:name, :score, :length, :date, :speed, :replay) do
14
+ def initialize(name:, score:, length:, date:, speed:, replay: nil) = super
15
+ end
16
+
17
+ LIMIT = 100
18
+
19
+ def self.default_path(environment = ENV)
20
+ data = environment["XDG_DATA_HOME"].to_s
21
+ data = File.join(Dir.home, ".local", "share") if data.empty?
22
+ File.join(data, "pixelsnake", "scores.json")
23
+ end
24
+
25
+ # The last game that made a table in this session, if one did.
26
+ attr_reader :newest
27
+
28
+ def initialize(path)
29
+ @file = SaveFile.new(path, Array)
30
+ @entries = load
31
+ @newest = nil
32
+ end
33
+
34
+ # The games at one speed, best first.
35
+ def table(speed) = @entries.select { |entry| entry.speed == speed }
36
+
37
+ def best(speed) = table(speed).first&.score || 0
38
+
39
+ def empty? = @entries.empty?
40
+
41
+ # Adds a finished game and returns its place on the table for its speed,
42
+ # counting from one, or nil when it did not make the table. A tie goes
43
+ # below the score it ties with.
44
+ def record(name:, score:, length:, speed:, replay: nil, date: Date.today)
45
+ return if score.zero?
46
+
47
+ table = table(speed)
48
+ place = table.index { |other| other.score < score } || table.size
49
+ return if place >= LIMIT
50
+
51
+ @newest = Entry.new(name, score, length, date.iso8601, speed, replay)
52
+ @entries.insert(@entries.index { |other| other.score < score } || @entries.size, @newest)
53
+ @entries.delete_at(@entries.rindex { |entry| entry.speed == speed }) if table.size == LIMIT
54
+ save
55
+ place + 1
56
+ end
57
+
58
+ # Puts a name on the newest game, as when the player types one in.
59
+ def sign(name)
60
+ index = @entries.index { |entry| entry.equal?(@newest) }
61
+ @newest = @entries[index] = @newest.with(name:)
62
+ save
63
+ end
64
+
65
+ def clear
66
+ @entries = []
67
+ @newest = nil
68
+ save
69
+ end
70
+
71
+ private
72
+
73
+ # Games that tie stay in the order they were kept in.
74
+ def load
75
+ games = @file.read.filter_map { |saved| entry(saved) }
76
+ games.each_with_index.sort_by { |game, place| [-game.score, place] }.map(&:first)
77
+ end
78
+
79
+ def entry(saved)
80
+ return unless saved.is_a?(Hash) && saved[:score].is_a?(Integer) && saved[:score].positive? && saved[:length].is_a?(Integer)
81
+
82
+ date = Day.read(saved[:date])
83
+ speed = Game.speed_named(saved[:speed])
84
+ Entry.new(Name.clean(saved[:name]), saved[:score], saved[:length], date, speed, Recording.read(saved[:replay], speed)) if date
85
+ end
86
+
87
+ def save
88
+ @file.write(@entries.map { |entry| entry.to_h.merge(replay: entry.replay&.saved) })
89
+ end
90
+ end
91
+ end