# File: snake1.py # # A simple program that uses the graphics module # and the curses module to draw a "snake" on # the graphics window that is controlled by # the arrow keys on the keyboard # # Step 1: check that the curses and graphics # modules can coexist. from graphics import * import time import curses def main(): def drawBox(x, y, color): box = Rectangle(Point(x,y), Point(x+20,y+20)) box.setFill(color) box.setWidth(0) box.draw(win) # start curses # don't print to screen # don't wait for 'enter' to be pressed # map special keys to curses constants stdscr = curses.initscr() curses.noecho() curses.cbreak() stdscr.keypad(1) # make a window for drawing stuff win = GraphWin("Hello", 500, 500) # cursor control done = False while not done: # get a character c = stdscr.getch() if c == curses.KEY_LEFT : print("left\r") drawBox(240,240,"orange") elif c == curses.KEY_RIGHT : print("right\r") elif c == curses.KEY_UP : print("up\r") elif c == curses.KEY_DOWN : print("down\r") elif c == ord('q'): done = True else: print(".\r") # end of while not done # graphics module exercised x = 0 y = 240 for i in range(40): drawBox(x,y,"white") x = (x + 20) % 500 drawBox(x,y,"orange") time.sleep(.2) # end of for i # wait before closing window time.sleep(60) # make the window go away win.close() # restore things to normal stdscr.keypad(0) curses.nocbreak() curses.echo() curses.endwin() # end of main() main()