Class: Board

Inherits:
Object
  • Object
show all
Defined in:
lib/board.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(width: 60, height: 30) ⇒ Board

Returns a new instance of Board.



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/board.rb', line 3

def initialize(width: 60, height: 30)
  @top_right = Point.new(width, 0)
  @bottom_left = Point.new(0, height)

  @width = width
  @height = height
  @_game_board = Hash.new {|hash, key| hash[key] = {}}
  @win = Curses::Window.new(height, width, 0, 0)
  Curses.stdscr.keypad(true)
  @win.box('|', '-')
  Curses.init_screen
  Curses.curs_set(0)
  Curses.crmode
  Curses.noecho
  Curses.stdscr.nodelay = true
end

Instance Attribute Details

#heightObject

Returns the value of attribute height.



2
3
4
# File 'lib/board.rb', line 2

def height
  @height
end

#widthObject

Returns the value of attribute width.



2
3
4
# File 'lib/board.rb', line 2

def width
  @width
end

Instance Method Details

#draw(snake:, fruit:) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/board.rb', line 36

def draw(snake:, fruit:)
  @win.clear
  @win.box('|', '-')
  Curses.init_screen

  current_pos = snake.head
  @win.setpos(*current_pos.graphics_to_a)
  @win << snake.head_direction
  snake.body.each do |body_part|
    @win.setpos(*body_part.graphics_to_a)
    @win << 'o'
  end
  @win.setpos(*fruit.graphics_to_a)
  @win << '🍏'
  @win.refresh
end

#initialize_snakeObject



20
21
22
23
24
25
# File 'lib/board.rb', line 20

def initialize_snake
  x, y = @width / 2, @height / 2
  # TODO Make this adjust based on survival likelihood
  @_game_board[x][y] = "^"
  return { starting_position: Point.new(x, y), vector: Point.new(0, 1) }
end

#is_legal?(positions) ⇒ Boolean

Returns:

  • (Boolean)


27
28
29
30
31
32
33
34
# File 'lib/board.rb', line 27

def is_legal?(positions)
  positions.all? do |position|
    position.x > @bottom_left.x &&
      position.x < @top_right.x - 1 &&
      position.y > @top_right.y &&
      position.y < @bottom_left.y - 1
  end
end

#random_positionObject



53
54
55
# File 'lib/board.rb', line 53

def random_position
  Point.new(Random.rand(width - 2) + 1, Random.rand(height - 2) + 1)
end