# 6.00.2x Problem Set 2: Simulating robots import math import random import ps2_visualize import pylab # For Python 2.7: from ps2_verify_movement27 import testRobotMovement # If you get a "Bad magic number" ImportError, you are not using # Python 2.7 and using most likely Python 2.6: # === Provided class Position class Position(object): """ A Position represents a location in a two-dimensional room. """ def __init__(self, x, y): """ Initializes a position with coordinates (x, y). """ self.x = x self.y = y def getX(self): return self.x def getY(self): return self.y def getNewPosition(self, angle, speed): """ Computes and returns the new Position after a single clock-tick has passed, with this object as the current position, and with the specified angle and speed. Does NOT test whether the returned position fits inside the room. angle: number representing angle in degrees, 0 <= angle < 360 speed: positive float representing speed Returns: a Position object representing the new position. """ old_x, old_y = self.getX(), self.getY() angle = float(angle) # Compute the change in position delta_y = speed * math.cos(math.radians(angle)) delta_x = speed * math.sin(math.radians(angle)) # Add that to the existing position new_x = old_x + delta_x new_y = old_y + delta_y return Position(new_x, new_y) def __str__(self): return "(%0.2f, %0.2f)" % (self.x, self.y) # === Problem 1 class RectangularRoom(object): def __init__(self, width, height): self.cleanTiles = [[False for x in range(height)] for x in range(width)] def cleanTileAtPosition(self, pos): self.cleanTiles[int(pos.getX())][int(pos.getY())] = True def isTileCleaned(self, m, n): return self.cleanTiles[m][n] def getNumTiles(self): return len(self.cleanTiles)*len(self.cleanTiles[0]) def getNumCleanedTiles(self): return sum(map(sum, self.cleanTiles)) def getRandomPosition(self): return Position(random.random()*len(self.cleanTiles),random.random()*len(self.cleanTiles[0])) def isPositionInRoom(self, pos): return 0 <= pos.getX() < len(self.cleanTiles) and 0 <= pos.getY() < len(self.cleanTiles[0]) class Robot(object): def __init__(self, room, speed): self.room = room self.speed = speed self.pos = self.room.getRandomPosition() self.direction = int(random.random()*360) self.room.cleanTileAtPosition(self.pos) def getRobotPosition(self): return self.pos def getRobotDirection(self): return self.direction def setRobotPosition(self, position): self.pos = position def setRobotDirection(self, direction): self.direction = direction def updatePositionAndClean(self): raise NotImplementedError class StandardRobot(Robot): def updatePositionAndClean(self): if self.room.isPositionInRoom(self.pos.getNewPosition(self.direction, self.speed)): self.setRobotPosition(self.pos.getNewPosition(self.direction, self.speed)) self.room.cleanTileAtPosition(self.pos) else: self.setRobotDirection(int(random.random()*360)) # Uncomment this line to see your implementation of StandardRobot in action! ##testRobotMovement(StandardRobot, RectangularRoom) # === Problem 3 def runSimulation(num_robots, speed, width, height, min_coverage, num_trials, robot_type): """ Runs NUM_TRIALS trials of the simulation and returns the mean number of time-steps needed to clean the fraction MIN_COVERAGE of the room. The simulation is run with NUM_ROBOTS robots of type ROBOT_TYPE, each with speed SPEED, in a room of dimensions WIDTH x HEIGHT. num_robots: an int (num_robots > 0) speed: a float (speed > 0) width: an int (width > 0) height: an int (height > 0) min_coverage: a float (0 <= min_coverage <= 1.0) num_trials: an int (num_trials > 0) robot_type: class of robot to be instantiated (e.g. StandardRobot or RandomWalkRobot) """ # Initialization Variables time2complete = [] # Trials for _ in range(num_trials): room = RectangularRoom(width,height) robots = [] for __ in range(num_robots): # create the robots robots.append(StandardRobot(room,speed)) # Uncomment this line to see how much your simulation takes on average ##print runSimulation(1, 1.0, 10, 10, 0.75, 30, StandardRobot) # === Problem 4 class RandomWalkRobot(Robot): """ A RandomWalkRobot is a robot with the "random walk" movement strategy: it chooses a new direction at random at the end of each time-step. """ def updatePositionAndClean(self): """ Simulate the passage of a single time-step. Move the robot to a new position and mark the tile it is on as having been cleaned. """ raise NotImplementedError def showPlot1(title, x_label, y_label): """ What information does the plot produced by this function tell you? """ num_robot_range = range(1, 11) times1 = [] times2 = [] for num_robots in num_robot_range: print "Plotting", num_robots, "robots..." times1.append(runSimulation(num_robots, 1.0, 20, 20, 0.8, 20, StandardRobot)) times2.append(runSimulation(num_robots, 1.0, 20, 20, 0.8, 20, RandomWalkRobot)) pylab.plot(num_robot_range, times1) pylab.plot(num_robot_range, times2) pylab.title(title) pylab.legend(('StandardRobot', 'RandomWalkRobot')) pylab.xlabel(x_label) pylab.ylabel(y_label) pylab.show() def showPlot2(title, x_label, y_label): """ What information does the plot produced by this function tell you? """ aspect_ratios = [] times1 = [] times2 = [] for width in [10, 20, 25, 50]: height = 300/width print "Plotting cleaning time for a room of width:", width, "by height:", height aspect_ratios.append(float(width) / height) times1.append(runSimulation(2, 1.0, width, height, 0.8, 200, StandardRobot)) times2.append(runSimulation(2, 1.0, width, height, 0.8, 200, RandomWalkRobot)) pylab.plot(aspect_ratios, times1) pylab.plot(aspect_ratios, times2) pylab.title(title) pylab.legend(('StandardRobot', 'RandomWalkRobot')) pylab.xlabel(x_label) pylab.ylabel(y_label) pylab.show() # === Problem 5 # # 1) Write a function call to showPlot1 that generates an appropriately-labeled # plot. # # (... your call here ...) # # # 2) Write a function call to showPlot2 that generates an appropriately-labeled # plot. # # (... your call here ...) #
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question