Python and duck curses
Posted: May 18, 2012 Filed under: Programming Languages | Tags: Python Leave a comment »Today at lunch I realized that life would be much easier if I could check the status of my simulations in some sort of interactive menu over ssh. When I got up to my office, someone told me about Python and curses. Curses is pretty much a module that allows you to deal with terminal-independent screen-painting and keyboard-handling over text-based terminals.
So… 10 minutes after reading this neat tutorial, and inspired by the craziness happening at 38 studios, I wrote my first game playable via ssh. You control a duck that collects worms… yes, how vapid.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
import curses, random def draw_duck(top_pos,left_pos): duck=( " _ ", " =')_// ", " (___/ ") screen.clear() for iterator in duck: screen.addstr(top_pos, left_pos, iterator) top_pos+=1 def update_screen(top_pos,left_pos,worm_location,worms_eaten): draw_duck(top_pos,left_pos) if (top_pos+1==worm_location[0]) and (left_pos+1==worm_location[1]): worms_eaten+=1 worm_location=[ random.randrange(1, screen_dimensions[0]), random.randrange(1, screen_dimensions[1]) ] screen.addstr(worm_location[0], worm_location[1],"~") say_this="Score=%d duck=(%d,%d) worm=(%d,%d)" % (worms_eaten, top_pos , left_pos, worm_location[0], worm_location[1]) screen.addstr(21,0,say_this) return (worm_location,worms_eaten) screen = curses.initscr() curses.noecho() curses.curs_set(0) screen.keypad(1) worm_location=[ random.randrange(1, screen_dimensions[0]), random.randrange(1, screen_dimensions[1]) ] worms_eaten=0 screen.addstr("Use the cursor keys to move the duck!\n") top_pos = 1 left_pos = 1 while True: event = screen.getch() if event == ord("q"): break elif event == curses.KEY_UP: top_pos-=1 if (top_pos<=0): top_pos=0 if (top_pos>=20): top_pos=20 worm_location, worms_eaten = update_screen(top_pos,left_pos,worm_location,worms_eaten) elif event == curses.KEY_DOWN: top_pos+=1 if (top_pos<=0): top_pos=0 if (top_pos>=20): top_pos=20 worm_location, worms_eaten = update_screen(top_pos,left_pos,worm_location,worms_eaten) elif event == curses.KEY_LEFT: left_pos-=1 if (left_pos<=0): left_pos=0 if (left_pos>=20): left_pos=20 worm_location, worms_eaten = update_screen(top_pos,left_pos,worm_location,worms_eaten) elif event == curses.KEY_RIGHT: left_pos+=1 if (left_pos<=0): left_pos=0 if (left_pos>=20): left_pos=20 worm_location, worms_eaten = update_screen(top_pos,left_pos,worm_location,worms_eaten) elif event == ord(" "): screen.clear() screen.addstr("Press 'q' to exit") curses.endwin() |

