Example #1
0
    def run_selected_item(self):
        # start child process
        selected = self.selected_item()
        GPIO_cleanup()
        proc = subprocess.Popen([sys.executable, selected["file"]],
                                stdout=subprocess.PIPE,
                                close_fds=False)

        # make proc.stdout a non-blocking file
        fd = proc.stdout.fileno()
        fl = fcntl.fcntl(fd, fcntl.F_GETFL)
        fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)

        finished = False
        percentage = 0  # percentage of loading
        # display loading screen until child process wants the led matrix
        while not proc.poll() and not finished:
            x_pos = led_matrix.width()
            y_pos = int(led_matrix.height() / 2) - int(loading_text.height)
            while x_pos >= -loading_text.width:
                led_matrix.erase()
                # print "LOADING..."
                led_matrix.sprite(loading_text, (x_pos, y_pos))
                # print progress bar
                led_matrix.rect((0, y_pos + int(loading_text.height) + 2),
                                (int(percentage * led_matrix.width()), 3),
                                fill=True)
                led_matrix.show()
                x_pos -= 1

                # read stdout of the game process
                try:
                    data = proc.stdout.readline()
                except:
                    data = False

                # check if child process is ready to take control of matrix
                if data:
                    game_printout = data.decode("utf-8")
                    # update progress bar if "P**" is given
                    if game_printout[0] == "P" and game_printout[1:-1].isdigit(
                    ):
                        new_percentage = int(game_printout[1:-1])
                        if 0 <= new_percentage <= 100:
                            percentage = int(
                                new_percentage) / 100  # update percentage

                    # break out of while loop to let game take over led matrix
                    elif game_printout == "READY\n":
                        finished = True
                        break
                time.sleep(0.05)

        led_matrix.erase()  # clear the display
        led_matrix.show()
        # TODO: find out if we need to clean up led matrix too
        # wait till child process finishes
        proc.wait()
        GPIO_setup()  # resetup GPIO
Example #2
0
def button_handler(channel):
    global curr_state
    global curr_speed
    global curr_width
    global curr_direction
    global blocks
    global button_pressed
    button_pressed = True

    # if START pressed exit the game
    if channel in [START, SELECT]:
        curr_state = State.EXIT
        return

    # else the button must be A
    if curr_state == State.PLAYING:
        # stop the block
        blocks[-1].stop()

        # check if block is touching previous block and crop
        if len(blocks) > 1:
            top_block = blocks[-1]
            base_block = blocks[-2]
            if top_block.adjacent(base_block):
                # crop block only if it hangs off the edge
                #                if (top_block.origin[0] + top_block.width - 1) > (base_block.origin[0] + base_block.width - 1):
                top_block.crop(base_block)

                # if hit the ceiling, display win screen
                if len(blocks) == HEIGHT:
                    curr_state = State.WIN
                    return
            else:
                # top block was not touching base block, so we lose
                curr_state = State.LOSE
                return

        # create new block
        if len(blocks) % change_level == 0:  # check if to up difficulty
            if curr_width > 1:
                curr_width -= 1
            curr_speed += 8  # update current speed
        curr_width = min(blocks[-1].width, curr_width)
        blocks.append(
            Block([LEFT_EDGE + 1, blocks[-1].origin[1] + 1], curr_width))

    elif curr_state in [State.IDLE, State.WIN, State.LOSE]:
        # set up game
        blocks = [Block([LEFT_EDGE + 1, 0], start_width)]  # set up first block
        curr_width = start_width
        curr_speed = start_speed
        led_matrix.erase()
        draw_blocks()
        led_matrix.show()
        curr_state = State.PLAYING
def scroll_text(string):
    """Scrolls the given text"""
    msg = led_matrix.LEDText(string, font_name='large')
    prev_state = state
    for i in range(len(string)*6 + 15):
        if state != prev_state:
            return  # leav if state has changed in the middle of scrolling
        led_matrix.erase()
        led_matrix.text(msg, (15 - i, 7))
        led_matrix.show()
        time.sleep(0.1)
Example #4
0
def button_handler(channel):
    global curr_state
    global curr_speed
    global curr_width
    global curr_direction
    global blocks
    global button_pressed
    button_pressed = True
    
    # if START pressed exit the game
    if channel in [START, SELECT]:
        curr_state = State.EXIT
        return
    
    # else the button must be A
    if curr_state == State.PLAYING:
        # stop the block
        blocks[-1].stop()
        
        # check if block is touching previous block and crop
        if len(blocks) > 1:
            top_block = blocks[-1]
            base_block = blocks[-2]
            if top_block.adjacent(base_block):
                # crop block only if it hangs off the edge
#                if (top_block.origin[0] + top_block.width - 1) > (base_block.origin[0] + base_block.width - 1):
                top_block.crop(base_block)
                    
                # if hit the ceiling, display win screen 
                if len(blocks) == HEIGHT:
                    curr_state = State.WIN
                    return
            else:
                # top block was not touching base block, so we lose
                curr_state = State.LOSE
                return
        
        # create new block
        if len(blocks) % change_level == 0:  # check if to up difficulty
            if curr_width > 1:
                curr_width -= 1
            curr_speed += 8  # update current speed
        curr_width = min(blocks[-1].width, curr_width)
        blocks.append(Block([LEFT_EDGE+1, blocks[-1].origin[1]+1], curr_width))
        
    elif curr_state in [State.IDLE, State.WIN, State.LOSE]:
        # set up game
        blocks = [Block([LEFT_EDGE+1,0], start_width)]  # set up first block
        curr_width = start_width
        curr_speed = start_speed
        led_matrix.erase()
        draw_blocks()
        led_matrix.show()
        curr_state = State.PLAYING
Example #5
0
    def run_selected_item(self):
        # start child process
        selected = self.selected_item()
        GPIO_cleanup()
        proc = subprocess.Popen([sys.executable, selected["file"]], stdout=subprocess.PIPE, close_fds=False)
        
        # make proc.stdout a non-blocking file
        fd = proc.stdout.fileno()
        fl = fcntl.fcntl(fd, fcntl.F_GETFL)
        fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
        
        finished = False
        percentage = 0   # percentage of loading
        # display loading screen until child process wants the led matrix
        while not proc.poll() and not finished:
            x_pos = led_matrix.width()
            y_pos = int(led_matrix.height()/2) - int(loading_text.height)
            while x_pos >= -loading_text.width:
                led_matrix.erase()
                # print "LOADING..."
                led_matrix.sprite(loading_text, (x_pos, y_pos))
                # print progress bar
                led_matrix.rect((0,y_pos + int(loading_text.height) + 2), (int(percentage*led_matrix.width()), 3), fill=True)
                led_matrix.show()
                x_pos -= 1

                # read stdout of the game process
                try: 
                    data = proc.stdout.readline()
                except:
                    data = False
                    
                # check if child process is ready to take control of matrix
                if data:
                    game_printout = data.decode("utf-8")
                    # update progress bar if "P**" is given
                    if game_printout[0] == "P" and game_printout[1:-1].isdigit():
                        new_percentage = int(game_printout[1:-1])
                        if 0 <= new_percentage <= 100:
                            percentage = int(new_percentage)/100  # update percentage
                            
                    # break out of while loop to let game take over led matrix
                    elif game_printout == "READY\n":
                        finished = True
                        break
                time.sleep(0.05)
                
        led_matrix.erase()  # clear the display
        led_matrix.show()
        # TODO: find out if we need to clean up led matrix too
        # wait till child process finishes
        proc.wait()
        GPIO_setup() # resetup GPIO
Example #6
0
 def __init__(self, menu_items, show_loading=False):
     items = []
     # convert titles
     for i, item in enumerate(menu_items):
         if show_loading:
             led_matrix.erase()
             led_matrix.text(str(len(menu_items) - i))
             led_matrix.show()
         f = os.path.join(os.path.dirname(os.path.abspath(__file__)), item[1])
         if not os.path.isfile(f):
             raise IOError("File '" + f + "' could not be found.")
         items.append({
             "title": item[0], 
             "file": f,
             "text": led_matrix.LEDText(item[0], font_name="large")
             })
     self.items = items
     self.scrolling_text_pos = 0
     self.scrolling_text_clock = Menu.HOLD_CLOCK_TIME  # clock used to slow down scrolling text
     self.scrolling_text_cycle = 5  # number of cycles between scrolling tick
Example #7
0
 def __init__(self, menu_items, show_loading=False):
     items = []
     # convert titles
     for i, item in enumerate(menu_items):
         if show_loading:
             led_matrix.erase()
             led_matrix.text(str(len(menu_items) - i))
             led_matrix.show()
         f = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                          item[1])
         if not os.path.isfile(f):
             raise IOError("File '" + f + "' could not be found.")
         items.append({
             "title": item[0],
             "file": f,
             "text": led_matrix.LEDText(item[0], font_name="large")
         })
     self.items = items
     self.scrolling_text_pos = 0
     self.scrolling_text_clock = Menu.HOLD_CLOCK_TIME  # clock used to slow down scrolling text
     self.scrolling_text_cycle = 5  # number of cycles between scrolling tick
Example #8
0
from rstem import led_matrix, speaker
import time
import os

led_matrix.init_grid()  # This sets up the led matrix. It must be run before displaying anything.
led_matrix.erase()      # This clears the led matrix display incase anything is currently being displayed.

# 1. Create sprite variables of a face with mouth open and closed from .spr files.
mouth_closed = led_matrix.LEDSprite(os.path.abspath("mouth_closed.spr"))
mouth_open = led_matrix.LEDSprite(os.path.abspath("mouth_open.spr"))

# 2. Create a speech object of "Hello World"
my_speech = speaker.Speech("Hello World")

# 3. Play my_speech
my_speech.play()

# 4. Create a while loop that keeps looping until the Raspberry Pi has stopped talking.
while my_speech.is_playing():

    # 5. Clear the led matrix
    led_matrix.erase()
    
    # 6. Draw the face with its mouth open
    led_matrix.sprite(mouth_open)
    
    # 7. Show the new face on the display and add a delay
    led_matrix.show()
    time.sleep(.1)
    
    # 8. Clear the led matrix of the previous face
Example #9
0
from rstem import led_matrix
import time

led_matrix.init_grid()  # This sets up the led matrix. It must be run before displaying anything.
led_matrix.erase()      # This clears the led matrix display incase anything is currently being displayed.


# Scrolling the led matrix. ===============================================

# Create a variable that holds information about the sprite
my_text_sprite = led_matrix.LEDText("Hello World!")

# Make a while loop that keeps looping forever
while True:  # by making the conditional True, the while loop will never break because True is always True!
   
    # Get the width of the text in pixels.
    text_width = my_text_sprite.width   # this is the number of LEDs wide our my_text_sprite is.

    # Set the original x value to be the width of the led matrix display.
    x = led_matrix.width()   # this is the number of LEDs wide the display is. 
    
    # Make another while loop that keeps moving the text to the left.
    #   - When x is less then -text_width, our text will not be on the display anymore.
    #   - When this happens we want to stop this while loop and run through the outside while loop.
    while x > -text_width:   # when x is less then -text_width, our text will not be on the display anymore
        
        # Erase the previous drawn text
        led_matrix.erase()
        
        # Draw the text at this current x position
        led_matrix.sprite(text, (x, 0))
Example #10
0
            curr_state = State.DONE
            continue

        # check if piece can't move down, and if so, add piece to stack and start blinking any full lines
        if not curr_piece.can_movedown():
            stack.add(curr_piece)  # add piece to stack
            curr_piece = None  # piece is no longer curr_piece
            blinking_clock = BLINKING_TIME  # set up blinking clock
            curr_state = State.BLINKING  # goto blinking state
            continue

        # otherwise move piece down
        curr_piece.movedown()

        # show screen
        led_matrix.erase()
        curr_piece.draw()
        stack.draw()
        if sidebar is not None:
            sidebar.draw()
        led_matrix.show()

        # speed up delay if DOWN button is held down
        if GPIO.input(DOWN) == 0:
            time.sleep(.005)
        else:
            time.sleep(speed)

    # when piece has hit that stack and we determine if a line has been filled
    elif curr_state == State.BLINKING:
        # when blinking clock counts down to zero, remove full lines and start a new piece
Example #11
0
print("P70")
sys.stdout.flush()

GPIO.setmode(GPIO.BCM)
GPIO.setup(START, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(SELECT, GPIO.IN, pull_up_down=GPIO.PUD_UP)

# notify of progress
print("P100")
sys.stdout.flush()

# notify menu we are ready for the led matrix
print("READY")
sys.stdout.flush()

while True:
    if GPIO.input(START) == 0 or GPIO.input(SELECT) == 0:
        button.cleanup()
        led_matrix.cleanup()
        sys.exit(0)
        
    hour = time.strftime("%I", time.localtime())
    hour = led_matrix.LEDText(hour)
    minute = time.strftime("%M", time.localtime())
    minute = led_matrix.LEDText(minute)
    
    led_matrix.erase()
    led_matrix.text(hour)
    led_matrix.text(minute, (hour.width + 2, 0))
    led_matrix.show()
Example #12
0
# create flag to indicate to display some dice initially on start up
just_started = True

# get base_elevation
base_elevation = accel.angles()[2]

# set change in angle/acceleration needed to roll dice
THRESHOLD = 20

# notify menu we are ready for the led matrix
print("READY")
sys.stdout.flush()

while True:
    # exit if start button is pressed
    if GPIO.input(START) == 0 or GPIO.input(SELECT) == 0:
        led_matrix.cleanup()
        GPIO.cleanup()
        sys.exit(0)
    
    # roll dice if A button is pressed or accelerometer detects steep enough angle
    if just_started or GPIO.input(A) == 0 or abs(accel.angles()[2] - base_elevation) > THRESHOLD:
        led_matrix.erase()  # clear old dice values
        # set a new random die at each matrix
        for y in range(0, led_matrix.height(), 8):
            for x in range(0, led_matrix.width(), 8):
                led_matrix.sprite(random.choice(dice), (x+1,y+1))
        just_started = False

    led_matrix.show()
    # notify of progress
    print("P80")
    sys.stdout.flush()
    curr_gen = random_grid(num_cols, num_rows)

    # notify of progress
    print("P90")
    sys.stdout.flush()
    next_gen = [[0 for i in range(num_cols)] for j in range(num_rows)]
    # TODO allow sprite input instead of random grid?

    # notify menu we are ready for the led matrix
    print("READY")
    sys.stdout.flush()

    # single game loop
    while True:
        if exit_button.is_pressed():
            # clean up stuff and exit the program
            button.cleanup()
            led_matrix.cleanup()
            sys.exit(0)
        elif restart_button.is_pressed():
            break  # break out of this inner loop (lets us restart generations)
        else:
            led_matrix.erase()   # clear the display
            draw_grid()          # draw the current generation
            led_matrix.show()    # show on display
            next_generation()    # update generation to next generation
    
Example #14
0
    # notify of progress
    print("P80")
    sys.stdout.flush()
    curr_gen = random_grid(num_cols, num_rows)

    # notify of progress
    print("P90")
    sys.stdout.flush()
    next_gen = [[0 for i in range(num_cols)] for j in range(num_rows)]
    # TODO allow sprite input instead of random grid?

    # notify menu we are ready for the led matrix
    print("READY")
    sys.stdout.flush()

    # single game loop
    while True:
        if exit_button.is_pressed():
            # clean up stuff and exit the program
            button.cleanup()
            led_matrix.cleanup()
            sys.exit(0)
        elif restart_button.is_pressed():
            break  # break out of this inner loop (lets us restart generations)
        else:
            led_matrix.erase()  # clear the display
            draw_grid()  # draw the current generation
            led_matrix.show()  # show on display
            next_generation()  # update generation to next generation