Пример #1
0
def Part1(lines):
    grid = com.CartesianGrid()
    myShip = waterVessel()
    shipPoint = com.Point(0, 0, myShip)
    grid.addPoint(shipPoint)
    myShip.setPoint(shipPoint)
    for line in lines:
        command = line[0]
        units = int(line[1:].strip())
        if command == 'N':
            myShip.moveNorth(units)
        elif command == 'E':
            myShip.moveEast(units)
        elif command == 'S':
            myShip.moveSouth(units)
        elif command == 'W':
            myShip.moveWest(units)
        elif command == 'L':
            # turning left should be the same as moving negative degrees
            myShip.turn(-units)
        elif command == 'R':
            myShip.turn(units)
        elif command == 'F':
            myShip.moveForward(units)
    return shipPoint.ManhattenDistance(com.Point(0, 0, None))
Пример #2
0
def runSimulation(lines, getOldAndNewSeatFcn):
    grid = com.CartesianGrid(' ')
    x = 0
    y = 0
    for line in lines:
        for char in line.strip():
            point = com.Point(x, y, char)
            grid.addPoint(point)
            x += 1
        x = 0
        y -= 1

    loops = 0
    while True:
        newGrid = com.CartesianGrid(' ')
        hadChange = False
        for y in range(0, -1 * len(lines), -1):
            for x in range(len(lines[0].strip())):
                oldSeat, newSeat = getOldAndNewSeatFcn(grid, x, y)
                newPoint = com.Point(x, y, newSeat)
                hadChange |= oldSeat != newSeat
                newGrid.addPoint(newPoint)
        grid = newGrid
        if not hadChange:
            break
        loops += 1

    count = 0
    for point in grid.getAllPoints():
        if point.data == '#':
            count += 1
    return count
Пример #3
0
 def inputHandler():
     nonlocal grid, currentPoint, OPEN, WALL, north, east, south, west, directions, facingIdx, directionInputs, nextPoint, turned
     while True:
         leftIdx = (facingIdx + 1) % 4
         newCoords = currentPoint + directions[leftIdx]
         leftPoint = grid.getPoint(newCoords[0], newCoords[1])
         if leftPoint is None:
             nextPoint = com.Point(newCoords[0], newCoords[1], 99999999)
             grid.addPoint(nextPoint)
             print('left point at ', nextPoint.x, nextPoint.y, ' not visited. Facing', facingIdx)
             turned = True
             return directionInputs[leftIdx]
         elif leftPoint.data >= OPEN:
             nextPoint = leftPoint
             facingIdx = leftIdx
             print('left point at ', nextPoint.x, nextPoint.y, ' is open. Facing', facingIdx)
             return directionInputs[leftIdx]
         
         # go straight
         newCoords = currentPoint + directions[facingIdx]
         forwardPoint = grid.getPoint(newCoords[0], newCoords[1])
         if forwardPoint is None:
             forwardPoint = com.Point(newCoords[0], newCoords[1], 99999999)
             grid.addPoint(forwardPoint)
             print('fwd point at ', nextPoint.x, nextPoint.y, ' is empty. Facing', facingIdx)
         elif forwardPoint.data == WALL:
             facingIdx = (facingIdx - 1) % 4
             print('fwd point at ', nextPoint.x, nextPoint.y, ' is Wall. Facing', facingIdx)
             continue
         else:
             print('fwd point at ', nextPoint.x, nextPoint.y, ' is open. Facing', facingIdx)
         nextPoint = forwardPoint
         return directionInputs[facingIdx]
Пример #4
0
def runEnhancementCalcs(lines, numEnhancements):
    enhancementAlgorithm = None
    picture = com.CartesianGrid(flipOutput=True)
    squareSize = 0
    y = 0
    for line in lines:
        stripped = line.strip()
        if stripped == '':
            continue
        if enhancementAlgorithm is None:
            enhancementAlgorithm = stripped
            continue
        x = 0
        for char in stripped:
            point = com.Point(x, y, char)
            picture.addPoint(point)
            x += 1
        y += 1
        squareSize = max(squareSize, y)

    print(picture)
    extrasToAdd = 1
    outsideValue = '.'
    for i in range(numEnhancements):
        #print('Before')
        #print(picture)
        picture.moveAllPoints(extrasToAdd, extrasToAdd)
        squareSize += (extrasToAdd * 2)
        for x in range(squareSize):
            for extra in range(extrasToAdd):
                picture.addPoint(com.Point(x, extra, outsideValue))
                picture.addPoint(com.Point(extra, x, outsideValue))
                picture.addPoint(
                    com.Point(squareSize - (extra + 1), x, outsideValue))
                picture.addPoint(
                    com.Point(x, squareSize - (extra + 1), outsideValue))

        #print('After Shift')
        #print(picture)
        picture = enhance(picture, enhancementAlgorithm, outsideValue)
        #print('After Enhance')
        #print(picture)

        outsideValue = enhancementAlgorithm[0]
        if i % 2 != 0 and outsideValue == '#':
            outsideValue = enhancementAlgorithm[-1]

    print(picture)
    total = 0
    for point in picture.getAllPoints():
        if point.data == '#':
            total += 1
    return total
Пример #5
0
def Part1(lines):
    grid = com.CartesianGrid()
    centralPort = com.Point(0, 0, -1)
    lineId = 0
    smallestDistance = 99999999999
    for line in lines:
        x = 0
        y = 0
        for split in line.split(','):
            direction = split[0]
            length = int(split[1:])
            xDelta = 0
            yDelta = 0
            if direction == 'U':
                yDelta = length
            elif direction == 'D':
                yDelta = -length
            elif direction == 'R':
                xDelta = length
            elif direction == 'L':
                xDelta = -length
            if xDelta:
                newX = x + xDelta
                for xRange in range(min(x, newX), max(x, newX), 1):
                    point = com.Point(xRange, y, lineId)
                    existingPoint = grid.getPoint(xRange, y)
                    if existingPoint and point.data != existingPoint.data:
                        distance = centralPort.ManhattenDistance(point)
                        if distance > 0 and distance < smallestDistance:
                            smallestDistance = distance
                            closestPoint = point
                    grid.addPoint(point)
                x = newX

            if yDelta:
                newY = y + yDelta
                for yRange in range(min(y, newY), max(y, newY), 1):
                    point = com.Point(x, yRange, lineId)
                    existingPoint = grid.getPoint(x, yRange)
                    if existingPoint and point.data != existingPoint.data:
                        distance = centralPort.ManhattenDistance(point)
                        if distance > 0 and distance < smallestDistance:
                            smallestDistance = distance
                            closestPoint = point
                    grid.addPoint(point)
                y = newY

        lineId = lineId + 1
    print('smallest = ' + str(smallestDistance) + ': ' + str(closestPoint.x) +
          ', ' + str(closestPoint.y))
Пример #6
0
def doOrigami(lines: List[str], isPart1):
    parseFolds = False
    folds = list()
    grid = com.CartesianGrid(flipOutput=True)
    for line in lines:
        if line.strip() == "":
            parseFolds = True
            continue
        if parseFolds:
            axis, num = line.strip().split(' ')[2].split('=')
            folds.append((axis, int(num)))
        else:
            x, y = line.strip().split(',')
            point = com.Point(int(x), int(y), '#')
            grid.addPoint(point)

    for axis, lineNum in folds:
        foldGrid(grid, axis, lineNum)
        # part 1 is just one fold
        if isPart1:
            break

    if part1:
        return len(grid.getAllPoints())
    else:
        # Easier to just print out the grid and read it to submit
        print(grid)
        return None
Пример #7
0
def makeBlankGrid():
    grid = com.CartesianGrid()
    for y in range(5):
        for x in range(5):
            point = com.Point(x, y, '.')
            grid.addPoint(point)
            x += 1
        y += 1
        x = 0
    return grid
Пример #8
0
def makeCaveGrid(lines):
    grid = com.CartesianGrid(flipOutput=True)
    y = 0
    for line in lines:
        x = 0
        for char in line.strip():
            point = com.Point(x, y, int(char))
            grid.addPoint(point)
            x += 1
        y += 1
    return grid
Пример #9
0
def Part1(lines):
    point = com.Point(0, 0, None)
    for line in lines:
        direction, amount = line.split(' ')
        amount = int(amount)
        if (direction == 'forward'):
            point.x += amount
        if (direction == 'up'):
            point.y -= amount
        if (direction == 'down'):
            point.y += amount
    return point.x * point.y
Пример #10
0
 def outputCallback(output):
     nonlocal grid, currentX, currentY
     value = chr(output)
     if output == 10:
         currentY += 1
         currentX = 0
         print('\n', end='')
     else:
         currentPoint = com.Point(currentX, currentY, value)
         grid.addPoint(currentPoint)
         currentX += 1
         print(value, end='')
Пример #11
0
def Part1(lines):
    global compys, grid, keepRunning
    compys.append([None, [0, 0], [], deque()])
    origin = com.Point(0, 0, None)
    grid.addPoint(origin)
    intCode = com.intCode(lines[0],
                          False,
                          hasOutputCallback=outputCallback(0),
                          needsInputCallback=inputCallback(0))
    compys[0][0] = intCode
    while keepRunning:
        intCode.RunIntCodeComputer()
Пример #12
0
def Part2(lines):
    grid = com.CartesianGrid()
    myShip = waterVessel()
    shipPoint = com.Point(0, 0, myShip)
    grid.addPoint(shipPoint)
    myShip.setPoint(shipPoint)
    waypoint = waterVessel()
    waypointPoint = com.Point(10, 1, waypoint)
    grid.addPoint(waypointPoint)
    waypoint.setPoint(waypointPoint)
    origin = com.Point(0, 0, None)
    grid.addPoint(origin)
    for line in lines:
        command = line[0]
        units = int(line[1:].strip())
        if command == 'N':
            waypoint.moveNorth(units)
        elif command == 'E':
            waypoint.moveEast(units)
        elif command == 'S':
            waypoint.moveSouth(units)
        elif command == 'W':
            waypoint.moveWest(units)
        elif command == 'L':
            # turning left should be the same as moving negative degrees
            rotateWaypoint(origin, -units, waypointPoint)
        elif command == 'R':
            rotateWaypoint(origin, units, waypointPoint)
        elif command == 'F':
            print('ship ' + str(shipPoint.x) + ', ' + str(shipPoint.y))
            print('waypoint ' + str(waypointPoint.x) + ', ' +
                  str(waypointPoint.y))
            scaledVector = com.util.vector_math(
                mul, [waypointPoint.x, waypointPoint.y], [units, units])
            print('scaledVector ' + str(scaledVector[0]) + ', ' +
                  str(scaledVector[1]))
            shipPoint.move(*scaledVector)
            # don't actually need to move the waypoint as it's always relative to the ship
            print('movedShip ' + str(shipPoint.x) + ', ' + str(shipPoint.y))
    return shipPoint.ManhattenDistance(com.Point(0, 0, None))
Пример #13
0
def Part1(lines):
    grid = com.CartesianGrid(' ')
    keysAndDoors = {}
    start = None
    KEY = 0
    DOOR = 1
    remainingKeys = set()
    openSpaces = []
    y = 0
    openSpaceIdx = 0
    for line in lines:
        x = 0
        for char in line.strip():
            if char != '#':
                data = char
                if char == '.':
                    data = openSpaceIdx
                    openSpaceIdx += 1
                point = com.Point(x, y, data)
                grid.addPoint(point)
                if char == '@':
                    start = point
                elif char != '.':
                    charToLower = char.lower()
                    existing = keysAndDoors.get(charToLower)
                    if existing is None:
                        existing = [None, None]
                        keysAndDoors[charToLower] = existing
                    if charToLower == char:
                        existing[KEY] = point
                        remainingKeys.add(point.data)
                    else:
                        existing[DOOR] = point
            x += 1
        y += 1
    ownedKeys = set()
    graph = com.Graph(False, edgeWeightFcn(ownedKeys))
    for point in grid.getAllPoints():
        graph.add_node(point.data)
        previouslyHit = set()
        previouslyHit.add(point)
        connected = connectedGridElements(grid, point, 0, previouslyHit)
        for edge in connected:
            graph.add_edge(point.data, edge[0], edge[1], False)

    for openSpace in range(openSpaceIdx):
        graph.remove_node(openSpace)
    
    answer, path = findShortest(graph, '@', ownedKeys, remainingKeys, 0)
    print(answer)
    print(path)
    return answer
Пример #14
0
 def outputCallback(output):
     nonlocal x, y, tid, grid, numBlocks
     if x is None:
         x = output
     elif y is None:
         y = output
     elif tid is None:
         tid = output
         point = com.Point(x, y, tid)
         if tid == 2:
             numBlocks += 1
         grid.addPoint(point)
         x = None
         y = None
         tid = None
Пример #15
0
    def __init__(self, ID, spawnPosition):

        if not isinstance(ID, str):
            raise Exception("ID must be string")
        if not isinstance(spawnPosition, common.Point):
            if isinstance(spawnPosition, str):
                spawnPosition = common.Point(spawnPosition)
            else:
                raise Exception(
                    "spawnPosition must be or a string inform of a point or a point "
                )
        self.ID = ID
        self.selector = "@e[name={0}]".format(self.ID)
        self.spawnPosition = spawnPosition

        CartPivot.used.append(self)
Пример #16
0
def runRobot(line, startingColor):
    grid = com.CartesianGrid(' ', cellStr)
    black = 0
    white = 1
    currentPoint = com.Point(0, 0, startingColor)
    grid.addPoint(currentPoint)
    painted = set()
    needsColorOutput = True
    up = [0, 1]
    right = [1, 0]
    down = [0, -1]
    left = [-1, 0]
    directions = [up, right, down, left]
    facingIdx = 0

    def outputCallback(output):
        nonlocal needsColorOutput, currentPoint, painted, directions, facingIdx
        if needsColorOutput:
            currentPoint.data = output
            painted.add(currentPoint)
            needsColorOutput = False
        else:
            if output == 0:
                facingIdx -= 1
            else:
                facingIdx += 1

            facingIdx %= 4
            nextX = currentPoint.x + directions[facingIdx][0]
            nextY = currentPoint.y + directions[facingIdx][1]
            currentPoint = grid.getPoint(nextX, nextY)
            if currentPoint is None:
                currentPoint = com.Point(nextX, nextY, 0)
                grid.addPoint(currentPoint)

            needsColorOutput = True

    def inputCallback():
        nonlocal currentPoint
        return currentPoint.data

    intcode = com.intCode(lines[0],
                          printOutput=False,
                          needsInputCallback=inputCallback,
                          hasOutputCallback=outputCallback)
    intcode.RunIntCodeComputer()
    return painted, grid
Пример #17
0
 def outputCallback(output):
     nonlocal grid, currentX, currentY, gridFinished
     if not gridFinished:
         if output > 256:
             print(output)
             return
         value = chr(output)
         if output == 10:
             currentY += 1
             currentX = 0
             print('\n', end='')
         else:
             currentPoint = com.Point(currentX, currentY, value)
             grid.addPoint(currentPoint)
             currentX += 1
             print(value, end='')
     else:
         print(output)
Пример #18
0
def enhance(picture: com.CartesianGrid, algorithm: str, outsideValue: str):
    newPicture = com.CartesianGrid(flipOutput=True)
    for point in picture.getAllPoints(True):
        lookup = ''
        pointsToCheck = picture.getAdjacentPoints(point.x, point.y, True, True)
        pointsToCheck.append(point)
        pointsToCheck = sorted(pointsToCheck, key=lambda x: (x.y, x.x))
        if len(pointsToCheck) != 9:
            test = 0
        for x in pointsToCheck:
            data = x.data
            if data is None:
                data = outsideValue
            if data == '#':
                lookup += '1'
            else:
                lookup += '0'
        newValue = algorithm[int(lookup, 2)]
        newPicture.addPoint(com.Point(point.x, point.y, newValue))
    return newPicture
Пример #19
0
 def outputCallback(output):
     nonlocal x, y, tid, grid, score, ball, paddle
     if x is None:
         x = output
     elif y is None:
         y = output
     elif tid is None:
         tid = output
         point = com.Point(x, y, tid)
         if tid > 4 and x == -1 and y == 0:
             score = tid
         else:
             if tid == 4:
                 ball = point
             elif tid == 3:
                 paddle = point
             grid.addPoint(point)
         x = None
         y = None
         tid = None
Пример #20
0
def buyorder(typeid, price, quantity):
    quickbar.openItem(typeid)
    cm.sleep(3)
    thing = pyautogui.locateOnScreen('imgs/placebuyorder.png')
    buyorderpos = cm.Point(thing.left + thing.width / 2,
                           thing.top + thing.height / 2)
    cm.clickPoint(buyorderpos)
    cm.sleep(2)
    thing = pyautogui.locateOnScreen('imgs/buyorderadvanced.png')
    if thing is not None:
        advanced = cm.Point(thing.left + thing.width / 2,
                            thing.top + thing.height / 2)
        cm.clickPoint(advanced)
        cm.sleep(1)
    thing = pyautogui.locateOnScreen('imgs/buyorderoriginpoint.png')
    bidpricefield = cm.Point(thing.left + 143, thing.top + 33)
    quantityfield = cm.Point(thing.left + 143, thing.top + 169)
    duration = cm.Point(thing.left + 143, thing.top + 190)
    threemonths = cm.Point(thing.left + 143, thing.top + 332)
    buything = pyautogui.locateOnScreen('imgs/buyandcancel.png')
    buybutton = cm.Point(buything.left + 25, buything.top + 7)
    cm.clickPoint(bidpricefield, 2)
    cm.sleep(0.3)
    cm.safetypewrite(price)
    cm.clickPoint(quantityfield, 2)
    cm.sleep(0.3)
    cm.safetypewrite(quantity)
    cm.clickPoint(duration)
    for _ in range(10):
        pyautogui.press('down')
    cm.clickPoint(duration)
    cm.clickPoint(buybutton, 1)
    cm.sleep(0.6)
    thing = pyautogui.locateOnScreen('imgs/confirmorder.png')
    confirmyes = cm.Point(thing.left + 149, thing.top + 197)
    cm.clickPoint(confirmyes)
    thing = pyautogui.locateOnScreen("imgs/warning.png", confidence=0.9)
    if thing is not None:
        cm.clickPointPNG("imgs/yesno.png", 20, 10)
Пример #21
0
    def outputCallback(output):
        nonlocal needsColorOutput, currentPoint, painted, directions, facingIdx
        if needsColorOutput:
            currentPoint.data = output
            painted.add(currentPoint)
            needsColorOutput = False
        else:
            if output == 0:
                facingIdx -= 1
            else:
                facingIdx += 1

            facingIdx %= 4
            nextX = currentPoint.x + directions[facingIdx][0]
            nextY = currentPoint.y + directions[facingIdx][1]
            currentPoint = grid.getPoint(nextX, nextY)
            if currentPoint is None:
                currentPoint = com.Point(nextX, nextY, 0)
                grid.addPoint(currentPoint)

            needsColorOutput = True
Пример #22
0
def Part2(lines):
    global grids
    x = 0
    y = 4
    base_grid = getGridAtLevel(0)
    for line in lines:
        for char in line.strip():
            point = com.Point(x, y, char)
            base_grid.addPoint(point)
            x += 1
        y -= 1
        x = 0
    
    for minute in range(1, 201):
        changes = []
        for gridLvl in [key for key in grids.keys()]:
            if abs(gridLvl) > minute:
                continue
            for point in grids[gridLvl].getAllPoints():
                if point.x == 2 and point.y == 2:
                    continue
                if newValue2(point, grids[gridLvl], gridLvl) != point.data:
                    changes.append(point)
        for change in changes:
            if change.data == '#':
                change.data = '.'
            else:
                change.data = '#'
        print('minute=', minute)
        #keys = sorted([key for key in grids.keys()])
        #for grid in keys:
        #    print('grid', grid)
        #    print(grids[grid])
        minute += 1
    bugs = 0
    for grid in grids:
        for point in grids[grid].getAllPoints():
            if point.data == '#':
                bugs += 1
    print(bugs)
Пример #23
0
def Part1(lines):
    x = 0
    y = 4
    grid = com.CartesianGrid()
    for line in lines:
        for char in line.strip():
            point = com.Point(x, y, char)
            grid.addPoint(point)
            x += 1
        y -= 1
        x = 0
    
    minute = 1
    states = {}
    while True:
        changes = []
        for point in grid.getAllPoints():
            if newValue(point, grid) != point.data:
                changes.append(point)
        for change in changes:
            if change.data == '#':
                change.data = '.'
            else:
                change.data = '#'
        print(minute, '\n', grid, sep='')
        state = tuple(i.data for i in grid.getAllPoints())
        foundState = states.get(state)
        if foundState is not None:
            break
        states[state] = True
        minute += 1
    biodiversity = 0
    powerOfTwo = 1
    for point in grid.getAllPoints():
        if point.data == '#':
            biodiversity += powerOfTwo
        powerOfTwo *= 2
    print(biodiversity)
Пример #24
0
def shoot_probe(xMin: int, xMax: int, yMin: int, yMax: int, xVelocity: int,
                yVelocity: int, currentMaxHeight: Optional[int]):
    "Returns None if the probe misses the target or doesn't go over the current max height, else max height"
    global grid
    position = com.Point(0, 0, None)
    grid.addPoint(position)
    previousHeight = 0
    maxHeight = 0

    # Bail if we overshot in the X direction
    while (position.x <= xMax):
        if in_target(xMin, xMax, yMin, yMax, position):
            if not currentMaxHeight:
                # Part2 just needs to know if we hit the target
                return True
            if maxHeight > currentMaxHeight:
                return maxHeight
            return None

        position.move(xVelocity, yVelocity)
        maxHeight = max(maxHeight, position.y)

        if previousHeight > position.y:
            if currentMaxHeight and maxHeight < currentMaxHeight:
                # Bail if we didn't reach high enough
                return None
            elif position.y < yMin:
                # Bail if we overshot in the Y direction
                return None

        previousHeight = position.y
        yVelocity -= 1
        if xVelocity > 0:
            xVelocity -= 1
        elif xVelocity < 0:
            xVelocity += 1

    return None
Пример #25
0
    def internalCallback():
        nonlocal inputValue, inputIdx, compy
        if inputValue is None:
            if compy[3]:
                realInput = compy[3].pop()
            else:
                realInput = input()
                while realInput == 'print':
                    print(grid)
                    realInput = input()
            if realInput.startswith(take):
                ownedItems.add(realInput.replace(take, ''))
            move = False
            if realInput == north:
                compy[1] = com.vector_math(add, compy[1], grid.UP)
                move = True
            elif realInput == south:
                compy[1] = com.vector_math(add, compy[1], grid.DOWN)
                move = True
            elif realInput == west:
                compy[1] = com.vector_math(add, compy[1], grid.LEFT)
                move = True
            elif realInput == east:
                compy[1] = com.vector_math(add, compy[1], grid.RIGHT)
                move = True
            if move:
                point = com.Point(*compy[1], None)
                grid.addPoint(point)

            inputValue = toAsciiInts(realInput + '\n')
            inputIdx = 0

        valueToReturn = inputValue[inputIdx]
        inputIdx += 1
        if inputIdx == len(inputValue):
            inputValue = None
        return valueToReturn
Пример #26
0
def Part2(lines):
    grid = com.CartesianGrid()
    #centralPort = com.Point(0, 0, {-1 : 999999})
    lineId = 0
    smallestDistance = 99999999999
    for line in lines:
        x = 0
        y = 0
        steps = 0
        for split in line.split(','):
            direction = split[0]
            length = int(split[1:])
            xDelta = 0
            yDelta = 0
            if direction == 'U':
                yDelta = length
            elif direction == 'D':
                yDelta = -length
            elif direction == 'R':
                xDelta = length
            elif direction == 'L':
                xDelta = -length
            if xDelta:
                newX = x + xDelta
                rangeX = None
                if xDelta > 0:
                    rangeX = range(x, newX, 1)
                else:
                    rangeX = range(x, newX, -1)

                for xRange in rangeX:
                    if (xRange != 0 or y != 0):
                        steps = steps + 1
                    point = com.Point(xRange, y, {lineId: steps})
                    existingPoint = grid.getPoint(xRange, y)
                    if (xRange != 0 or y != 0
                        ) and existingPoint and existingPoint.data.get(
                            lineId) is None:
                        distance = existingPoint.data[0] + steps
                        if distance > 0 and distance < smallestDistance:
                            smallestDistance = distance
                            closestPoint = point
                    grid.addPoint(point)
                x = newX

            if yDelta:
                newY = y + yDelta
                rangeY = None
                if yDelta > 0:
                    rangeY = range(y, newY, 1)
                else:
                    rangeY = range(y, newY, -1)

                for yRange in rangeY:
                    if (x != 0 or yRange != 0):
                        steps = steps + 1
                    point = com.Point(x, yRange, {lineId: steps})
                    existingPoint = grid.getPoint(x, yRange)
                    if (x != 0 or yRange != 0
                        ) and existingPoint and existingPoint.data.get(
                            lineId) is None:
                        distance = existingPoint.data[0] + steps
                        if distance > 0 and distance < smallestDistance:
                            smallestDistance = distance
                            closestPoint = point
                    grid.addPoint(point)
                y = newY

        lineId = lineId + 1
    #print(grid)
    print('smallest = ' + str(smallestDistance) + ': ' + str(closestPoint.x) +
          ', ' + str(closestPoint.y))
Пример #27
0
 logging.basicConfig(level=logging.DEBUG, filename="logfile.txt", filemode="a+",
                     format="%(asctime)-15s %(levelname)-8s %(message)s")
 #need this for the sleep calls in cm.clickpoint
 variables.init()
 tradedaystart = cm.getEVETimestamp()
 process = multiprocessing.Process(target=mainwrapper.doTradeBot, args=(tradedaystart,))
 process.start()
 while True:
     try:
         if not process.is_alive():
             sys.exit()
         cl = pyautogui.locateOnScreen("imgs/connectionlost.png", confidence=0.9)
         if(cl is not None):
             process.terminate()
             print("we lost connection, initiating restart procedure")
             point = cm.Point(cl.left + 169, cl.top + 194)
             cm.clickPoint(point, 5)
             #wait 20 minutes for internet to come back or eve to restart
             time.sleep(1200)
             lg = pyautogui.locateOnScreen("imgs/launchgroup.png")
             pn = pyautogui.locateOnScreen("imgs/playnow.png")
             while (lg is None and pn is None):
                 cm.clickPointPNG("imgs/evetaskbar.png", 5, 5)
                 lg = pyautogui.locateOnScreen("imgs/launchgroup.png")
                 pn = pyautogui.locateOnScreen("imgs/playnow.png")
                 time.sleep(5)
             print("starting eve client")
             cm.clickPointPNG("imgs/launchgroup.png", 10, 10)
             cm.clickPointPNG("imgs/playnow.png", 10, 10)
             #wait for game to start
             time.sleep(60)
Пример #28
0
def Part2(lines):
    OPEN = 1
    WALL = 0
    currentPoint = com.Point(0, 0, OPEN)
    nextPoint = None
    north = [0, 1]
    east = [1, 0]
    south = [0, -1]
    west = [-1, 0]
    directions = [east, north, west, south]
    directionInputs = [4, 1, 3, 2]
    facingIdx = 0
    turned = False
    maxSteps = 9999999999999
    def outputPoint(point):
        nonlocal facingIdx, currentPoint
        if point.data == 0:
            return '#'
        elif point == currentPoint:
            if facingIdx == 0:
                return '>'
            elif facingIdx == 1:
                return '^'
            elif facingIdx == 2:
                return '<'
            elif facingIdx == 3:
                return 'v'
        return '.'
    grid = com.CartesianGrid(' ', outputPoint)
    grid.addPoint(currentPoint)

    def inputHandler():
        nonlocal grid, currentPoint, OPEN, WALL, north, east, south, west, directions, facingIdx, directionInputs, nextPoint, turned
        while True:
            leftIdx = (facingIdx + 1) % 4
            newCoords = currentPoint + directions[leftIdx]
            leftPoint = grid.getPoint(newCoords[0], newCoords[1])
            if leftPoint is None:
                nextPoint = com.Point(newCoords[0], newCoords[1], 99999999)
                grid.addPoint(nextPoint)
                #print('left point at ', nextPoint.x, nextPoint.y, ' not visited. Facing', facingIdx)
                turned = True
                return directionInputs[leftIdx]
            elif leftPoint.data >= OPEN:
                nextPoint = leftPoint
                facingIdx = leftIdx
                #print('left point at ', nextPoint.x, nextPoint.y, ' is open. Facing', facingIdx)
                return directionInputs[leftIdx]
            
            # go straight
            newCoords = currentPoint + directions[facingIdx]
            forwardPoint = grid.getPoint(newCoords[0], newCoords[1])
            if forwardPoint is None:
                forwardPoint = com.Point(newCoords[0], newCoords[1], 99999999)
                grid.addPoint(forwardPoint)
                #print('fwd point at ', nextPoint.x, nextPoint.y, ' is empty. Facing', facingIdx)
            elif forwardPoint.data == WALL:
                facingIdx = (facingIdx - 1) % 4
                #print('fwd point at ', nextPoint.x, nextPoint.y, ' is Wall. Facing', facingIdx)
                continue
            else:
                pass
                #print('fwd point at ', nextPoint.x, nextPoint.y, ' is open. Facing', facingIdx)
            nextPoint = forwardPoint
            return directionInputs[facingIdx]
    
    def outputHandler(output):
        nonlocal grid, currentPoint, OPEN, WALL, nextPoint, turned, facingIdx, maxSteps
        localTurned = turned
        turned = False
        if output == WALL:
            nextPoint.data = output
            #print('Ran into wall at', nextPoint.x, nextPoint.y)
        elif output == 2:
            print('Oxygen system at ', nextPoint.x, nextPoint.y, 'with steps', currentPoint.data)
            for point in grid.getAllPoints():
                if point.data > WALL:
                    point.data = 9999999999999999999999999
            nextPoint.data = WALL # make it a wall so we don't go back
            currentPoint = nextPoint
            maxSteps = 0
            return
        elif output == OPEN:
            steps = currentPoint.data + 1
            if steps < nextPoint.data:
                nextPoint.data = steps
                if maxSteps < steps:
                    maxSteps = steps
            #print('Walked to', nextPoint.x, nextPoint.y, 'with steps', steps)
            if steps % 20 == 0:
                print(grid)
            if localTurned:
                facingIdx = (facingIdx + 1) % 4
            currentPoint = nextPoint

    compy = com.intCode(lines[0], False, None, inputHandler, outputHandler)
    compy.RunIntCodeComputer()
Пример #29
0
		self.name=name
		self.rowStreak=0
	def makeLink(self,name,command):
		if self.rowStreak > ChatHub.maxRow:
			self.rowStreak=0
			name+="\n"
		self.links.append((name,command))
	def breakRow(self):
		self.rowStreak=0
	def show(self):
		start=self.start
		toRet='/tellraw @p { "text":"==='+self.name+'===]\\n","extra":['
		i=0
		for link in self.links:
			cmd="/setblock {} {} {} redstone_block".format(start.x,start.y,start.z+i)
			toRet+='{"text":"'+link[0]+' ","clickEvent":{"action":"run_command","value":"'+cmd+'"}}'
			i+=1
			if i <len(self.links):
				toRet+=","
			

		toRet+=']}'
		print ("saying to the chat "+toRet)
		return toRet
	def action(self,i):
		try:
			return self.links[i][1]
		except IndexError:
			return "/say This link is broken"
chatHub=ChatHub("LinkHub",common.Point(46,12,-3))
Пример #30
0
def sellitemininventory(typeid, price):
    item = api.getNameFromID(typeid)
    cm.clickPointPNG('imgs/inventorytopright.png', 0, 25, 2, cache=True)
    cm.sleep(0.2)
    cm.safetypewrite(item)

    stackitems(item)

    cm.sleep(0.5)

    thing = pyautogui.locateOnScreen('imgs/inventoryitemhangar.png')
    inventorylist = cm.Area(thing.left + 25, thing.top + 70, 500, 250)

    cm.sleep(1)

    box = inventorylist.toAbsTuple()
    ocr = cm.grabandocr(box)

    #todo implement ocr with highestsim check
    for s in ocr.splitlines():
        if (s.split()[-1][:5] in item.lower()):
            offsetpos = inventorylist
            mousex = offsetpos.x + int(s.split()[6]) / 4 + 5
            mousey = offsetpos.y + int(s.split()[7]) / 4 + 5
            cm.clickxy(mousex, mousey, clicks=1, right=True)
            cm.sleep(0.2)

            box = (mousex + 15, mousey + 2, mousex + 15 + 135,
                   mousey + 3 + 200)
            ocr = cm.grabandocr(box)

            for s in ocr.splitlines():
                if (s.split()[-1] == "sell"):
                    mousex = mousex + 18 + int(s.split()[6]) / 4 + 5
                    mousey = mousey + 3 + int(s.split()[7]) / 4 + 5
                    cm.clickxy(mousex, mousey)
                    cm.sleep(5)
                    #todo replace this with clickpointpng
                    thing = pyautogui.locateOnScreen('imgs/sellitems.png')
                    pricefield = cm.Point(thing.left + thing.width / 2,
                                          thing.top + 80)
                    thing = pyautogui.locateOnScreen(
                        'imgs/sellitemsellcancel.png')
                    sellbutton = cm.Point(thing.left + 25, thing.top + 12)
                    thing = pyautogui.locateOnScreen(
                        'imgs/sellitemduration.png')
                    duration = cm.Point(thing.left - 50, thing.top + 28)

                    #set duration to 3 months
                    cm.clickPoint(duration)
                    for _ in range(10):
                        pyautogui.press('down')
                    cm.clickPoint(duration)

                    #set price
                    pyautogui.moveTo(pricefield.x, pricefield.y)
                    cm.sleep(0.3)
                    pyautogui.doubleClick(pricefield.x, pricefield.y)
                    cm.safetypewrite(price)

                    cm.clickPoint(sellbutton)
                    cm.sleep(0.5)
                    thing = pyautogui.locateOnScreen(
                        'imgs/sellitemconfirm.png')
                    confirmbutton = cm.Point(thing.left + 145, thing.top + 193)
                    cm.clickPoint(confirmbutton)
                    thing = pyautogui.locateOnScreen("imgs/warning.png",
                                                     confidence=0.9)
                    if thing is not None:
                        cm.clickPointPNG("imgs/yesno.png", 20, 10)

                    return 1
    return 0