Created
September 15, 2017 17:57
-
-
Save dustMason/8237769fbbde4f37c3ebeb4acd3f8b2c to your computer and use it in GitHub Desktop.
This file contains hidden or 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
require 'io/console' | |
class Game | |
attr_reader :playing | |
def initialize | |
@width = 50 | |
@height = 30 | |
@snake = [] | |
@score = 0 | |
init_snake! | |
@food = random_coordinate | |
@playing = true | |
@direction = [1, 0] | |
end | |
def render | |
system 'clear' | |
@height.times do |y| | |
@width.times do |x| | |
if @snake.include? [x, y] | |
print "X" | |
elsif @food == [x, y] | |
print "F" | |
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! | |
new_head = [@snake[0][0] + @direction[0], @snake[0][1] + @direction[1]] | |
@snake.unshift new_head | |
@snake.pop | |
end | |
def handle_collisions | |
if out_of_bounds? | |
@playing = false | |
elsif 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 | |
coord_space = [].tap do |space| | |
@width.times do |x| | |
@height.times do |y| | |
space << [x, y] | |
end | |
end | |
end | |
(coord_space - @snake).sample | |
end | |
def init_snake! | |
@snake = [[@width/2, @height/2], [@width/2 + 1, @height/2]] | |
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