#!/usr/bin/ruby require "io/console" # Directions. D = [[0, -1], [0, 1], [1, 0], [-1, 0], !1] # Color palette. R = ["\e[0m"] + "#,'h_(e(#kek#df/)de/`(f)f.#j".scan(/../).map{|x|"\e[#{x.ord-5};#{x[1].ord}m"} + "## []()@@OO%%XX++".scan(/../) r = "" S = "aqqqyydraqqyfsaqqydrraqyfssaqyerrraygsssaydrrrayfsssaycpyybqyyerydryfsygsyetyguyjvykpyhvyipyhwyixyltymuycryycsyya".split(/y/).map{|x| x == "" ? r : r = x.bytes.map{|y| R[y - 97]} * "" } # 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. p, q = IO.console.winsize if p < 12 || q < 39 print "console too small\n" exit end # Convert console dimensions to game grid dimensions. # - Width minus 1 is to avoid margins, otherwise things may wrap poorly. # - Height minus 2 is to account for for margin and status bar. # # 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. W = ~-q / 2 H = p - 2 # Game states. c = 1 # Current player color (0 or 1). b = 2 # Current direction (0..3). h = [] # Previous player positions. g = 2 # Desired length of player. s = 0 # Player score. a = 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. cc = 0 # 1 bit frame counter, for blinking effect. f = !1 # Next item to be placed. e = !1 # True if we have entered endgame. # 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. p = ARGV[0].to_f M = p >= 0.1 ? 1 / p : 0.2 # Ring buffer of next directions, written by input_thread and read by # main thread. We buffer inputs so that quick consecutive keystrokes # are not lost. ii = [0] * 8 j = 0 # Next position to write to. k = 0 # Next position to read from. # Initialize game field. o = [] H.times{|w| o += [[5] + [w > 0 && w < H - 1 ? 6 : 5] * (W - 2) + [5]] } # Mark initial player location. o[p = H / 2][q = W / 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][W - 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 # Try assigning initial set of items. [*1..(W - 2)].product([*1..(H - 2)]).shuffle.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. (f = z % 6 / 3 + 7) && [*-1..1].product([*-1..1]).all?{|p, q| i = o[y + q][x + p] i == f || i == 6 } o[y][x] = f z += 1 end } # Render function. render = -> { # 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. w = " #{s}" v = " " * (W * 2 - 6 - w.size) if n > 0 v = " %-#{W * 2 - 8 - w.size}s" % "#{n} chain" i = [v.size, n * 2].min v = R[n > 9 ? (v.upcase!; 14) : 13] + v[0, i] + "\e[0m" + v[i, v.size] end print "\e[#{H + 1}A\r" + S[m * 2 + a - 7] + v + "\e[1m#{w}\e[0m\n\r" + o.map{|x| x.map{|y| S[y * 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. it = 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. v = "\e[".index(w = STDIN.getch) ? !1 : ("AwBsCdDa".index(w) || 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 v ii[w = -~j % 8] = v # Update index after array element has been written, to avoid a # race with reading the array contents. j = w end end } # Disable echo, hide cursor, and clear window. STDIN.echo = !1 print "\e[?25l\n" * H # Draw initial frame. render.call # Game loop. tt = Time::now while r # Make chain status blink if we are currently at max chain. if m > 2 print "\e[#{H + 1}A\r#{S[a - 1 + cc]}\e[#{H + 1}B" cc ^= 2 end # Apply buffered action. if k != j d = D[w = ii[k = -~k % 8]] d = d ? o[q + d[1]][p + d[0]] : (c ^= 1) # Do not allow player to turn back onto themselves, or into a wall. # For a color change, next_cell evaluates to 0 or 2, which is outside # of the range of the allowed turn destinations. if d > 5 && d < 9 b = w # Cause direction changes to take effect right away. tt = Time.at(0) end # Force immediate redraw on input. We only need it for color change, # but doing it here saves 4 bytes. render.call 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. t = Time::now if t - tt < M # Wait a bit before polling input queue again. sleep 0.02 else tt = t # 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. d = D[b] d = o[q += d[1]][p += d[0]] if d != 6 # Collision check. if d == c + 7 # Update score. s += 10 if m % 3 > 0 if a == d # 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. a = d m = 1 n = 0 end else # Starting chain. a = d 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. u = 1 3.times{|w| [*1..(W - 2)].product([*1..(H - 2)]).shuffle.map{|x, y| if [u, o[y][x] == 6, (x - p).abs > 3 || (y - q).abs > 3, (f = z % 6 / 3 + 7) && [*-1..1].product([*-1..1]).all?{|p, q| i = o[y + q][x + p] i == f || i == 6 }].take(4 - w).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 ||= w > 0 && (o[H - 1][W - 1] = f + 7) # Place item. o[y][x] = f # Update flag to say we have placed an item, with a low # probability that we would place more after that. # Most Most other classical snake games don't do this, # which is why we do it. # # There is a very low probability that this would cause # us to enter endgame prematurely, but it's not worth # the extra bytes to prevent this. u = rand < 0.1 # 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 } } # Redraw grid after applying movement. render.call else # Mark mark tombstone. o[q][p] = 13 render.call # Game over. print "\e[#{H / 2 + 1}A\r\e[#{W - 8}C\e[0m GAME OVER ", "\n\r" * (H / 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. render.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[#{H}A" + t.map{|x, y| "\e[#{y}B\r\e[#{x * 2}C#{S[o[y][x] * 2 + c]}\e[#{y}A" } * "" + "\e[#{H}B" end end end # Wait for input thread to consume the extra keystroke after the game # over message. it.join # Draw extra frame to erase the game over message. render.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. a = (H - 2) * (W - 2) g = "Dot eater" if l > 0 i = a / 2 4.times{|w| if h.size > a * (w * 0.3 - 0.1) || s > i * 10 + i / 3 * 100 * 2 ** (w * 3 - 2) g = "CBAS"[w] end } end # Restore cursor and output final game stats. print "\e[0m\e[?25h\nArea: \e[1m#{h.size * 100 / a}%\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