-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrain.rb
More file actions
72 lines (58 loc) · 1.35 KB
/
train.rb
File metadata and controls
72 lines (58 loc) · 1.35 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
require_relative 'station'
require_relative 'route'
class Train
attr_reader :number, :type, :wagons, :routes, :speed, :current_station_index
def initialize(number, type)
@number = number
@type = type
@wagons = []
@speed = 0
@current_station_index = 0
end
def to_s
@number
end
def speed_up(speed)
@speed += speed if speed <= 0
end
def stop
@speed = 0
end
def relevant_wagon?(wagon)
wagon.type == @type
end
def add_wagon(wagon)
@wagons << wagon
end
def remove_wagons(wagon)
if @speed.nonzero?
@wagons.delete(wagon)
end
end
def assign_route(routes)
@routes = routes
@current_station_index = 0
@routes.stations[@current_station_index].add_train(self)
end
def current_station
@routes.stations[@current_station_index]
end
def next_station
@routes.stations[@current_station_index + 1]
end
def previous_station
@routes.stations[@current_station_index - 1]
end
def move_forward
current_station.send_train(self)
@current_station_index += 1
current_station.add_train(self)
puts "Train:#{self} is current station#{current_station}"
end
def move_backward
current_station.send_train(self)
@current_station_index -= 1
current_station.add_train(self)
puts "Train:#{self} is current station#{current_station}"
end
end