Skip to content

Instantly share code, notes, and snippets.

@dustMason
Created September 18, 2017 19:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dustMason/384a3a34987c98a8e845564a2ab8acc3 to your computer and use it in GitHub Desktop.
Save dustMason/384a3a34987c98a8e845564a2ab8acc3 to your computer and use it in GitHub Desktop.
require 'io/console'
class Game
attr_reader :playing
def initialize
@width = 50
@height = 30
@board = [].tap { |s| @width.times { |x| @height.times { |y| s << [x, y] } } }
@snake = []
@score = 0
@snake = [[@width/2, @height/2], [@width/2 + 1, @height/2]]
place_new_food!
@playing = true
@direction = [1, 0]
end
def render
system 'clear'
@height.times do |y|
@width.times do |x|
if @snake.include? [x, y]
print "S"
elsif @food == [x, y]
print "O"
else
print "."
end
end
puts
end
end
def move delta_x, delta_y
@direction = [delta_x, delta_y]
end
def tick!
walk_snake!
handle_collisions
render
end
private
def walk_snake!
@snake.unshift [@snake[0][0] + @direction[0], @snake[0][1] + @direction[1]]
@snake.pop
end
def handle_collisions
if out_of_bounds? || eating_self?
@playing = false
elsif eating_food?
eat!
place_new_food!
end
end
def out_of_bounds?
@snake[0][0] < 0 || @snake[0][1] < 0 || @snake[0][0] >= @width || @snake[0][1] >= @height
end
def eating_self?
@snake[1..-1].any? { |(x, y)| @snake[0][0] == x && @snake[0][1] == y }
end
def eating_food?
@snake[0] == @food
end
def eat!
@snake.unshift @food
end
def place_new_food!
@food = random_coordinate
end
def random_coordinate
(@board - @snake).sample
end
end
game = Game.new
loop do
break unless game.playing
system "stty raw"
key = STDIN.read_nonblock(1) rescue nil
system "stty -raw"
if key == 'w'
game.move 0, -1
elsif key == 'a'
game.move -1, 0
elsif key == 's'
game.move 0, 1
elsif key == 'd'
game.move 1, 0
end
system 'sleep 0.1'
game.tick!
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment