In: Computer Science
#python. Explain code script of each part using
comments for the reader. The code script must work without any
errors or bugs.
Ball moves in a 2D coordinate system beginning from the original
point (0,0). The ball can
move upwards, downwards, left and right using x and y coordinates.
Code must ask the
user for the destination (x2, y2) coordinate point by using the
input x2 and y2 and the known
current location, code can use the euclidean distance formula to
work out the distance
to the destination. Code should repeatedly ask the user to input
the destination
coordinates to shift the ball further but, once the user types the
value 999, the code
should print all previous movements of the ball by showing the
distance of each step. Also trace function
prints the total distance travelled by the ball.
Please find below the code, code screenshots and output screenshots. Please refer to the screenshot of the code to understand the indentation of the code. Please get back to me if you need any change in code. Else please upvote
CODE:
import math
x_cordinates = [0] #Declare list to store the x cordinates and initialize it with starting x cordinate 0
y_cordinates = [0] #Declare list to store the y cordinates and initialize it with starting y cordinate 0
while True: #Loop continuously
x = int(input("\nEnter the destination x coordinate to shift the ball: ")) #Reading the x cordinate of destination
if(x == 999): #If the value entered is 999, break the loop
break
y = int(input("Enter the destination y coordinate to shift the ball: ")) #Reading the y cordinate of destination
if(y == 999): #If the value entered is 999, break the loop
break
x_cordinates.append(x) #Adding the x cordinate to list x_cordinates
y_cordinates.append(y) #Adding the y cordinate to list y_cordinates
print("\nSource Destination Distance") #Displaying table header
for i in range(len(x_cordinates) - 1): #Loop through each index in list
#getting the current x and y cordinates to x1 and y1
x1 = x_cordinates[i]
y1 = y_cordinates[i]
#getting the next x and y cordinates to x2 and y2
x2 = x_cordinates[i+1]
y2 = y_cordinates[i+1]
distance = math.sqrt( ((x1-x2)**2)+((y1-y2)**2)) #Calculating the distance between the two points
print("({:d},{:d}) ({:d}, {:d}) {:>15.2f}".format(x1, y1, x2, y2, distance)) #Displaying the cordinates and distance
OUTPUT: