#File I/O. #Read/parse a robot script and make the robot take the action #specified by the script. #Released to the public domain Feb 2009, Jay Summet # # from myro import * init() #Global variable to hold the list of commands commands = [] #This function takes a line command as a string. #It splits it apart, and then returns a list that is #the command. def parseCommand(line): splitLine = line.split(",") #What type of command is this? if (splitLine[0] == "S"): #sound command durationStr = splitLine[1] freqStr = splitLine[2] duration = float(durationStr) freq = float(freqStr) command = ["S", duration, freq ] return(command) elif (splitLine[0] == "F"): #Forward command speedStr = splitLine[1] durationStr = splitLine[2] duration = float(durationStr) speed = float(speedStr) command = ["F", speed, duration ] return(command) elif (splitLine[0] == "B"): #Backward command durationStr = splitLine[1] duration = float(durationStr) command = ["B", duration ] return(command) elif (splitLine[0] == "R"): #Right command durationStr = splitLine[1] duration = float(durationStr) command = ["R", duration ] return(command) else: print "command not recognized!" return(None) def readCommands(fileName): #the commands variable is a global variable! global commands myFile = open(fileName, "r") allCommands = myFile.readlines() myFile.close() for line in allCommands: myCmd = parseCommand(line) commands.append(myCmd) print "Just added: ", myCmd, " to the command list" def followScript( commands ): for cmd in commands: print "Command is:", cmd cmdLetter = cmd[0] if cmdLetter == "F": print "Going forward" forward(cmd[1], cmd[2] ) elif cmdLetter == "B": print "Going Backwards" backward(1,cmd[1]) elif cmdLetter == "R": print "Turning Right" turnRight(1, cmd[1]) elif cmdLetter == "L": print "Turning Left" turnLeft(1, cmd[1]) elif cmdLetter == "S": print "Beeping (a sound)" beep( cmd[1], cmd[2]) else: print "Unrecognized command!" #Un-comment the following "multi-line string" comment to create the #robotCommands.txt file. """ commands = [ ["S", 1, 440], [ "F",0.5, 2], ["B", 1], ["R", 0.5] ] def writeCommands(commands, fileName): f = open(fileName, "w") for cmd in commands: for item in cmd: itemStr = str(item) f.write(itemStr) f.write(", ") f.write("\n") f.close() writeCommands(commands, "robotCommands.txt")""" #Regular demo code, requires the robotCommands.txt file. readCommands("robotCommands.txt") followScript(commands)