Exemplo n.º 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
Exemplo n.º 2
0
def win():
    string = "You won! Score: %i" % (score)
    msg = led_matrix.LEDText(string, font_name='large')
    for i in range(len(string) * 6 + 15):
        led_matrix.fill(0)
        led_matrix.text(msg, (15 - i, 7))
        led_matrix.show()
    sys.exit(0)
Exemplo n.º 3
0
def win():
	string = "You won! Score: %i" % (score)
	msg = led_matrix.LEDText(string, font_name='large')
	for i in range(len(string)*6 + 15):
		led_matrix.fill(0)
		led_matrix.text(msg, (15 - i, 7))
		led_matrix.show()
	sys.exit(0)
Exemplo n.º 4
0
def lose():
	string = "You lost! Score: %i" % (score)
	msg = led_matrix.LEDText(string, font_name='large')
	for i in range(len(string)*6 + 15):
		led_matrix.fill(0)
		led_matrix.text(msg, (15 - i, 7))
		led_matrix.show()
#		time.sleep(0.1)
	sys.exit(0)
Exemplo n.º 5
0
def lose():
    string = "You lost! Score: %i" % (score)
    msg = led_matrix.LEDText(string, font_name='large')
    for i in range(len(string) * 6 + 15):
        led_matrix.fill(0)
        led_matrix.text(msg, (15 - i, 7))
        led_matrix.show()
#		time.sleep(0.1)
    sys.exit(0)
def lose():
    GPIO.cleanup()
    text = "Game Over!"
    msg = led_matrix.LEDText(text, font_name="large")
    for i in range(len(text)*6 + 15):
        led_matrix.fill(0)
        led_matrix.text(msg, (15 - i,7))
        led_matrix.show()
        time.sleep(0.1)
    sys.exit(0)
def win():
    GPIO.cleanup()
    text = "You Won in %is" % (int(time.time() - start_time))
    msg = led_matrix.LEDText(text, font_name="large")
    for i in range(len(text) * 6 + 15):
        led_matrix.fill(0)
        led_matrix.text(msg, (15 - i, 7))
        led_matrix.show()
        time.sleep(0.1)
    sys.exit()
def win():
    GPIO.cleanup()
    text = "You Won in %is" % (int(time.time()-start_time))
    msg = led_matrix.LEDText(text, font_name="large")
    for i in range(len(text)*6+15):
        led_matrix.fill(0)
        led_matrix.text(msg, (15-i, 7))
        led_matrix.show()
        time.sleep(0.1)
    sys.exit()
def lose():
    GPIO.cleanup()
    text = "Game Over!"
    msg = led_matrix.LEDText(text, font_name="large")
    for i in range(len(text) * 6 + 15):
        led_matrix.fill(0)
        led_matrix.text(msg, (15 - i, 7))
        led_matrix.show()
        time.sleep(0.1)
    sys.exit(0)
Exemplo n.º 10
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
Exemplo n.º 11
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
Exemplo n.º 12
0
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)
Exemplo n.º 13
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
Exemplo n.º 14
0
    def update(self):
        global state
        self.bounced_x = False
        self.bounced_y = False
        self.can_move_x = True
        self.can_move_y = True
#        Player wins if there are no more bricks
        if len(bricks) == 0:
            state = State.WIN
            return
#        Bounce off edge of screen
        if self.pos[1] >= 15 and self.dir[1] == 1:
            self.dir[1] = -1
        if self.pos[0] <= 0 and self.dir[0] == -1:
            self.dir[0] = 1
        if self.pos[0] >= 15 and self.dir[0] == 1:
            self.dir[0] = -1

#        Loop through bricks and check for collisions
        self.brick_col()

#        If one col check to see if we are inbetween two bricks
        if self.bounced_x or self.bounced_y:
            self.brick_col()

#        If the ball hits the paddle reverse its y direction                            
        if (self.pos[1] + self.dir[1] == p.pos[1]) and (self.pos[0] + self.dir[0] >= p.pos[0]) and (self.pos[0] + self.dir[0] < p.pos[0] + p.size[0]):
            self.dir[1] = -self.dir[1]
#        Lose if the ball passes the paddle
        if self.pos[1] <= 0:
            for i in range(4):
                led_matrix.point(self.pos[0], self.pos[1])
                led_matrix.show()
                time.sleep(0.1)
                led_matrix.point(self.pos[0], self.pos[1], 0)
                led_matrix.show()
                time.sleep(0.1)
            state = State.LOSE
            return
        if self.can_move_x:
            self.pos[0] = clamp(self.pos[0] + self.dir[0], 0, 15)
        if self.can_move_y:
            self.pos[1] = clamp(self.pos[1] + self.dir[1], 0, 15)
Exemplo n.º 15
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
Exemplo n.º 16
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
Exemplo n.º 17
0
#!/usr/bin/env python
import numpy as np
import cv2
from rstem import led_matrix
ANGLE_FACTOR = 1
GRID_SIZE = 6
IMAGE_SIZE = ANGLE_FACTOR*8*GRID_SIZE
cap = cv2.VideoCapture(0)
cap.set(3, IMAGE_SIZE) #width
cap.set(4, IMAGE_SIZE) #height
cap.set(11, 1)
led_matrix.init_grid(GRID_SIZE, GRID_SIZE)
offset = int(round( (IMAGE_SIZE-(8*GRID_SIZE))/2 ))
try:
	while True:
		ret, img = cap.read()
		img = cv2.flip(img, 0)
		new_img = img[offset:offset+8*GRID_SIZE,offset:offset+8*GRID_SIZE]
		grey = cv2.cvtColor(new_img, cv2.COLOR_BGR2GRAY)
		canny = cv2.Canny(grey, 100, 200)
		led_matrix.frame(canny)
		led_matrix.show()
except KeyboardInterrupt:	
	pass
finally:
	led_matrix.cleanup()
	cap.release()

        #       Update and redraw missles
        for m in missles:
            m.update()
            led_matrix.point(m.pos[0], m.pos[1])

#       Get angles from accelerometer
        data = accel.angles()

        #       Generate smooth movement data using IIR filter, and make a 1/4 turn move
        #       the player to the edge of the screen
        player_pos[0] = player_pos[0] + (clamp(data[0] * 8 * 4 / 90 + 7) -
                                         player_pos[0]) * 0.1

        #       Draw player
        led_matrix.point(int(round(player_pos[0])), int(round(player_pos[1])))

        #       Show framebuffer
        led_matrix.show()

        #       Delay one game tick, in this case 1ms
        time.sleep(0.001)

#Stop if player hits Ctrl-C
except KeyboardInterrupt:
    pass

#Clean everything up
finally:
    GPIO.cleanup()
    led_matrix.cleanup()
Exemplo n.º 19
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
Exemplo n.º 20
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