3 '''This demonstrates controlling a screen oriented application (curses).
4 It starts two instances of gnuchess and then pits them against each other.
11 REGEX_MOVE = '(?:[a-z]|\x1b\[C)(?:[0-9]|\x1b\[C)(?:[a-z]|\x1b\[C)(?:[0-9]|\x1b\[C)'
12 REGEX_MOVE_PART = '(?:[0-9]|\x1b\[C)(?:[a-z]|\x1b\[C)(?:[0-9]|\x1b\[C)'
16 def __init__(self, engine = "/usr/local/bin/gnuchess -a -h 1"):
17 self.child = pexpect.spawn (engine)
18 self.term = ANSI.ANSI ()
20 self.child.expect ('Chess')
21 if self.child.after != 'Chess':
22 raise IOError, 'incompatible chess program'
23 self.term.process_list (self.before)
24 self.term.process_list (self.after)
25 self.last_computer_move = ''
26 def read_until_cursor (self, r,c)
28 self.child.read(1, 60)
30 if self.term.cur_r == r and self.term.cur_c == c:
33 def do_first_move (self, move):
34 self.child.expect ('Your move is')
35 self.child.sendline (move)
36 self.term.process_list (self.before)
37 self.term.process_list (self.after)
40 def do_move (self, move):
41 read_until_cursor (19,60)
42 #self.child.expect ('\[19;60H')
43 self.child.sendline (move)
47 def get_first_computer_move (self):
48 self.child.expect ('My move is')
49 self.child.expect (REGEX_MOVE)
50 # print '', self.child.after
51 return self.child.after
53 def get_computer_move (self):
55 i = self.child.expect (['\[17;59H', '\[17;58H'])
58 self.child.expect (REGEX_MOVE)
59 if len(self.child.after) < 4:
60 self.child.after = self.child.after + self.last_computer_move[3]
62 self.child.expect (REGEX_MOVE_PART)
63 self.child.after = self.last_computer_move[0] + self.child.after
64 print '', self.child.after
65 self.last_computer_move = self.child.after
66 return self.child.after
69 self.child.sendline ('switch')
71 def set_depth (self, depth):
72 self.child.sendline ('depth')
73 self.child.expect ('depth=')
74 self.child.sendline ('%d' % depth)
77 self.child.sendline ('quit')
82 white.child.expect ('Your move is')
86 move_white = white.get_first_computer_move()
87 print 'first move white:', move_white
89 white.do_move ('e7e5')
90 move_white = white.get_computer_move()
91 print 'move white:', move_white
92 white.do_move ('f8c5')
93 move_white = white.get_computer_move()
94 print 'move white:', move_white
95 white.do_move ('b8a6')
96 move_white = white.get_computer_move()
97 print 'move white:', move_white
105 white.child.expect ('Your move is')
108 move_white = white.get_first_computer_move()
109 print 'first move white:', move_white
111 black.do_first_move (move_white)
112 move_black = black.get_first_computer_move()
113 print 'first move black:', move_black
115 white.do_move (move_black)
119 move_white = white.get_computer_move()
120 print 'move white:', move_white
122 black.do_move (move_white)
123 move_black = black.get_computer_move()
124 print 'move black:', move_black
126 white.do_move (move_black)