Exemplo n.º 1
0
def main():
    # Setup the screen.
    bext.bg('black')
    bext.clear()

    global FISHES, BUBBLERS, BUBBLES, KELPS

    # Generate the global variables:
    FISHES = []
    for i in range(NUM_FISH):
        FISHES.append(generateFish())

    BUBBLERS = []  # NOTE: Bubbles are drawn, but not the bubblers themselves.
    for i in range(NUM_BUBBLERS):
        # Each bubbler starts at a random position.
        BUBBLERS.append(random.randint(0, WIDTH - 1))
    BUBBLES = []

    KELPS = []
    for i in range(NUM_KELP):
        kelp = {'x': random.randint(0, WIDTH - 2), 'segments': []}
        # Generate each segment of the kelp.
        for i in range(random.randint(6, HEIGHT - 1)):
            kelp['segments'].append(random.choice(['(', ')']))
        KELPS.append(kelp)

    # Run the simulation:
    step = 1
    while True:
        drawAquarium(step)
        time.sleep(1 / FRAMES_PER_SECOND)
        clearAquarium()
        #bext.clear()
        step += 1
def main():
    bext.bg('black')
    bext.fg('white')
    bext.clear()
    print('''Flood It, by Al Sweigart [email protected]

Set the color of the upper left square, which fills in all the
adjacent squares of that color. Try to make the entire board the
same color.''')
    gameBoard = getNewBoard()
    movesLeft = 20

    while True:  # Main game loop.
        displayBoard(gameBoard)

        print('Moves left:', movesLeft)
        playerMove = askForPlayerMove()
        changeTile(playerMove, gameBoard, 0, 0)
        movesLeft -= 1

        if hasWon(gameBoard):
            displayBoard(gameBoard)
            print('You have won!')
            break
        elif movesLeft == 0:
            displayBoard(gameBoard)
            print('You have run out of moves!')
            break
Exemplo n.º 3
0
def main():
    global FISHES, BUBBLERS, BUBBLES, KELPS, STEP
    bext.bg('black')
    bext.clear()

    # Generate the global variables:
    FISHES = []
    for i in range(NUM_FISH):
        FISHES.append(generateFish())

    # NOTE: Bubbles are drawn, but not the bubblers themselves.
    BUBBLERS = []
    for i in range(NUM_BUBBLERS):
        # Each bubbler starts at a random position.
        BUBBLERS.append(random.randint(LEFT_EDGE, RIGHT_EDGE))
    BUBBLES = []

    KELPS = []
    for i in range(NUM_KELP):
        kelpx = random.randint(LEFT_EDGE, RIGHT_EDGE)
        kelp = {'x': kelpx, 'segments': []}
        # Generate each segment of the kelp:
        for i in range(random.randint(6, HEIGHT - 1)):
            kelp['segments'].append(random.choice(['(', ')']))
        KELPS.append(kelp)

    # Run the simulation:
    STEP = 1
    while True:
        simulateAquarium()
        drawAquarium()
        time.sleep(1 / FRAMES_PER_SECOND)
        clearAquarium()
        STEP += 1
    def move(self):
        """Move the painter, while painting the floor behind them."""
        possibleMoves = [NORTH, SOUTH, EAST, WEST]
        # Remove any moves that would move off of the floor:
        if self.x == 0:
            possibleMoves.remove(WEST)
        if self.x == WIDTH - 1:
            possibleMoves.remove(EAST)
        if self.y == 0:
            possibleMoves.remove(NORTH)
        if self.y == HEIGHT - 1:
            possibleMoves.remove(SOUTH)

        # Remove any moves that go to a space already painted:
        if (NORTH in possibleMoves
                and self.floor[(self.x, self.y - 1)] == self.color):
            possibleMoves.remove(NORTH)
        if (SOUTH in possibleMoves
                and self.floor[(self.x, self.y + 1)] == self.color):
            possibleMoves.remove(SOUTH)
        if (WEST in possibleMoves
                and self.floor[(self.x - 1, self.y)] == self.color):
            possibleMoves.remove(WEST)
        if (EAST in possibleMoves
                and self.floor[(self.x + 1, self.y)] == self.color):
            possibleMoves.remove(EAST)

        # But if every space is already painted, move anywhere that
        # isn't off of the floor:
        if possibleMoves == []:
            if self.x != 0:
                possibleMoves.append(WEST)
            if self.x != WIDTH - 1:
                possibleMoves.append(EAST)
            if self.y != 0:
                possibleMoves.append(NORTH)
            if self.y != HEIGHT - 1:
                possibleMoves.append(SOUTH)

        move = random.choice(possibleMoves)
        bext.bg(self.color)

        # Move the painter:
        if move == NORTH:
            self.y -= 1
        elif move == SOUTH:
            self.y += 1
        elif move == WEST:
            self.x -= 1
        elif move == EAST:
            self.x += 1

        # Paint the floor at the new location:
        bext.goto(self.x * 2, self.y)
        print('  ', end='')
        self.floor[(self.x, self.y)] = self.color
Exemplo n.º 5
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)
Exemplo n.º 6
0
def displayBoard(board, ants, changedTiles):
    # Draw the board data structure:
    for x, y in changedTiles:
        bext.goto(x, y)
        if board.get((x, y), False):
            bext.bg(BLACK)
        else:
            bext.bg(WHITE)

        antIsHere = False
        for ant in ants:
            if (x, y) == (ant['x'], ant['y']):
                antIsHere = True
                if ant['direction'] == NORTH:
                    print('^', end='')
                elif ant['direction'] == SOUTH:
                    print('v', end='')
                elif ant['direction'] == EAST:
                    print('>', end='')
                elif ant['direction'] == WEST:
                    print('<', end='')
                break
        if not antIsHere:
            print(' ', end='')

    bext.goto(0, HEIGHT)
    bext.bg(WHITE)
    print('Press Ctrl-C to quit.', end='')

    sys.stdout.flush()  # (Required for bext-using programs.)
    time.sleep(PAUSE_AMOUNT)
Exemplo n.º 7
0
def main():
    bext.bg('black')
    bext.fg('white')
    bext.clear()
    print('''Floodplane, by Al Sweigart [email protected]

Set the upper left color/shape, which fills in all the
adjacent squares of that color/shape. Try to make the
entire board the same color/shape.''')

    print('Do you want to play in colorblind mode? Y/N')
    response = input('> ')
    if response.upper().startswith('Y'):
        displayMode = SHAPE_MODE
    else:
        displayMode = COLOR_MODE

    gameBoard = getNewBoard()
    movesLeft = MOVES_PER_GAME

    while True:  # Main game loop.
        displayBoard(gameBoard, displayMode)

        print('Moves left:', movesLeft)
        playerMove = askForPlayerMove(displayMode)
        changeTile(playerMove, gameBoard, 0, 0)
        movesLeft -= 1

        if hasWon(gameBoard):
            displayBoard(gameBoard, displayMode)
            print('You have won!')
            break
        elif movesLeft == 0:
            displayBoard(gameBoard, displayMode)
            print('You have run out of moves!')
            break
Exemplo n.º 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)
Exemplo n.º 9
0
        startx = random.randint(1, width - 2)
        starty = random.randint(1, height - 2)

        if board[(startx, starty)] != WHITE:
            continue  # Get a new random start point.
        else:
            break

    # Flood fill algorithm:
    colorToPaint = random.choice([RED, YELLOW, BLUE, BLACK])
    pointsToPaint = set([(startx, starty)])
    while len(pointsToPaint) > 0:
        x, y = pointsToPaint.pop()
        board[(x, y)] = colorToPaint
        if board[(x - 1, y)] == WHITE:
            pointsToPaint.add((x - 1, y))
        if board[(x + 1, y)] == WHITE:
            pointsToPaint.add((x + 1, y))
        if board[(x, y - 1)] == WHITE:
            pointsToPaint.add((x, y - 1))
        if board[(x, y + 1)] == WHITE:
            pointsToPaint.add((x, y + 1))

# Draw the board data structure:
for y in range(height):
    for x in range(width):
        bext.bg(board[(x, y)])
        print(' ', end='')

    print()
Exemplo n.º 10
0
# Langton's Ant, by Al Sweigart [email protected]
# More info: https://en.wikipedia.org/wiki/Langton%27s_ant

import random, copy, bext

WIDTH = 79
HEIGHT = 24
NUMBER_OF_ANTS = 10

# Setup the screen:
bext.fg('yellow') # Set foreground color.
bext.bg('blue')   # Set background color.
bext.clear()

# 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']):
Exemplo n.º 11
0
def main():
    bext.fg(ANT_COLOR)  # The ants' color is the foreground color.
    bext.bg(WHITE_TILE)  # Set the background to white to start.
    bext.clear()

    # 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([NORTH, SOUTH, EAST, WEST]),
        }
        ants.append(ant)

    # Keep track of which tiles have changed and need to be redrawn on
    # the screen:
    changedTiles = []

    while True:  # Main program loop.
        displayBoard(board, ants, changedTiles)
        changedTiles = []

        # nextBoard is what the board will look like on the next step in
        # the simulation. Start with a copy of the current step's board:
        nextBoard = copy.copy(board)

        # Run a single simulation step for each ant:
        for ant in ants:
            if board.get((ant['x'], ant['y']), False) == True:
                nextBoard[(ant['x'], ant['y'])] = False
                # Turn clockwise:
                if ant['direction'] == NORTH:
                    ant['direction'] = EAST
                elif ant['direction'] == EAST:
                    ant['direction'] = SOUTH
                elif ant['direction'] == SOUTH:
                    ant['direction'] = WEST
                elif ant['direction'] == WEST:
                    ant['direction'] = NORTH
            else:
                nextBoard[(ant['x'], ant['y'])] = True
                # Turn counter clockwise:
                if ant['direction'] == NORTH:
                    ant['direction'] = WEST
                elif ant['direction'] == WEST:
                    ant['direction'] = SOUTH
                elif ant['direction'] == SOUTH:
                    ant['direction'] = EAST
                elif ant['direction'] == EAST:
                    ant['direction'] = NORTH
            changedTiles.append((ant['x'], ant['y']))

            # Move the ant forward in whatever direction it's facing:
            if ant['direction'] == NORTH:
                ant['y'] -= 1
            if ant['direction'] == SOUTH:
                ant['y'] += 1
            if ant['direction'] == WEST:
                ant['x'] -= 1
            if ant['direction'] == EAST:
                ant['x'] += 1

            # If the ant goes past the edge of the screen,
            # it should wrap around to other side.
            ant['x'] = ant['x'] % WIDTH
            ant['y'] = ant['y'] % HEIGHT

            changedTiles.append((ant['x'], ant['y']))

        board = nextBoard
Exemplo n.º 12
0
# ASCII Aquarium, by Al Sweigart [email protected] 2019/2/12
from __future__ import print_function

import bext, random, time, sys
WIDTH, HEIGHT = bext.size()
WIDTH -= 1  # Adjustment for a Windows newline bug that happens when you print on the right edge.

# Setup the screen.
bext.bg('black')
bext.clear()

# Constants
NUM_KELP = 2
NUM_FISH = 10
NUM_BUBBLERS = 2
PAUSE = 0.25

FISH_TYPES = [
    {
        'right': ['><>'],
        'left': ['<><']
    },
    {
        'right': ['>||>'],
        'left': ['<||<']
    },
    {
        'right': ['>))>'],
        'left': ['<[[<']
    },
    {
Exemplo n.º 13
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)

# Clear the previously drawn text:
bext.fg(FILLED_COLOR)
bext.bg(EMPTY_COLOR)
bext.clear()

step = 0
try:
    while len(
            ants) > 0:  # Keep running the simulation as long as we have ants.
        # Draw the board data structure.
        if step % DISPLAY_AFTER_STEPS == 0:
            bext.goto(0, 0)
            for y in range(0, board['height'], 2):
                for x in range(board['width']):
                    top = board.get((x, y), False)
                    bottom = board.get((x, y + 1), False)

                    antTop = False
                break

        # Flood fill algorithm:
        colorToPaint = random.choice([RED, YELLOW, BLUE, BLACK])
        pointsToPaint = set([(startx, starty)])
        while len(pointsToPaint) > 0:
            x, y = pointsToPaint.pop()
            canvas[(x, y)] = colorToPaint
            if canvas[(x - 1, y)] == WHITE:
                pointsToPaint.add((x - 1, y))
            if canvas[(x + 1, y)] == WHITE:
                pointsToPaint.add((x + 1, y))
            if canvas[(x, y - 1)] == WHITE:
                pointsToPaint.add((x, y - 1))
            if canvas[(x, y + 1)] == WHITE:
                pointsToPaint.add((x, y + 1))

    # Draw the canvas data structure:
    for y in range(height):
        for x in range(width):
            bext.bg(canvas[(x, y)])
            print(' ', end='')

        print()

    # Prompt user to create a new one:
    try:
        input('Press Enter for another work of art, or Ctrl-C to quit.')
    except KeyboardInterrupt:
        sys.exit()
Exemplo n.º 15
0
def main():
    # Setup the screen:
    bext.fg('yellow')  # Set foreground color.
    bext.bg('blue')  # Set background color.
    bext.clear()

    # 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)

    # Keep running the simulation as long as we have ants:
    while len(ants) > 0:  # Main program loop.
        # 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:
                if ant['direction'] == 'N':
                    ant['direction'] = 'E'
                elif ant['direction'] == 'E':
                    ant['direction'] = 'S'
                elif ant['direction'] == 'S':
                    ant['direction'] = 'W'
                elif ant['direction'] == 'W':
                    ant['direction'] = 'N'
            else:
                nextBoard[(ant['x'], ant['y'])] = True
                # Turn counter clockwise:
                if ant['direction'] == 'N':
                    ant['direction'] = 'W'
                elif ant['direction'] == 'W':
                    ant['direction'] = 'S'
                elif ant['direction'] == 'S':
                    ant['direction'] = 'E'
                elif ant['direction'] == 'E':
                    ant['direction'] = 'N'

            # Move the ant forward:
            if ant['direction'] == 'N':
                ant['y'] -= 1
            if ant['direction'] == 'S':
                ant['y'] += 1
            if ant['direction'] == 'W':
                ant['x'] -= 1
            if ant['direction'] == 'E':
                ant['x'] += 1

            # If the ant goes past the edge of the screen,
            # it should wrap around to other side.
            ant['x'] = ant['x'] % WIDTH - 1
            ant['y'] = ant['y'] % HEIGHT - 1

        board = nextBoard
Exemplo n.º 16
0
def main():
    """Run the Langton's Ant simulation."""
    bext.fg('red')
    bext.bg(WHITE)  # Set the background to white to start.
    bext.clear()

    # 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([NORTH, SOUTH, EAST, WEST]),
        }
        ants.append(ant)

    changedTiles = set()

    while True:  # Main program loop.
        displayBoard(board, ants, changedTiles)
        changedTiles = set()

        # 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:
                if ant['direction'] == NORTH:
                    ant['direction'] = EAST
                elif ant['direction'] == EAST:
                    ant['direction'] = SOUTH
                elif ant['direction'] == SOUTH:
                    ant['direction'] = WEST
                elif ant['direction'] == WEST:
                    ant['direction'] = NORTH
            else:
                nextBoard[(ant['x'], ant['y'])] = True
                # Turn counter clockwise:
                if ant['direction'] == NORTH:
                    ant['direction'] = WEST
                elif ant['direction'] == WEST:
                    ant['direction'] = SOUTH
                elif ant['direction'] == SOUTH:
                    ant['direction'] = EAST
                elif ant['direction'] == EAST:
                    ant['direction'] = NORTH
            changedTiles.add((ant['x'], ant['y']))

            # Move the ant forward:
            if ant['direction'] == NORTH:
                ant['y'] -= 1
            if ant['direction'] == SOUTH:
                ant['y'] += 1
            if ant['direction'] == WEST:
                ant['x'] -= 1
            if ant['direction'] == EAST:
                ant['x'] += 1

            # If the ant goes past the edge of the screen,
            # it should wrap around to other side.
            ant['x'] = ant['x'] % WIDTH
            ant['y'] = ant['y'] % HEIGHT

            changedTiles.add((ant['x'], ant['y']))

        board = nextBoard
Exemplo n.º 17
0
import logging
LOG_FILE = 'chase_log.txt'  # Set to None to display logs on the screen instead.
logging.basicConfig(filename=LOG_FILE,
                    level=logging.DEBUG,
                    format='%(asctime)s - %(levelname)s - %(message)s')
#logging.disable(logging.CRITICAL) # Uncomment this line out to disable logs.
logging.debug('Start of program.')

import random, sys, os
try:
    import bext  #  # Attempt to import the bext module for colorful text.
except:
    bext = None  # It's no big deal if bext isn't installed.

if bext is not None:
    bext.bg('black')  # Set the background color to black.

WALL = chr(9608)  # Character 9608 is '█'


def fg(color):
    if bext is not None:
        bext.fg(color)  # Set the foreground color, if bext is installed.


def clearScreen():
    # Clear the previously drawn text:
    if sys.platform == 'win32':
        os.system('cls')  # Clears Windows terminal.
    else:
        os.system('clear')  # Clears macOS/Linux terminal.