Created
August 4, 2011 14:09
-
-
Save daviddavis/1125230 to your computer and use it in GitHub Desktop.
Snake!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
board_size, snake_length, snake_positions, snake_vector, fruit_position = 15, 3, [[5,6],[5,5],[5,4]], [1,0], [rand(15), rand(15)] # set game board size, snake starting position, snake starting direction and fruit position | |
system "stty -icanon -echoke" # set console to non-canonical mode so it doesn't require end of line to get input | |
loop do # loop infinitely | |
if ( input = select([$stdin], nil, nil, 0.2) ) then if ( STDIN.getc.chr == "\e" ) then if ( STDIN.getc == ?[) then input = STDIN.getc end end end # get input | |
if ( input == ?A ) then snake_vector = [0,-1] elsif ( input == ?B ) then snake_vector = [0,1] elsif ( input == ?C ) then snake_vector = [1,0] elsif ( input == ?D ) then snake_vector = [-1,0] end # set snake movement direction based on input | |
snake_positions = (snake_positions.count < snake_length ? snake_positions.concat([[snake_positions.last[0] + snake_vector[0], snake_positions.last[1] + snake_vector[1]]]) : snake_positions.drop(1).concat([[snake_positions.last[0] + snake_vector[0], snake_positions.last[1] + snake_vector[1]]]) ) # calculate snake head and tail positions | |
if ( snake_positions.index(fruit_position) and snake_positions.last != fruit_position ) then fruit_position = [rand(board_size), rand(board_size)] elsif ( snake_positions.last == fruit_position ) then snake_length, fruit_position = snake_length + 1, [rand(board_size), rand(board_size)] elsif ( snake_positions.last[0] + 1 > board_size or snake_positions.last[1] + 1 > board_size or snake_positions.last[0] + 1 == 0 or snake_positions.last[1] + 1 == 0 or snake_positions[0..-2].index(snake_positions[-1]) != nil ) then exit end # respond to collisions | |
(board_size + 3).times { |y| (board_size + 3).times { |x| if ( y == 0) then print "\e[2J\e[1;1H" elsif ( snake_positions.index([x - 1,y - 2]) ) then print "#" elsif ( fruit_position == [x - 1,y - 2] ) then print "@" elsif ( x == board_size + 2 ) then print "\n" elsif ( y == 1 or y == board_size + 2) then print "X" elsif ( x == 0 or x == board_size + 1) then print "X" else print " " end } } # clear screen and render | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment