def startGame(board, playerSide, ai): parser = InputParser(board, playerSide) while True: print() print(board) print() if board.isCheckmate(): if board.currentSide == playerSide: print("Checkmate, you lost") else: print("Checkmate! You won!") return if board.isStalemate(): if board.currentSide == playerSide: print("Stalemate") else: print("Stalemate") return if board.currentSide == playerSide: move = playerMove(playerSide, board, 0, -99999, 99999) makeMove(move, board) else: move = ai.getBestMove() move.notation = parser.notationForMove(move) makeMove(move, board)
def startGame(board, playerSide, ai): parser = InputParser(board, playerSide) while True: print() print(board) print() if board.isCheckmate(): if board.currentSide == playerSide: print("Checkmate, you lost") else: print("Checkmate! You won!") return if board.isStalemate(): if board.currentSide == playerSide: print("Stalemate") else: print("Stalemate") return if board.currentSide == playerSide: #printPointAdvantage(board) try: move = getAlphaBetaMove(board, parser)[1] #move = alphaBetaMove(board, parser, -999999, 999999, 3)[1] except ValueError as error: print("%s" % error) continue makeMove(move, board) else: print("AI thinking...") move = ai.getBestMove() move.notation = parser.notationForMove(move) makeMove(move, board)
def startGame(board, playerSide, ai): parser = InputParser(board, playerSide) while True: print() print(board) print() if board.isCheckmate(): if board.currentSide == playerSide: print("Checkmate, you lost") else: print("Checkmate! You won!") return if board.isStalemate(): if board.currentSide == playerSide: print("Stalemate") else: print("Stalemate") return if board.currentSide == playerSide: print("Player making random move...") move = getRandomMove(board, parser) makeMove(move, board) else: print("AI thinking...") move = ai.getBestMove() move.notation = parser.notationForMove(move) makeMove(move, board)
def startGame(board, playerSide, ai): parser = InputParser(board, playerSide) while True: print() print(board) print() if board.isCheckmate(): if board.currentSide == playerSide: print("Checkmate, you lost") else: print("Checkmate! You won!") return if board.isStalemate(): if board.currentSide == playerSide: print("Stalemate") else: print("Stalemate") return if board.currentSide == playerSide: # printPointAdvantage(board) move = None command = input("It's your move." " Type '?' for options. ? ") if command.lower() == 'u': undoLastTwoMoves(board) continue elif command.lower() == '?': printCommandOptions() continue elif command.lower() == 'l': printAllLegalMoves(board, parser) continue elif command.lower() == 'r': move = getRandomMove(board, parser) elif command.lower() == 'exit' or command.lower() == 'quit': return try: move = parser.parse(command) except ValueError as error: print("%s" % error) continue makeMove(move, board) else: print("AI thinking...") move = ai.getBestMove() print(move) # TODO we have done check cordinate system returns # printAllLegalMoves(board, InputParser(board, False)) # TODO we will hack to different notation move.notation = parser.notationForMove(move) print("Ai says", move.notation) makeMove(move, board) moveMotor(move)
class VagoCore(): '''Controlador principal definido para procesar los datos''' def __init__(self): self.inputParser = InputParser() self.workData = WorkData() self.fileProcessing = FileProcessing() self.dataProcessing = DataProcessing() self.vagoCoreOutput = VagoCoreOutput() def run(self): self.process_input_file() self.prepare_workdata() def process_input_file(self): ''' Lectura del archivo y almacenamiento en la clase WorkData Lee el archivo y almacena las lineas en la lista workdata.input_file_lines ''' # Mostrar en pantalla proceso iniciado# self.vagoCoreOutput.print_input_file_processing_started() # -------------------------------------# _check_file_existance_result = self.inputParser.check_if_file_exists() if _check_file_existance_result: self.workData.input_file_path = _check_file_existance_result self.workData.input_file_type = self.inputParser.get_file_type() _input_file_lines = self.fileProcessing.read_input_file( self.workData.input_file_path, self.workData.input_file_type) if _input_file_lines: self.workData.input_file_lines = _input_file_lines else: sys.exit() else: sys.exit() def prepare_workdata(self): ''' Prepara al objeto workdata que contiene los datos necesarios para generar los archivos para graficar ''' # Mostrar en pantalla proceso iniciado# self.vagoCoreOutput.print_work_data_processing_started() # -------------------------------------# self.workData.number_of_lines = len(self.workData.input_file_lines) self.workData.passwords_table = self.dataProcessing.convert_to_password_hashtable( self.workData.input_file_lines, self.workData.input_file_type) self.workData.number_of_passwords = len(self.workData.passwords_table) # Ejemplo de impresión for _key in self.workData.passwords_table: print _key + ":" + str( self.workData.passwords_table[_key].freq) + ":" + str( self.workData.passwords_table[_key].text) + ":" + str( self.workData.passwords_table[_key].mask) + ":" + str( self.workData.passwords_table[_key].hash)
def process_file(filename): parser = InputParser() ridelist, bonus, simsteps, num_rows, num_cols, cars = parser.parse( "../input/" + filename + ".in") cmd = CommandCenter(ridelist, simsteps, cars, bonus) cmd.planCars() output = cmd.getOutput() outputfile = open("../output/" + filename + ".out", 'w') outputfile.write(output)
def startGame(board, playerSide, ai): parser = InputParser(board, playerSide) while True: print(board) print() if board.isCheckmate(): if board.currentSide == playerSide: print("Checkmate, you lost") else: print("Checkmate! You won!") return if board.isStalemate(): if board.currentSide == playerSide: print("Stalemate") else: print("Stalemate") return if board.currentSide == playerSide: printPointAdvantage(board) move = None command = input( "It's your move, what do you want to do? Type '?' for options. " ).lower() if command == 'u': undoLastTwoMoves(board) continue elif command == '?': printCommandOptions() continue elif command == 'l': printAllLegalMoves(board, parser) continue elif command == 'r': move = getRandomMove(board, parser) else: move = parser.moveForShortNotation(command) if move: makeMove(move, board) else: print( "Couldn't parse input, make sure you entered a valid command or move" ) else: print("AI thinking...") move = ai.getBestMove() move.notation = parser.notationForMove(move) makeMove(move, board)
def startGame(board, playerSide, ai): parser = InputParser(board, playerSide) while True: print() print(board) print() if board.isCheckmate(): if board.currentSide == playerSide: print("Checkmate, you lost") else: print("Checkmate! You won!") return if board.isStalemate(): if board.currentSide == playerSide: print("Stalemate") else: print("Stalemate") return if board.currentSide == playerSide: # printPointAdvantage(board) # move = None # command = input("It's your move." # " Type '?' for options. ? ") # if command.lower() == 'u': # undoLastTwoMoves(board) # continue # elif command.lower() == '?': # printCommandOptions() # continue # elif command.lower() == 'l': # printAllLegalMoves(board, parser) # continue # elif command.lower() == 'r': # move = getRandomMove(board, parser) # elif command.lower() == 'exit' or command.lower() == 'quit': # return try: move = getRandomMove(board, parser) except ValueError as error: print("%s" % error) continue makeMove(move, board) else: print("AI thinking...") move = ai.getBestMove() move.notation = parser.notationForMove(move) makeMove(move, board)
def startGame(board, playerSide, ai): parser = InputParser(board, playerSide) while True: print() print(board) print() if board.isCheckmate(): if board.currentSide == playerSide: print("Checkmate, you lost") else: print("Checkmate! You won!") return if board.isStalemate(): if board.currentSide == playerSide: print("Stalemate") else: print("Stalemate") return if board.currentSide == playerSide: # printPointAdvantage(board) move = None command = input("It's your move." " Type '?' for options. ? ") if command.lower() == 'u': undoLastTwoMoves(board) continue elif command.lower() == '?': printCommandOptions() continue elif command.lower() == 'l': printAllLegalMoves(board, parser) continue elif command.lower() == 'r': move = getRandomMove(board, parser) elif command.lower() == 'exit' or command.lower() == 'quit': return try: move = parser.parse(command) except ValueError as error: print("%s" % error) continue makeMove(move, board) else: print("AI thinking...") move = ai.getBestMove() move.notation = parser.notationForMove(move) makeMove(move, board)
def startGame(board, playerSide, ai): parser = InputParser(board, playerSide) while True: print(board) print() if board.isCheckmate(): if board.currentSide == playerSide: print("ВЫ ПРОИГРАЛИ!") else: print("ВЫ ПОБЕДИЛИ!") return if board.isStalemate(): if board.currentSide == playerSide: print("ПАТ") else: print("ПАТ") return if board.currentSide == playerSide: # printPointAdvantage(board) - доделать move = None command = input("Ваша очередь ходить." " Нажмите '?' для вызова меню. ").lower() if command == 'u': undoLastTwoMoves(board) continue elif command == '?': printCommandOptions() continue elif command == 'l': printAllLegalMoves(board, parser) continue elif command == 'r': move = getRandomMove(board, parser) elif command == 'quit': return else: move = parser.moveForShortNotation(command) if move: makeMove(move, board) else: print("Некорректный синтаксический ввод, повторите запрос") else: print("AI думает...") move = ai.getBestMove() move.notation = parser.notationForMove(move) makeMove(move, board)
def startGame(board, playerSide, ai): parser = InputParser(board, playerSide) while True: print(board) print() if board.isCheckmate(): if board.currentSide == playerSide: print("Checkmate, you lost") else: print("Checkmate! You won!") return if board.isStalemate(): if board.currentSide == playerSide: print("Stalemate") else: print("Stalemate") return if board.currentSide == playerSide: printPointAdvantage(board) move = None command = input("It's your move." " Type '?' for options. ? ").lower() if command == 'u': undoLastTwoMoves(board) continue elif command == '?': printCommandOptions() continue elif command == 'l': printAllLegalMoves(board, parser) continue elif command == 'r': move = getRandomMove(board, parser) elif command == 'quit': return else: move = parser.moveForShortNotation(command) if move: makeMove(move, board) else: print("Couldn't parse input, enter a valid command or move.") else: print("AI thinking...") move = ai.getBestMove() move.notation = parser.notationForMove(move) makeMove(move, board)
def loadGame(self, filename): board = Board() board.pieces.clear() parserWhite = InputParser(board, WHITE) parserBlack = InputParser(board, BLACK) gameFile = open(filename, "r") lines = [] for line in gameFile: lines.append(line) gameFile.close() histStr = lines[8] currentSide = ('W' == histStr[0]) board.currentSide = currentSide pieceDict = dict.fromkeys(['p', '0', '1', '6', '7'], Pawn) pieceDict.update(dict.fromkeys(['k'], Knight)) pieceDict.update(dict.fromkeys(['b'], Bishop)) pieceDict.update(dict.fromkeys(['r', '2', '3', '8', '9'], Rook)) pieceDict.update(dict.fromkeys(['q'], Queen)) pieceDict.update(dict.fromkeys(['k', '4', '5', 'm'], King)) for i in range(8): for j, p in enumerate(lines[i]): if p == '-': continue coords = C(j, i) movesMade = 0 if p.isalpha(): side = p.isupper() #WHITE if True, else BLACK if p.lower() == 'm': #king on either side movesMade = 2 #movesMade += 1 + int(p.isupper()) #movesMade = 1 or 2 based on p's case #if p.lower() in "ab" and ((side == WHITE and coords[1] == 1) \ # or (side == BLACK and coords[1] == 6)): #proves p is a pawn that hasn't moved # movesMade = 0 else: numP = int(p) side = (numP % 2 == 0) #WHITE if True, else BLACK movesMade = 1 + int(numP > 5) board.pieces.extend(pieceDict[p.lower()](board, side, coords, movesMade)) #TODO: Process last move to enter into board.history return board
def setInputs(self, arg_list): self.inputs_list = [] for arg in arg_list: if not arg[1] or arg[1] == DataType.UNKNOWN: continue self.inputs_list.append(InputParser.parseInput(arg[0], arg[1])) return self.inputs_list
def main(): if len(sys.argv) != 3: print "Spatne parametry programu. " print "Program ocekava 1. parametr soubor s instanci RCPSP (.sm) a 2. parametr pocet aktivit v dane instanci (bez aktivity zahajeni a ukonceni projektu)." exit(1) fileName = sys.argv[1] n = int(sys.argv[2]) try: succ, jbs, cap, dur = InputParser.ParseInput(fileName) except: print "Chyba pri zpracovavani vstupniho souboru." exit(2) #cp = CriticalPath(succ, dur); #print fileName, ": ", cp.ComputeCRLB() bestMakespan = 0 try: bestMakespan = AntCycle(jbs[0], jbs, cap, n, succ, dur) except: print "Chyba pri hledani reseni, zkontrolujte parametry." exit(2) if bestMakespan == -1: print "Chyba, nalezene reseni nesplnuje omezujici podminky" exit(2) print fileName, ": ", bestMakespan
def setOutput(self, res): self.expected_res = None if not res[1] or res[1] == DataType.UNKNOWN: return self.expected_res self.expected_res = InputParser.parseInput(res[0], res[1]) self.output_type = res[1] return self.expected_res
def twoPlayerGame(board): WHITE = True BLACK = False parserWhite = InputParser(board, WHITE) parserBlack = InputParser(board, BLACK) while True: print() print(board) print() if board.isCheckmate(): print("Checkmate") return if board.isStalemate(): print("Stalemate") return # printPointAdvantage(board) if board.currentSide == WHITE: parser = parserWhite else: parser = parserBlack move = None command = input("It's your move, {}.".format(board.currentSideRep()) + \ " Type '?' for options. ? ") if command.lower() == 'u': undoLastTwoMoves(board) continue elif command.lower() == '?': printCommandOptions() continue elif command.lower() == 'l': printAllLegalMoves(board, parser) continue elif command.lower() == 'r': move = getRandomMove(board, parser) elif command.lower() == 'exit' or command.lower() == 'quit': return try: move = parser.parse(command) except ValueError as error: print("%s" % error) continue makeMove(move, board)
def process_file(filename): parser = InputParser() parser.parse("in/" + filename + ".in") manager = CacheManager() manager.videos = parser.getVideos() manager.caches = parser.getCaches() manager.endpoints = parser.getEndPoints() manager.requests = parser.getRequests() manager.FillCaches() outputstring = manager.OutputString() outputfile = open("out/" + filename + ".out", 'w') outputfile.write(outputstring)
class AI: depth = 1 board = None side = None num_analyzed_moves = 0 def __init__(self, board, side, depth): self.board = board self.side = side self.depth = depth self.parser = InputParser(self.board, self.side) def getFirstMove(self, side): move = list(self.board.get_all_legal_moves(side))[0] return move def getAllMovesLegalConcurrent(self, side): p = Pool(8) unfilteredMovesWithBoard = \ [(move, copy.deepcopy(self.board)) for move in self.board.getAllMovesUnfiltered(side)] legal_moves = p.starmap(self.returnMoveIfLegal, unfilteredMovesWithBoard) p.close() p.join() return list(filter(None, legal_moves)) def minChildrenOfNode(self, node): lowestNodes = [] for child in node.children: if not lowestNodes: lowestNodes.append(child) elif child < lowestNodes[0]: lowestNodes = [] lowestNodes.append(child) elif child == lowestNodes[0]: lowestNodes.append(child) return lowestNodes def maxChildrenOfNode(self, node): highestNodes = [] for child in node.children: if not highestNodes: highestNodes.append(child) elif child < highestNodes[0]: highestNodes = [] highestNodes.append(child) elif child == highestNodes[0]: highestNodes.append(child) return highestNodes def _populate_child_nodes(self, node): node.advantage_points = self.board.get_advantage_points(self.side) node.depth = node.get_depth() if node.depth == self.depth: return side = self.board.player # which side is in turn to play legal_moves = self.board.get_all_legal_moves(side) if not legal_moves: if self.board.is_checkmate(): node.move.checkmate = True return elif self.board.is_stalemate(): node.move.stalemate = True node.advantage_points = 0 return raise Exception() for move in legal_moves: self.num_analyzed_moves += 1 node.children.append(MoveNode(move, [], node)) self.board.make_move(move) self._populate_child_nodes(node.children[-1]) self.board.undo_last_move() def _gen_move_tree(self): ''' get AI's entire move tree in current status ''' move_tree = [] for move in self.board.get_all_legal_moves(self.side): move_tree.append(MoveNode(move, [], None)) for node in move_tree: self.board.make_move(node.move) self._populate_child_nodes(node) self.board.undo_last_move() return move_tree def _get_advantage_points(self, node): ''' get AI's advantage points over human ''' if node.children: for child in node.children: child.advantage_points = self._get_advantage_points(child) # If the depth is divisible by 2, # it's a move for the AI's side, so return max if node.children[0].depth % 2 == 1: return(max(node.children).advantage_points) else: return(min(node.children).advantage_points) else: return node.advantage_points def _get_best_move(self, move_tree): ''' get best move with the given move tree You should not call this function directly, instead, call the wrapper function get_best_move(self) ''' best_nodes = [] # best move nodes for node in move_tree: node.advantage_points = self._get_advantage_points(node) if not best_nodes: best_nodes.append(node) elif node > best_nodes[0]: best_nodes = [] best_nodes.append(node) elif node == best_nodes[0]: best_nodes.append(node) return [node.move for node in best_nodes] def get_best_move(self): ''' get AI's best move in current status ''' move_tree = self._gen_move_tree() best_moves = self._get_best_move(move_tree) rand_best_move = random.choice(best_moves) rand_best_move.notation = self.parser.get_move_code(rand_best_move) return rand_best_move def make_best_move(self): self.board.make_move(self.get_best_move()) def _is_valid_move(self, move, side): for m in self.board.get_all_legal_moves(side): if move == m: return True return False def get_random_move(self): ''' get a random move from all legal moves ''' moves = list(self.board.get_all_legal_moves(self.side)) return random.choice(moves) def make_random_move(self): ''' AI makes a random move for next step ''' moveToMake = self.get_random_move() self.board.make_move(moveToMake)
if self.ticksToFree > 0: self.ticksToFree -= 1 def get_free_cars(): result = [] for car in cars: if car.ticksToFree == 0: result.append(car) return result possibleRides = [] impossibleRides = [] inputData = InputParser(FILE + ".in") rows, columns, vehicles, numebrOfRides, bonusOnTime, steps = inputData.readLine( ) inputData.close() rides = pd.read_table(FILE + ".in", sep=' ') counter = 0 for i in rides.values: if (abs(i[2] - i[0]) + abs(i[3] - i[1])) >= abs(i[5] - i[4]): impossibleRides.append(np.insert(i, 0, counter)) else: possibleRides.append(np.insert(i, 0, counter)) counter += 1 # Sorting
def __init__(self): self.inputParser = InputParser() self.workData = WorkData() self.fileProcessing = FileProcessing() self.dataProcessing = DataProcessing() self.vagoCoreOutput = VagoCoreOutput()
from OutputModule import OutputModule #Python modules import string import sys ########################## Begin ############################ if (len(sys.argv) == 2 and sys.argv[1] == "--help"): print "Usage: ./COCOAss cocoaInputFile.txt baseCOCOADescriptionFile output.txt" sys.exit() if (len(sys.argv) != 4): print "Bad usage. Type ./COCOAss --help" sys.exit() #Names nameOfCocoa = sys.argv[2] nameOfInput = sys.argv[1] nameOfCVS = sys.argv[3] #InputParser myParser = InputParser(nameOfInput, nameOfCocoa) #TagExpander myExpander = TagExpander(myParser.read()) expanded = myExpander.expand() #JobManager manager = JobManager(nameOfCocoa, expanded) output = manager.loop() #WriteOutput outputObject = OutputModule(nameOfCVS, output) outputObject.write()
class AI: depth = 1 board = None side = None movesAnalyzed = 0 def __init__(self, board, side, depth): self.board = board self.side = side self.depth = depth self.parser = InputParser(self.board, self.side) def getFirstMove(self, side): move = list(self.board.getAllMovesLegal(side))[0] return move def getAllMovesLegalConcurrent(self, side): p = Pool(8) unfilteredMovesWithBoard = \ [(move, copy.deepcopy(self.board)) for move in self.board.getAllMovesUnfiltered(side)] legalMoves = p.starmap(self.returnMoveIfLegal, unfilteredMovesWithBoard) p.close() p.join() return list(filter(None, legalMoves)) def minChildrenOfNode(self, node): lowestNodes = [] for child in node.children: if not lowestNodes: lowestNodes.append(child) elif child < lowestNodes[0]: lowestNodes = [] lowestNodes.append(child) elif child == lowestNodes[0]: lowestNodes.append(child) return lowestNodes def maxChildrenOfNode(self, node): highestNodes = [] for child in node.children: if not highestNodes: highestNodes.append(child) elif child < highestNodes[0]: highestNodes = [] highestNodes.append(child) elif child == highestNodes[0]: highestNodes.append(child) return highestNodes def getRandomMove(self): legalMoves = list(self.board.getAllMovesLegal(self.side)) randomMove = random.choice(legalMoves) return randomMove def generateMoveTree(self): moveTree = [] for move in self.board.getAllMovesLegal(self.side): moveTree.append(MoveNode(move, [], None)) for node in moveTree: self.board.makeMove(node.move) self.populateNodeChildren(node) self.board.undoLastMove() return moveTree def populateNodeChildren(self, node): node.pointAdvantage = self.board.getPointAdvantageOfSide(self.side) node.depth = node.getDepth() if node.depth == self.depth: return side = self.board.currentSide legalMoves = self.board.getAllMovesLegal(side) if not legalMoves: if self.board.isCheckmate(): node.move.checkmate = True return elif self.board.isStalemate(): node.move.stalemate = True node.pointAdvantage = 0 return raise Exception() for move in legalMoves: self.movesAnalyzed += 1 node.children.append(MoveNode(move, [], node)) self.board.makeMove(move) self.populateNodeChildren(node.children[-1]) self.board.undoLastMove() def getOptimalPointAdvantageForNode(self, node): if node.children: for child in node.children: child.pointAdvantage = \ self.getOptimalPointAdvantageForNode(child) # If the depth is divisible by 2, # it's a move for the AI's side, so return max if node.children[0].depth % 2 == 1: return(max(node.children).pointAdvantage) else: return(min(node.children).pointAdvantage) else: return node.pointAdvantage def getBestMove(self): moveTree = self.generateMoveTree() bestMoves = self.bestMovesWithMoveTree(moveTree) randomBestMove = random.choice(bestMoves) randomBestMove.notation = self.parser.notationForMove(randomBestMove) return randomBestMove def makeBestMove(self): self.board.makeMove(self.getBestMove()) def bestMovesWithMoveTree(self, moveTree): bestMoveNodes = [] for moveNode in moveTree: moveNode.pointAdvantage = \ self.getOptimalPointAdvantageForNode(moveNode) if not bestMoveNodes: bestMoveNodes.append(moveNode) elif moveNode > bestMoveNodes[0]: bestMoveNodes = [] bestMoveNodes.append(moveNode) elif moveNode == bestMoveNodes[0]: bestMoveNodes.append(moveNode) return [node.move for node in bestMoveNodes] def traverseTreeForBestMove(self, side, moveTree, layersTraversed, bestMovesFound): if layersLeft < self.depth: for move in moveTree: board.makeMove(move) return traverseTreeForBestMove(moveTree[move], layersLeft+1, bestMoveFound) if layersLeft == self.depth: for move in moveTree: board.makeMove(move) pointAdvantage = board.getPointAdvantageOfSide(side) previousBestAdvantage = 1 return move def isValidMove(self, move, side): for legalMove in self.board.getAllMovesLegal(side): if move == legalMove: return True return False def makeRandomMove(self): moveToMake = self.getRandomMove() self.board.makeMove(moveToMake)
# read information from config file config = configparser.ConfigParser() config.read('config.ini') requested_url = config['DEFAULT']['RequestedUrl'] max_requests = int(config['DEFAULT']['Limit_requests']) test_file_dir = config['DEFAULT']['TestFileDir'] result_file_dir = config['DEFAULT']['ResultFileDir'] # argument parse and input parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('--test_file', dest='path of test file') args = parser.parse_args() InputParser = InputParser() if not args.test_file: # generate samples sampleGenerator = SampleGenerator() test_file_path = sampleGenerator.generate_sample_files(test_file_dir, dup=False) # read ids ids = InputParser.parse_ids_from_file(test_file_path) else: try: ids = InputParser.parse_ids_from_file(args.test_file) except: logger.info( "Error happen, --test_file not valid! Program terminated.")
from InputParser import InputParser if __name__ == "__main__": parser = InputParser() parser.parse("Inputfiles/small.in")
import sys from InputParser import InputParser flag = True command = '' ip = InputParser('CenturyClub') while(flag): sys.stdout.write('>>>') command = raw_input() if(command == 'exit'): flag = False else: print ip.parse(command.split(" "))
class AI: depth = 1 board = None side = None movesAnalyzed = 0 def __init__(self, board, side, depth): self.board = board self.side = side self.depth = depth self.parser = InputParser(self.board, self.side) def getFirstMove(self, side): move = list(self.board.getAllMovesLegal(side))[0] return move # создаем многопроцессорный пул, который находит возможные ходы и возвращает их список def getAllMovesLegalConcurrent(self, side): p = Pool(8) unfilteredMovesWithBoard = \ [(move, copy.deepcopy(self.board)) for move in self.board.getAllMovesUnfiltered(side)] legalMoves = p.starmap(self.returnMoveIfLegal, unfilteredMovesWithBoard) p.close() p.join() return list(filter(None, legalMoves)) def minChildrenOfNode(self, node): lowestNodes = [] for child in node.children: if not lowestNodes: lowestNodes.append(child) elif child < lowestNodes[0]: lowestNodes = [] lowestNodes.append(child) elif child == lowestNodes[0]: lowestNodes.append(child) return lowestNodes def maxChildrenOfNode(self, node): highestNodes = [] for child in node.children: if not highestNodes: highestNodes.append(child) elif child < highestNodes[0]: highestNodes = [] highestNodes.append(child) elif child == highestNodes[0]: highestNodes.append(child) return highestNodes def getRandomMove(self): legalMoves = list(self.board.getAllMovesLegal(self.side)) randomMove = random.choice(legalMoves) return randomMove # генерация дерева решений def generateMoveTree(self): moveTree = [] for move in self.board.getAllMovesLegal(self.side): moveTree.append(MoveNode(move, [], None)) for node in moveTree: self.board.makeMove(node.move) self.populateNodeChildren(node) self.board.undoLastMove() return moveTree def populateNodeChildren(self, node): node.pointAdvantage = self.board.getPointAdvantageOfSide(self.side) node.depth = node.getDepth() if node.depth == self.depth: return side = self.board.currentSide legalMoves = self.board.getAllMovesLegal(side) if not legalMoves: if self.board.isCheckmate(): node.move.checkmate = True return elif self.board.isStalemate(): node.move.stalemate = True node.pointAdvantage = 0 return raise Exception() for move in legalMoves: self.movesAnalyzed += 1 node.children.append(MoveNode(move, [], node)) self.board.makeMove(move) self.populateNodeChildren(node.children[-1]) self.board.undoLastMove() def getOptimalPointAdvantageForNode(self, node): if node.children: for child in node.children: child.pointAdvantage = \ self.getOptimalPointAdvantageForNode(child) # Если глубина делится на 2, # Это ход для AI ----> возвращаем max if node.children[0].depth % 2 == 1: return(max(node.children).pointAdvantage) else: return(min(node.children).pointAdvantage) else: return node.pointAdvantage # находит лучший ход def getBestMove(self): moveTree = self.generateMoveTree() bestMoves = self.bestMovesWithMoveTree(moveTree) randomBestMove = random.choice(bestMoves) randomBestMove.notation = self.parser.notationForMove(randomBestMove) return randomBestMove # выбирает лучший ход def makeBestMove(self): self.board.makeMove(self.getBestMove()) def bestMovesWithMoveTree(self, moveTree): bestMoveNodes = [] for moveNode in moveTree: moveNode.pointAdvantage = \ self.getOptimalPointAdvantageForNode(moveNode) if not bestMoveNodes: bestMoveNodes.append(moveNode) elif moveNode > bestMoveNodes[0]: bestMoveNodes = [] bestMoveNodes.append(moveNode) elif moveNode == bestMoveNodes[0]: bestMoveNodes.append(moveNode) return [node.move for node in bestMoveNodes] def isValidMove(self, move, side): for legalMove in self.board.getAllMovesLegal(side): if move == legalMove: return True return False def makeRandomMove(self): moveToMake = self.getRandomMove() self.board.makeMove(moveToMake)
if groups[autos[6]].set == Group.VERTICAL and groups[ autos[6]].number < q: groups[autos[6]].number += 1 self.state = groups[autos[6]].state groups[autos[6]].autos.append(self) return def changeState(self, autos, stepCounter, stepInfo): if stepCounter == 0: self.firstStep(autos, stepCounter, stepInfo) else: self.secondStep(autos, stepCounter, stepInfo) inputData = InputParser(PATH + FILE + ".in") rows, columns, p, q = inputData.readLine() autos = [] for i in range(rows): autos_row = [] row = inputData.readLine()[0] x = 0 for ing in row: autos_row.append(PizzaAuto(x, i, PizzaAuto.ING[ing])) x += 1 autos.append(autos_row) inputData.close() pizza = CellularAutomaton(autos) pizza.doStep(stepInfo=(p, q))
def startGame(board, playerSide, ai): parser = InputParser(board, playerSide) previous_count = 0 count = 0 while True: if len(open(op_input).readlines()) == 0: break else: print("Please Clear the op_input.txt first!") while True: if board.isCheckmate(): if board.currentSide == playerSide: print("--------------------") print("AI: Today is a beautiful day!") print("--------------------") else: print("--------------------") print("AI: NOOOOOOOOOOOOOOOOOOOOOOOOOO!") print("--------------------") return if board.isStalemate(): if board.currentSide == playerSide: print("--------------------") print("AI: Live together? See you next time") print("--------------------") else: print("--------------------") print("AI: Live together? See you next time") print("--------------------") return if board.currentSide == playerSide: # printPointAdvantage(board) move = None command = input("It's your move." " Type '?' for options. ? ") if command.lower() == 'u': undoLastTwoMoves(board) continue elif command.lower() == '?': printCommandOptions() continue elif command.lower() == 'l': printAllLegalMoves(board, parser) continue elif command.lower() == 'r': move = getRandomMove(board, parser) elif command.lower() == 'exit' or command.lower() == 'quit': return try: move = parser.parse(command) print("move: ", command) except ValueError as error: print("%s" % error) continue move = getRandomMove(board, parser) while True: previous_count = count count = len(open(op_input).readlines()) if count - previous_count > 0: with open(op_input) as f: read_data = f.read().splitlines() op_latest_input = read_data[-1] print("--------------------") print("BELOW IS YOUR MOVE") print("--------------------") move = parser.parse(op_latest_input) f.closed break makeMove(move, board) else: print("--------------------") print("AI: I will beat you!") print("--------------------") move = ai.getBestMove() move.notation = parser.notationForMove(move) makeMove(move, board) with open(AI_output, 'a+') as f: f.write(move.notation + '\n') f.closed # move = getRandomMove(board, parser) print(board)
def minUIGame(board, playerSide, ai, useCamera): WHITE = True BLACK = False parserWhite = InputParser(board, WHITE) parserBlack = InputParser(board, BLACK) parser = parserWhite physInputWhite = PhysInput(WHITE) physInputBlack = PhysInput(BLACK) physInput = physInputWhite PvP = not ai chessGUI = None if __name__ != '__main__': chessGUI = Gui.GUI(physInput) while True: if not chessGUI: if showBoard: print() print(board) print() if board.isCheckmate(): if PvP: if board.currentSide == WHITE: #white has no legal moves winner = 'Black' else: winner = 'White' display("Checkmate! {} wins!".format(winner), chessGUI, title="Game Over") elif board.currentSide == playerSide: display("Checkmate, you lost", chessGUI, title="Game Over") else: display("Checkmate! You won!", chessGUI, title="Game Over") return if board.isStalemate(): display("Stalemate", chessGUI, title="Game Over") return if PvP or board.currentSide == playerSide: # printPointAdvantage(board) if board.currentSide == WHITE: parser = parserWhite physInput = physInputWhite plRep = 'Wh' else: parser = parserBlack physInput = physInputBlack plRep = 'Bl' if not PvP: plRep = 'Pl' if chessGUI: chessGUI.physInput = physInput command = physInput.getPlayerMove(useCamera) else: command = input(plRep + " : ") move = None if command.lower() == 'u': undoLastTwoMoves(board) continue elif command.lower() == '?': printCommandOptions() continue elif command.lower() == 'l': printAllLegalMoves(board, parser) continue elif command.lower() == 'r': move = getRandomMove(board, parser) elif command.lower() == 'p': print() print(board) print() continue elif command.lower() == 's' or command.lower() == 'save': saveGame(board) continue elif command.lower() == 'exit' or command.lower() == 'quit' \ or command.lower() == 'q': return try: move = parser.convertInput(command) except ValueError as error: display("{}\nCorrect your move and press OK.".format(error), chessGUI, title="Error") continue makeMoveReadable(move, board, False) if PvP: player = "WHITE" if board.currentSide == BLACK: player = "BLACK" if useCamera: physInput.promptCamera(True) chessGUI.showinfo("Next move", "{}, make your next move and press OK.".format(player)) else: #print("AI thinking...") move = ai.getBestMove() move.notation = parser.notationForMove(move) makeMoveReadable(move, board, True, chessGUI)
newReed = [[0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], \ [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], \ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], \ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], \ [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], \ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], \ [0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0], \ [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0]] table12 = ChessTable(1) currentBoard = newReed move = table12.getMoveNew(board12, currentBoard) print(move) print() parser = InputParser(board12, WHITE) notation = parser.notationForMove(move) if notation == "e4": numPassed = numPassed + 1 board12.makeChosenMove(move) print("Passed move 1 of 30") print() print(board12) else: print("Failed move 1 of 30") enter = input("Enter to continue") #---------------------- 2 of 30 ---------------------------# newReed = [[0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], \
class AI: depth = 1 board = None side = None movesAnalyzed = 0 def __init__(self, board, side, depth): self.board = board self.side = side self.depth = depth self.parser = InputParser(self.board, self.side) def getFirstMove(self, side): move = list(self.board.getAllMovesLegal(side))[0] return move def getAllMovesLegalConcurrent(self, side): p = Pool(8) unfilteredMovesWithBoard = [ (move, copy.deepcopy(self.board)) for move in self.board.getAllMovesUnfiltered(side) ] legalMoves = p.starmap(self.returnMoveIfLegal, unfilteredMovesWithBoard) p.close() p.join() return list(filter(None, legalMoves)) def minChildrenOfNode(self, node): lowestNodes = [] for child in node.children: if not lowestNodes: lowestNodes.append(child) elif child < lowestNodes[0]: lowestNodes = [] lowestNodes.append(child) elif child == lowestNodes[0]: lowestNodes.append(child) return lowestNodes def maxChildrenOfNode(self, node): highestNodes = [] for child in node.children: if not highestNodes: highestNodes.append(child) elif child < highestNodes[0]: highestNodes = [] highestNodes.append(child) elif child == highestNodes[0]: highestNodes.append(child) return highestNodes def getRandomMove(self): legalMoves = list(self.board.getAllMovesLegal(self.side)) randomMove = random.choice(legalMoves) return randomMove def generateMoveTree(self): moveTree = [] for move in self.board.getAllMovesLegal(self.side): moveTree.append(MoveNode(move, [], None)) for node in moveTree: self.board.makeMove(node.move) self.populateNodeChildren(node) self.board.undoLastMove() return moveTree def populateNodeChildren(self, node): node.pointAdvantage = self.board.getPointAdvantageOfSide(self.side) node.depth = node.getDepth() if node.depth == self.depth: return side = self.board.currentSide legalMoves = self.board.getAllMovesLegal(side) if not legalMoves: if self.board.isCheckmate(): node.move.checkmate = True return elif self.board.isStalemate(): node.move.stalemate = True node.pointAdvantage = 0 return raise Exception() for move in legalMoves: self.movesAnalyzed += 1 node.children.append(MoveNode(move, [], node)) self.board.makeMove(move) self.populateNodeChildren(node.children[-1]) self.board.undoLastMove() def getOptimalPointAdvantageForNode(self, node): if node.children: for child in node.children: child.pointAdvantage = self.getOptimalPointAdvantageForNode( child) #If the depth is divisible by 2, it's a move for the AI's side, so return max if node.children[0].depth % 2 == 1: return (max(node.children).pointAdvantage) else: return (min(node.children).pointAdvantage) else: return node.pointAdvantage def getBestMove(self): moveTree = self.generateMoveTree() bestMoves = self.bestMovesWithMoveTree(moveTree) randomBestMove = random.choice(bestMoves) randomBestMove.notation = self.parser.notationForMove(randomBestMove) return randomBestMove def makeBestMove(self): self.board.makeMove(self.getBestMove()) def bestMovesWithMoveTree(self, moveTree): bestMoveNodes = [] for moveNode in moveTree: moveNode.pointAdvantage = self.getOptimalPointAdvantageForNode( moveNode) if not bestMoveNodes: bestMoveNodes.append(moveNode) elif moveNode > bestMoveNodes[0]: bestMoveNodes = [] bestMoveNodes.append(moveNode) elif moveNode == bestMoveNodes[0]: bestMoveNodes.append(moveNode) return [node.move for node in bestMoveNodes] def traverseTreeForBestMove(self, side, moveTree, layersTraversed, bestMovesFound): if layersLeft < self.depth: for move in moveTree: board.makeMove(move) return traverseTreeForBestMove(moveTree[move], layersLeft + 1, bestMoveFound) if layersLeft == self.depth: for move in moveTree: board.makeMove(move) pointAdvantage = board.getPointAdvantageOfSide(side) previousBestAdvantage = 1 return move def isValidMove(self, move, side): for legalMove in self.board.getAllMovesLegal(side): if move == legalMove: return True return False def makeRandomMove(self): moveToMake = self.getRandomMove() self.board.makeMove(moveToMake)
def getStationData(): return { 'LAB': 6, 'XRAY': 12, 'LAB_VISIT_1': 10, 'BREAKFAST': 20 } def initializeStation(): stationWithTimeMap = getStationData() stationQueue = {} for station in stationWithTimeMap: stationQueue[station] = Queue() return stationQueue, stationWithTimeMap if __name__ == "__main__": # dataset = getDataSet() # filteredData = filterDataSet(dataset) filteredData = getDataSetTest() stationQueueInit, stationTimeMap = initializeStation() stationQueue, patientList = InputParser().processPatientList(stationQueueInit, filteredData) patientManager = PatientManager(stationQueue, patientList, stationTimeMap) timeKeeper = TimeKeeper(patientManager) predictTime = timeKeeper.predictTime()
if(len(sys.argv) == 2 and sys.argv[1] == "--help"): print "Usage: ./COCOAss cocoaInputFile.txt baseCOCOADescriptionFile output.txt" sys.exit() if(len(sys.argv) != 4): print "Bad usage. Type ./COCOAss --help" sys.exit() #Names nameOfCocoa = sys.argv[2] nameOfInput = sys.argv[1] nameOfCVS = sys.argv[3] #InputParser myParser = InputParser(nameOfInput, nameOfCocoa) #TagExpander myExpander = TagExpander(myParser.read()) expanded = myExpander.expand() #JobManager manager = JobManager(nameOfCocoa, expanded) output = manager.loop() #WriteOutput outputObject = OutputModule(nameOfCVS, output) outputObject.write()
def __init__(self, board, side, depth): self.board = board self.side = side self.depth = depth self.parser = InputParser(self.board, self.side)
def startGame(self): parser = InputParser(self.board, self.playerSide) movecount = 0 while True: #print("player side") #print(self.playerSide) print() print(self.board) #print(self.uciBoard) print() reedBoard = self.table.reedBoard.getBoard() self.compareBoard(reedBoard) if self.uciBoard.is_game_over(): if self.uciBoard.is_stalemate(): print("Stalemate") self.ledMatrix.sendMultLines("STALE","MATE") self.table.moveto(0,0) time.sleep(1) elif self.board.currentSide == self.playerSide: print("Checkmate, you lost") self.ledMatrix.sendMultLines("YOU","LOST") self.table.moveto(0,0) time.sleep(1) else: print("Checkmate! You won!") self.ledMatrix.sendMultLines("YOU","WON") self.table.moveto(0,0) time.sleep(1) return if self.board.currentSide == self.playerSide: voiceCommandMade = False #if Bluetooth vs AI if (self.gameMode == 3): move = self.btMove(parser) else: if self.led: if self.gameMode == 5: self.ledMatrix.sendMultLines("DEMO","MOVE") else: if self.playerSide == WHITE: self.ledMatrix.sendMultLines("WHITE","MOVE") else: self.ledMatrix.sendMultLines("BLACK","MOVE") self.scrollButton.startListener() self.selectButton.startListener() self.voice1.startListener() if self.reedBoardOption: scrollCount = 0 menuOpened = False voiceCommandMade = False startTime = datetime.now() timerUp = False while True: if (datetime.now() - startTime).total_seconds() >= 2: timerUp = True if self.selectButton.wasPressed() or (timerUp and not(menuOpened) and self.gameMode == 5): if menuOpened: if scrollCount == 1 or scrollCount == 2: move = None self.scrollButton.stopListener() self.selectButton.stopListener() self.voice1.stopListener() break #end the current game elif scrollCount == 3: self.table.moveto(0,0) self.scrollButton.stopListener() self.selectButton.stopListener() self.voice1.stopListener() return elif scrollCount == 4: print("Closing the program and shutting down the Pi") self.table.moveto(0,0) self.scrollButton.stopListener() self.selectButton.stopListener() self.voice1.stopListener() self.ledMatrix.sendMultLines("!SHUT","DOWN") time.sleep(1) self.ledMatrix.sendMultLines("!IN","5 SEC") time.sleep(2) self.ledMatrix.sendString("clear") os.system("sudo shutdown -h now") sys.exit(0) else: if self.gameMode == 5: self.ledMatrix.sendString("load") move = self.getUCIEngineMove(self.aiDepth*1000) self.ledMatrix.sendString("l") self.scrollButton.stopListener() self.selectButton.stopListener() self.voice1.stopListener() break else: moveReturn = self.table.getMove(self.board) move = moveReturn[0] if move: print("FOUND IT!") else: moveError = moveReturn[1] self.printReedBoard(self.table.playableBoard) self.scrollButton.stopListener() self.selectButton.stopListener() self.voice1.stopListener() break self.selectButton.stopListener() elif self.scrollButton.wasPressed(): menuOpened = True self.scrollButton.stopListener() time.sleep(self.sleepTime) self.scrollButton.startListener() scrollCount = scrollCount + 1 print("Scroll Button was Pressed") print(scrollCount) if scrollCount == 1: self.ledMatrix.sendMultLines("@GAME","MENU") elif scrollCount == 2: self.ledMatrix.sendMultLines("CARRY","ON") elif scrollCount == 3: self.ledMatrix.sendMultLines("NEW","GAME") elif scrollCount == 4: self.ledMatrix.sendMultLines("!END","GAME") else: self.ledMatrix.sendMultLines("CARRY","ON") scrollCount = 2 elif self.voiceControl: if menuOpened == False: if self.voice1.wasPressed(): self.ledMatrix.sendMultLines("REC","VOICE") voiceCommandMade = True result, voicemove = self.voiceListener1.listen(self.board) if result == "move": #if self.board.moveIsLegal(voicemove): # fails if king would be in check after move move = voicemove #else: # print("illegal move") # move = None # self.ledMatrix.sendMultLines("MOVE","ERROR") # time.sleep(2) else: move = None self.scrollButton.stopListener() self.selectButton.stopListener() self.voice1.stopListener() break else: command = input("It's your move." " Type '?' for options. ? ").lower() if command == 'u': self.undoLastTwoMoves() continue elif command == '?': self.printCommandOptions() continue elif command == 'l': self.printAllLegalMoves(parser) continue elif command == 'x': self.printAllUnfilteredMoves(self.board) continue elif command == 'r': move = self.getRandomMove(parser) elif command == 'quit': return else: parser.side = self.playerSide move = parser.moveForShortNotation(command) ''' self.ledMatrix.sendString("clear") alphaPos = self.board.positionToHumanCoord(move.newPos) self.ledMatrix.sendString("move" + str(move.piece.stringRep) + str(alphaPos)) time.sleep(3) ''' if move: if self.board.moveIsLegal(move): self.makeMove(move) self.moveWasMade = 1 if voiceCommandMade or self.gameMode == 5: ''' alphaPos = self.board.positionToHumanCoord(move.newPos) self.ledMatrix.sendString("move" + str(move.piece.stringRep).lower() + str(alphaPos).upper()) self.table.move(move) if move.pieceToCapture: self.ledMatrix.sendString("capture" + str(move.pieceToCapture.stringRep).lower()) time.sleep(3) ''' alphaPos = self.board.positionToHumanCoord(move.newPos) self.table.move(move, self.ledMatrix, alphaPos) print("Human Move: ") print(move) if self.bt == 0: print("bluetooth is on") moveStr = str(move.oldPos[0]) + str(move.oldPos[1]) + str(move.newPos[0]) + str(move.newPos[1]) print(moveStr) self.bluetooth.sendmove(moveStr) else: print("bt is off ") else: self.ledMatrix.sendMultLines("MOVE","ERROR") time.sleep(2) else: if voiceCommandMade: if result == "illegal move": print(result) self.ledMatrix.sendMultLines("MOVE","ERROR") elif result == "bad record": print(result) self.ledMatrix.sendMultLines("SPEAK","AGAIN") elif result == "multiple targets": print(result) self.ledMatrix.sendMultLines("SPEAK","COORD") time.sleep(2) elif menuOpened: if self.playerSide == WHITE: self.ledMatrix.sendMultLines("WHITE","MOVE") else: self.ledMatrix.sendMultLines("BLACK","MOVE") else: reedBoard = self.table.reedBoard.getBoard() if moveError == 1: self.ledMatrix.sendMultLines("CHECK","BOARD") time.sleep(2) self.compareBoard(reedBoard) elif moveError == 3: self.ledMatrix.sendMultLines("MOVE","ERROR") time.sleep(2) self.compareBoard(reedBoard) elif moveError == 2: self.ledMatrix.sendMultLines("MAKE","MOVE") time.sleep(2) else: self.ledMatrix.sendMultLines("MOVE","ERROR") time.sleep(2) self.compareBoard(reedBoard) #Player 2 else: #if Human vs Bluetooth if (self.gameMode == 2): print("Bluetooth Player's Turn...") elif (self.gameMode == 4): print("Player 2's Turn") else: print("AI thinking...") #if Human vs Bluetooth if (self.gameMode == 2): self.ledMatrix.sendMultLines("BT","MOVE") move = self.btMove(parser) move.notation = parser.notationForMove(move) elif (self.gameMode == 4): print("gameMode is 4") parser2 = InputParser(self.board, self.btSide) if self.led: if self.playerSide == WHITE: self.ledMatrix.sendMultLines("BLACK","MOVE") else: self.ledMatrix.sendMultLines("WHITE","MOVE") self.scrollButton.startListener() self.selectButton.startListener() self.voice2.startListener() if self.reedBoardOption: scrollCount = 0 menuOpened = False voiceCommandMade = False while True: if self.selectButton.wasPressed(): if menuOpened: if scrollCount == 1 or scrollCount == 2: move = None self.scrollButton.stopListener() self.selectButton.stopListener() self.voice2.stopListener() #switched from voice 1 to voice 2 break elif scrollCount == 3: self.table.moveto(0,0) self.scrollButton.stopListener() self.selectButton.stopListener() self.voice2.stopListener() return elif scrollCount == 4: print("Closing the program and shutting down the Pi") self.table.moveto(0,0) self.scrollButton.stopListener() self.selectButton.stopListener() self.voice1.stopListener() self.ledMatrix.sendMultLines("!SHUT","DOWN") time.sleep(1) self.ledMatrix.sendMultLines("!IN","5 SEC") time.sleep(2) self.ledMatrix.sendString("clear") os.system("sudo shutdown -h now") sys.exit(0) else: moveReturn = self.table.getMove(self.board) move = moveReturn[0] moveError = moveReturn[1] self.scrollButton.stopListener() self.selectButton.stopListener() self.voice2.stopListener() break elif self.scrollButton.wasPressed(): menuOpened = True self.scrollButton.stopListener() time.sleep(self.sleepTime) self.scrollButton.startListener() scrollCount = scrollCount + 1 print("Scroll Button was Pressed") print(scrollCount) if scrollCount == 1: self.ledMatrix.sendMultLines("@GAME","MENU") elif scrollCount == 2: self.ledMatrix.sendMultLines("CARRY","ON") elif scrollCount == 3: self.ledMatrix.sendMultLines("NEW","GAME") elif scrollCount == 4: self.ledMatrix.sendMultLines("!END","GAME") else: self.ledMatrix.sendMultLines("CARRY","ON") scrollCount = 2 elif self.voiceControl: if menuOpened == False: if self.voice2.wasPressed(): self.ledMatrix.sendMultLines("REC","VOICE") voiceCommandMade = True result2, voicemove = self.voiceListener2.listen(self.board) if result2 == "move": #if self.board.moveIsLegal(voicemove): # fails if king would be in check after move move = voicemove else: move = None self.scrollButton.stopListener() self.selectButton.stopListener() self.voice2.stopListener() break else: self.ledMatrix.sendString("load") move = self.getUCIEngineMove(self.aiDepth*1000) self.ledMatrix.sendString("l") if move: if self.board.moveIsLegal(move): self.makeMove(move) if self.gameMode != 4: alphaPos = self.board.positionToHumanCoord(move.newPos) self.table.move(move, self.ledMatrix, alphaPos) elif voiceCommandMade: alphaPos = self.board.positionToHumanCoord(move.newPos) self.ledMatrix.sendString("move" + str(move.piece.stringRep).lower() + str(alphaPos).upper()) self.table.move(move) if move.pieceToCapture: self.ledMatrix.sendString("capture" + str(move.pieceToCapture.stringRep).lower()) time.sleep(3) else: self.ledMatrix.sendMultLines("MOVE","ERROR") time.sleep(2) else: if voiceCommandMade: if result2 == "illegal move": print(result2) self.ledMatrix.sendMultLines("MOVE","ERROR") elif result2 == "bad record": print(result2) self.ledMatrix.sendMultLines("SPEAK","AGAIN") elif result2 == "multiple targets": print(result2) self.ledMatrix.sendMultLines("SPEAK","COORD") time.sleep(2) elif menuOpened: if self.playerSide == WHITE: self.ledMatrix.sendMultLines("BLACK","MOVE") else: self.ledMatrix.sendMultLines("WHITE","MOVE") else: reedBoard = self.table.reedBoard.getBoard() if moveError == 1: self.ledMatrix.sendMultLines("CHECK","BOARD") time.sleep(2) self.compareBoard(reedBoard) elif moveError == 3: self.ledMatrix.sendMultLines("MOVE","ERROR") time.sleep(2) self.compareBoard(reedBoard) elif moveError == 2: self.ledMatrix.sendMultLines("MAKE","MOVE") time.sleep(2) else: self.ledMatrix.sendMultLines("MOVE","ERROR") time.sleep(2) self.compareBoard(reedBoard) print("Couldn't parse input, enter a valid command or move.") if self.uciBoard.is_check(): print("King was put in check") self.ledMatrix.sendString("CHECK") time.sleep(5) self.ledMatrix.sendString("clear")
def main(args): parser = InputParser(args) # (args.algoname, args.outfile) are required params = parser.parse(args.infile) algo_creator = Algorithm() algo = algo_creator.create(params) print (algo.run())