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):
27 fout = open ('log','a')
29 k = self.child.read(1, 10)
31 fout.write ('(r,c):(%d,%d)\n' %(self.term.cur_r, self.term.cur_c))
33 if self.term.cur_r == r and self.term.cur_c == c:
40 fout = open ('log','a')
42 c = self.child.read(1,10)
44 fout.write ('(r,c):(%d,%d)\n' %(self.term.cur_r, self.term.cur_c))
49 def do_move (self, move):
50 self.read_until_cursor (19,60)
51 self.child.sendline (move)
54 def get_computer_move (self):
56 i = self.child.expect (['\[17;59H', '\[17;58H'])
59 self.child.expect (REGEX_MOVE)
60 if len(self.child.after) < 4:
61 self.child.after = self.child.after + self.last_computer_move[3]
63 self.child.expect (REGEX_MOVE_PART)
64 self.child.after = self.last_computer_move[0] + self.child.after
65 print '', self.child.after
66 self.last_computer_move = self.child.after
67 return self.child.after
70 self.child.sendline ('switch')
72 def set_depth (self, depth):
73 self.child.sendline ('depth')
74 self.child.expect ('depth=')
75 self.child.sendline ('%d' % depth)
78 self.child.sendline ('quit')
83 white.read_until_cursor (19,60)
84 c1 = white.term.get_abs(17,58)
85 c2 = white.term.get_abs(17,59)
86 c3 = white.term.get_abs(17,60)
87 c4 = white.term.get_abs(17,61)
88 fout = open ('log','a')
89 fout.write ('Computer:%s%s%s%s\n' %(c1,c2,c3,c4))
92 white.read_until_cursor (19,60)
93 c1 = white.term.get_abs(17,58)
94 c2 = white.term.get_abs(17,59)
95 c3 = white.term.get_abs(17,60)
96 c4 = white.term.get_abs(17,61)
97 fout = open ('log','a')
98 fout.write ('Computer:%s%s%s%s\n' %(c1,c2,c3,c4))
102 #white.do_move ('b8a6')
103 #move_white = white.get_computer_move()
104 #print 'move white:', move_white
112 white.child.expect ('Your move is')
115 move_white = white.get_first_computer_move()
116 print 'first move white:', move_white
118 black.do_first_move (move_white)
119 move_black = black.get_first_computer_move()
120 print 'first move black:', move_black
122 white.do_move (move_black)
126 move_white = white.get_computer_move()
127 print 'move white:', move_white
129 black.do_move (move_white)
130 move_black = black.get_computer_move()
131 print 'move black:', move_black
133 white.do_move (move_black)