import random XSIZE = 15 YSIZE = 12 _world = [] _x_pos = -1 _y_pos = -1 def init_world(): """ Initializes the world to a rectangle of empty cells and adds some obstacles. """ # make rectangle of empty cells for y in range(YSIZE): _world[y:] = [[' '] * XSIZE] # add some obstacles # obstacle 1 _world[YSIZE-2][XSIZE-2] = 'w' _world[YSIZE-1][XSIZE-2] = 'w' _world[YSIZE-2][XSIZE-1] = 'w' _world[YSIZE-1][XSIZE-1] = 'w' # obstacle 2 for y in [3,4]: for x in range(2,9): _world[y][x] = 'w' for y in [5,6,7]: _world[y][2] = 'w' _world[y][3] = 'w' _world[5][7] = 'w' _world[5][8] = 'w' def init_robot(): """ Chooses a random position in the world and places the robot there, if the position is free. Otherwise it tries again. """ placed = False while not placed: global _x_pos _x_pos = random.randint(0,XSIZE-1) global _y_pos _y_pos = random.randint(0,YSIZE-1) if _world[_y_pos][_x_pos] == ' ': _world[_y_pos][_x_pos] = 'R' placed = True def display_world(): """ Print out a representation of the world on the screen. """ print "= " * (XSIZE + 2) for row in _world: print "|", for cell in row: print cell, print"|\n", print "= " * (XSIZE + 2) def get_cell(x,y): """ Returns the 'content' of the grid cell at position x and y. Returns 'w' if either x or y are beyond the boundaries of the grid. """ if x < 0 or y < 0 or x >= XSIZE or y >= YSIZE: return 'w' else: return _world[y][x] def move(where): """ Tries to move the robot into the direction specified by the parameter where. Nothing happens if it is not possible to move the robot into that direction because of a wall. """ global _y_pos global _x_pos if where == 'n' and get_cell(_x_pos,_y_pos-1)!='w': _world[_y_pos][_x_pos] = ' ' _y_pos = _y_pos - 1 _world[_y_pos][_x_pos] = 'R' elif where == 'e' and get_cell(_x_pos+1,_y_pos)!='w': _world[_y_pos][_x_pos] = ' ' _x_pos = _x_pos + 1 _world[_y_pos][_x_pos] = 'R' elif where == 's' and get_cell(_x_pos,_y_pos+1)!='w': _world[_y_pos][_x_pos] = ' ' _y_pos = _y_pos + 1 _world[_y_pos][_x_pos] = 'R' elif where == 'w' and get_cell(_x_pos-1,_y_pos)!='w': _world[_y_pos][_x_pos] = ' ' _x_pos = _x_pos - 1 _world[_y_pos][_x_pos] = 'R' def agent_function(): """ Specifies the rules according to which the robot moves. """ where = random.choice(['n','e','s','w']) move(where) def main(): # initialize the grid world init_world() # place the robot in the grid world init_robot() display_world() # make the robot move one step at a time as long as the user keeps on # pressing return more = raw_input("Press return for the next step; 'q' and return to stop\n") while more != 'q': agent_function() display_world() more = raw_input("Press return for the next step; 'q' and return to stop\n") main()