def play(id, pos): try: p = Popen('../src/AI', stdin=PIPE, stdout=PIPE) res = '' while p.poll() is None: output = get_output(p) if 'ERROR' in output: raise Exception if 'CMD' not in output: continue if 'SURRENDER' in output: res = 'Congratz! AI surrendered.' if 'PLAY' in output: #[%d,%d] -> python list a = get_output(p) choice = map(int, a[a.find('[') + 1:a.find(']')].split(',')) Go.play(id, 'black', choice) res = str(choice) if 'GETINPUT' in output: p.stdin.write(str(pos) + '\n') if 'GETBOARD' in output: p.stdin.write(str(Go.get_board_as_list(id)) + '\n') if 'GETSCORE' in output: p.stdin.write(Go.estimate_score(id, 'black') + '\n') if 'PASS' in output: Go.ai_pass(id) res = 'AI passed' return res except Exception as e: print e return 'Error ... (ToT)' finally: if p.poll() is None: p.kill() p.wait()
def command(): id = hashlib.md5(get_remote_addr()).hexdigest() if (request.json['cmd'] == 'SURRENDER'): Go.restart(id) return jsonify({'res': 'OK'}) elif (request.json['cmd'] == 'GETBOARD'): return jsonify({'res': Go.get_board(id)}) elif (request.json['cmd'] == 'GETBOARDASLIST'): return jsonify({'res': Go.get_board_as_list(id)}) elif (request.json['cmd'] == 'GETSCORE'): return jsonify({'res': Go.estimate_score(id, 'white')}) elif (request.json['cmd'] == 'PLAY'): #check if Go.isWhiteTurn(id) and type(request.json['pos']) is list: Go.play(id, 'white', request.json['pos']) msg = AI.play(id, request.json['pos']) if 'Congratz' in msg: win(id) Go.soft_reset(id) return jsonify({'res': msg}) else: return jsonify({'res': 'Invalid play'}) elif (request.json['cmd'] == 'PASS'): #you can't pass :), so you should make AI surrender. return else: return