# File: snake3.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 # # This version, the box continues in same direction # unless the direction is altered by the arrow keys. # 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 # don't wait for keypress stdscr = curses.initscr() curses.noecho() curses.cbreak() stdscr.keypad(1) stdscr.nodelay(True) # make a window for drawing stuff win = GraphWin("Hello", 500, 500) # initial position x = 0 y = 240 drawBox(x,y,"orange") # initial direction is right x_inc = 20 y_inc = 0 done = False while not done: # get a character c = stdscr.getch() # use arrow keys to determine new direction # if c == curses.KEY_LEFT : x_inc = -20 y_inc = 0 elif c == curses.KEY_RIGHT : x_inc = 20 y_inc = 0 elif c == curses.KEY_UP : x_inc = 0 y_inc = -20 elif c == curses.KEY_DOWN : x_inc = 0 y_inc = 20 elif c == ord('q'): done = True # erase previous location drawBox(x,y,"white") # update x & y x = (x + x_inc) % 500 y = (y + y_inc) % 500 # draw new box drawBox(x, y,"orange") time.sleep(.1) # end of while not done # wait before closing window time.sleep(2) # make the window go away win.close() # restore things to normal stdscr.nodelay(False) stdscr.keypad(0) curses.nocbreak() curses.echo() curses.endwin() # end of main() main()