# File: snake2.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 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) # initial position x = 0 y = 240 drawBox(x,y,"orange") done = False while not done: # get a character c = stdscr.getch() arrowKeyPressed = False new_x = x new_y = y # use arrow keys to specify # location of next point if c == curses.KEY_LEFT : arrowKeyPressed = True new_x = (x - 20) % 500 elif c == curses.KEY_RIGHT : arrowKeyPressed = True new_x = (x + 20) % 500 elif c == curses.KEY_UP : arrowKeyPressed = True new_y = (y - 20) % 500 elif c == curses.KEY_DOWN : arrowKeyPressed = True new_y = (y + 20) % 500 elif c == ord('q'): done = True # update box drawn if needed if arrowKeyPressed: # erase previous location drawBox(x,y,"white") # draw new box drawBox(new_x, new_y,"orange") x = new_x y = new_y 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.keypad(0) curses.nocbreak() curses.echo() curses.endwin() # end of main() main()