Highschool Back Tracking. Looking for a simple code in python for a back trackin
ID: 3719123 • Letter: H
Question
Highschool Back Tracking.
Looking for a simple code in python for a back tracking robot car that is supposed to travel through the maze. The car has a distance sensor and when it detects a crossroad it chooses a path and explores it. when it comes to a dead end I want it to turn around and retrace its steps and get back at the point where it was when it was at the cross point. I want it to
So...
1) Store all movements in a stack.
2) When at a cross roads mark that cross road
3) Continue storing movement in a stack
4) When sensor detect that the car is at a dead end the car will turn 180 degree. (I already have the function to make a 180 when at a dead end so You can just put in a place holder here ans I can plug it in. What I need from you is how to connect this to the next part.)
5) Car will now do the opposite movements it had done to go back to the crossroads place.
here is how the car moves and turns
Explanation / Answer
import random
# initialize a stack globally and assign some codes to all the possible directions the bot can travel from a crossroad
# a : straight
# b : about turn
# c: right
# d left
# this stack will store the codes of the movements made by the bot
stack = []
# Also initialize an empty dict to store identifiers of all the movements that led to a dead end
dead_end = {}
# pass this stack as an argument to the crossroad method
def crossroad(stack,dead_ends):
# use this method whenever the bot encounters a crossroad. stack parameter serves as a history of th bot movements
direction = random.choice(['a','b','c','d'])
make_move(stack,direction,dead_ends)
# defined towards the end of the code
def dead_end(stack,dead_ends):
# use this method whenever the bot encounters a dead end
identifier = ''.join(stack)
# this identifier helps us uniquely identify each move
if identifier not in dead_ends:
dead_ends[identifier] = True
last_move = stack.pop()
turn_around()
def make_move(direction,stack,dead_ends):
# this method first checks if the said move leads into a dead_end. If yes it skips it and else it allows and records the move in history stack
stack.append(direction)
identifier = ''.join(stack)
if identifier in dead_ends:
stack.pop()
else:
if direction=='a':
move_straight()
# you haven't defined this method but i assume it would be fairly trivial for you
elif direction=='b':
turn_around()
elif direction=='c':
turn_right()
else:
turn_left()
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.