Exemplo n.º 1
0
def car_actions(maze, cars, functions, debug=False):
    """
        Runs any functions a car is on.
    """

    # Do signal first so it's enabled before any functions are run.
    signals = []
    for car in cars:
        if maze[car.y][car.x].name == 'signal':
            signals.append(maze[car.y][car.x].value)

    logs = ''
    removed = []
    for car in cars:

        # Count down any paused cars.
        if car.pause:
            car.pause -= 1
            continue

        cell = maze[car.y][car.x]

        # Actions:
        if cell.name == 'wall':
            funcs.error('Car got in wall.')

        elif cell.name == 'path':
            pass

        elif cell.name == 'pause':
            car.pause = int(cell.value)

        elif cell.name == 'hole':
            removed.append(car)

        elif cell.name == 'out':
            logs += str(car.value)

        elif cell.name == 'ln-out':
            logs += str(car.value) + '\n'

        elif cell.name == 'in':
            car.value = input('> ')

        elif cell.name == 'one-use':
            cell.name = 'wall'
            cell.value = controls.display['wall']

        elif cell.name == 'direction':
            car.direction = cell.value[1]

        elif cell.name == 'function':
            function = functions[cell.value]

            try:
                result = str(function(car.value))
            except TypeError:
                result = str(function(car.value, signals))

            if not result == 'None':
                match = re.match(controls.regexes['direction'], result)
                if match:
                    car.direction = result[1]
                else:
                    car.value = str(result)

    # Remove any deleted cars.
    for car in removed:
        cars.remove(car)

    return maze, cars, logs
Exemplo n.º 2
0
def move_cars(maze, cars):
    """
        Moves all the cars one frame.
    """
    maze_after = copy.deepcopy(maze)
    cars_after = copy.deepcopy(cars)

    for i in range(len(cars)):
        car = cars_after[i]

        # Don't move a car if it is paused.
        if car.pause:
            continue

        # Splitters do their own thing.
        if maze[car.y][car.x].name == 'splitter':
            car_copy = copy.deepcopy(car)
            cars_after.append(car_copy)

            car.direction = 'R'
            car.x += 1
            car_copy.direction = 'L'
            car_copy.x -= 1

        else:

            if car.direction in 'Nn':
                continue

            directions = ['U', 'R', 'D', 'L']

            # Move current direction to front
            try:
                directions.remove(car.direction.lower())
            except ValueError:
                directions.remove(car.direction.upper())
            directions.insert(0, car.direction)

            # Move current backwards direction to back
            opp = opp_dir(car.direction)
            try:
                directions.remove(opp.lower())
            except ValueError:
                directions.remove(opp.upper())
            directions.append(opp)

            # Check all directions.
            for d in directions:
                x, y = dir_to_pos(car, d)
                can_move_dir = check_pos(maze, x, y)

                if can_move_dir: break

            # If car can move.
            if can_move_dir:
                car.x = x
                car.y = y
                car.direction = d

    # Error if any cars share a cell.
    if len(cars) is not len(set((car.x, car.y) for car in cars)):
        funcs.error('Multiple cars in same cell.')

    return maze_after, cars_after
Exemplo n.º 3
0
def get_function(line):
    """
        Parses and returns a function on the given line.
    """

    # Get function name from before the function assignment operator.
    match = re.search(controls.regexes['function'], line.split('->')[0])
    if not match:
        funcs.error('Invalid function, invalid name.')
    name = match.group()

    # Make sure the function has an function assignment operator.
    match = re.search(controls.regexes['function'] + r' *-> *', line)
    if not match:
        funcs.error('Invalid function.')
    function = line[match.end():]

    # Function type: conditional or assignment.
    if function.lower().startswith('if'):  # Conditional

        # Get Condition
        match = re.search(r'([<>]=?)|==|(\*(?=[\*A-Za-z0-9]))', function)
        if not match:
            funcs.error('Invalid function, invalid condition.')
        condition = match.group()

        # Get condition value
        if condition == '*':
            match = re.search(controls.regexes['signal'], function)
            try:
                number = match.group()
            except (ValueError, AttributeError):
                funcs.error('Invalid function, invalid value for signal.')
        else:
            match = re.search(
                r'(-?[0-9]+)|((?<=")[^"]*(?=")|(?<=\')[^\']*(?=\'))', function)
            if match.group(1):
                number = int(match.group(1))
                string = None
            elif isinstance(match.group(2), str) and condition == '==':
                number = None
                string = str(match.group(2))
            else:
                funcs.error('Invalid function, invalid value for condition.')

        # Get 'then' keyword and statement.
        match = re.search(r' *then *', function.lower())
        if not match:
            funcs.error('Invalid function, no THEN keyword.')
        then_keywd = match.group()
        function = function[match.end():]

        match = re.search(controls.regexes['direction'], function)
        if not match:
            funcs.error('Invalid function, no THEN statement.')
        then = match.group()

        # Get 'else' keyword and statement.
        match = re.search(r' *else *', function.lower())
        if not match:
            else_ = None
        else:
            function = function[match.end():]

            match = re.search(controls.regexes['direction'], function)
            else_ = match.group()
            if not else_:
                funcs.error('Invalid function, no ELSE statement.')

        # Create lambda representing the function.
        if condition == '*':
            if number == '*':
                function = lambda value, signal: then if signal else else_
            else:
                function = lambda value, signal: then if '*' in signal or number in signal else else_

        elif condition == '<=':
            function = lambda value: then if int(value) <= number else else_
        elif condition == '==':
            if isinstance(string, str):
                function = lambda value: then if funcs.escape(
                    value) == string else else_
            else:
                function = lambda value: then if int(value
                                                     ) == number else else_
        elif condition == '>=':
            function = lambda value: then if int(value) >= number else else_
        elif condition == '>':
            function = lambda value: then if int(value) > number else else_
        elif condition == '<':
            function = lambda value: then if int(value) < number else else_

    else:  # Assignment

        # Make sure it has an assignment operator.
        match = re.search(r'[-+*/]?=', function)
        if not match:
            funcs.error('Invalid function, invalid operator.')
        operator = match.group()

        # Create lambdas representing the assignment.
        if operator == '=':
            # Find a string or an int
            quotes = r'(?<=")[^"]*(?=")|(?<=\')[^\']*(?=\')'
            str_match = re.search(quotes, function)
            int_match = re.search(r'-?[0-9]+', function)
            if not str_match and not int_match:
                funcs.error('Invalid function, invalid assignment value.')

            assign = (str_match or int_match).group()

            # Fix new lines in string assignment
            assign = '\n'.join(assign.split('\\n'))

            function = lambda value: assign

        else:
            # Find an int
            match = re.search(r'-?[0-9]+', function)
            try:
                number = int(match.group())
            except (ValueError, AttributeError):
                funcs.error('Invalid function, invalid value for operator.')

            if operator == '-=':
                function = lambda value: int(int(value) - number)
            elif operator == '+=':
                function = lambda value: int(int(value) + number)
            elif operator == '*=':
                function = lambda value: int(int(value) * number)
            elif operator == '/=':
                function = lambda value: int(int(value) / number)

    return {name: function}
Exemplo n.º 4
0
search = input("Please type searched page: " + Fore.YELLOW).title()

# Wikipedia'dan yapılan ilk 10 aramayı bir liste halinde searchQuery değerine aktarır.
try:
    searchQuery = wikipedia.search(search)
except:
    mahmut()  # ;)

# listSearch fonksiyonu searchQuery'den aldığı 10 değişkenli listeyi kullanıcıya gösterebilmesi için listSearch fonksiyonuna yollar
listSearch(searchQuery)

# Kullanıcıdan 1 ila 10 arasında bir değer alınarak listedeki değer ile eşlenir.
selectedPage = input(
    "Please choose one of the following options (Press enter for first option)=> "
    + Fore.YELLOW)

# SelectedPage değişkeninde belirlenen ve okunmak istenen madde query değeri ile beraber pageSelect fonksiyonuna yollanır.
# pageSelect searchQuery içindeki selectedPage'in indeksteki karşılığı olan maddeyi alıp sorgulatır ve ardından hepsini page değişkenine uygular.
page = pageSelect(searchQuery, selectedPage)
emptyLine()

# page değeri içindeki title vb. içerikler düzenlenerek kullanıcının okuyabileceği bir formata getirilir.
resultRender(page)

# Aranan sorgunun Wiki URL'i kullanıcının clipboard'una otomatik olarak yapıştırılır. İleride bu seçenek opsiyonel olacak.
try:
    pyperclip.copy(page.url)
    print(Fore.RED + "Full URL copied to your clipboard")
except pyperclip.PyperclipException:
    error("Your clipboard engine doesnt work or not exist.")
Exemplo n.º 5
0
def car_actions(maze, cars, functions, debug=False):
    """
        Runs any functions a car is on.
    """
    global switchgate
    global xcoordplot
    global ycoordplot

    # Do signal first so it's enabled before any functions are run.
    signals = []
    for car in cars:
        if maze[car.y][car.x].name == 'signal':
            signals.append(maze[car.y][car.x].value)

    logs = ''
    removed = []
    for car in cars:

        # Count down any paused cars.
        if car.pause:
            car.pause -= 1
            continue

        cell = maze[car.y][car.x]

        # Actions:
        if cell.name == 'wall':
            funcs.error('Car got in wall.')

        elif cell.name == 'path':
            pass

        elif cell.name == 'pause':
            car.pause = int(cell.value)

        elif cell.name == 'hole':
            removed.append(car)

        elif cell.name == 'out':
            logs += str(car.value)

        elif cell.name == 'ln-out':
            logs += str(car.value) + '\n'

        elif cell.name == 'in':
            car.value = input('> ')

        elif cell.name == 'one-use':
            cell.name = 'wall'
            cell.value = controls.display['wall']

        elif cell.name == 'direction':
            car.direction = cell.value[1]

        elif cell.name == 'function':
            function = functions[cell.value]
            try:
                result = str(function(car.value))
            except TypeError:
                result = str(function(car.value, signals))

            if not result == 'None':
                match = re.match(controls.regexes['direction'], result)
                if match:
                    car.direction = result[1]
                else:
                    car.value = str(result)
        elif cell.name == 'passenger':
            car.busstop = str(cell.value)
        elif cell.name == 'bus-stop':
            #Passenger and bench Operations
            op = car.busstop
            if op == ';-':
                car.passengers[-1] = Decimal(car.passengers[-1]) - Decimal(
                    cell.bench)
            if op == ';+':
                car.passengers[-1] = Decimal(car.passengers[-1]) + Decimal(
                    cell.bench)
            if op == ';*':
                car.passengers[-1] = Decimal(car.passengers[-1]) * Decimal(
                    cell.bench)
            if op == ';/':
                car.passengers[-1] = Decimal(car.passengers[-1]) / Decimal(
                    cell.bench)
            if op == ';$':
                car.passengers.append(Decimal(cell.corner))
            if op == ';s':
                passbuff = Decimal(car.passengers[-1])
                drivbuff = Decimal(car.value)
                car.value = Decimal(passbuff)
                car.passengers[-1] = Decimal(drivbuff)
            if op == ';c':
                car.passengers.append(Decimal(car.value))
            if op == ';k':
                car.passengers = car.passengers[:-1]
            if op == ';l':
                cell.bench = Decimal(car.passengers[-1])
                car.passengers = car.passengers[:-1]
            if op == ';h':
                car.value = Decimal(cell.bench)
                cell.bench = Decimal(0)
            if op == ';w':
                switchgate = car.value
            if op == ';u':
                car.value = switchgate
            if op == ';x':
                xcoordplot.append(Decimal(car.value))
            if op == ';y':
                ycoordplot.append(Decimal(car.value))
            if op == ';t':
                tcoordplot.append(Decimal(car.value))
            if op == ';p':
                a = [tcoordplot, xcoordplot, ycoordplot]
                at = [
                    reduce(lambda z, k: str(z) + " " + str(k), list(x))
                    for x in zip(*a)
                ]
                lines = ['t x y']
                lines.extend(at)
                end = [
                    "", "", "set xlabel <xlabel>'", "set ylabel '<ylabel>'",
                    "set title '<title>'", "set pointsize 1.5 ",
                    "set terminal png size 1200,900 enhanced font \"Helvetica,20\"",
                    "set key top right", "set output 'output.png'",
                    "plot \"Plotdata.dat\" using 1:2 title '<x series>', \"Plotdata.dat\" using 1:3 title '<y series>'",
                    "quit"
                ]
                lines.extend(end)
                file = open("Plotdata.dat", "w")
                for line in lines:
                    file.write(line + "\r\n")
                file.close()

            car.busstop = ''
    # Remove any deleted cars.
    for car in removed:
        cars.remove(car)

    return maze, cars, logs
Exemplo n.º 6
0
#--------------------------------------------------------------
#--------------------------------------------------------------

for i in range(1000):
    error_for_all = np.zeros(3)
    for i in range(len(toes)):
        input = np.array([toes[i], wlrec[i], nfans[i]])

        true = np.array([injuries[i], win[i], sadness[i]])

        prediction = f.neural_network(input, weights)

        delta = f.delta(true, prediction)

        error = f.error(delta)

        error_for_all += error

        weight_deltas = f.weight_deltas(input, delta)

        weights = f.weights_balance(weights, weight_deltas)

    print("Error:", *error_for_all)

print("\n----------------------------------------------------\n\nWeights:")
for i in weights:
    for j in i:
        print("%9f" % round(j, 5), end='  ')
    print()