#!/usr/bin/ruby require "io/console" # Directions. I = [[0, -1], [0, 1], [1, 0], [-1, 0], !1] # Color palette. K = ["\e[0m"] + "#,'h_(e(#kek#df/)de/`(f)f.#j".scan(/../).map{|x|"\e[#{x.ord-5};#{x[1].ord}m"} + "## []()@@OO%%XX++".scan(/../) # Convert console dimensions to game grid dimensions. # - R = Height minus 2 is to account for for margin and status bar. # - U = Width minus 1 is to avoid margins, otherwise things may wrap poorly. # # The divide by 2 is to account for 1:2 aspect ratio of the character # cell. Well, my terminal fonts are close enough to 1:2, yours might # be vastly different, but there isn't a cheap way to detect and # adjust for this. a = IO.console.winsize R = a[0] - 2 U = ~-a[1] / 2 G = "aqqqyydraqqyfsaqqydrraqyfssaqyerrraygsssaydrrrayfsssaycpyybqyyerydryfsygsyetyguyjvykpyhvyipyhwyixyltymuycryycsyya".split(/y/).map{|x| x == "" ? a : a = x.bytes.map{|y| K[y - 97]} * "" } # Movement speed in number of units moved per second. Use command line # argument if that's specified, otherwise default to 5 cells per second. # # Note that slowest allowed speed is 0.1 cells per second, so players can # wait up to 10 seconds to make a move. We used to allow even longer # delays when there is an explicit quit function, but since that's # removed and player must rely on death to end the game, we want to put # some bounds on how long the player must wait for games to end. A = (a = ARGV[0].to_f) >= 0.1 ? 1 / a : 0.2 # Check window dimensions. Game grid will be sized accordingly. # # We need at least enough columns to hold the status bar, and enough # rows such that there will be room to place items. # # By the way, you might think that a really small grid will make an easy # game, but what that really provides is a short game. It's actually # more difficult to score long chains with a small grid because there is # less room to maneuver. if R < 10 || U < 19 print "console too small\n" exit end # Game states. r = 1 # True if game is still in progress. c = 1 # Current player color (0 or 1). d = 2 # Current direction (0..3). h = [] # Previous player positions. g = 2 # Desired length of player. s = 0 # Player score. b = 8 # Color of last item eaten (7 or 8). m = 0 # Number of items in current chain. n = 0 # Current chain length. l = 0 # Maximum achieved chain length. fc = 0 # 1 bit frame counter, for blinking effect. f = !1 # Next item to be placed. e = !1 # True if we have entered endgame. # Ring buffer of next directions, written by T (input_thread) and read by # main thread. We buffer inputs so that quick consecutive keystrokes # are not lost. a = [0] * 8 j = 0 # Next position to write to. k = 0 # Next position to read from. # Shuffled list of positions, used for item generation. u = [*1..(U - 2)].product([*1..(R - 2)]).shuffle v = 0 # Initialize game field. o = [] R.times{|i| o += [[5] + [i > 0 && i < R - 1 ? 6 : 5] * (U - 2) + [5]] } # Mark initial player location. o[q = R / 2][p = U / 4] = 9 # Place the first item just in front of the player. This guarantees that # there is at least one item. # # First item is white, since player starts off in white. o[q][U - p] = 8 # Item serial number starts at 4. It doesn't start at 0 because of the # first item that was just placed above, and it doesn't start at 1 because # how we have arranged the item sequence to be [black*3, white*3]. z = 4 # Check if a position is eligible for placing new items, based on whether # it's near the player's head and whether it is adjacent to items of # the same color. # # Note that the heuristics here will also cause us to avoid placing # new items near walls, or near player's tail. # # Sets new_item to be the next item to be generated. ef = ->(x, y) { # Items are generated in groups of 3s. This is so that player can # complete chains even when the number of available items is small. f = z % 6 / 3 + 7 r = *-1..1 r.product(r).all?{|p, q| r = o[y + q][x + p] r == f || r == 6 } } # Try assigning initial set of items. u.map{|x, y| if # Avoid the rows near player's starting position. (y - q).abs > 1 && # Unconditionally skip some of the cells, otherwise the initial # grid is too dense. rand < 0.1 && # Update new_item, and verify that the selected position is eligible. # # We used to also enforce that the initial set of items do not # form excessively large clusters, but that is mostly covered by # "rand < 0.1" constraint above. ef.call(x, y) o[y][x] = f z += 1 end } # Render function. rf = -> { # Build status line. # 1. Draw current chain status (6 characters wide) on the left. # 2. Draw score on the right (right-aligned). # 3. Fill the middle bits with current chain length. # # The middle bit used to only grow up to 9 units (i.e. max chain length), # but it looks nicer to make use of the full width, so that's what we have # done. To indicate that the max chain has been reached, the bar color # changes from cyan to bright cyan, and chain text changes to uppercase. x = " #{s}" y = " " * (U * 2 - 6 - x.size) if n > 0 y = " %-#{U * 2 - 8 - x.size}s" % "#{n} chain" i = [y.size, n * 2].min y = K[n > 9 ? (y.upcase!; 14) : 13] + y[0, i] + "\e[0m" + y[i, y.size] end print "\e[#{R + 1}A\r" + G[m * 2 + b - 7] + y + "\e[1m" + x + "\e[0m\n\r" + o.map{|p| p.map{|q| G[q * 2 + c]} * "" } * "\e[0m\n\r" + "\n" } # Input loop. This happens in a separate thread so that the main # display loop runs more or less at constant rate. T = Thread.new{ while r # Wait for keystroke. # # Alternatively, can read this without a timeout so that we can # poll for game status once in a while (and thus exit cleanly # when game has ended), but on windows that causes a serious # input lag, so now we just do a blocking read. # # But this leads to a separate problem where if we just kill the # input thread while it's waiting for keystroke, the terminal # might be left in a bad state (e.g. with echo off), so we force # the player to feed an extra keystroke on exit. i = "\e[".index(y = STDIN.getch) ? !1 : ("AwBsCdDa".index(y) || 8) / 2 # Add input to ring buffer. We used to try to apply the action # right away, but no matter how fast we do it, some keys just # always get lost, so now we buffer them. # # Also, it used to be that moving in the same direction causes # player to change color, but that leads to some unpredictable # color changes, so now we require the dedicated key for that # purpose. (Previously this was a nice feature because it made # it easier to play one-handed, but I suppose that's still # possible depending on keyboard layout). if i a[x = -~j % 8] = i # Update index after array element has been written, to avoid a # race with reading the array contents. j = x end end } # Disable echo, hide cursor, and clear window. STDIN.echo = !1 print "\e[?25l\n" * R # Draw initial frame. rf.call # Game loop. lt = Time::now while r # Make chain status blink if we are currently at max chain. if m > 2 print "\e[#{R + 1}A\r#{G[b - 1 + fc]}\e[#{R + 1}B" fc ^= 2 end # Apply buffered action. if k != j i = I[w = a[k = -~k % 8]] i = i ? o[q + i[1]][p + i[0]] : (c ^= 1) # Do not allow player to turn back onto themselves, or into a wall. # For a color change, i (next_cell) evaluates to 0 or 2, which # is outside of the range of the allowed turn destinations. if i >= 6 && i <= 8 d = w # Cause direction changes to take effect right away. lt = Time.at(0) else # Force immediate redraw on color change. rf.call end end # Apply movement based on elapsed time, as opposed to using the # frame counter. This appears to be more reliable than trying to # maintain a constant frame rate via sleep. # # On the other hand, not doing any sleep means this script will peg # one CPU core, which is unfortunate. Again, blame it on windows, # where any kind of sleep or timeout just don't get the same level # of precision we get with linux. ct = Time::now if ct - lt < A # Wait a bit before polling input queue again. sleep 0.02 else lt = ct # Mark old player positions. h += t = [[p, q]] o[q][p] = 10 t += [i = h[h.size / 2]] o[i[1]][i[0]] = 11 t += [i = h[h.size / 4]] o[i[1]][i[0]] = 12 # Update player position. i = I[d] i = o[q += i[1]][p += i[0]] if i != 6 # Collision check. if i == c + 7 # Update score. s += 10 if m % 3 > 0 if b == i # Continuing current chain. m += 1 if m == 3 n += 1 l = [l, n].max s += 2 ** [n - 1, 8].min * 100 end else # Broke current chain. b = i m = 1 n = 0 end else # Starting chain. b = i m = 1 end g += 2 # Mark new player position. This also removes the item from # current cell. o[q][p] = 9 # Add new item. Do this in three passes: # - First pass avoids placing items near the player head or # existing items. # - Second pass avoids placing items near the player head. # - Third pass takes whatever spot is available. w = 0 3.times{|i| u.size.times{ if (w & (1 << i)) < 1 # Only increment round robin selector if we still need # to place more items, otherwise we will always generate # new items in the same position. x, y = u[v = -~v % u.size] if [o[y][x] == 6, (x - p).abs > 3 || (y - q).abs > 3, ef.call(x, y)].take(3 - i).all? # Enter endgame if position is assigned in pass 1 or 2, # and update hint display. # # If we are already in endgame, these steps would be # redundant, but it's OK since item color would already # be fixed. e ||= i > 0 && (o[R - 1][U - 1] = f + 7) # Place item. o[y][x] = f # Update bits to say we have placed an item. For second # and third pass, this unconditionally blocks additional # items from being placed. But for first pass only, # there is a low probability that we might place more # than one item. Most other classical snake games don't # do this, which is why we do it. # # The probability is set to 0.1, which makes a # relatively subtle effect. Player might not notice # that the grid is filling up slightly faster than # usual, and that's how we like it. w = rand < 0.1 ? 6 : 7 # Increase serial number if we have not entered endgame # yet. This means item colors will alternate every 3 # items before endgame, and remain fixed during endgame. z += e ? 0 : 1 end end } } # Redraw grid after applying movement. rf.call else # Mark mark tombstone. o[q][p] = 13 rf.call # Game over. print "\e[#{R / 2 + 1}A\r\e[#{U - 8}C\e[0m GAME OVER ", "\n\r" * (R / 2) r = !1 end else # Mark new player position. o[q][p] = 9 t += [[p, q]] # Grow player. if h.size > g x, y = h.shift o[y][x] = 6 t += [[x, y]] # Stop flashing chain status once player has stopped growing. if m == 3 m = 0 # Need to do a full redraw to clear the status line. rf.call # Don't need to draw the dirty pixels since we did a full redraw, # but we can save 4 bytes if we draw it anyway. end end # Redraw the dirty pixels. print "\e[#{R}A" + t.map{|x, y| "\e[#{y}B\r\e[#{x * 2}C" + G[o[y][x] * 2 + c] + "\e[#{y}A" } * "" + "\e[#{R}B" end end end # Wait for input thread to consume the extra keystroke after the game # over message. T.join # Draw extra frame to erase the game over message. rf.call # Ikaruga gives out a grade at the end of each level purely based on # score. We can also do a score-based thing for assigning grades, but: # # - Due to exponential bonus from chains, getting high scores will # require maximizing number of consecutive chains. # # - Snakes is hard enough as it is, maximizing for consecutive chains # means most players will not survive very long. # # In other words, even though we would like to reward both grid # coverage and high score, those two are somewhat mutually exclusive. # # Instead of choosing one, high grades are given if players have a # high completion ratio *or* a high score. # # Players who did not make any chains are always assigned "dot eater" # grade. Due to how item colors are fixed in endgame phase, players # will inevitably form a few chains if they covered enough area, so # it's impossible to reach 100% while maintaining dot eater grade. x = (R - 2) * (U - 2) g = "Dot eater" if l > 0 y = x / 2 4.times{|i| if h.size > x * (i * 0.3 - 0.1) || s > y * 10 + y / 3 * 100 * 2 ** (i * 3 - 2) g = "CBAS"[i] end } end # Restore cursor and output final game stats. print "\e[0m\e[?25h\nArea: \e[1m#{h.size * 100 / x}%\e[0m\nScore: \e[1m#{s}\e[0m\nMax: \e[1m#{l} chain\e[0m\nGrade: \e[1m#{g}\e[0m\n" # Restore echo. STDIN.echo = true