Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: ff4e9d55be
Fetching contributors…

Cannot retrieve contributors at this time

file 107 lines (84 sloc) 2.13 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
require 'constants'

class Snake
  attr_reader :moving, :score, :high_score
  
  def initialize(field)
    @field = field
    @keycheck = false
    @score = @high_score = 0
  end

  def eat
    @size = @size + 1
    @score = @score + 1
    @high_score = @score if @score > @high_score
    bake
  end
  
  def bake
    found = false
    
    while !found
     food = Field.rand
     found = @field.status(food) == Status::GROUND
    end
    
    @field.paint(food, Status::FOOD)
  end
  
  def reset
    # Resetting stuff...
    @moving = true
    @cells = [Field.rand]
    @size = 1
    @score = 0
    bake
    
    # moving the snake to the center from its random spot
    center = Array.new(2, FIELD_SIZE / 2)
        
    if center[0] - @cells.first[0] == 0
      @direction = center[1] > @cells.first[1] ? :down : :up
    else
      slope = (center[1] - @cells.first[1]) / (center[0] - @cells.first[0])
      
      if slope.zero?
        @direction = center[0] > @cells.first[0] ? :right : :left
      elsif slope > 0
        @direction = :left
      else
        @direction = :right
      end
    end
  end
  
  def turn(key)
    return if !@keycheck
   
    # don't let them pull a uturn
    if DIRECTIONS.keys.include?(key)
      uturn = UTURNS[@direction]
      
      if key.to_s != uturn || @size == 1
        @direction = key
      end
    end
    
    @keycheck = false
  end
  
  def inside(field)
    field.between?(0, FIELD_SIZE - 1)
  end
  
  def move
    @keycheck = true
    dir = DIRECTIONS[@direction]
    cell = [@cells.first[0] + dir[0], @cells.first[1] + dir[1]]
    
    @moving = inside(cell[0]) && inside(cell[1])
    return if !@moving
    
    status = @field.status(cell)
    
    case status
    when Status::FOOD
      eat
    when Status::SNAKE
      @moving = false
      return
    end
      
    @cells.insert(0, cell)
    
    # delete the tail
    if @cells.size > @size
      tail = @cells.delete_at(@size)
      @field.paint(tail)
    end
    
    if @size > 1
     # @field.paint(@cells[1], Status::SNAKE)
    end
    
    @field.paint(@cells.first, Status::SNAKE, true)
  end
end
Something went wrong with that request. Please try again.