# File: snake7.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 # # In this version, the program checks if the # snake intersects itself. If so, when the # tail reaches the point of intersection, # we don't erase the box at the intersection. 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) # draw initial configuration pos = [ (0,240) ] drawBox(0,240,"orange") # snake is how long? snakeLen = 20 # initial direction is right x_inc = 20 y_inc = 0 done = False while not done: # get current position (x,y) = pos[-1] # get a character c = stdscr.getch() 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 oldest location if len(pos) >= snakeLen: (oldest_x, oldest_y) = pos.pop(0) # check if oldest point, is in buffer elsewhere selfIntersect = False for (p,q) in pos: if oldest_x == p and oldest_y == q: selfIntersect = True # if self-intersect, do not erase if not selfIntersect: drawBox(oldest_x,oldest_y,"white") # draw new box new_x = (x + x_inc) % 500 new_y = (y + y_inc) % 500 drawBox(new_x, new_y,"orange") # store new position pos.append((new_x, 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.nodelay(False) stdscr.keypad(0) curses.nocbreak() curses.echo() curses.endwin() # end of main() main()