1212
1313from config import *
1414from vehicle import Driver
15+ from enum import Enum ,auto
16+
17+ def too_close (lidar ,dir ):
18+ # if dir==True: we're near the right wall
19+ R = 0.83
20+ l = len (lidar )
21+ straight = lidar [l // 2 ]
22+ if dir :
23+ nearest = min (lidar [l // 2 :])
24+ else :
25+ nearest = min (lidar [:l // 2 ])
26+ theta = np .arccos (nearest / straight )
27+ L = R * (1 - np .sin (theta ))
28+ return nearest < L
29+
30+ class State (Enum ):
31+ AI = auto ()
32+ BACK = auto ()
1533
1634class VehicleDriver (Driver ):
1735 """
@@ -21,6 +39,7 @@ class VehicleDriver(Driver):
2139
2240 def __init__ (self ):
2341 super ().__init__ ()
42+ self .state = State .AI
2443
2544
2645 basicTimeStep = int (self .getBasicTimeStep ())
@@ -94,22 +113,34 @@ def observe(self):
94113 # green -> 1
95114 # blue -> 0
96115
97- return np . concatenate ([
116+ return (
98117 sensor_data ,
99118 lidar_data ,
100119 camera_data
101- ] )
120+ )
102121 except :
103122 #En cas de non retour lidar
104- return np . concatenate ([
123+ return (
105124 np .array (self .touch_sensor .getValue (), dtype = np .float32 ),
106125 np .zeros (self .lidar .getNumberOfPoints (), dtype = np .float32 )
107- ] )
126+ )
108127
109128 #Fonction step de l"environnement GYM
110129 def step (self ):
111- # sends observation to the supervisor
130+ match self .state :
131+ case State .AI :
132+ self .ai ()
133+ case State .BACK :
134+ self .back ()
112135
136+ return super ().step ()
137+
138+
139+
140+ def ai (self ):
141+ # sends observation to the supervisor
142+ self .emitter .send (np .concatenate (self .observe ()).tobytes ())
143+
113144 # First to be executed
114145
115146 self .log .info ("Starting step" )
@@ -136,7 +167,25 @@ def step(self):
136167 self .setSteeringAngle (action_steering )
137168 self .setCruisingSpeed (action_speed )
138169
139- return super ().step ()
170+ if self .touch_sensor .getValue ():
171+ self .state = State .BACK
172+
173+
174+ def back (self ):
175+ #si mur de "dir": braquer à "dir"" et reculer jusqu'à pouvoir réavancer (distance au mur à vérif)
176+ lidar ,cam = self .observe ()[1 :]
177+ S = sum (cam )
178+ dir = S > 0
179+ if dir :
180+ self .setSteeringAngle (0.33 )
181+ if too_close (lidar ,dir ):
182+ self .setCruisingSpeed (- 2 )
183+ else : self .state = State .AI
184+ else :
185+ self .setSteeringAngle (- 0.33 )
186+ if too_close (lidar ,dir ):
187+ self .setCruisingSpeed (- 2 )
188+ else : self .state = State .AI
140189
141190 def run (self ):
142191 # this call is just there to make sure at least one step
0 commit comments