Class: SnakeGame::BaitManager
- Inherits:
-
Object
- Object
- SnakeGame::BaitManager
show all
- Includes:
- Constants
- Defined in:
- lib/bait_manager.rb
Overview
Class for managing and updating baits (snake food)
Constant Summary
Constants included
from Constants
Constants::EVASION, Constants::FPS, Constants::HEIGHT, Constants::NEXTLEVEL, Constants::STEP, Constants::WIDTH
Instance Attribute Summary collapse
Instance Method Summary
collapse
Constructor Details
Returns a new instance of BaitManager.
12
13
14
15
|
# File 'lib/bait_manager.rb', line 12
def initialize
@baits = []
@images = ImageDatabase.new
end
|
Instance Attribute Details
#baits ⇒ Object
Returns the value of attribute baits.
11
12
13
|
# File 'lib/bait_manager.rb', line 11
def baits
@baits
end
|
Instance Method Details
#add_bait(position) ⇒ Object
26
27
28
|
# File 'lib/bait_manager.rb', line 26
def add_bait(position)
@baits << (Bait.new position, @images.bait)
end
|
#calculate_random_movement ⇒ Object
#draw ⇒ Object
70
71
72
|
# File 'lib/bait_manager.rb', line 70
def draw
@baits.each(&:draw)
end
|
#free?(position, snake) ⇒ Boolean
51
52
53
54
55
56
57
58
59
60
|
# File 'lib/bait_manager.rb', line 51
def free?(position, snake)
free = true
snake.snake_parts.each do |part|
free = false if part.position == position
end
@baits.each do |bait|
free = false if bait.position == position
end
free
end
|
#random_free_position(snake) ⇒ Object
30
31
32
33
34
35
36
|
# File 'lib/bait_manager.rb', line 30
def random_free_position(snake)
loop do
position = Position.new (rand * WIDTH).round(-1) % WIDTH,
(rand * HEIGHT).round(-1) % HEIGHT
return position if free? position, snake
end
end
|
#update(snake) ⇒ Object
17
18
19
20
21
22
23
24
|
# File 'lib/bait_manager.rb', line 17
def update(snake)
if @baits.count.zero?
position = random_free_position snake
add_bait position
else
update_baits snake
end
end
|
#update_baits(snake) ⇒ Object
38
39
40
41
42
43
44
45
46
47
48
49
|
# File 'lib/bait_manager.rb', line 38
def update_baits(snake)
@baits.each do |bait|
next if rand < EVASION
loop do
new_position = bait.position + calculate_random_movement
if free? new_position, snake
bait.position = new_position
break
end
end
end
end
|