Skip to content

Instantly share code, notes, and snippets.

@Aniq55
Created July 15, 2023 10:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Aniq55/2a8dae77ec663869faa20190a573c489 to your computer and use it in GitHub Desktop.
Save Aniq55/2a8dae77ec663869faa20190a573c489 to your computer and use it in GitHub Desktop.
Drone Search
# Create your search Drone
## Create a class for a drone which can move in a 2D space within fixed boundaries
## The drones perform random walk
## There are 2 targets on the ground that we want to track
## Deploy 2 drones and stop if both targets are found
# create a 2D grid space of size L x L, L = 50 (create this in your mind)
L = 50
# Create two tuples for each target, specifying the x and y coordinates,
# 0 < x < L, 0 < y < L
t1 = tuple(np.random.uniform(0, L, (1,2))[0])
t2 = tuple(np.random.uniform(0, L, (1,2))[0])
targets = [t1, t2]
# create a class for a Drone with attributes: x, y, speed, range
# and a function called: update_position()
class Drone:
def __init__(self, x,y, speed, rng):
self.x = x
self.y = y
self.speed = speed
self.rng = rng
def update_position(self):
self.x += self.speed*np.random.uniform(-1,1)
self.y += self.speed*np.random.uniform(-1,1)
m = 10
# make sure that: 0 < self.x < L and 0 < self.y < L
# HINT: Use if-else
# If it is < 0, make it m
# If it is > L, make it L - m
# m = 10
if self.x < 0:
self.x = m
elif self.x > L:
self.x = L - m
if self.y < 0:
self.y = m
elif self.y > L:
self.y = L - m
def find_target(self):
# (self.x, self.y) <---> target's (x,y)
for target in targets:
distance = np.sqrt( (self.x - target[0])**2 + (self.y - target[1])**2 )
if distance < self.rng:
print('target found at {}'.format(target))
targets.remove(target)
# Assignment
# [] print when a new target is found, and stop when all targets are found
# [] plot the trajectory for each drone
# Run a loop for time-steps
drone_list = []
drone_list.append(Drone(np.random.uniform(0,L),
np.random.uniform(0,L),
np.random.uniform(5,10),
10.0 ))
drone_list.append(Drone(np.random.uniform(0,L),
np.random.uniform(0,L),
np.random.uniform(5,10),
10.0 ))
# Dictionaries to save the trajectory of each drone
X = {}
Y = {}
for i, drone in enumerate(drone_list):
X[i] = []
Y[i] = []
# Time-loop
T = 500
for t in range(T):
for i, drone in enumerate(drone_list):
drone.update_position()
drone.find_target()
X[i].append(drone.x)
Y[i].append(drone.y)
# found all targets
if len(targets) == 0:
break
plt.figure()
for i in range(len(drone_list)):
plt.plot(X[i], Y[i], 'x-', label='drone #{}'.format(i))
plt.legend()
plt.xlim([0,L])
plt.ylim([0,L])
plt.xlabel('x-coordinate')
plt.ylabel('y-coordinate')
plt.title('Drone Trajectory')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment