def start_game(self): a = False while a == False: if Tree().height() == True: print("It's your step, {}. You are 'X'".format( self.first_name)) try: self.position = int(input('Enter cells position: ')) except ValueError: print("Please try again") if self.position > 0 and self.position <= 9: if self.board[self.position - 1] == None: self.board[self.position - 1] = 'X' self.print_board() self.count += 1 Tree().insert('O') self.position.remove(self.position) else: raise ValueError('Try again') else: raise ValueError('Try again') else: print("It's computer step") self.position = random.choice(self.possible_position) if self.board[self.position - 1] == None: self.board[self.position - 1] = 'O' self.print_board() self.count += 1 Tree().insert('O') if self.check() == True: break print("You win")
def recursion(tree): free_cells = tree.root.free_cells() if not free_cells or tree.root.check_win(): return if len(free_cells) == 1: board = deepcopy(tree.root) board.last_move = board.get_player(board.last_move) board.data[free_cells[0][0]][free_cells[0] [1]] = board.last_move tree.right = Tree(board) recursion(tree.right) return board1 = deepcopy(tree.root) board1.last_move = board1.get_player(board1.last_move) position = random.choice(free_cells) free_cells.remove(position) board1.data[position[0]][position[1]] = board1.last_move tree.right = Tree(board1) board2 = deepcopy(tree.root) board2.last_move = board2.get_player(board2.last_move) position = random.choice(free_cells) free_cells.remove(position) board2.data[position[0]][position[1]] = board2.last_move tree.left = Tree(board2) recursion(tree.right) recursion(tree.left)
def __init__(self): self._orders_by_id: Dict[int, Order] = dict() self._s_orders_by_price: Tree = Tree( config.MAX_PRICE_THRESHOLD) # add an artificial root. self._b_orders_by_price: Tree = Tree( config.MIN_PRICE_THRESHOLD) # add an artificial root. self._expected_trades: Deque[Trade] = deque( ) # expected trades when new orders coming in self._expected_x_orders: Set[int] = set( ) # orders to be deleted as result of expected trades self._errors = ErrorsDictionary() self._recent_trade_price: float = config.MAX_PRICE_THRESHOLD self._recent_trade_qty: int = 0
def turn(self): if self.board.last_turn == "0": coordinates = input("Enter coordinate: ").split() if self.board.state[int(coordinates[0])][int( coordinates[1])] != "_": raise IndexError if int(coordinates[0]) > 2 or int(coordinates[1]) > 2 or 0 > int( coordinates[0]) or 0 > int(coordinates[1]): raise IndexError new_row = "" for j in range(3): if j != int(coordinates[1]): new_row += self.board.state[int(coordinates[0])][int( coordinates[0])] else: new_row += "x" self.board.state[int(coordinates[0])] = new_row self.board.last_turn = "x" else: tree = Tree(self.board) tree.generate() if tree.root.right.check() > tree.root.left.check(): self.board = tree.root.right.root.data else: self.board = tree.root.left.root.data self.board.last_turn = "0" self.board.show_board()
def make_step(self, field, current, cur_node=None): """ Makes step on field """ fst = False new_node = Tree(field) if cur_node == None: cur_node = new_node fst = True if field.is_full() or field.winner_sign(): cur_node.add_node(Node(field)) for x in range(3): for y in range(3): if field.field[x][y] == " ": field.field[x][y] = Board.PLAYER_SIGNS[current] self.make_step(deepcopy(field), (current + 1) % 2, new_node) field.field[x][y] = " " if fst: win_rates = [win_rate(node, current) for node in new_node.childs] step = win_rates.index(max(win_rates)) field.field = new_node.childs[step].data.field return else: cur_node.add_node(new_node) return cur_node
def insert(self, data): ''' 插入 ''' if not self.base: self.base = Tree(data=data) return pp = None p = self.base while p: pp = p p = p.ltree if p.data > data else p.rtree new_p = Tree(data=data) if pp.data > data: pp.ltree = new_p else: pp.rtree = new_p
def map(): script = Script() tree = Tree.from_file() temp_tree = Tree(filename='map.db') temp_tree.compact() script.add_string(request.get_data()) data = [] for k, v in tree: temp_tree[k] = script.invoke('mapper', k, v) data = script.invoke('reducer', temp_tree.__iter__()) return jsonify(result=data)
def compute_score(self): has_winner = self.has_winner() if has_winner: winner_scores = { Board.NOUGHT_WINNER: 1, Board.CROSS_WINNER: -1, Board.DRAW: 0 } return winner_scores[has_winner] n1 = Node(self) board = Tree() board.root = n1 right_board = left_board = copy.deepcopy(self) left_move, right_move = left_board.make_random_move( ), right_board.make_random_move() board.root.left = Node(left_move) board.root.right = Node(right_move) return left_board.compute_score() + right_board.compute_score()
def computer(self): tree = Tree() tree.set_root(deepcopy(self.board)) def new_check(board): if self.check_board(board) == self.comput: return 1 elif self.check_board(board) == self.player: return -1 elif self.check_board(board) == 0: return 0 else: return None def add(item, state=True): if self.check_board(item.data) in ["O", 0, "X"]: item.res = new_check(item.data) else: for i in range(3): if len(item.children) == 2: break for j in range(3): if item.data[i][j] == " ": new = deepcopy(item.data) new[i][j] = self.comput if state else self.player tree.add(item, new) add(item.children[-1], state=not state) if len(item.children) == 2: break add(tree._root) def calculate(item, func): if item.res != None: return item.res item.res = func(item.children, key=lambda x: \ calculate(x, min if func == max else max)).res return item.res calculate(tree._root, max) board = max(tree._root.children, key=lambda x: x.res) self.board = board.data
def main(): for j in range(30): tree = Tree(max_size=3) for i in range(j + 1): tree[i] = i**2 fancy_print(tree) print(tree) print('COMMMMIITTTTTT') tree.commit() print('IMPORRRTTTTT') new_tree = Tree.from_file() print(new_tree) print('IMUPPORRTTAANTT', new_tree) fancy_print(new_tree) new_tree[2] = 20 fancy_print(new_tree) print('IMUPPORRTTAANTT', new_tree) fancy_print(new_tree) new_tree[3] = 30 print('IMUPPORRTTAANTT', new_tree) fancy_print(new_tree) del new_tree[0] fancy_print(new_tree) print('IMUPPORRTTAANTT', new_tree) fancy_print(new_tree) print(getsize(new_tree.filename)) print('COOOOMMMPPPAAACCCTTT') new_tree.compact() print(getsize(new_tree.filename)) print('IMPORT COOOOMMMPPPAAACCCTTT') new_tree = Tree.from_file() new_tree[2] = 30 print("PRRRRRINIINNT 11111") fancy_print(new_tree) del new_tree[3] print("PRRRRRINIINNT 2222222") fancy_print(new_tree) print() print()
def compute_score(self): """ The function returns sum of all scores in binary tree """ board = Tree(self) if self.has_winner(): winner_scores = { Board.NOUGHT_WINNER: 1, Board.CROSS_WINNER: -1, Board.DRAW: 0 } return winner_scores[self.has_winner()] board.key = Node(self) left_board = deepcopy(self) left_move = left_board.make_random_move() board.key.left = Node(left_move) right_board = deepcopy(self) right_move = right_board.make_random_move() board.key.right = Node(right_move) return left_board.compute_score() + right_board.compute_score()
def count_score(self): has_winner = self.has_winner() if has_winner: scores = { Board.NOUGHT_WINNER: 1, Board.CROSS_WINNER: -1, Board.DRAW: 0 } return scores[has_winner] else: board = Tree() board.root = Node(self) board_left = copy.deepcopy(self) board_right = copy.deepcopy(self) move_L = board_left.make_random_move() move_R = board_right.make_random_move() board.root.left = Node(move_L) board.root.right = Node(move_R) result = board_left.count_score() + board_right.count_score() return result
def main(): ''' Launches the tic-tac-toe game ''' board = Board() free_list = board.free_cells() choice = random.choice(free_list) board.move(choice) while not board.is_filled(): board.draw() #move of the player try: move = input("The coordinates of your move: ").split(",") board.move((int(move[0]),int(move[1])) , False) except IndexError: continue #move of the computer tree = Tree(copy.deepcopy(board)) tree.build_tree() right_wins = tree.count_wins(tree._root._right) left_wins = tree.count_wins(tree._root._left) if right_wins > left_wins: move = board.last_move(tree._root._right) else: move = board.last_move(tree._root._left) board.move(list(move)[0]) #check for winning combination win = board.check_win() if win == 1: return "You lose the game!" elif win == -1: return "You win the game!" return "The draw!"
def compute_score(self): """ Chooses better move :return: int """ has_winner = self.has_winner() if has_winner: winner_scores = { Board.NOUGHT_WINNER: 1, Board.CROSS_WINNER: -1, Board.DRAW: 0 } return winner_scores[has_winner] board = Tree() board.root = Node(self) left_board = copy.deepcopy(self) right_board = copy.deepcopy(self) left_move = left_board.make_random_move() right_move = right_board.make_random_move() board.root.left = Node(left_move) board.root.right = Node(right_move) return left_board.compute_score() + right_board.compute_score()
def build_decision_tree(self): """Build decision tree for TicTacToe game""" self.tree = Tree() def recurse(board, node=None, player=self.first_player): """Recursively build tree of all possible moves in TicTacToe game player: 1 if human makes a move, 0 - if computer""" if node is None: curr_node = self.tree.add_root(board) else: curr_node = self.tree.add_child(node, board) # if current state is not final yet: curr_state = \ curr_node.item.current_state(first_player=self.first_player) if curr_state is None: for i in range(3): for j in range(3): if curr_node.item.board[i][j] is None: move = (Board.FIRST_MARK if player ^ self.first_player ^ 1 else Board.SECOND_MARK, (i, j)) next_board = Board.new_board(curr_node.item, move) recurse(next_board, curr_node, player ^ 1) if player: # consider that human makes the best move curr_node.score = min(c.score for c in curr_node.children) else: # try to make teh best move curr_node.score = max(c.score for c in curr_node.children) else: curr_node.score = curr_state recurse(self.board)
from btree import Tree from btnode import Node moves = { 1: (0, 0), 2: (0, 1), 3: (0, 2), 4: (1, 0), 5: (1, 1), 6: (1, 2), 7: (2, 0), 8: (2, 1), 9: (2, 2) } board = Board() tr = Tree(Node(board)) while type(board.check_board()) != int: try: user_move = int(input("To make move enter number from 1 to 9 : ")) except ValueError: response = input("Invalid input! Do you want to continue? (yes/no) : ") if response.lower() == "yes": continue else: break coor = moves[user_move] try: if board.right_position(user_move): board.add((coor[0], coor[1]), "X") except TypeError: response = input("Invalid input! Do you want to continue? (yes/no) : ")
def computer_turn(self): """() -> NoneType Generates computer's turn """ self.play_tree = Tree(self.board) self.board = self.play_tree.choose('x' if self.side == 'o' else 'o')
def __init__(self, database, table, key): self.key = key self.table = table self.database = database self.btree = Tree(self.database, self.table, self.key) self.db_file = db_file_path(DATA_META_DB)
from btree import Node, Tree tree = Tree() tree.add(3) tree.add(4) tree.add(0) tree.add(8) tree.add(2) tree.printTree() print(tree.height())
def game(board): """ Start two moves - first one of a player, second one of a computer. Return Board representation of result. :param board: Board :return: Board """ # I know how to use exceptions, but here it would be too hard, because I have to continue game. def get_pos(text): """ Get number from one to three from player. :param text: str :return: int """ i = input(text) if i in ['1', '2', '0']: return int(i) else: print("Sorry, you had to enter a number from 0 to 2! Please, try again!") return get_pos(text) def get_input(board): """ Get position from player. :param board: Board :return: tuple """ # Getting player input: col = get_pos("Player, please, enter column number (from 0 to 2): ") row = get_pos("Player, please, enter row number (from 0 to 2): ") # Checking input: if tuple([row, col]) not in board.free_positions(): print("Sorry, but this position is not free! Please, try again!") return get_input(board) return tuple([row, col]) # First move is made by a player. tupl = get_input(board) row = tupl[0] col = tupl[1] # Make a new board: new_board = Board() # Make a move on a new board: field = board.data[:] field[row][col] = False new_board.set_field(field) new_board.set_last_move(tupl, False) # Check if game is finished and if it is, return new board. if new_board.get_state() == 1 or not new_board.free_positions(): return new_board # Print new version of a board on the screen: new_board.print_board() print("_" * 120) # Now it is time for a robot to choose its path. # Building a binary search tree: tree = Tree(new_board) tree.finish() final_board = tree.best_board() print("Robot made its choice!") final_board.print_board() print("_" * 120) return final_board
def __init__(self, board, last_turn=None): """Create new Board""" self.board = board # string self.opponent = self.board[last_turn] if last_turn is not None else 'O' self.player = 'O' if self.opponent == 'X' else 'X' self.tree = Tree()
successor_pp = successor successor = successor.ltree p.data = successor.da pp, p = successor_pp, successor child = p.ltree if p.ltree else p.rtree if not pp: self.base = child elif pp.ltree == p: pp.ltree = p else: pp.rtree = child if __name__ == '__main__': tree = Tree(data=3) bst = BinarySearchTree(tree) bst.insert(3) bst.insert(4) bst.insert(5) bst.insert(8) bst.insert(10) bst.insert(13) bst.insert(33) bst.insert(44) bst.insert(1) bst.insert(2) target = bst.find(8) print("--------------------") print(target.data) print(target.ltree)