Ejemplo n.º 1
0
def tree_timer_check():
    for seed in seeds:
        seed.timer += 1
        if seed.is_grounded:
            if seed.timer >= 250 + seed.timer_displace:
                tree_colour_select(seed, 1)
                sprouts.append(
                    Tree(seed.x, seed.y, seed.size, seed.colour,
                         seed.colour_value, 0, seed.timer_displace,
                         seed.leaf_colour, seed.type, seed.leaf_displace))
                seeds.pop(seeds.index(seed))
    for sprout in sprouts:
        sprout.timer += 1
        if sprout.timer >= 500 + sprout.timer_displace * 2:
            tree_colour_select(sprout, 2)
            leaf_colour_select(sprout, 2)
            saplings.append(
                Tree(sprout.x, sprout.y, sprout.size, sprout.colour,
                     sprout.colour_value, 0, sprout.timer_displace,
                     sprout.leaf_colour, sprout.type, sprout.leaf_displace))
            sprouts.pop(sprouts.index(sprout))
    for sapling in saplings:
        sapling.timer += 1
        if sapling.timer >= 750 + sapling.timer_displace * 3:
            tree_colour_select(sapling, 3)
            leaf_colour_select(sapling, 3)
            trees.append(
                Tree(sapling.x, sapling.y, sapling.size, sapling.colour,
                     sapling.colour_value, 0, sapling.timer_displace,
                     sapling.leaf_colour, sapling.type, sapling.leaf_displace))
            saplings.pop(saplings.index(sapling))
Ejemplo n.º 2
0
def p_assignment_new_name(p):
    """
	assignment : NAME ASSIGN arithmeticexpr
	"""
    global noOfAssignDecl
    noOfAssignDecl += 1
    p[0] = Tree(Tree(p[1], None, 'VAR'), p[3][0], 'ASGN')
    if (not p[3][1]):
        print("syntax error at =")
        sys.exit()
Ejemplo n.º 3
0
def p_startwithany_define(p):
    """
	startwithany : POINTER startwithany
				| AMPERSAND startwithany
				| NAME
	"""
    if p[1] == '*':
        x = Tree(p[2], None, 'DEREF')
    elif p[1] == '&':
        x = Tree(p[2], None, 'ADDR')
    else:
        x = Tree(p[1], None, 'VAR')
    p[0] = x
Ejemplo n.º 4
0
def build_RF_trees_prediction(n, train, target, n_random_columns, max_depth,
                              sample_size):

    test = get_test()
    for i in range(0, n):
        print('________________________________________________________')
        print('--------------> CREANDO ARBOL ' + str(i) + '...')
        ts = time.time()
        print('--------------> INICIO: ' +
              str(datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S')))
        tree = Tree(train.sample(sample_size), target, n_random_columns,
                    max_depth)
        print('--------------> ARBOL NUEVO: ' + str(i))
        ts1 = time.time()
        print('--------------> SE CREO EN: ' + str(round((ts1 - ts) / 60, 2)) +
              ' MINUTOS ')
        print('--------------> CALCULANDO PREDICCION...')
        write_csv(
            get_tree_prediction(test, tree).items(),
            str(i) + 'prediction.csv'
        )  # aca va el nombre de como se crean los csv de resultados
        print('--------------> SE CALCULO PREDICCION EN: ' +
              str(round((time.time() - ts1) / 60, 2)) + ' MINUTOS')
        print('--------------> DEMORO UN TOTAL DE: ' +
              str(round((time.time() - ts) / 60, 2)) + ' MINUTOS')
Ejemplo n.º 5
0
def p_assignment_new_startwithstar(p):
    """
	assignment : startwithstar ASSIGN arithmeticexpr
	"""
    global noOfAssignDecl
    noOfAssignDecl += 1
    p[0] = Tree(p[1], p[3][0], 'ASGN')
Ejemplo n.º 6
0
def p_booleanexpr_term(p):
    """
	booleanexpr : booleanexpr OR booleanexpr
	            | booleanexpr AND booleanexpr
	            | LPAREN booleanexpr RPAREN
	            | NEGATION booleanexpr
	"""
    if p[2] == '||':
        x = Tree(p[1], p[3], 'OR')
    elif p[2] == '&&':
        x = Tree(p[1], p[3], 'AND')
    elif p[1] == '(':
        x = p[2]
    else:
        x = Tree(p[2], None, 'NOT')

    p[0] = x
Ejemplo n.º 7
0
def p_ifblock_ifelse(p):
    """
	ifblock : IF LPAREN CONDITION RPAREN  conditionalbody ELSE ifelsehandler
	"""

    x = Tree(p[3], [p[5], p[7]], 'IFELSE')

    p[0] = x
Ejemplo n.º 8
0
def p_arithmeticexpr_binop(p):
    """
	arithmeticexpr : arithmeticexpr PLUS arithmeticexpr
				   | arithmeticexpr MINUS arithmeticexpr
				   | arithmeticexpr POINTER arithmeticexpr
				   | arithmeticexpr DIVIDE arithmeticexpr
	"""
    if p[2] == '+':
        x = Tree(p[1][0], p[3][0], 'PLUS')
    elif p[2] == '-':
        x = Tree(p[1][0], p[3][0], 'MINUS')
    elif p[2] == '*':
        x = Tree(p[1][0], p[3][0], 'MUL')
    elif p[2] == '/':
        x = Tree(p[1][0], p[3][0], 'DIV')

    p[0] = [x, p[1][1] or p[3][1]]
Ejemplo n.º 9
0
def build_RF_trees(n, train, target, n_random_columns, max_depth, sample_size):
    for i in range(0, n):
        print('CREANDO ARBOL ' + str(i))
        print(datetime.datetime.fromtimestamp(ts).strftime('%H:%M:%S'))
        tree = Tree(train.sample(sample_size), target, n_random_columns,
                    max_depth)
        serialize_tree(tree, (str(i) + 'RF_3_5.pkl'))
        print('<------------------------------------ARBOL NUEVO = ' + str(i) +
              ' ------------------------------------>')
        print('SE CREO EN: ' + str((time.time() - ts) / 60) + ' MINUTOS')
Ejemplo n.º 10
0
def recursive_minimax(game: 'Game') -> Any:
    """
    A recursive minimax implementation that returns the best score that the 
    a player can make for a certain game.
    
    @param game 'Game': a Game object that represents the current game being
                        played
                        
    @rtype: Any
    """
    t = Tree((game.current_state, [], None, None))
    return recursive_helper(t, game)
Ejemplo n.º 11
0
def p_conditionalbody_def(p):
    """
	conditionalbody : line SEMICOLON 
					| LFBRACK lines RFBRACK 
	"""
    if p[1] == '{':
        p[0] = p[2]
    else:
        if p[1][1]:
            p[0] = [p[1][0]]
        else:
            sys.exit()
            p[0] = Tree(None, None, 'None')
Ejemplo n.º 12
0
def p_boolfromarith_def(p):
    """
	boolfromarith : arithmeticexpr LTE arithmeticexpr
		        	 | arithmeticexpr GTE arithmeticexpr
		        	 | arithmeticexpr LT arithmeticexpr
		        	 | arithmeticexpr GT arithmeticexpr
		        	 | arithmeticexpr COMPARENOTEQUAL arithmeticexpr
		        	 | arithmeticexpr COMPAREEQUAL arithmeticexpr
	"""
    if p[2] == '<=':
        x = Tree(p[1][0], p[3][0], 'LE')
    elif p[2] == '>=':
        x = Tree(p[1][0], p[3][0], 'GE')
    elif p[2] == '<':
        x = Tree(p[1][0], p[3][0], 'LT')
    elif p[2] == '>':
        x = Tree(p[1][0], p[3][0], 'GT')
    elif p[2] == '!=':
        x = Tree(p[1][0], p[3][0], 'NE')
    elif p[2] == '==':
        x = Tree(p[1][0], p[3][0], 'EQ')

    p[0] = x
Ejemplo n.º 13
0
def recursive_helper(t: 'Tree', game: 'Game') -> Any:
    """
    A recursive minimax helper function that returns the best available move
    that can be played by a player for a certain game.
    
    @param t 'Tree': a Tree onject that is a representation of a specific state 
                     within the game
    @param game 'Game': a Game object that represents the current game being
                        played
                        
    @rtype: Any
    """
    if t.value.get_possible_moves() == []:
        old_state = game.current_state
        game.current_state = t.value

        if not game.is_winner('p1') and not game.is_winner('p2'):
            t.score = 0
            game.current_state = old_state

        else:
            t.score = -1
            game.current_state = old_state

        return t.score

    elif t.value.get_possible_moves() != [] and \
         t.value.__repr__() != game.current_state.__repr__():
        for move in t.value.get_possible_moves():
            q = Tree((t.value.make_move(move), [], None, move))

            if q.value.get_possible_moves() == []:
                q.score = recursive_helper(q, game)

            else:
                q.score = max([-1 * \
                               recursive_helper(Tree((q.value.make_move(x), \
                                                        [], None, x,)), game)\
                               for x in q.value.get_possible_moves()])

            t.children.append(q)

        t.score = max([x.score * -1 for x in t.children])
        return t.score

    else:
        for value in game.current_state.get_possible_moves():
            node = Tree((t.value.make_move(value), [], None, value))
            t.children.append(node)

        for node in t.children:
            if node.value.get_possible_moves() == []:
                return node.move_made

        lst = []
        t.score = max([-1 * recursive_helper(x, game) for x in t.children])
        for node in t.children:
            if node.score == t.score * -1:
                lst.append(node.move_made)

        return random.choice(lst)
Ejemplo n.º 14
0
def p_ifblock_if(p):
    """
	ifblock : IF LPAREN CONDITION  RPAREN conditionalbody
	"""
    x = Tree(p[3], p[5], 'IF')
    p[0] = x
Ejemplo n.º 15
0
from classes import Tree

if __name__ == '__main__':

    tree = Tree()

    nodes = [50, 70, 60, 80, 30, 20, 40]

    for node in nodes:
        tree.add(node)

    tree.add(65)
    tree.remove(50)
    tree.xprint()
    # tree.xprint()
    # print(f'Min value: {tree.find_min()}\nMax value: {tree.find_max()}')
    # print(f'Left height: {tree.left_height()}')
    # print(f'Right height: {tree.right_height()}')

#       50
#     /    \
#   30      70
#  /  \    /  \
# 20  40  60  80
Ejemplo n.º 16
0
def p_whileblock_def(p):
    """
	whileblock : WHILE LPAREN CONDITION RPAREN conditionalbody
	"""
    x = Tree(p[3], p[5], 'WHILE')
    p[0] = x
Ejemplo n.º 17
0
def p_startwithstar_define(p):
    """
	startwithstar : POINTER startwithany
	"""
    p[0] = Tree(p[2], None, 'DEREF')
Ejemplo n.º 18
0
def p_arithmeticexpr_terminal_NUMBER(p):
    """
	arithmeticexpr : NUMBER
				   | FLOATNUM
	"""
    p[0] = [Tree(p[1], None, 'CONST'), False]
Ejemplo n.º 19
0
def p_arithmeticexpr_uminus(p):
    """
	arithmeticexpr : MINUS arithmeticexpr %prec UMINUS
	"""
    p[0] = [Tree(p[2][0], None, 'UMINUS'), p[2][1]]
Ejemplo n.º 20
0
def iterative_minimax(game: 'Game') -> Any:
    """
    Returns the best score available for a certain game using an iterative 
    approach.
    
    @param game 'Game': the Game object that represents the game being played
    
    @rtype: Any
    """
    tree_list = []
    tree_list.append(Tree((game.current_state, [], None, None)))

    s = Stack()
    s.add(tree_list[0])

    a_lst = []

    while not s.is_empty():
        p = s.remove()
        if (p.children == []) and p.value.get_possible_moves() != []:
            moves = [p]

            for value in p.value.get_possible_moves():
                q = Tree((p.value.make_move(value), [], None, value))
                p.children.append(q)
                tree_list.append(q)
                moves.append(q)

            a_lst.append(moves)

            for node in tree_list:
                s.add(node)

        elif (p.children == []) and p.value.get_possible_moves() == []:
            old_state = game.current_state
            game.current_state = p.value

            if not game.is_winner('p1') and not game.is_winner('p2'):
                p.score = 0
                game.current_state = old_state

            else:
                p.score = -1
                game.current_state = old_state

        else:
            lst_scores = []
            for node in p.children:
                lst_scores.append(node.score * -1)

            p.score = max(lst_scores)

    for outer_list in a_lst:
        if game.current_state.__repr__() == outer_list[0].value.__repr__() \
           and outer_list[0].children != []:

            lst = []
            for node in outer_list[0].children:
                if node.value.get_possible_moves() == []:
                    lst.append(node.move_made)

            if len(lst) == 1:
                return lst[0]

            elif len(lst) >= 1:
                return random.choice(lst)

            m = [(node.move_made, node.score) for node in outer_list[1:]]
            lst = []

            for item in m:
                if item[1] == outer_list[0].score * -1:
                    lst.append(item[0])

            return random.choice(lst)

    return -1
Ejemplo n.º 21
0
     for tree in trees:
         is_touching(pos, 2, tree)
         if tree.touching:
             if tree.type == 1:
                 wood1 += tree.size * 5
             if tree.type == 2:
                 wood2 += tree.size * 5
             if tree.type == 3:
                 wood3 += tree.size * 5
             trees.pop(trees.index(tree))
             tree.touching = False
 elif seed_type == 1:
     if seed1_amount > 0:
         seeds.append(
             Tree(pos[0], pos[1],
                  random.randint(4, 6), 0,
                  random.randint(1, 5), 0,
                  random.randint(20, 120), 0, 1))
         seed1_amount -= 1
 elif seed_type == 2:
     if seed2_amount > 0:
         seeds.append(
             Tree(pos[0], pos[1],
                  random.randint(4, 6), 0,
                  random.randint(1, 5), 0,
                  random.randint(20, 120), 0, 2,
                  random.randint(0, 30)))
         seed2_amount -= 1
 elif seed_type == 3:
     if seed3_amount > 0:
         seeds.append(
             Tree(pos[0], pos[1],