def testRover(): try: import Rover except: print "Error: No file named Rover.py found in current directory." return try: for left in range(4): for back in range(4): for right in range(4): assertEquals(constants.INFECT, Rover.getMove(constants.OTHER, left, back, right)) for left in range(4): for back in range(4): for right in range(4): assertEquals(constants.HOP, Rover.getMove(constants.EMPTY, left, back, right)) moves = {} for front in [constants.SAME, constants.WALL]: for left in range(4): for back in range(4): for right in range(4): move = Rover.getMove(front, left, back, right) if move in moves: moves[move] += 1 else: moves[move] = 1 assertEquals(45 < moves[constants.LEFT] < 80, True) assertEquals(45 < moves[constants.RIGHT] < 80, True) except CritterTestError: failed.append("Rover") return except: failed.append("Rover") raise passed.append("Rover")
def __init__(self): pygame.init() self.clock = pygame.time.Clock() self.gameDisplay = pygame.display.set_mode( (constants.DISPLAY_WIDTH, constants.DISPLAY_HEIGTH)) pygame.display.set_caption('RaceTrackSimulator') self.img = pygame.image.load('car.png') self.done = False self.rover = Rover() self.obstacles = [] self.run()
def testCreateNormalRover(self): rover = Rover.Rover(1, 2, 'N', 'L', self.plateau) self.assertEqual(rover.x, 1) self.assertEqual(rover.y, 2) self.assertEqual(rover.orientation, 'N') self.assertEqual(rover.commands, 'L') self.assertEqual(rover.plateau, self.plateau)
def create_rover(start_position, commands, plateau, out=sys.stdout): """ Return a new Rover if it has a valid initial position and set of commands, otherwise nothing will be returned :param start_position: String representing a rover's initial position. Valid start_positions will have two Integers followed by a space and either N, E, S or W :param commands: String representing a rover's set of instructions. Valid characters in commands are either L, R or M :param plateau: the Plateau that the Rover will explore :param out: Output stream for messages during execution :return: Rover if no errors were found in the input, otherwise None """ raw_position = re.match('^(\d \d [NESW])$', start_position) raw_commands = re.match('^[LRM]+$', commands) if raw_position and raw_commands: formatted_position = process_regex(raw_position) coordinates = convert_to_int_list(formatted_position[:2]) if not plateau.is_valid_position(coordinates[0], coordinates[1]): out.write(RoverInvalidPositionError().warning( raw_position.group())) else: return Rover(coordinates[0], coordinates[1], formatted_position[2], raw_commands.group(), plateau) else: out.write(RoverSetupError().warning(start_position, commands))
def testEdgeMove(self): rover = Rover.Rover(4, 4, 'E', 'M', self.plateau) self.assertEqual(rover.x, 4) self.assertEqual(rover.y, 4) self.assertEqual(rover.orientation, 'E') rover.move() self.assertEqual(rover.x, 5) self.assertEqual(rover.y, 4) self.assertEqual(rover.orientation, 'E')
def testNormalMove(self): rover = Rover.Rover(1, 2, 'E', 'M', self.plateau) self.assertEqual(rover.x, 1) self.assertEqual(rover.y, 2) self.assertEqual(rover.orientation, 'E') rover.move() self.assertEqual(rover.x, 2) self.assertEqual(rover.y, 2) self.assertEqual(rover.orientation, 'E')
def testExample2Explore(self): rover = Rover.Rover(3, 3, 'E', 'MMRMMRMRRM', self.plateau) self.assertEqual(rover.x, 3) self.assertEqual(rover.y, 3) self.assertEqual(rover.orientation, 'E') rover.explore() self.assertEqual(rover.x, 5) self.assertEqual(rover.y, 1) self.assertEqual(rover.orientation, 'E')
def testExample1Explore(self): rover = Rover.Rover(1, 2, 'N', 'LMLMLMLMM', self.plateau) self.assertEqual(rover.x, 1) self.assertEqual(rover.y, 2) self.assertEqual(rover.orientation, 'N') rover.explore() self.assertEqual(rover.x, 1) self.assertEqual(rover.y, 3) self.assertEqual(rover.orientation, 'N')
def testIllegalMove(self): rover = Rover.Rover(5, 5, 'E', 'M', self.plateau) self.assertEqual(rover.x, 5) self.assertEqual(rover.y, 5) self.assertEqual(rover.orientation, 'E') rover.move() self.assertEqual(rover.x, 5) self.assertEqual(rover.y, 5) self.assertEqual(rover.orientation, 'E')
def testMoveSpinCommand(self): rover = Rover.Rover(1, 2, 'E', 'M', self.plateau) self.assertEqual(rover.x, 1) self.assertEqual(rover.y, 2) self.assertEqual(rover.orientation, 'E') rover.command('M') self.assertEqual(rover.x, 2) self.assertEqual(rover.y, 2) self.assertEqual(rover.orientation, 'E')
def testTwoCommandExplore(self): rover = Rover.Rover(1, 2, 'E', 'LM', self.plateau) self.assertEqual(rover.x, 1) self.assertEqual(rover.y, 2) self.assertEqual(rover.orientation, 'E') rover.explore() self.assertEqual(rover.x, 1) self.assertEqual(rover.y, 3) self.assertEqual(rover.orientation, 'N')
def testRoverTwoStepRotateRight(self): rover = Rover("rover1", 0, 0, "N", self.plateau) rover.oneStep() rover.oneStep() rover.rotateRight() self.assertEqual(rover.position.coords, (0, 2)) self.assertEqual(rover.direction, "E")
def main(): print("Enter the information of the ships and instructions") plateuX, plateuY = input("Plateu: (X Y) ").split(" ") howManyRovers = int(input("How many rovers do you want control? ")) plateau = Plateau(int(plateuX), int(plateuY)) for item in range(0, howManyRovers): roverX, roverY, roverDirection = input("Landing: (X Y D)").split(" ") instructions = input("Instructions: (LRM)") rover = Rover("rover" + str(item + 1), int(roverX), int(roverY), roverDirection, plateau) executeRoverInstructions(rover, instructions)
def commandInterpreter(command, *args): global plateau if command is InputFileParser.PlateauConfigState.Commands.CREATE_PLATEAU: plateau = Plateau(args[0] + 1, args[1] + 1) elif command is InputFileParser.RoverInstructionsState.Commands.CREATE_ROVER: rover_name = args[0] rover_position = tuple(args[1:3]) rover_bearing = args[3] rover_instructions = args[4] rover = Rover(rover_name, plateau.getPosition(*rover_position), rover_bearing) execute_rover_instructions(rover, rover_instructions) print_rover_position(rover)
def testInstructionsRover(self): #Plateau:5 5 #Rover1 Landing:1 2 N #Rover1 Instructions:LMLMLMLMM rover = Rover("rover1", 1, 2, "N", self.plateau) instructions = "LMLMLMLMM" for this_char in instructions: if this_char is 'L': rover.rotateLeft() elif this_char is 'R': rover.rotateRight() elif this_char is 'M': rover.oneStep() else: raise "Invalid Intructions: L or R or M" self.assertEqual(rover.position.coords, (1, 3)) self.assertEqual(rover.direction, "N")
# -*- coding: utf-8 -*- import time import Rover import socket import sys import json # Create a TCP/IP socket serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_name = sys.argv[1] server_address = (server_name, 31415) engine = Rover.Engine() phil = Rover.Sensor() sonic = Rover.UltraSonic() def sendToServer(message): try: # Send message print >> sys.stderr, 'sending "%s"' % message serverSocket.sendall(message) finally: return def run(): serverSocket.connect(server_address) print(' ~~~~\t~~~~\t~~~~\t') #makes output pretty :) while True:
def testSetNegativeOrientation(self): rover = Rover.Rover(1, 2, 'N', 'R', self.plateau) self.assertEqual(rover.orientation, 'N') rover.set_orientation('R', -1) self.assertEqual(rover.orientation, 'N')
def testNormalLeftSpin(self): rover = Rover.Rover(1, 2, 'E', 'L', self.plateau) self.assertEqual(rover.orientation, 'E') rover.spin('L') self.assertEqual(rover.orientation, 'N')
class Simulation(): def __init__(self): pygame.init() self.clock = pygame.time.Clock() self.gameDisplay = pygame.display.set_mode( (constants.DISPLAY_WIDTH, constants.DISPLAY_HEIGTH)) pygame.display.set_caption('RaceTrackSimulator') self.img = pygame.image.load('car.png') self.done = False self.rover = Rover() self.obstacles = [] self.run() def run(self): self.get_initial_rover_position() while not self.done or self.outOfBounds(): self.keyboardEventHandeling() self.rover.lead_x, self.rover.lead_y = self.getNextPosition() self.updateScreen() self.endSession() def loadWorld(self): lines = open('worlds/world.txt', 'r') world = [] for line in lines: world.append(line) return world def pixelizeWorld(self): world = self.loadWorld() self.obstacles = [] y = 0 x = 0 for lines in world: for pixel in lines: if pixel == 'o': obstacle = Obstacle() obstacle.x = round( x * constants.BLOCK_SIZE / constants.BLOCK_SIZE) * constants.BLOCK_SIZE obstacle.y = round( y * constants.BLOCK_SIZE / constants.BLOCK_SIZE) * constants.BLOCK_SIZE gameDisplay = pygame.display.get_surface() rect = (obstacle.x, obstacle.y, constants.BLOCK_SIZE, constants.BLOCK_SIZE) pygame.draw.rect(gameDisplay, constants.BLACK, rect) self.obstacles.append(obstacle) x += 1 y += 1 x = 0 def get_initial_rover_position(self): world = self.loadWorld() y = 0 x = 0 for lines in world: for pixel in lines: if pixel == 'x': self.rover.lead_x = round( x * constants.BLOCK_SIZE / constants.BLOCK_SIZE) * constants.BLOCK_SIZE self.rover.lead_y = round( y * constants.BLOCK_SIZE / constants.BLOCK_SIZE) * constants.BLOCK_SIZE x += 1 y += 1 x = 0 def getNextPosition(self): new_x = self.rover.lead_x + self.rover.lead_x_change new_y = self.rover.lead_y + self.rover.lead_y_change if self.rover.canMove(new_x, new_y, self.obstacles): return new_x, new_y else: return self.rover.lead_x, self.rover.lead_y def endSession(self): self.done = True pygame.quit() quit() def outOfBounds(self): if self.rover.lead_x >= constants.DISPLAY_WIDTH or self.rover.lead_x < 0 or self.rover.lead_y >= constants.DISPLAY_HEIGTH or self.rover.lead_y < 0: self.done = True return True else: return False def updateScreen(self): self.gameDisplay.fill(constants.WHITE) self.pixelizeWorld() roverimg = self.rover.rotateImg(self.img) self.gameDisplay.blit(roverimg, [ self.rover.lead_x, self.rover.lead_y, constants.BLOCK_SIZE, constants.BLOCK_SIZE ]) self.rover.getFOV() pygame.display.update() self.clock.tick(constants.FPS) def keyboardEventHandeling(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.done = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: self.rover.lead_x_change = -constants.BLOCK_SIZE self.rover.lead_y_change = 0 self.rover.direction = "left" elif event.key == pygame.K_RIGHT: self.rover.lead_x_change = constants.BLOCK_SIZE self.rover.lead_y_change = 0 self.rover.direction = "right" elif event.key == pygame.K_UP: self.rover.lead_y_change = -constants.BLOCK_SIZE self.rover.lead_x_change = 0 self.rover.direction = "up" elif event.key == pygame.K_DOWN: self.rover.lead_y_change = constants.BLOCK_SIZE self.rover.lead_x_change = 0 self.rover.direction = "down"
def testInstructionsTwoRovers(self): #Plateau:5 5 #Rover1 Landing:1 2 N #Rover1 Instructions:LMLMLMLMM #Rover2 Landing:3 3 E #Rover2 Instructions:MMRMMRMRRM rover1 = Rover("rover1", 1, 2, "N", self.plateau) rover1.instructions = "LMLMLMLMM" rover2 = Rover("rover2", 3, 3, "E", self.plateau) rover2.instructions = "MMRMMRMRRM" rovers = [rover1, rover2] for item in rovers: for this_char in item.instructions: if this_char is 'L': item.rotateLeft() elif this_char is 'R': item.rotateRight() elif this_char is 'M': item.oneStep() else: raise "Invalid Intructions: L or R or M" self.assertEqual(rover1.position.coords, (1, 3)) self.assertEqual(rover1.direction, "N") self.assertEqual(rover2.position.coords, (5, 1)) self.assertEqual(rover2.direction, "E") print('{0}:{1} {2} {3}'.format(rover1.getName(), rover1.getPosition()[0], rover1.getPosition()[1], rover1.getDirection())) print('{0}:{1} {2} {3}'.format(rover2.getName(), rover2.getPosition()[0], rover2.getPosition()[1], rover2.getDirection()))
def testEdgeRightSpin(self): rover = Rover.Rover(1, 2, 'W', 'R', self.plateau) self.assertEqual(rover.orientation, 'W') rover.spin('R') self.assertEqual(rover.orientation, 'N')
def testRoverRotateRightOneStep(self): rover = Rover("rover1", 0, 0, "N", self.plateau) rover.rotateRight() rover.oneStep() self.assertEqual(rover.position.coords, (1, 0))
def testRoverRotateRight(self): rover = Rover("rover1", 0, 0, "N", self.plateau) rover.rotateRight() self.assertEqual(rover.direction, "E")
def testRightSpinCommand(self): rover = Rover.Rover(5, 5, 'E', 'R', self.plateau) self.assertEqual(rover.orientation, 'E') rover.command('R') self.assertEqual(rover.orientation, 'S')
import Rover,Traverse input_data = ['5 5','1 2 N','LMLMLMLMM'] # input_data = ['5 5','3 3 E','MMRMMRMRRM'] Rover = Rover.Rover() Rover.set_data(input_data) data=Rover.get_data() max=data[0] data.pop(0) Traverse = Traverse.Traverse(data) Traverse.get_Coordinates() for i in Traverse.get_TraverseString(): if (i == 'L'): Traverse.L() if (i == 'R'): Traverse.R() if (i == 'M'): Traverse.M() print Traverse.printdata()
def testTwoStepMoveRover(self): rover = Rover("rover1", 0, 0, "N", self.plateau) rover.oneStep() rover.oneStep() self.assertEqual(rover.position.coords, (0, 2))
def testLeftSpinCommand(self): rover = Rover.Rover(5, 5, 'E', 'L', self.plateau) self.assertEqual(rover.orientation, 'E') rover.command('L') self.assertEqual(rover.orientation, 'N')
# -*- coding: utf-8 -*- # RUNS ON ROVER import socket import sys import Rover # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_name = sys.argv[1] server_address = (server_name, 31417) print >> sys.stderr, 'starting up on %s port %s' % server_address sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(server_address) engine = Rover.Engine() # Listen for incoming connections sock.listen(5) while True: try: # Wait for a connection print >> sys.stderr, 'waiting for a connection' connection, client_address = sock.accept() while True: data = connection.recv(50) print("received data:" + data) if data: if data == 'FORWARD': engine.forward() elif data == 'BACKWARD':
# the rover moves up to the last possible point and reports the obstacle. # TODO: make tests independent of one another (the test framework does not have a before()) # TODO: refactor tests following "effective unit testing" best practices from Navigator import * from Rover import * CARDINAL_POINTS = ('N', 'S', 'E', 'W') with given.a_rover: x = 0 y = 0 starting_point = {'x': x, 'y': y} initial_direction = 'N' rover = Rover(starting_point, initial_direction) the(isinstance(rover, Rover)).should.be(True) with when.supplied_the_starting_point: with then.the_starting_point_should_have_two_axis: the(starting_point).should.contain('x') the(starting_point).should.contain('y') with then.the_initial_direction_should_belong_to_NSEW: the(initial_direction in CARDINAL_POINTS).should.be(True) with when.supplied_with_a_character_command: with and_.the_rover_should_give_current_position: the(rover.position).should.be(starting_point)