-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontroler.rb
75 lines (61 loc) · 1.54 KB
/
controler.rb
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
class Controler
attr_accessor :storage, :x_direction, :y_direction
def initialize(init_store = [])
@storage = init_store
@x_direction = 50
@y_direction = 0
end
def extract_positions(snake)
@storage = snake.map { |i| { x: i.x, y: i.y }}
end
def move(snake_instance, coin_generator, game)
pp game.score
snake = snake_instance.snake
coins = coin_generator.storage
leading_pice = snake[snake.length - 1]
new_leading_pos = {
x: validate(leading_pice.x + @x_direction),
y: validate(leading_pice.y + @y_direction)
}
eaten_self = snake.drop(1).find { |i| i.x == new_leading_pos[:x] && i.y == new_leading_pos[:y] }
if eaten_self
game.game_over_song
game.stop
end
eaten_coin = coins.find { |i| i.x == new_leading_pos[:x] && i.y == new_leading_pos[:y] }
if eaten_coin
coin_generator.remove(eaten_coin)
snake_instance.increase_snake
increase_positions
game.increase_stats
end
update_store(new_leading_pos)
draw(snake)
end
def increase_positions
x = @storage[0][:x]
y = @storage[0][:y]
@storage.unshift({ x: x, y: y})
end
private
def update_store(new_pos)
@storage.shift
@storage.push(new_pos)
end
def draw(snake)
snake.each_with_index do |i, x|
current_pos = @storage[x]
i.x = current_pos[:x]
i.y = current_pos[:y]
end
end
def validate(poss)
if poss > 450
0
elsif poss < 0
450
else
poss
end
end
end