Skip to main content
reordered statements to match original code
Source Link
200_success
  • 144.2k
  • 22
  • 188
  • 473
from collections import namedtuple
import curses
from itertools import chain, cycle, islice, repeat
from random import randrange
import sys
import time

SCREEN = namedtuple('Screen', 'height width')(*curses.initscr().getmaxyx())
curses.endwin()

class Raindrop:
    def __init__(self, x, y, speed):
        self.x, self.y, self.speed = x, y, speed

def drop_generator(batch_size=1, **drop_params):
    while True:
        yield [
            Raindrop(**{key: next(gen) for key, gen in drop_params.items()})
            for _ in range(batch_size)
        ]

def move_drops(drops):
    """Move each drop down according to its speed, and remove drops from the
       set that have fallen off."""
    for drop in drops:
        drop.y += drop.speed
    drops.difference_update([drop for drop in drops if drop.y >= SCREEN.height])

def render_drops(drops, char='#'):
    """Return a string representation of the entire screen."""
    scr = {
        int(drop.y) * SCREEN.width + int(drop.x): char for drop in drops
    }
    return '\n'.join(
        ''.join(scr.get(y * SCREEN.width + x, ' ') for x in range(SCREEN.width))
        for y in range(SCREEN.height)
    )


drop_params = {
    'x': (randrange(0, SCREEN.width) for _ in repeat(True)),
    'y': repeat(0),
    'speed': cycle([0.5, 1]),
}
precipitation = chain.from_iterable([
    islice(drop_generator(batch_size=4, **drop_params), 25),
    repeat([])  # ... then generate nothing as existing drops keep falling
])
drops = set(next(precipitation))
while drops:
    drops.update(next(precipitation))
    move_drops(drops)
    print(render_drops(drops))
    # Python 2.7 seems to have a curses bug that necessitates flushing
    sys.stdout.flush()
    move_drops(drops)
    time.sleep(0.100)
from collections import namedtuple
import curses
from itertools import chain, cycle, islice, repeat
from random import randrange
import sys
import time

SCREEN = namedtuple('Screen', 'height width')(*curses.initscr().getmaxyx())
curses.endwin()

class Raindrop:
    def __init__(self, x, y, speed):
        self.x, self.y, self.speed = x, y, speed

def drop_generator(batch_size=1, **drop_params):
    while True:
        yield [
            Raindrop(**{key: next(gen) for key, gen in drop_params.items()})
            for _ in range(batch_size)
        ]

def move_drops(drops):
    """Move each drop down according to its speed, and remove drops from the
       set that have fallen off."""
    for drop in drops:
        drop.y += drop.speed
    drops.difference_update([drop for drop in drops if drop.y >= SCREEN.height])

def render_drops(drops, char='#'):
    """Return a string representation of the entire screen."""
    scr = {
        int(drop.y) * SCREEN.width + int(drop.x): char for drop in drops
    }
    return '\n'.join(
        ''.join(scr.get(y * SCREEN.width + x, ' ') for x in range(SCREEN.width))
        for y in range(SCREEN.height)
    )


drop_params = {
    'x': (randrange(0, SCREEN.width) for _ in repeat(True)),
    'y': repeat(0),
    'speed': cycle([0.5, 1]),
}
precipitation = chain.from_iterable([
    islice(drop_generator(batch_size=4, **drop_params), 25),
    repeat([])  # ... then generate nothing as existing drops keep falling
])
drops = set(next(precipitation))
while drops:
    drops.update(next(precipitation))
    move_drops(drops)
    print(render_drops(drops))
    # Python 2.7 seems to have a curses bug that necessitates flushing
    sys.stdout.flush()
    time.sleep(0.100)
from collections import namedtuple
import curses
from itertools import chain, cycle, islice, repeat
from random import randrange
import sys
import time

SCREEN = namedtuple('Screen', 'height width')(*curses.initscr().getmaxyx())
curses.endwin()

class Raindrop:
    def __init__(self, x, y, speed):
        self.x, self.y, self.speed = x, y, speed

def drop_generator(batch_size=1, **drop_params):
    while True:
        yield [
            Raindrop(**{key: next(gen) for key, gen in drop_params.items()})
            for _ in range(batch_size)
        ]

def move_drops(drops):
    """Move each drop down according to its speed, and remove drops from the
       set that have fallen off."""
    for drop in drops:
        drop.y += drop.speed
    drops.difference_update([drop for drop in drops if drop.y >= SCREEN.height])

def render_drops(drops, char='#'):
    """Return a string representation of the entire screen."""
    scr = {
        int(drop.y) * SCREEN.width + int(drop.x): char for drop in drops
    }
    return '\n'.join(
        ''.join(scr.get(y * SCREEN.width + x, ' ') for x in range(SCREEN.width))
        for y in range(SCREEN.height)
    )


drop_params = {
    'x': (randrange(0, SCREEN.width) for _ in repeat(True)),
    'y': repeat(0),
    'speed': cycle([0.5, 1]),
}
precipitation = chain.from_iterable([
    islice(drop_generator(batch_size=4, **drop_params), 25),
    repeat([])  # ... then generate nothing as existing drops keep falling
])
drops = set(next(precipitation))
while drops:
    drops.update(next(precipitation))
    print(render_drops(drops))
    # Python 2.7 seems to have a curses bug that necessitates flushing
    sys.stdout.flush()
    move_drops(drops)
    time.sleep(0.100)
Oops, misinterpreted the formula
Source Link
200_success
  • 144.2k
  • 22
  • 188
  • 473

In createRandomDrops(), instead of the cryptic formula min((i % 2) + 0.5, 1), use itertools.cycle([1[0.5, 1.5]1]). I would turn createRandomDrops() into an infinite generator.

from collections import namedtuple
import curses
from itertools import chain, cycle, islice, repeat
from random import randrange
import sys
import time

SCREEN = namedtuple('Screen', 'height width')(*curses.initscr().getmaxyx())
curses.endwin()

class Raindrop:
    def __init__(self, x, y, speed):
        self.x, self.y, self.speed = x, y, speed

def drop_generator(batch_size=1, **drop_params):
    while True:
        yield [
            Raindrop(**{key: next(gen) for key, gen in drop_params.items()})
            for _ in range(batch_size)
        ]

def move_drops(drops):
    """Move each drop down according to its speed, and remove drops from the
       set that have fallen off."""
    for drop in drops:
        drop.y += drop.speed
    drops.difference_update([drop for drop in drops if drop.y >= SCREEN.height])

def render_drops(drops, char='#'):
    """Return a string representation of the entire screen."""
    scr = {
        int(drop.y) * SCREEN.width + int(drop.x): char for drop in drops
    }
    return '\n'.join(
        ''.join(scr.get(y * SCREEN.width + x, ' ') for x in range(SCREEN.width))
        for y in range(SCREEN.height)
    )


drop_params = {
    'x': (randrange(0, SCREEN.width) for _ in repeat(True)),
    'y': repeat(0),
    'speed': cycle([1[0.5, 1.5]1]),
}
precipitation = chain.from_iterable([
    islice(drop_generator(batch_size=4, **drop_params), 25),
    repeat([])  # ... then generate nothing as existing drops keep falling
])
drops = set(next(precipitation))
while drops:
    drops.update(next(precipitation))
    move_drops(drops)
    print(render_drops(drops))
    # Python 2.7 seems to have a curses bug that necessitates flushing
    sys.stdout.flush()
    time.sleep(0.100)

In createRandomDrops(), instead of the cryptic formula min((i % 2) + 0.5, 1), use itertools.cycle([1, 1.5]). I would turn createRandomDrops() into an infinite generator.

from collections import namedtuple
import curses
from itertools import chain, cycle, islice, repeat
from random import randrange
import sys
import time

SCREEN = namedtuple('Screen', 'height width')(*curses.initscr().getmaxyx())
curses.endwin()

class Raindrop:
    def __init__(self, x, y, speed):
        self.x, self.y, self.speed = x, y, speed

def drop_generator(batch_size=1, **drop_params):
    while True:
        yield [
            Raindrop(**{key: next(gen) for key, gen in drop_params.items()})
            for _ in range(batch_size)
        ]

def move_drops(drops):
    """Move each drop down according to its speed, and remove drops from the
       set that have fallen off."""
    for drop in drops:
        drop.y += drop.speed
    drops.difference_update([drop for drop in drops if drop.y >= SCREEN.height])

def render_drops(drops, char='#'):
    """Return a string representation of the entire screen."""
    scr = {
        int(drop.y) * SCREEN.width + int(drop.x): char for drop in drops
    }
    return '\n'.join(
        ''.join(scr.get(y * SCREEN.width + x, ' ') for x in range(SCREEN.width))
        for y in range(SCREEN.height)
    )


drop_params = {
    'x': (randrange(0, SCREEN.width) for _ in repeat(True)),
    'y': repeat(0),
    'speed': cycle([1, 1.5]),
}
precipitation = chain.from_iterable([
    islice(drop_generator(batch_size=4, **drop_params), 25),
    repeat([])  # ... then generate nothing as existing drops keep falling
])
drops = set(next(precipitation))
while drops:
    drops.update(next(precipitation))
    move_drops(drops)
    print(render_drops(drops))
    # Python 2.7 seems to have a curses bug that necessitates flushing
    sys.stdout.flush()
    time.sleep(0.100)

In createRandomDrops(), instead of the cryptic formula min((i % 2) + 0.5, 1), use itertools.cycle([0.5, 1]). I would turn createRandomDrops() into an infinite generator.

from collections import namedtuple
import curses
from itertools import chain, cycle, islice, repeat
from random import randrange
import sys
import time

SCREEN = namedtuple('Screen', 'height width')(*curses.initscr().getmaxyx())
curses.endwin()

class Raindrop:
    def __init__(self, x, y, speed):
        self.x, self.y, self.speed = x, y, speed

def drop_generator(batch_size=1, **drop_params):
    while True:
        yield [
            Raindrop(**{key: next(gen) for key, gen in drop_params.items()})
            for _ in range(batch_size)
        ]

def move_drops(drops):
    """Move each drop down according to its speed, and remove drops from the
       set that have fallen off."""
    for drop in drops:
        drop.y += drop.speed
    drops.difference_update([drop for drop in drops if drop.y >= SCREEN.height])

def render_drops(drops, char='#'):
    """Return a string representation of the entire screen."""
    scr = {
        int(drop.y) * SCREEN.width + int(drop.x): char for drop in drops
    }
    return '\n'.join(
        ''.join(scr.get(y * SCREEN.width + x, ' ') for x in range(SCREEN.width))
        for y in range(SCREEN.height)
    )


drop_params = {
    'x': (randrange(0, SCREEN.width) for _ in repeat(True)),
    'y': repeat(0),
    'speed': cycle([0.5, 1]),
}
precipitation = chain.from_iterable([
    islice(drop_generator(batch_size=4, **drop_params), 25),
    repeat([])  # ... then generate nothing as existing drops keep falling
])
drops = set(next(precipitation))
while drops:
    drops.update(next(precipitation))
    move_drops(drops)
    print(render_drops(drops))
    # Python 2.7 seems to have a curses bug that necessitates flushing
    sys.stdout.flush()
    time.sleep(0.100)
Source Link
200_success
  • 144.2k
  • 22
  • 188
  • 473

Cool animation!

Let's get some linting out of the way. As per PEP 8, you should use 4 spaces of indentation consistently, and function names should be snake_case.

Scalability

The main weakness of your design is scalability. If you extend the loop to run indefinitely, then you will eventually run into performance issues.

One problem is that the drops list grows with each iteration, and is never pruned. The drops don't disappear after falling to the ground; they keep falling forever, invisibly, off-screen. The solution is to have moveDrops() delete drops when they fall beyond the bottom. (That's a smarter strategy than having dropsOnScreen() re-examine every drop on every animation frame.)

Furthermore, to place the drops on the grid, you do an O(n) scan for each position on the screen with '#' if any([drop['x'] == x and int(drop['y']) == y for drop in drops]). I would rewrite drawDrops() so that each drop places itself, using a dictionary or a 2-D array. I would also prefer to use comprehensions than repeated append operations, but that is mostly a style preference.

Data types

Your comment says that the screen dimensions are 80×25, but your code says screen = {'x': 80, 'y': 20}. Ideally, the dimensions should be detected at runtime using the curses library. Since screen is used as a global variable, I would like to see it named SCREEN and made immutable. A namedtuple would make it immutable, with the additional benefit of allowing the dot accessor rather than the clumsy [] notation. I think that width and height would be more appropriate names than x and y.

Similarly, defining a class for the raindrops would avoid the drop['x'] notation. Furthermore, the createRainDrop() function cries out to be a constructor.

Creating drops and looping

The rest of the code is an exercise in Pythonic iteration. Everything can be handled with liberal usage of iterators.

In createRandomDrops(), instead of the cryptic formula min((i % 2) + 0.5, 1), use itertools.cycle([1, 1.5]). I would turn createRandomDrops() into an infinite generator.

In the solution below, parameters such as the speed, intensity, and duration are all centrally tweakable by modifying drop_params and precipitation. For example, precipitation = drop_generator(**drop_params) would result in an infinite loop with just one new drop per frame.

Suggested solution

from collections import namedtuple
import curses
from itertools import chain, cycle, islice, repeat
from random import randrange
import sys
import time

SCREEN = namedtuple('Screen', 'height width')(*curses.initscr().getmaxyx())
curses.endwin()

class Raindrop:
    def __init__(self, x, y, speed):
        self.x, self.y, self.speed = x, y, speed

def drop_generator(batch_size=1, **drop_params):
    while True:
        yield [
            Raindrop(**{key: next(gen) for key, gen in drop_params.items()})
            for _ in range(batch_size)
        ]

def move_drops(drops):
    """Move each drop down according to its speed, and remove drops from the
       set that have fallen off."""
    for drop in drops:
        drop.y += drop.speed
    drops.difference_update([drop for drop in drops if drop.y >= SCREEN.height])

def render_drops(drops, char='#'):
    """Return a string representation of the entire screen."""
    scr = {
        int(drop.y) * SCREEN.width + int(drop.x): char for drop in drops
    }
    return '\n'.join(
        ''.join(scr.get(y * SCREEN.width + x, ' ') for x in range(SCREEN.width))
        for y in range(SCREEN.height)
    )


drop_params = {
    'x': (randrange(0, SCREEN.width) for _ in repeat(True)),
    'y': repeat(0),
    'speed': cycle([1, 1.5]),
}
precipitation = chain.from_iterable([
    islice(drop_generator(batch_size=4, **drop_params), 25),
    repeat([])  # ... then generate nothing as existing drops keep falling
])
drops = set(next(precipitation))
while drops:
    drops.update(next(precipitation))
    move_drops(drops)
    print(render_drops(drops))
    # Python 2.7 seems to have a curses bug that necessitates flushing
    sys.stdout.flush()
    time.sleep(0.100)