# File: snake5.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 length of the snake is 1 # initially. The snake grows longer until # max length is reached. # 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") # 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 tail # check if length is greater than max if len(pos) >= 20: (oldest_x, oldest_y) = pos.pop(0) 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()