def main(): theFloor = getNewFloor() paintedAreas = set() # Generate painters: painters = [] for color in THE_PAINTERS: painters.append(Painter(color, theFloor)) bext.fg('black') bext.clear() while True: # Main simulation loop. for painter in painters: # Keep track of the painted floors: paintedAreas.add((painter.x, painter.y)) if len(paintedAreas) == WIDTH * HEIGHT: # Move the text cursor to the bottom right so that # new text doesn't overwrite our painting. bext.goto(bext.width() - 1, bext.height() - 1) print() # Print a newline. print('Seed: {} Width: {} Height: {}'.format( SEED, (WIDTH + 1) * 2, HEIGHT)) sys.exit() # The floor is completely painted, so quit. painter.move() sys.stdout.flush() time.sleep(PAUSE_LENGTH)
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
def display(self): for zombie in self.zombies: bext.goto(zombie._x, zombie._y) bext.fg(zombie.color) # Display the zombie's text character: if zombie.direction == NORTH: print(FACE_UP, end='') elif zombie.direction == SOUTH: print(FACE_DOWN, end='') elif zombie.direction == EAST: print(FACE_RIGHT, end='') elif zombie.direction == WEST: print(FACE_LEFT, end='') # Display a count of each kind of zombie: # TODO - potential bug - erase full first bext.goto(0, HEIGHT) count = {} for zombie in self.zombies: count.setdefault(zombie.__class__, 0) count[zombie.__class__] += 1 for zombieType in sorted(count.keys(), key=lambda x: x.__name__): bext.fg(zombieType.color) print(zombieType.__name__ + ': ' + str(count[zombieType]) + ' ', end='') print('', flush=True)
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='')
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 displayBoard(board, displayMode): """Display the board on the screen.""" bext.fg('white') # Display the top edge of the board: print(DOWNRIGHT + (LEFTRIGHT * BOARD_WIDTH) + DOWNLEFT) # Display each row: for y in range(BOARD_HEIGHT): bext.fg('white') if y == 0: # The first row begins with '>'. print('>', end='') else: # Later rows begin with a white vertical line. print(UPDOWN, end='') # Display each tile in this row: for x in range(BOARD_WIDTH): bext.fg(COLORS_MAP[board[(x, y)]]) if displayMode == COLOR_MODE: print(BLOCK, end='') elif displayMode == SHAPE_MODE: print(SHAPES_MAP[board[(x, y)]], end='') bext.fg('white') print(UPDOWN) # Rows end with a white vertical line. # Display the bottom edge of the board: print(UPRIGHT + (LEFTRIGHT * BOARD_WIDTH) + UPLEFT)
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.)
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)
def main(): bext.fg('white') print(' FLOOD IT! '.center(40, '*')) gameBoard = getNewBoard() movesLeft = 20 while True: drawBoard(gameBoard) print('Moves left:', movesLeft) playerMove = getPlayerMove() changeTile(playerMove, gameBoard, 0, 0) movesLeft -= 1 if hasWon(gameBoard): drawBoard(gameBoard) print('You have won!') break elif movesLeft == 0: print('You have run out of moves!') break
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)
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)
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)
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
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='') else: bext.fg('reset') print(forest[(x, y)], end='') print() bext.fg('reset') # Use the default font color. print('Grow chance: {}% Lightning chance: {}%'.format( GROW_CHANCE, LIGHTNING_CHANCE)) print('Press Ctrl-C to quit.')
def askForPlayerMove(): """Let the player select a color to paint the upper left tile.""" while True: bext.fg('white') print('Choose one of ', end='') bext.fg('red') print('R ', end='') bext.fg('green') print('G ', end='') bext.fg('blue') print('B ', end='') bext.fg('yellow') print('Y ', end='') bext.fg('cyan') print('C ', end='') bext.fg('purple') print('P ', end='') bext.fg('white') print(' or QUIT:') move = input('> ').upper() if move == 'QUIT': sys.exit() if move in COLORS: return move
# 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']):
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
'y': 0, 'frequency': random.randint(2, 6), 'next': 1 }, { 'x': 10, 'y': 0, 'frequency': random.randint(2, 6), 'next': 1 }, { '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:
if scalex is None: scalex = DEFAULT_SCALEX if scaley is None: scaley = DEFAULT_SCALEY if translatex is None: translatex = DEFAULT_TRANSLATEX if translatey is None: translatey = DEFAULT_TRANSLATEY return (int(point1[0] * scalex + translatex), int(point1[1] * scaley + translatey), int(point2[0] * scalex + translatex), int(point2[1] * scaley + translatey)) bext.fg('random') # Set up the points of the cube: ''' Cube points: 0+-----+1 / /| / / | -y 2+-----+3 | | | 4+ | +5 +-- +x | | / / | |/ +z 6+-----+7 ''' points = [[-1, -1, -1], [1, -1, -1], [-1, -1, 1], [1, -1, 1], [-1, 1, -1], [1, 1, -1], [-1, 1, 1], [1, 1, 1]]
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.
def displayBoard(board): """Display the board on the screen.""" bext.fg('white') print(DOWNRIGHT + (LEFTRIGHT * WIDTH) + DOWNLEFT) # Print first row with '>'. bext.fg('white') print('>', end='') for x in range(WIDTH): bext.fg(CMAP[board[(x, 0)]]) print(BLOCK, end='') bext.fg('white') print(UPDOWN) # Print each row after the first. for y in range(1, HEIGHT): bext.fg('white') print(UPDOWN, end='') for x in range(WIDTH): bext.fg(CMAP[board[(x, y)]]) print(BLOCK, end='') bext.fg('white') print(UPDOWN) bext.fg('white') print(UPRIGHT + (LEFTRIGHT * WIDTH) + UPLEFT)
BLOCK = chr(9608) # Ask user what speed to run the simulation at: 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
def askForPlayerMove(displayMode): """Let the player select a color to paint the upper left tile.""" while True: bext.fg('white') print('Choose one of ', end='') if displayMode == COLOR_MODE: bext.fg('red') print('(R)ed ', end='') bext.fg('green') print('(G)reen ', end='') bext.fg('blue') print('(B)lue ', end='') bext.fg('yellow') print('(Y)ellow ', end='') bext.fg('cyan') print('(C)yan ', end='') bext.fg('purple') print('(P)urple ', end='') elif displayMode == SHAPE_MODE: bext.fg('red') print('(H)eart, ', end='') bext.fg('green') print('(T)riangle, ', end='') bext.fg('blue') print('(D)iamond, ', end='') bext.fg('yellow') print('(B)all, ', end='') bext.fg('cyan') print('(C)lub, ', end='') bext.fg('purple') print('(S)pade, ', end='') bext.fg('white') print('or QUIT:') response = input('> ').upper() if response == 'QUIT': print('Thanks for playing!') sys.exit() if displayMode == COLOR_MODE: # Return a tile type number based on the response: return {'R': 0, 'G': 1, 'B': 2, 'Y': 3, 'C': 4, 'P': 5}[response] if displayMode == SHAPE_MODE: # Return a tile type number based on the response: return {'H': 0, 'T': 1, 'D': 2, 'B': 3, 'C': 4, 'S': 5}[response]
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)
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)
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 elif ball['direction'] == 'downright':
except ImportError: print("""This program requires the bext module, which you can install by opening a Terminal window (on macOS & Linux) and running: python3 -m pip install --user bext or a Command Prompt window (on Windows) and running: python -m pip install --user bext""") sys.exit() indent = 10 # How many spaces to indent. while True: print(' ' * indent, end='') bext.fg('red') print('##', end='') bext.fg('yellow') print('##', end='') bext.fg('green') print('##', end='') bext.fg('blue') print('##', end='') bext.fg('cyan') print('##', end='') bext.fg('purple') print('##') if random.randint(0, 1) == 0: # Increase the number of spaces: indent = indent + 1
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='') # Draw the initially uncut grass field: bext.clear() bext.hide() bext.fg('green') for i in range(HEIGHT): 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:
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='')
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='')