Advertisement
Guest User

ruby 1.9

a guest
Jul 20th, 2011
1,240
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 2.04 KB | None | 0 0
  1. 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
  2. system "stty -icanon -echoke" # set console to non-canonical mode so it doesn't require end of line to get input
  3. loop do # loop infinitely
  4.   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
  5.   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
  6.   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
  7.   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
  8.   (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
  9. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement