|
| 1 | +import cmd, sys |
| 2 | +from turtle import * |
| 3 | + |
| 4 | +class TurtleShell(cmd.Cmd): |
| 5 | + intro = 'Welcome to the turtle shell. Type help or ? to list commands.\n' |
| 6 | + prompt = '(turtle) ' |
| 7 | + file = None |
| 8 | + |
| 9 | + # ----- basic turtle commands ----- |
| 10 | + def do_forward(self, arg): |
| 11 | + 'Move the turtle forward by the specified distance: FORWARD 10' |
| 12 | + forward(*parse(arg)) |
| 13 | + def do_right(self, arg): |
| 14 | + 'Turn turtle right by given number of degrees: RIGHT 20' |
| 15 | + right(*parse(arg)) |
| 16 | + def do_left(self, arg): |
| 17 | + 'Turn turtle left by given number of degrees: LEFT 90' |
| 18 | + left(*parse(arg)) |
| 19 | + def do_goto(self, arg): |
| 20 | + 'Move turtle to an absolute position with changing orientation. GOTO 100 200' |
| 21 | + goto(*parse(arg)) |
| 22 | + def do_home(self, arg): |
| 23 | + 'Return turtle to the home position: HOME' |
| 24 | + home() |
| 25 | + def do_circle(self, arg): |
| 26 | + 'Draw circle with given radius an options extent and steps: CIRCLE 50' |
| 27 | + circle(*parse(arg)) |
| 28 | + def do_position(self, arg): |
| 29 | + 'Print the current turle position: POSITION' |
| 30 | + print('Current position is %d %d\n' % position()) |
| 31 | + def do_heading(self, arg): |
| 32 | + 'Print the current turle heading in degrees: HEADING' |
| 33 | + print('Current heading is %d\n' % (heading(),)) |
| 34 | + def do_color(self, arg): |
| 35 | + 'Set the color: COLOR BLUE' |
| 36 | + color(arg.lower()) |
| 37 | + def do_undo(self, arg): |
| 38 | + 'Undo (repeatedly) the last turtle action(s): UNDO' |
| 39 | + def do_reset(self, arg): |
| 40 | + 'Clear the screen and return turtle to center: RESET' |
| 41 | + reset() |
| 42 | + def do_bye(self, arg): |
| 43 | + 'Stop recording, close the turtle window, and exit: BYE' |
| 44 | + print('Thank you for using Turtle') |
| 45 | + self.close() |
| 46 | + bye() |
| 47 | + return True |
| 48 | + |
| 49 | + # ----- record and playback ----- |
| 50 | + def do_record(self, arg): |
| 51 | + 'Save future commands to filename: RECORD rose.cmd' |
| 52 | + self.file = open(arg, 'w') |
| 53 | + def do_playback(self, arg): |
| 54 | + 'Playback commands from a file: PLAYBACK rose.cmd' |
| 55 | + self.close() |
| 56 | + with open(arg) as f: |
| 57 | + self.cmdqueue.extend(f.read().splitlines()) |
| 58 | + def precmd(self, line): |
| 59 | + line = line.lower() |
| 60 | + if self.file and 'playback' not in line: |
| 61 | + print(line, file=self.file) |
| 62 | + return line |
| 63 | + def close(self): |
| 64 | + if self.file: |
| 65 | + self.file.close() |
| 66 | + self.file = None |
| 67 | + |
| 68 | +def parse(arg): |
| 69 | + 'Convert a series of zero or more numbers to an argument tuple' |
| 70 | + return tuple(map(int, arg.split())) |
| 71 | + |
| 72 | +if __name__ == '__main__': |
| 73 | + TurtleShell().cmdloop() |
0 commit comments