/Demo/curses/life.py

http://unladen-swallow.googlecode.com/ · Python · 216 lines · 182 code · 3 blank · 31 comment · 4 complexity · 53bbc2cd47417559ba14b81a8a8690e5 MD5 · raw file

  1. #!/usr/bin/env python
  2. # life.py -- A curses-based version of Conway's Game of Life.
  3. # Contributed by AMK
  4. #
  5. # An empty board will be displayed, and the following commands are available:
  6. # E : Erase the board
  7. # R : Fill the board randomly
  8. # S : Step for a single generation
  9. # C : Update continuously until a key is struck
  10. # Q : Quit
  11. # Cursor keys : Move the cursor around the board
  12. # Space or Enter : Toggle the contents of the cursor's position
  13. #
  14. # TODO :
  15. # Support the mouse
  16. # Use colour if available
  17. # Make board updates faster
  18. #
  19. import random, string, traceback
  20. import curses
  21. class LifeBoard:
  22. """Encapsulates a Life board
  23. Attributes:
  24. X,Y : horizontal and vertical size of the board
  25. state : dictionary mapping (x,y) to 0 or 1
  26. Methods:
  27. display(update_board) -- If update_board is true, compute the
  28. next generation. Then display the state
  29. of the board and refresh the screen.
  30. erase() -- clear the entire board
  31. makeRandom() -- fill the board randomly
  32. set(y,x) -- set the given cell to Live; doesn't refresh the screen
  33. toggle(y,x) -- change the given cell from live to dead, or vice
  34. versa, and refresh the screen display
  35. """
  36. def __init__(self, scr, char=ord('*')):
  37. """Create a new LifeBoard instance.
  38. scr -- curses screen object to use for display
  39. char -- character used to render live cells (default: '*')
  40. """
  41. self.state = {}
  42. self.scr = scr
  43. Y, X = self.scr.getmaxyx()
  44. self.X, self.Y = X-2, Y-2-1
  45. self.char = char
  46. self.scr.clear()
  47. # Draw a border around the board
  48. border_line = '+'+(self.X*'-')+'+'
  49. self.scr.addstr(0, 0, border_line)
  50. self.scr.addstr(self.Y+1,0, border_line)
  51. for y in range(0, self.Y):
  52. self.scr.addstr(1+y, 0, '|')
  53. self.scr.addstr(1+y, self.X+1, '|')
  54. self.scr.refresh()
  55. def set(self, y, x):
  56. """Set a cell to the live state"""
  57. if x<0 or self.X<=x or y<0 or self.Y<=y:
  58. raise ValueError, "Coordinates out of range %i,%i"% (y,x)
  59. self.state[x,y] = 1
  60. def toggle(self, y, x):
  61. """Toggle a cell's state between live and dead"""
  62. if x<0 or self.X<=x or y<0 or self.Y<=y:
  63. raise ValueError, "Coordinates out of range %i,%i"% (y,x)
  64. if self.state.has_key( (x,y) ):
  65. del self.state[x,y]
  66. self.scr.addch(y+1, x+1, ' ')
  67. else:
  68. self.state[x,y] = 1
  69. self.scr.addch(y+1, x+1, self.char)
  70. self.scr.refresh()
  71. def erase(self):
  72. """Clear the entire board and update the board display"""
  73. self.state = {}
  74. self.display(update_board=False)
  75. def display(self, update_board=True):
  76. """Display the whole board, optionally computing one generation"""
  77. M,N = self.X, self.Y
  78. if not update_board:
  79. for i in range(0, M):
  80. for j in range(0, N):
  81. if self.state.has_key( (i,j) ):
  82. self.scr.addch(j+1, i+1, self.char)
  83. else:
  84. self.scr.addch(j+1, i+1, ' ')
  85. self.scr.refresh()
  86. return
  87. d = {}
  88. self.boring = 1
  89. for i in range(0, M):
  90. L = range( max(0, i-1), min(M, i+2) )
  91. for j in range(0, N):
  92. s = 0
  93. live = self.state.has_key( (i,j) )
  94. for k in range( max(0, j-1), min(N, j+2) ):
  95. for l in L:
  96. if self.state.has_key( (l,k) ):
  97. s += 1
  98. s -= live
  99. if s == 3:
  100. # Birth
  101. d[i,j] = 1
  102. self.scr.addch(j+1, i+1, self.char)
  103. if not live: self.boring = 0
  104. elif s == 2 and live: d[i,j] = 1 # Survival
  105. elif live:
  106. # Death
  107. self.scr.addch(j+1, i+1, ' ')
  108. self.boring = 0
  109. self.state = d
  110. self.scr.refresh()
  111. def makeRandom(self):
  112. "Fill the board with a random pattern"
  113. self.state = {}
  114. for i in range(0, self.X):
  115. for j in range(0, self.Y):
  116. if random.random() > 0.5:
  117. self.set(j,i)
  118. def erase_menu(stdscr, menu_y):
  119. "Clear the space where the menu resides"
  120. stdscr.move(menu_y, 0)
  121. stdscr.clrtoeol()
  122. stdscr.move(menu_y+1, 0)
  123. stdscr.clrtoeol()
  124. def display_menu(stdscr, menu_y):
  125. "Display the menu of possible keystroke commands"
  126. erase_menu(stdscr, menu_y)
  127. stdscr.addstr(menu_y, 4,
  128. 'Use the cursor keys to move, and space or Enter to toggle a cell.')
  129. stdscr.addstr(menu_y+1, 4,
  130. 'E)rase the board, R)andom fill, S)tep once or C)ontinuously, Q)uit')
  131. def keyloop(stdscr):
  132. # Clear the screen and display the menu of keys
  133. stdscr.clear()
  134. stdscr_y, stdscr_x = stdscr.getmaxyx()
  135. menu_y = (stdscr_y-3)-1
  136. display_menu(stdscr, menu_y)
  137. # Allocate a subwindow for the Life board and create the board object
  138. subwin = stdscr.subwin(stdscr_y-3, stdscr_x, 0, 0)
  139. board = LifeBoard(subwin, char=ord('*'))
  140. board.display(update_board=False)
  141. # xpos, ypos are the cursor's position
  142. xpos, ypos = board.X//2, board.Y//2
  143. # Main loop:
  144. while (1):
  145. stdscr.move(1+ypos, 1+xpos) # Move the cursor
  146. c = stdscr.getch() # Get a keystroke
  147. if 0<c<256:
  148. c = chr(c)
  149. if c in ' \n':
  150. board.toggle(ypos, xpos)
  151. elif c in 'Cc':
  152. erase_menu(stdscr, menu_y)
  153. stdscr.addstr(menu_y, 6, ' Hit any key to stop continuously '
  154. 'updating the screen.')
  155. stdscr.refresh()
  156. # Activate nodelay mode; getch() will return -1
  157. # if no keystroke is available, instead of waiting.
  158. stdscr.nodelay(1)
  159. while (1):
  160. c = stdscr.getch()
  161. if c != -1:
  162. break
  163. stdscr.addstr(0,0, '/')
  164. stdscr.refresh()
  165. board.display()
  166. stdscr.addstr(0,0, '+')
  167. stdscr.refresh()
  168. stdscr.nodelay(0) # Disable nodelay mode
  169. display_menu(stdscr, menu_y)
  170. elif c in 'Ee':
  171. board.erase()
  172. elif c in 'Qq':
  173. break
  174. elif c in 'Rr':
  175. board.makeRandom()
  176. board.display(update_board=False)
  177. elif c in 'Ss':
  178. board.display()
  179. else: pass # Ignore incorrect keys
  180. elif c == curses.KEY_UP and ypos>0: ypos -= 1
  181. elif c == curses.KEY_DOWN and ypos<board.Y-1: ypos += 1
  182. elif c == curses.KEY_LEFT and xpos>0: xpos -= 1
  183. elif c == curses.KEY_RIGHT and xpos<board.X-1: xpos += 1
  184. else:
  185. # Ignore incorrect keys
  186. pass
  187. def main(stdscr):
  188. keyloop(stdscr) # Enter the main loop
  189. if __name__ == '__main__':
  190. curses.wrapper(main)