示例#1
0
def drawMower(x, y, direction):
    bext.fg('red')
    if direction == 'right':
        mowerText = MOWER_RIGHT
    elif direction == 'left':
        mowerText = MOWER_LEFT

    for i in range(MOWER_LEN):
        if 0 <= mowerx + i < WIDTH:
            bext.goto(x + i, mowery)
            print(mowerText[i], end='')
示例#2
0
def drawMower(mowerx, mowery, direction):
    """Draw the lawn mower with its left edge at mowerx, mowery."""
    bext.fg('red')
    if direction == 'right':
        mowerText = MOWER_RIGHT
    elif direction == 'left':
        mowerText = MOWER_LEFT

    for i in range(MOWER_LEN):
        if 0 <= mowerx + i < WIDTH:
            bext.goto(mowerx + i, mowery)
            print(mowerText[i], end='')
def drawLinesBetweenPoints(points, character):
    """Prints a line of characters between the specified points."""
    for i, point in enumerate(points):
        pointA = point
        if i == len(points) - 1:
            # The last point draws a line to the first point:
            pointB = points[0]
        else:
            # Draw the line to the next point:
            pointB = points[i + 1]
        # Loop over every x, y point from pointA to pointB:
        for x, y in line(pointA[X], pointA[Y], pointB[X], pointB[Y]):
            bext.goto(x, y)
            print(character, end='')
def displayForest(forest):
    """Display the forest data structure on the screen."""
    bext.goto(0, 0)
    for y in range(forest['height']):
        for x in range(forest['width']):
            if forest[(x, y)] == TREE:
                bext.fg('green')
                print(TREE, end='')
            elif forest[(x, y)] == FIRE:
                bext.fg('red')
                print(FIRE, end='')
            elif forest[(x, y)] == EMPTY:
                print(EMPTY, end='')
        print()
    bext.fg('reset')  # Use the default font color.
    print('Grow chance: {}%  '.format(GROW_CHANCE * 100), end='')
    print('Lightning chance: {}%  '.format(FIRE_CHANCE * 100), end='')
    print('Press Ctrl-C to quit.')
示例#5
0
def main():
    # Generate snake data structures:
    snakes = []
    for i in range(NUMBER_OF_SNAKES):
        snakes.append(Snake())

    bext.clear()
    while True:  # Main simulation loop.
        # Draw quit message.
        bext.fg('white')
        bext.goto(0, 0)
        print('Ctrl-C to quit.', end='')

        for snake in snakes:
            snake.display()

        for snake in snakes:
            snake.moveRandom()

        sys.stdout.flush()
        time.sleep(PAUSE_LENGTH)
示例#6
0
def main():
    # Generate worm data structures:
    worms = []
    for i in range(NUMBER_OF_WORMS):
        worms.append(Worm())

    bext.clear()
    while True:  # Main simulation loop.
        # Draw quit message.
        bext.fg('white')
        bext.goto(0, 0)
        print('Ctrl-C to quit.', end='')

        for worm in worms:
            worm.display()

        for worm in worms:
            worm.moveRandom()

        sys.stdout.flush()
        time.sleep(PAUSE_LENGTH)
示例#7
0
def main():
    theFloor = getNewFloor()

    # Generate painters:
    painters = []
    for color in THE_PAINTERS:
        painters.append(Painter(color, theFloor))

    bext.fg('black')
    bext.clear()
    while True:  # Main simulation loop.
        # Draw quit message.
        bext.bg('white')
        bext.goto(0, 0)
        print('Ctrl-C to quit.', end='')

        for painter in painters:
            painter.move()

        sys.stdout.flush()
        time.sleep(PAUSE_LENGTH)
示例#8
0
def displayBoard(board, ants, changedTiles):
    """Displays the board and ants on the screen. The changedTiles
    argument is a list of (x, y) tuples for tiles on the screen that
    have changed and need to be redrawn."""

    # Draw the board data structure:
    for x, y in changedTiles:
        bext.goto(x, y)
        if board.get((x, y), False):
            bext.bg(BLACK_TILE)
        else:
            bext.bg(WHITE_TILE)

        antIsHere = False
        for ant in ants:
            if (x, y) == (ant['x'], ant['y']):
                antIsHere = True
                if ant['direction'] == NORTH:
                    print(ANT_UP, end='')
                elif ant['direction'] == SOUTH:
                    print(ANT_DOWN, end='')
                elif ant['direction'] == EAST:
                    print(ANT_LEFT, end='')
                elif ant['direction'] == WEST:
                    print(ANT_RIGHT, end='')
                break
        if not antIsHere:
            print(' ', end='')

    # Display the quit message at the bottom of the screen:
    bext.goto(0, HEIGHT)
    bext.bg(WHITE_TILE)
    print('Press Ctrl-C to quit.', end='')

    sys.stdout.flush()  # (Required for bext-using programs.)
    time.sleep(PAUSE_AMOUNT)
def main():
    bext.fg('yellow')
    bext.clear()

    # Draw the quit message:
    bext.goto(0, 0)
    print('Ctrl-C to quit.', end='')

    # Display the walls of the hourglass:
    for wall in HOURGLASS:
        bext.goto(wall[X], wall[Y])
        print(WALL, end='')

    while True:  # Main program loop.
        allSand = list(INITIAL_SAND)

        # Draw the initial sand:
        for sand in allSand:
            bext.goto(sand[X], sand[Y])
            print(SAND, end='')

        runHourglassSimulation(allSand)
示例#10
0
def clearAquarium():
    global FISHES, BUBBLERS, BUBBLES, KELP

    # Draw the bubbles:
    for bubble in BUBBLES:
        bext.goto(bubble['x'], bubble['y'])
        print(' ', end='')

    # Draw the fish:
    for fish in FISHES:
        bext.goto(fish['location']['x'], fish['location']['y'])

        # Draw each character of the fish text in the right color.
        print(' ' * len(fish['left'][0]), end='')

    # Draw the kelp:
    for kelp in KELPS:
        for i, kelpSegment in enumerate(kelp['segments']):
            bext.goto(kelp['x'], HEIGHT - 2 - i)
            print('  ', end='')

    sys.stdout.flush()  # (Required for bext-using programs.)
示例#11
0
def drawAquarium(step):
    global FISHES, BUBBLERS, BUBBLES, KELP

    # Simulate the fish for one step:
    for fish in FISHES:
        # Move the fish horizontally:
        if step % fish['hspeed'] == 0:
            if fish['goingRight']:
                if fish['location']['x'] != WIDTH - 1 - LONGEST_FISH_LENGTH:
                    fish['location']['x'] += 1  # Move the fish left.
                else:
                    fish['goingRight'] = not fish[
                        'goingRight']  # Turn the fish around.
                    fish['colors'].reverse()  # Turn the colors around too.
            elif not fish['goingRight']:
                if fish['location']['x'] != 0:
                    fish['location']['x'] -= 1  # Move the fish right.
                else:
                    fish['goingRight'] = not fish[
                        'goingRight']  # Turn the fish around.
                    fish['colors'].reverse()  # Turn the colors around too.

        # Fish can randomly change their horizontal direction:
        fish['hchange'] -= 1
        if fish['hchange'] == 0:
            fish['hchange'] = random.randint(10, 60)
            fish['goingRight'] = not fish[
                'goingRight']  # Turn the fish around.

        # Move the fish vertically:
        if step % fish['vspeed'] == 0:
            if fish['goingDown']:
                if fish['location']['y'] != HEIGHT - 2:
                    fish['location']['y'] += 1  # Move the fish down.
                else:
                    fish['goingDown'] = not fish[
                        'goingDown']  # Turn the fish around.
            elif not fish['goingDown']:
                if fish['location']['y'] != 0:
                    fish['location']['y'] -= 1  # Move the fish up.
                else:
                    fish['goingDown'] = not fish[
                        'goingDown']  # Turn the fish around.

        # Fish can randomly change their vertical direction:
        fish['vchange'] -= 1
        if fish['vchange'] == 0:
            fish['vchange'] = random.randint(2, 20)
            fish['goingDown'] = not fish['goingDown']  # Turn the fish around.

    # Generate bubbles from bubblers:
    for bubbler in BUBBLERS:
        if random.randint(0, 5) == 0:
            BUBBLES.append({'x': bubbler, 'y': HEIGHT - 2})

    # Simulate the bubbles for one step:
    for bubble in BUBBLES:
        r = random.randint(1, 5)
        if (r == 1) and (bubble['x'] != 0):
            bubble['x'] -= 1  # Bubble goes left.
        elif (r == 2) and (bubble['x'] != WIDTH - 1):
            bubble['x'] += 1  # Bubble goes right.

        bubble['y'] -= 1  # The bubble always goes up.

    # Iterate over BUBBLES in reverse because I'm modifying BUBBLES while iterating over it.
    for i in range(len(BUBBLES) - 1, -1, -1):
        if BUBBLES[i]['y'] == 0:  # Delete bubbles that reach the top.
            del BUBBLES[i]

    # Simulate the kelp waving for one step:
    for kelp in KELPS:
        for i, kelpSegment in enumerate(kelp['segments']):
            if random.randint(1, 20) == 1:  # 1 in 20 chance to change waving.
                if kelpSegment == '(':
                    kelp['segments'][i] = ')'
                elif kelpSegment == ')':
                    kelp['segments'][i] = '('

    # Draw the bubbles:
    bext.fg('white')
    for bubble in BUBBLES:
        bext.goto(bubble['x'], bubble['y'])
        print(random.choice(('o', 'O', chr(176))), end='')  # 176 is '°'

    # Draw the fish:
    for fish in FISHES:
        bext.goto(fish['location']['x'], fish['location']['y'])

        # Get the correct right- or left-facing fish text.
        if fish['goingRight']:
            fishText = fish['right'][step % len(fish['right'])]
        elif not fish['goingRight']:
            fishText = fish['left'][step % len(fish['left'])]

        # Draw each character of the fish text in the right color.
        for i, fishPart in enumerate(fishText):
            bext.fg(fish['colors'][i])
            print(fishPart, end='')

    # Draw the kelp:
    bext.fg('green')
    for kelp in KELPS:
        for i, kelpSegment in enumerate(kelp['segments']):
            if i == 0:
                # Bottom segment is always (.
                kelp['segments'][i] = '('
            if kelpSegment == '(':
                bext.goto(kelp['x'], HEIGHT - 2 - i)
            elif kelpSegment == ')':
                bext.goto(kelp['x'] + 1, HEIGHT - 2 - i)
            print(kelpSegment, end='')

    # Draw quit message.
    bext.fg('white')
    bext.goto(0, 0)
    print('Ctrl-C to quit.', end='')

    # Draw the sand on the bottom:
    bext.fg('yellow')
    bext.goto(0, HEIGHT - 1)
    print(chr(9608) * (WIDTH - 1), end='')  # Draws '█' characters.
示例#12
0
bext.clear()
try:
    while True:  # Main program loop.
        # Print the cells:
        previousCells = currentCells  # Previous cells exists so we know which cells have changed, so we minimize flicker.
        currentCells = nextCells
        for y in range(0, HEIGHT, 2):  # Skip every other row.
            for x in range(WIDTH):
                top = (x, y) in currentCells
                bottom = (x, y + 1) in currentCells

                if (previousCells.get((x, y), False) != currentCells.get(
                    (x, y), False)) or (previousCells.get(
                        (x, y + 1), False) != currentCells.get(
                            (x, y + 1), False)):
                    bext.goto(x, y // 2)
                    if top and bottom:
                        print(FULL_BLOCK, end='')  # Fill in both halves.
                    elif top and not bottom:
                        print(TOP_BLOCK, end='')  # Fill in top half.
                    elif not top and bottom:
                        print(BOTTOM_BLOCK, end='')  # Fill in bottom half.
                    elif not top and not bottom:
                        print(' ', end='')  # Fill in nothing.

            print('')  # Print a newline at the end of the row.
        print('Press Ctrl-C to quit.', end='', flush=True)

        # Calculate next cells based on current cells:
        nextCells = {}
        for x in range(WIDTH):
示例#13
0
        screenPoints.extend(
            line(*transformPoint(rotatedPoints[4], rotatedPoints[5])))
        screenPoints.extend(
            line(*transformPoint(rotatedPoints[5], rotatedPoints[7])))
        screenPoints.extend(
            line(*transformPoint(rotatedPoints[7], rotatedPoints[6])))
        screenPoints.extend(
            line(*transformPoint(rotatedPoints[6], rotatedPoints[4])))

        screenPoints = tuple(
            frozenset(screenPoints))  # Get rid of duplicate points.

        # Draw cube:
        for x, y in screenPoints:
            # (Writing to the terminal will by far be the slowest part of this program.)
            bext.goto(x, y)
            print(BLOCK, end='')

        time.sleep(0.2)  # Pause for a bit.

        # Erase cube:
        for x, y in screenPoints:
            bext.goto(x, y)
            print(' ', end='')

        # Print quit message:
        bext.goto(0, HEIGHT - 1)
        print('Press Ctrl-C to quit.', end='')
except KeyboardInterrupt:
    pass
def main():
    bext.clear()

    #generate some logos
    logos = []
    for i in range(NUMBER_OF_LOGOS):
        logos.append({COLOR: random.choice(COLORS),
                      X: random.randint(1, (WIDTH - 4)),
                      Y: random.randint(1, HEIGHT - 1),
                      DIR: random.choice(DIRECTIONS)})
        if logos[-1][X] % 2 == 1:
            #make sure X is even so it can hit the corner
            logos[-1][X] -= 1

    cornerBounces = 0
    while True:
        for logo in logos:
            #erase the logo's current position
            bext.goto(logo[X], logo[Y])
            print('  ', end='')

            original_direction = logo[DIR]

            #see if the logo bounces off the corners
            if logo[X] == 0 and logo[Y] == 0:
                logo[DIR] = DOWN_RIGHT
                cornerBounces += 1
            elif logo[X] == 0 and logo[Y] == HEIGHT - 1:
                logo[DIR] = UP_RIGHT
                cornerBounces += 1
            elif logo[X] == WIDTH - 3 and logo[Y] == 0:
                logo[DIR] == DOWN_LEFT
                cornerBounces += 1
            elif logo[X] == WIDTH - 3 and logo[Y] == HEIGHT - 1:
                logo[DIR] == UP_LEFT
                cornerBounces += 1

            # See if the logo bounces off the left edge:
            elif logo[X] == 0 and logo[DIR] == UP_LEFT:
                logo[DIR] = UP_RIGHT
            elif logo[X] == 0 and logo[DIR] == DOWN_LEFT:
                logo[DIR] = DOWN_RIGHT

            # See if the logo bounces off the right edge:
            # (WIDTH - 3 because 'DVD' has 3 letters.)
            elif logo[X] == WIDTH - 3 and logo[DIR] == UP_RIGHT:
                logo[DIR] = UP_LEFT
            elif logo[X] == WIDTH - 3 and logo[DIR] == DOWN_RIGHT:
                logo[DIR] = DOWN_LEFT

            # See if the logo bounces off the top edge:
            elif logo[Y] == 0 and logo[DIR] == UP_LEFT:
                logo[DIR] = DOWN_LEFT
            elif logo[Y] == 0 and logo[DIR] == UP_RIGHT:
                logo[DIR] = DOWN_RIGHT

            # See if the logo bounces off the bottom edge:
            elif logo[Y] == HEIGHT - 1 and logo[DIR] == DOWN_LEFT:
                logo[DIR] = UP_LEFT
            elif logo[Y] == HEIGHT - 1 and logo[DIR] == DOWN_RIGHT:
                logo[DIR] = UP_RIGHT

            if logo[DIR] != original_direction:
                # Change color when the logo bounces:
                logo[COLOR] = random.choice(COLORS)

            #move the logo. (X moves by 2 because the terminal
            #vharacers are twice as tall as they are wide)
            if logo[DIR] == UP_RIGHT:
                logo[X] += 2
                logo[Y] -= 1
            elif logo[DIR] == UP_LEFT:
                logo[X] -= 2
                logo[Y] -= 1
            elif logo[DIR] == DOWN_RIGHT:
                logo[X] += 2
                logo[Y] += 1
            elif logo[DIR] == DOWN_LEFT:
                logo[X] -= 2
                logo[Y] += 1

        #display the number of corner bounces
        bext.goto(5,0)
        bext.fg('white')
        print('Corner bounces:', cornerBounces, end='')

        for logo in logos:
            #draw the logos at their new location
            bext.goto(logo[X], logo[Y])
            bext.fg(logo[COLOR])
            print('DVD', end='')

        bext.goto(0,0)
        sys.stdout.flush()
        time.sleep(PAUSE_AMOUNT)
示例#15
0
def main():
    print('Conway\'s Game of Life')
    print('By Al Sweigart [email protected]')
    print('Press Ctrl-C to quit...')
    time.sleep(3)

    # Create random cells:
    currentCells = {}
    nextCells = {}
    previousCells = {}
    for x in range(WIDTH):
        for y in range(HEIGHT):
            if random.randint(0, 1) == 0:
                nextCells[x, y] = True

    bext.clear()

    while True:  # Main program loop.
        previousCells = currentCells
        currentCells = nextCells

        # Print the cells:
        for y in range(0, HEIGHT, 2):  # Skip every other row.
            for x in range(WIDTH):
                prevTopHalf = previousCells.get((x, y), False)
                curTopHalf = currentCells.get((x, y), False)
                topHalfHasChanged = prevTopHalf != curTopHalf

                prevBottomHalf = previousCells.get((x, y + 1), False)
                curBottomHalf = currentCells.get((x, y + 1), False)
                bottomHalfHasChanged = prevBottomHalf != curBottomHalf
                if topHalfHasChanged or bottomHalfHasChanged:
                    bext.goto(x, y // 2)
                    if curTopHalf and curBottomHalf:
                        # Fill in both halves:
                        print(FULL_BLOCK, end='')
                    elif curTopHalf and not curBottomHalf:
                        # Fill in top half:
                        print(TOP_BLOCK, end='')
                    elif not curTopHalf and curBottomHalf:
                        # Fill in bottom half:
                        print(BOTTOM_BLOCK, end='')
                    elif not curTopHalf and not curBottomHalf:
                        # Fill in nothing:
                        print(' ', end='')

            print()  # Print a newline at the end of the row.
        print('Press Ctrl-C to quit.', end='', flush=True)

        # Calculate next cells based on current cells:
        nextCells = {}
        for x in range(WIDTH):
            for y in range(HEIGHT):
                # Get neighboring coordinates:
                leftCoord = (x - 1) % WIDTH
                rightCoord = (x + 1) % WIDTH
                topCoord = (y - 1) % HEIGHT
                bottomCoord = (y + 1) % HEIGHT

                # Count number of living neighbors:
                numNeighbors = 0
                if (leftCoord, topCoord) in currentCells:
                    numNeighbors += 1
                if (x, topCoord) in currentCells:
                    numNeighbors += 1
                if (rightCoord, topCoord) in currentCells:
                    numNeighbors += 1
                if (leftCoord, y) in currentCells:
                    numNeighbors += 1
                if (rightCoord, y) in currentCells:
                    numNeighbors += 1
                if (leftCoord, bottomCoord) in currentCells:
                    numNeighbors += 1
                if (x, bottomCoord) in currentCells:
                    numNeighbors += 1
                if (rightCoord, bottomCoord) in currentCells:
                    numNeighbors += 1

                # Set cell based on Conway's Game of Life rules:
                if currentCells.get((x, y), False):
                    if numNeighbors in (2, 3):
                        nextCells[x, y] = True
                else:
                    if numNeighbors == 3:
                        nextCells[x, y] = True

        time.sleep(PAUSE_LENGTH)  # Pause to reduce flickering.
示例#16
0
 def display(self):
     for i, (x, y) in enumerate(self.body):
         bext.goto(x * 2, y)
         bext.fg(self.colors[i])
         print(BLOCK + BLOCK, end='')
示例#17
0
 def _eraseLastBodySegment(self):
     # Erase the last body segment:
     bext.goto(self.body[-1][0] * 2, self.body[-1][1])
     print('  ', end='')
     self.body.pop()  # Delete the last (x, y) tuple in self.body.
示例#18
0
def main():
    bext.clear()

    # Generate some dots.
    dots = []
    for i in range(NUMBER_OF_DOTS):
        dots.append({
            COLOR: random.choice(COLORS),
            X: random.randint(1, WIDTH - 2),
            Y: random.randint(1, HEIGHT - 2),
            DIR: random.choice(DIRECTIONS)
        })

    while True:  # Main program loop.
        for dot in dots:  # Handle each dot in the dots list.
            # Erase the dot's current location:
            bext.goto(dot[X], dot[Y])
            print(' ', end='')

            # Move the dot:
            if dot[DIR] == UP_RIGHT:
                dot[X] += 1
                dot[Y] -= 1
            elif dot[DIR] == UP_LEFT:
                dot[X] -= 1
                dot[Y] -= 1
            elif dot[DIR] == DOWN_RIGHT:
                dot[X] += 1
                dot[Y] += 1
            elif dot[DIR] == DOWN_LEFT:
                dot[X] -= 1
                dot[Y] += 1

            # Draw the dots at their new location:
            bext.goto(dot[X], dot[Y])
            bext.fg(dot[COLOR])
            print(DOT_CHAR, end='')

            # See if the dot bounces off the corners:
            if dot[X] == 0 and dot[Y] == 0:
                dot[DIR] = DOWN_RIGHT
            elif dot[X] == 0 and dot[Y] == HEIGHT - 1:
                dot[DIR] = UP_RIGHT
            elif dot[X] == WIDTH - 1 and dot[Y] == 0:
                dot[DIR] = DOWN_LEFT
            elif dot[X] == WIDTH - 1 and dot[Y] == HEIGHT - 1:
                dot[DIR] = UP_LEFT

            # See if the dot bounces off the left edge:
            elif dot[X] == 0 and dot[DIR] == UP_LEFT:
                dot[DIR] = UP_RIGHT
            elif dot[X] == 0 and dot[DIR] == DOWN_LEFT:
                dot[DIR] = DOWN_RIGHT

            # See if the dot bounces off the right edge:
            elif dot[X] == WIDTH - 1 and dot[DIR] == UP_RIGHT:
                dot[DIR] = UP_LEFT
            elif dot[X] == WIDTH - 1 and dot[DIR] == DOWN_RIGHT:
                dot[DIR] = DOWN_LEFT

            # See if the dot bounces off the top edge:
            elif dot[Y] == 0 and dot[DIR] == UP_LEFT:
                dot[DIR] = DOWN_LEFT
            elif dot[Y] == 0 and dot[DIR] == UP_RIGHT:
                dot[DIR] = DOWN_RIGHT

            # See if the dot bounces off the bottom edge:
            elif dot[Y] == HEIGHT - 1 and dot[DIR] == DOWN_LEFT:
                dot[DIR] = UP_LEFT
            elif dot[Y] == HEIGHT - 1 and dot[DIR] == DOWN_RIGHT:
                dot[DIR] = UP_RIGHT

        sys.stdout.flush()  # (Required for bext-using programs.)
        time.sleep(PAUSE_AMOUNT)
    def runSimulationStep(self):
        random.shuffle(self.zombies)
        bittenZombies = []
        newZombies = []
        for zombie in self.zombies:
            action = zombie.getAction()
            if action == RIGHT:
                if zombie.direction == NORTH:
                    zombie.direction = EAST
                elif zombie.direction == SOUTH:
                    zombie.direction = WEST
                elif zombie.direction == EAST:
                    zombie.direction = SOUTH
                elif zombie.direction == WEST:
                    zombie.direction = NORTH
            elif action == LEFT:
                if zombie.direction == NORTH:
                    zombie.direction = WEST
                elif zombie.direction == SOUTH:
                    zombie.direction = EAST
                elif zombie.direction == EAST:
                    zombie.direction = NORTH
                elif zombie.direction == WEST:
                    zombie.direction = SOUTH
            elif action == FORWARD:
                if zombie.direction == NORTH:
                    onTopRow = zombie._y == 0
                    zombieToTheNorth = self.getZombieAt(zombie._x, zombie._y - 1)
                    if not onTopRow and zombieToTheNorth == None:
                        bext.goto(zombie._x, zombie._y)
                        print(' ', end='')
                        # Move north.
                        zombie._y -= 1

                elif zombie.direction == SOUTH:
                    onBottomRow = zombie._y == HEIGHT - 1
                    zombieToTheSouth = self.getZombieAt(zombie._x, zombie._y + 1)
                    if not onBottomRow and zombieToTheSouth == None:
                        bext.goto(zombie._x, zombie._y)
                        print(' ', end='')
                        # Move south.
                        zombie._y += 1

                elif zombie.direction == EAST:
                    onRightColumn = zombie._x == WIDTH - 1
                    zombieToTheEast = self.getZombieAt(zombie._x + 1, zombie._y)
                    if not onRightColumn and zombieToTheEast == None:
                        bext.goto(zombie._x, zombie._y)
                        print(' ', end='')
                        # Move east.
                        zombie._x += 1

                elif zombie.direction == WEST:
                    onLeftColumn = zombie._x == 0
                    zombieToTheWest = self.getZombieAt(zombie._x - 1, zombie._y)
                    if not onLeftColumn and zombieToTheWest == None:
                        bext.goto(zombie._x, zombie._y)
                        print(' ', end='')
                        # Move west.
                        zombie._x -= 1

            elif action == STAY:
                pass # Do nothing because the zombie is staying still.

            # Have the zombie bite the zombie in front of it:
            if zombie.direction == NORTH:
                zombieInFront = self.getZombieAt(zombie._x, zombie._y - 1)
            elif zombie.direction == SOUTH:
                zombieInFront = self.getZombieAt(zombie._x, zombie._y + 1)
            elif zombie.direction == EAST:
                zombieInFront = self.getZombieAt(zombie._x + 1, zombie._y)
            elif zombie.direction == WEST:
                zombieInFront = self.getZombieAt(zombie._x - 1, zombie._y)

            if zombieInFront != None and zombieInFront.__class__ != zombie.__class__:
                bittenZombieIndex = self.zombies.index(zombieInFront)
                newZombie = zombie.__class__(zombie.color)
                newZombie._x = zombieInFront._x
                newZombie._y = zombieInFront._y
                newZombie.direction = zombieInFront.direction
                self.zombies[bittenZombieIndex] = newZombie


        self.display()
        time.sleep(PAUSE_LENGTH)
示例#20
0
def drawAquarium():
    """Draw the aquarium on the screen."""
    global FISHES, BUBBLERS, BUBBLES, KELP, STEP

    # Draw quit message.
    bext.fg('white')
    bext.goto(0, 0)
    print('Fish Tank, by Al Sweigart    Ctrl-C to quit.', end='')

    # Draw the bubbles:
    bext.fg('white')
    for bubble in BUBBLES:
        bext.goto(bubble['x'], bubble['y'])
        print(random.choice(('o', 'O')), end='')

    # Draw the fish:
    for fish in FISHES:
        bext.goto(fish['x'], fish['y'])

        # Get the correct right- or left-facing fish text.
        if fish['goingRight']:
            fishText = fish['right'][STEP % len(fish['right'])]
        else:
            fishText = fish['left'][STEP % len(fish['left'])]

        # Draw each character of the fish text in the right color.
        for i, fishPart in enumerate(fishText):
            bext.fg(fish['colors'][i])
            print(fishPart, end='')

    # Draw the kelp:
    bext.fg('green')
    for kelp in KELPS:
        for i, kelpSegment in enumerate(kelp['segments']):
            if kelpSegment == '(':
                bext.goto(kelp['x'], BOTTOM_EDGE - i)
            elif kelpSegment == ')':
                bext.goto(kelp['x'] + 1, BOTTOM_EDGE - i)
            print(kelpSegment, end='')

    # Draw the sand on the bottom:
    bext.fg('yellow')
    bext.goto(0, HEIGHT - 1)
    print(chr(9617) * (WIDTH - 1), end='')  # Draws '░' characters.

    sys.stdout.flush()  # (Required for bext-using programs.)
        screenPoints.extend(
            line(*transformPoint(rotatedPoints[4], rotatedPoints[5])))
        screenPoints.extend(
            line(*transformPoint(rotatedPoints[5], rotatedPoints[7])))
        screenPoints.extend(
            line(*transformPoint(rotatedPoints[7], rotatedPoints[6])))
        screenPoints.extend(
            line(*transformPoint(rotatedPoints[6], rotatedPoints[4])))

        screenPoints = tuple(
            frozenset(screenPoints))  # Get rid of duplicate points.

        # Draw cube:
        for x, y in screenPoints:
            # (Writing to the terminal will by far be the slowest part of this program.)
            bext.goto(x, y)
            print(BLOCK, end='')

        time.sleep(0.2)  # Pause for a bit.

        # Erase cube:
        for x, y in screenPoints:
            bext.goto(x, y)
            print(' ', end='')

        # Print quit message:
        bext.goto(0, height - 1)
        print('Press Ctrl-C to quit.', end='')
except KeyboardInterrupt:
    pass
示例#22
0
while True:
    print('Move (F)ast or (S)low?')
    speed = input().upper()
    if speed == 'F' or speed == 'S':
        break

width, height = bext.size()
bext.clear()

try:
    while True:
        bext.fg('random')  # Set to a random color.
        x, y = width // 2, height // 2  # Start in the middle of the screen.

        # Display quit instructions:
        bext.goto(0, height - 2)
        print('Press Ctrl-C to quit.', end='')

        while (0 <= x < width) and (0 <= y < height):
            # Print the block at it's current location:
            bext.goto(x, y)
            print(BLOCK, end='')

            # Move the block:
            direction = random.randint(0, 3)
            if direction == 0:
                x += 1
            elif direction == 1:
                x -= 1
            elif direction == 2:
                y += 1
示例#23
0
    if random.randint(1, 50) == 1:
        bext.fg('random')

    for i, point in enumerate(points):
        # Draw our lines:
        if i == len(points) - 1:
            # The last point connects to the first point.
            pointA = point
            pointB = points[0]
        else:
            pointA = point
            pointB = points[i + 1]

        for x, y in line(pointA['x'], pointA['y'], pointB['x'], pointB['y']):
            bext.goto(x, y)
            print(LINE_CHAR, end='')

            oldpointPositions.append((x, y))
    sys.stdout.flush()  # (Required for bext-using programs.)
    time.sleep(0.1)

    for point in points:
        # Move our points:
        if point['direction'] == 'upright':
            point['x'] += 1
            point['y'] -= 1
        elif point['direction'] == 'upleft':
            point['x'] -= 1
            point['y'] -= 1
        elif point['direction'] == 'downright':
示例#24
0
        screenPoints.extend(
            line(*screenCoord(rotatedPoints[3], rotatedPoints[7])))

        screenPoints.extend(
            line(*screenCoord(rotatedPoints[4], rotatedPoints[5])))
        screenPoints.extend(
            line(*screenCoord(rotatedPoints[5], rotatedPoints[7])))
        screenPoints.extend(
            line(*screenCoord(rotatedPoints[7], rotatedPoints[6])))
        screenPoints.extend(
            line(*screenCoord(rotatedPoints[6], rotatedPoints[4])))

        screenPoints = tuple(
            frozenset(screenPoints))  # Get rid of duplicate points.

        # Draw cube
        for x, y in screenPoints:
            # Writing to the terminal will by far be the slowest part of this program.
            bext.goto(x, y)
            print(BLOCK, end='')

        time.sleep(0.1)

        # Erase cube
        for x, y in screenPoints:
            bext.goto(x, y)
            print(' ', end='')

except KeyboardInterrupt:
    pass
    'x': 30,
    'y': 0,
    'frequency': random.randint(2, 6),
    'next': 1
}]

bext.fg('yellow')
bext.clear()

allSand = []
while True:  # Main program loop.
    # Generate sand from each source.
    for source in sources:
        if source['next'] <= 0 and (source['x'], source['y']) not in allSand:
            allSand.append((source['x'], source['y']))
            bext.goto(source['x'], source['y'])
            print(SAND, end='')

            source['next'] = source['frequency']
        source['next'] -= 1

    # Simulate all sand in the sandspace:
    for i, sand in enumerate(allSand):
        if sand[Y] == HEIGHT - 1:
            continue  # Sand is on the very bottom, so it won't move at all.

        # If nothing is under this sand, move it down:
        if (sand[X], sand[Y] + 1) not in allSand:
            allSand[i] = (sand[X], sand[Y] + 1)
            bext.goto(sand[X], sand[Y])
            print(' ', end='')
示例#26
0
# Generate some balls.
balls = []
for i in range(NUMBER_OF_BALLS):
    balls.append({
        'color': random.choice(COLORS),
        'x': random.randint(1, WIDTH - 2),
        'y': random.randint(1, HEIGHT - 2),
        'direction': random.choice(DIRECTIONS)
    })

while True:  # Main game loop.
    oldBallPositions = []

    for ball in balls:
        # Draw our balls:
        bext.goto(ball['x'], ball['y'])
        bext.fg(ball['color'])
        print(BALL_CHAR, end='')

        oldBallPositions.append((ball['x'], ball['y']))
    sys.stdout.flush()  # (Required for bext-using programs.)
    time.sleep(0.1)

    for ball in balls:
        # Move our balls:
        if ball['direction'] == 'upright':
            ball['x'] += 1
            ball['y'] -= 1
        elif ball['direction'] == 'upleft':
            ball['x'] -= 1
            ball['y'] -= 1
示例#27
0
# Create a new board data structure:
board = {'width': WIDTH, 'height': HEIGHT}

# Create ant data structures:
ants = []
for i in range(NUMBER_OF_ANTS):
    ant = {'x': random.randint(0, WIDTH - 1),
           'y': random.randint(0, HEIGHT - 1),
           'direction': random.choice(['N', 'S', 'E', 'W'])}
    ants.append(ant)

try:
    while len(ants) > 0: # Keep running the simulation as long as we have ants.
        # Draw the board data structure:
        bext.goto(0, 0)
        for y in range(board['height']):
            for x in range(board['width']):
                if board.get((x, y), False):
                    print(chr(9608), end='') # Print a solid block.
                else:
                    print(' ', end='') # Print an empty space.
            print()
        print('Press Ctrl-C to quit.')

        # Run a single simulation step for each ant:
        nextBoard = copy.copy(board)
        for ant in ants:
            if board.get((ant['x'], ant['y']), False) == True:
                nextBoard[(ant['x'], ant['y'])] = False
                # Turn clockwise:
示例#28
0
def main():
    bext.clear()
    # Draw the circle of the clock:
    for y, row in enumerate(CLOCKFACE.splitlines()):
        for x, char in enumerate(row):
            if char != ' ':
                bext.goto(x, y)
                print(char)

    while True:  # Main program loop.
        # Get the current time from the computer's clock:
        currentTime = time.localtime()
        h = currentTime.tm_hour % 12  # Use 12-hour clock, not 24.
        m = currentTime.tm_min
        s = currentTime.tm_sec

        # Draw the second hand:
        secHandDirection = COMPLETE_ARC * (s / 60) + OFFSET_90_DEGREES
        secHandXPos = math.cos(secHandDirection)
        secHandYPos = math.sin(secHandDirection)
        secHandX = int(secHandXPos * SECOND_HAND_LENGTH + CENTERX)
        secHandY = int(secHandYPos * SECOND_HAND_LENGTH + CENTERY)
        secHandPoints = line(CENTERX, CENTERY, secHandX, secHandY)
        for x, y in secHandPoints:
            bext.goto(x, y)
            print(SECOND_HAND_CHAR, end='')

        # Draw the minute hand:
        minHandDirection = COMPLETE_ARC * (m / 60) + OFFSET_90_DEGREES
        minHandXPos = math.cos(minHandDirection)
        minHandYPos = math.sin(minHandDirection)
        minHandX = int(minHandXPos * MINUTE_HAND_LENGTH + CENTERX)
        minHandY = int(minHandYPos * MINUTE_HAND_LENGTH + CENTERY)
        minHandPoints = line(CENTERX, CENTERY, minHandX, minHandY)
        for x, y in minHandPoints:
            bext.goto(x, y)
            print(MINUTE_HAND_CHAR, end='')

        # Draw the hour hand:
        hourHandDirection = COMPLETE_ARC * (h / 12) + OFFSET_90_DEGREES
        hourHandXPos = math.cos(hourHandDirection)
        hourHandYPos = math.sin(hourHandDirection)
        hourHandX = int(hourHandXPos * HOUR_HAND_LENGTH + CENTERX)
        hourHandY = int(hourHandYPos * HOUR_HAND_LENGTH + CENTERY)
        hourHandPoints = line(CENTERX, CENTERY, hourHandX, hourHandY)
        for x, y in hourHandPoints:
            bext.goto(x, y)
            print(HOUR_HAND_CHAR, end='')

        sys.stdout.flush()  # (Required for bext-using programs.)

        # Keep looping until the second changes:
        while True:
            time.sleep(0.01)
            if time.localtime().tm_sec != currentTime.tm_sec:
                break

        # Erase the clock hands:
        for x, y in secHandPoints:
            bext.goto(x, y)
            print(' ', end='')
        for x, y in minHandPoints:
            bext.goto(x, y)
            print(' ', end='')
        for x, y in hourHandPoints:
            bext.goto(x, y)
            print(' ', end='')
def main():
    # Generate some points.
    points = []
    for i in range(NUMBER_OF_POINTS):
        points.append({
            'x': random.randint(1, WIDTH - 2),
            'y': random.randint(1, HEIGHT - 2),
            'direction': random.choice(DIRECTIONS)
        })

    while True:  # Main game loop.
        oldpointPositions = []

        if random.randint(1, 50) == 1:
            bext.fg('random')

        for i, point in enumerate(points):
            # Draw our lines:
            if i == len(points) - 1:
                # The last point connects to the first point.
                pointA = point
                pointB = points[0]
            else:
                pointA = point
                pointB = points[i + 1]

            for x, y in line(pointA['x'], pointA['y'], pointB['x'],
                             pointB['y']):
                bext.goto(x, y)
                print(LINE_CHAR, end='')

                oldpointPositions.append((x, y))
        sys.stdout.flush()  # (Required for bext-using programs.)
        time.sleep(0.1)

        for point in points:
            # Move our points:
            if point['direction'] == 'upright':
                point['x'] += 1
                point['y'] -= 1
            elif point['direction'] == 'upleft':
                point['x'] -= 1
                point['y'] -= 1
            elif point['direction'] == 'downright':
                point['x'] += 1
                point['y'] += 1
            elif point['direction'] == 'downleft':
                point['x'] -= 1
                point['y'] += 1

            # See if our points bounce off the corners:
            if point['x'] == 0 and point['y'] == 0:
                point['direction'] = 'downright'
            elif point['x'] == 0 and point['y'] == HEIGHT - 1:
                point['direction'] = 'upright'
            elif point['x'] == WIDTH - 1 and point['y'] == 0:
                point['direction'] = 'downleft'
            elif point['x'] == WIDTH - 1 and point['y'] == HEIGHT - 1:
                point['direction'] = 'upleft'

            # See if our points bounce off the walls:
            elif point['x'] == 0 and point['direction'] == 'upleft':
                point['direction'] = 'upright'
            elif point['x'] == 0 and point['direction'] == 'downleft':
                point['direction'] = 'downright'

            elif point['x'] == WIDTH - 1 and point['direction'] == 'upright':
                point['direction'] = 'upleft'
            elif point['x'] == WIDTH - 1 and point['direction'] == 'downright':
                point['direction'] = 'downleft'

            elif point['y'] == 0 and point['direction'] == 'upleft':
                point['direction'] = 'downleft'
            elif point['y'] == 0 and point['direction'] == 'upright':
                point['direction'] = 'downright'

            elif point['y'] == HEIGHT - 1 and point['direction'] == 'downleft':
                point['direction'] = 'upleft'
            elif point['y'] == HEIGHT - 1 and point['direction'] == 'downright':
                point['direction'] = 'upright'

        for pos in oldpointPositions:
            # Erase all of the points.
            bext.goto(pos[0], pos[1])
            print(' ', end='')
示例#30
0
    print(';' * WIDTH)
print('Press Ctrl-C to quit.')

# mowerx and mowery refer to the left edge of the lower, despite direction.
mowerx = -MOWER_LEN
mowery = 0
mowerDirection = 'right'
growMode = False

while True:
    # Draw the mower:
    drawMower(mowerx, mowery, mowerDirection)

    # Draw the cut grass:
    if (mowerDirection == 'right') and (mowerx - 1 >= 0):
        bext.goto(mowerx - 1, mowery)
        bext.fg('green')
        print(',', end='')
    elif (mowerDirection == 'left') and (mowerx < WIDTH - MOWER_LEN):
        bext.goto(mowerx + MOWER_LEN, mowery)
        bext.fg('green')
        print(',', end='')

    # Move the mower:
    if mowerDirection == 'right':
        mowerx += 1 # Move the mower right.
        if mowerx > WIDTH:
            # After going past the right edge,
            # change position and direction.
            mowerDirection = 'left'
            mowery += 1