# File: snake4.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, a five-square snake travels # around the screen (instead of a 1-square box). 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) # Use list to keep track of the position # of the five squares in the "snake" # Note that each item in the list is a tuple. pos = [ (0,240), (20,240), (40, 240), (60,240), (80, 240) ] # draw initial configuration drawBox(0,240,"orange") drawBox(20,240,"orange") drawBox(40,240,"orange") drawBox(60,240,"orange") drawBox(80,240,"orange") # 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() # arrow keys 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 # get position of the "tail" (oldest_x, oldest_y) = pos.pop(0) # erase the tail location 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()