Total Complexity | 6 |
Total Lines | 45 |
Duplicated Lines | 31.11 % |
Changes | 0 |
Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
1 | import logging |
||
2 | from curio import sleep |
||
3 | from bricknil import attach, start |
||
4 | from bricknil.hub import PoweredUpHub |
||
5 | from bricknil.sensor import TrainMotor, VisionSensor |
||
6 | from bricknil.process import Process |
||
7 | |||
8 | @attach(VisionSensor, name='train_sensor', capabilities=['sense_count', 'sense_distance']) |
||
9 | @attach(TrainMotor, name='motor') |
||
10 | class Train(PoweredUpHub): |
||
11 | |||
12 | View Code Duplication | async def train_sensor_change(self): |
|
|
|||
13 | self.message_info(f'Train sensor value change {self.train_sensor.value}') |
||
14 | distance = self.train_sensor.value[VisionSensor.capability.sense_distance] |
||
15 | count = self.train_sensor.value[VisionSensor.capability.sense_count] |
||
16 | |||
17 | if count > 3: |
||
18 | # Wave your hand more than three times in front of the sensor and the program ends |
||
19 | self.keep_running = False |
||
20 | |||
21 | # The closer your hand gets to the sensor, the faster the motor runs |
||
22 | self.motor_speed = (10-distance)*10 |
||
23 | |||
24 | # Flag a change |
||
25 | self.sensor_change = True |
||
26 | |||
27 | async def run(self): |
||
28 | self.message_info("Running") |
||
29 | self.motor_speed = 0 |
||
30 | self.keep_running = True |
||
31 | self.sensor_change = False |
||
32 | |||
33 | while self.keep_running: |
||
34 | if self.sensor_change: |
||
35 | await self.motor.ramp_speed(self.motor_speed, 900) # Ramp to new speed in 0.9 seconds |
||
36 | self.sensor_change = False |
||
37 | await sleep(1) |
||
38 | |||
39 | async def system(): |
||
40 | train = Train('My Train') |
||
41 | |||
42 | if __name__ == '__main__': |
||
43 | logging.basicConfig(level=logging.INFO) |
||
44 | start(system) |
||
45 |