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
def __init__(self, width=None): self.points = [] # 2D list that represents stacks's color for each point # if width is none, use the entire screen if width is None: self.width = led_matrix.width() else: self.width = width
def new_apple(self): # set up list of x and y choices x_pos = list(range(led_matrix.width())) y_pos = list(range(led_matrix.height())) # remove the position that player is currently in del x_pos[self.player.position[0]] del y_pos[self.player.position[1]] self.apple = Apple((random.choice(x_pos), random.choice(y_pos)))
def __init__(self, position=None, accel=False): # set position to be center of screen if position is not given if position is None: self.position = (int(led_matrix.width()/2), int(led_matrix.height()/2)) else: self.position = position self.accel = accel # True if controls are the accelometer, False if controls are buttons
def new_apple(self): # set up list of x and y choices x_pos = list(range(led_matrix.width())) y_pos = list(range(led_matrix.height())) # remove the position that player is currently in del x_pos[self.player.position[0]] del y_pos[self.player.position[1]] self.apple = Apple((random.choice(x_pos), random.choice(y_pos)))
def __init__(self, x_position=None, width=2, opening_height=3, opening_location=3): if x_position is None: self.x_position = led_matrix.width() else: self.x_position = x_position self.width = width self.opening_height = opening_height # height of opening from opening_location self.opening_location = opening_location # y coordinate of opening
def __init__(self, width=None): self.points = [ ] # 2D list that represents stacks's color for each point # if width is none, use the entire screen if width is None: self.width = led_matrix.width() else: self.width = width
def __init__(self, position=None, accel=False): # set position to be center of screen if position is not given if position is None: self.position = (int(led_matrix.width() / 2), int(led_matrix.height() / 2)) else: self.position = position self.accel = accel # True if controls are the accelometer, False if controls are buttons
def get_num_neighbors(curr_gen, x, y): """Returns the number of (alive) neighbors of given pixel""" count = 0 for j in range(y-1, y+2): for i in range(x-1, x+2): if not(i == x and j == y): # don't count itself if i >= 0 and i < led_matrix.width() and j >= 0 and j < led_matrix.height(): if curr_gen[j][i] == 0xF: count += 1 return count
def get_num_neighbors(curr_gen, x, y): """Returns the number of (alive) neighbors of given pixel""" count = 0 for j in range(y - 1, y + 2): for i in range(x - 1, x + 2): if not (i == x and j == y): # don't count itself if i >= 0 and i < led_matrix.width( ) and j >= 0 and j < led_matrix.height(): if curr_gen[j][i] == 0xF: count += 1 return count
def __init__(self, player): self.player = player empty_strikers = set() # initialize empty strikers for x_pos in range(led_matrix.width()): empty_strikers.add(Striker((x_pos, 0), Direction.UP)) for y_pos in range(led_matrix.height()): empty_strikers.add(Striker((0, y_pos), Direction.RIGHT)) self.empty_strikers = empty_strikers # strikers not used yet self.strikers = set() # active strikers self.apple = None
def __init__(self, player): self.player = player empty_strikers = set() # initialize empty strikers for x_pos in range(led_matrix.width()): empty_strikers.add(Striker((x_pos, 0), Direction.UP)) for y_pos in range(led_matrix.height()): empty_strikers.add(Striker((0, y_pos), Direction.RIGHT)) self.empty_strikers = empty_strikers # strikers not used yet self.strikers = set() # active strikers self.apple = None
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
def __init__(self, x_position=None, width=2, opening_height=3, opening_location=3): if x_position is None: self.x_position = led_matrix.width() else: self.x_position = x_position self.width = width self.opening_height = opening_height # height of opening from opening_location self.opening_location = opening_location # y coordinate of opening
def move(self, direction): if direction == Direction.UP: if self.position[1] < led_matrix.height() - 1: self.position = (self.position[0], self.position[1] + 1) elif direction == Direction.DOWN: if self.position[1] > 0: self.position = (self.position[0], self.position[1] - 1) elif direction == Direction.LEFT: if self.position[0] > 0: self.position = (self.position[0] - 1, self.position[1]) elif direction == Direction.RIGHT: if self.position[0] < led_matrix.width() - 1: self.position = (self.position[0] + 1, self.position[1]) else: raise ValueError("Invalid direction given.")
def move(self, direction): if direction == Direction.UP: if self.position[1] < led_matrix.height()-1: self.position = (self.position[0], self.position[1]+1) elif direction == Direction.DOWN: if self.position[1] > 0: self.position = (self.position[0], self.position[1]-1) elif direction == Direction.LEFT: if self.position[0] > 0: self.position = (self.position[0]-1, self.position[1]) elif direction == Direction.RIGHT: if self.position[0] < led_matrix.width()-1: self.position = (self.position[0]+1, self.position[1]) else: raise ValueError("Invalid direction given.")
def move(self): # check if the striker hit the wall and needs to bounce back if self.direction == Direction.LEFT and self.position[0] == 0: self.direction = Direction.RIGHT elif self.direction == Direction.RIGHT and self.position[0] == led_matrix.width()-1: self.direction = Direction.LEFT elif self.direction == Direction.DOWN and self.position[1] == 0: self.direction = Direction.UP elif self.direction == Direction.UP and self.position[1] == led_matrix.height()-1: self.direction = Direction.DOWN if self.direction == Direction.LEFT: self.position = (self.position[0]-1, self.position[1]) elif self.direction == Direction.RIGHT: self.position = (self.position[0]+1, self.position[1]) elif self.direction == Direction.DOWN: self.position = (self.position[0], self.position[1]-1) elif self.direction == Direction.UP: self.position = (self.position[0], self.position[1]+1)
def move(self): # check if the striker hit the wall and needs to bounce back if self.direction == Direction.LEFT and self.position[0] == 0: self.direction = Direction.RIGHT elif self.direction == Direction.RIGHT and self.position[ 0] == led_matrix.width() - 1: self.direction = Direction.LEFT elif self.direction == Direction.DOWN and self.position[1] == 0: self.direction = Direction.UP elif self.direction == Direction.UP and self.position[ 1] == led_matrix.height() - 1: self.direction = Direction.DOWN if self.direction == Direction.LEFT: self.position = (self.position[0] - 1, self.position[1]) elif self.direction == Direction.RIGHT: self.position = (self.position[0] + 1, self.position[1]) elif self.direction == Direction.DOWN: self.position = (self.position[0], self.position[1] - 1) elif self.direction == Direction.UP: self.position = (self.position[0], self.position[1] + 1)
def draw(self): # display menu items pos_y = 0 selected_item = self.selected_item() # display all other items regularly for item in self.items: if pos_y >= led_matrix.height(): # don't diplay items outside of display break if item["title"] == selected_item["title"]: # display selected text scrolling x = self.scrolling_text_pos led_matrix.sprite(selected_item["text"], (x, pos_y)) if self.scrolling_text_clock == self.scrolling_text_cycle: self.scrolling_text_clock = 0 if self.scrolling_text_pos < -selected_item["text"].width: self.scrolling_text_pos = led_matrix.width() - 1 else: self.scrolling_text_pos -= 1 self.scrolling_text_clock += 1 else: led_matrix.sprite(item["text"], (0, pos_y)) pos_y += item["text"].height + 1
def move(self): """Moves the snake in the give direction (if it can). Snake will grow as it moves. Need to use remove_tail() afterwards if no growth wanted. Returns if it was able to succesfully move.""" head_x, head_y = self.head() direction = snake.direction if direction == Direction.LEFT: if head_x == 0: return False new_point = (head_x - 1, head_y) elif direction == Direction.RIGHT: if head_x == led_matrix.width() - 1: return False new_point = (head_x + 1, head_y) elif direction == Direction.UP: if head_y == led_matrix.height() - 1: return False new_point = (head_x, head_y + 1) elif direction == Direction.DOWN: if head_y == 0: return False new_point = (head_x, head_y - 1) self.body = [new_point] + self.body # add as new head return True
def draw(self): # display menu items pos_y = 0 selected_item = self.selected_item() # display all other items regularly for item in self.items: if pos_y >= led_matrix.height( ): # don't diplay items outside of display break if item["title"] == selected_item["title"]: # display selected text scrolling x = self.scrolling_text_pos led_matrix.sprite(selected_item["text"], (x, pos_y)) if self.scrolling_text_clock == self.scrolling_text_cycle: self.scrolling_text_clock = 0 if self.scrolling_text_pos < -selected_item["text"].width: self.scrolling_text_pos = led_matrix.width() - 1 else: self.scrolling_text_pos -= 1 self.scrolling_text_clock += 1 else: led_matrix.sprite(item["text"], (0, pos_y)) pos_y += item["text"].height + 1
def move(self): """Moves the snake in the give direction (if it can). Snake will grow as it moves. Need to use remove_tail() afterwards if no growth wanted. Returns if it was able to succesfully move.""" head_x, head_y = self.head() direction = snake.direction if direction == Direction.LEFT: if head_x == 0: return False new_point = (head_x - 1, head_y) elif direction == Direction.RIGHT: if head_x == led_matrix.width() - 1: return False new_point = (head_x + 1, head_y) elif direction == Direction.UP: if head_y == led_matrix.height() - 1: return False new_point = (head_x, head_y + 1) elif direction == Direction.DOWN: if head_y == 0: return False new_point = (head_x, head_y - 1) self.body = [new_point] + self.body # add as new head return True
led_matrix.show() # check for collisions if field.player_collided_with_striker(): state = State.SCORE elif field.player_collided_with_apple(): field.new_apple() ret = field.add_striker() if ret == False: state = State.SCORE time.sleep(.1) elif state == State.IDLE: x = led_matrix.width() while x > -title.width: # break if state has changed, (don't wait for scroll to finish) if state != State.IDLE: break led_matrix.erase() led_matrix.sprite(title, (x, led_matrix.height()/2 - (title.height/2))) led_matrix.show() x -= 1 time.sleep(.05) elif state == State.SCORE: led_matrix.erase() led_matrix.text(str(len(field.strikers))) # led_matrix.text(str(len(field.horizontal_strikers) + len(field.vertical_strikers))) led_matrix.show()
bouncetime=100) GPIO.add_event_detect(SELECT, GPIO.FALLING, callback=button_handler, bouncetime=100) # notify menu we are ready for the led matrix print("READY") sys.stdout.flush() while True: if state == State.RESET: bird = None bird = Bird() pipes = [] pipe_start = led_matrix.width() pipe_clock = 0 state = State.IDLE elif state == State.IDLE: led_matrix.erase() bird.draw() led_matrix.show() elif state == State.PLAYING: led_matrix.erase() # draw pipes for pipe in pipes: pipe.draw()
led_matrix.erase() menu.draw() led_matrix.show() time.sleep(0.01) elif curr_state == IN_GAME: menu.run_selected_item() # run game and wait for it to die curr_state = IN_MENU elif curr_state == KONAMI: from random import shuffle, randint words = ["Brian", "Jason", "Jon", "Joe", "Steph", "Jed", "Tess"] shuffle(words) raspberrySTEM = "RaspberrySTEM" for name in words: sprite = led_matrix.LEDText(name, font_name="large") y_pos = randint(0,led_matrix.height()-sprite.height) x_pos = led_matrix.width() while x_pos >= -sprite.width: led_matrix.erase() led_matrix.sprite(sprite, (x_pos, y_pos)) led_matrix.show() x_pos -= 1 time.sleep(.05) logo = led_matrix.LEDText(raspberrySTEM, font_name="large") y_pos = int(led_matrix.height()/2) - int(logo.height/2) x_pos = led_matrix.width() while x_pos >= -logo.width: led_matrix.erase() led_matrix.sprite(logo, (x_pos, y_pos)) led_matrix.show() x_pos -= 1
# runt button_handler if START or A button is pressed GPIO.add_event_detect(A, GPIO.FALLING, callback=button_handler, bouncetime=100) GPIO.add_event_detect(START, GPIO.FALLING, callback=button_handler, bouncetime=100) GPIO.add_event_detect(SELECT, GPIO.FALLING, callback=button_handler, bouncetime=100) # notify menu we are ready for the led matrix print("READY") sys.stdout.flush() while True: if state == State.RESET: bird = None bird = Bird() pipes = [] pipe_start = led_matrix.width() pipe_clock = 0 state = State.IDLE elif state == State.IDLE: led_matrix.erase() bird.draw() led_matrix.show() elif state == State.PLAYING: led_matrix.erase() # draw pipes for pipe in pipes: pipe.draw()
# 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()
else: raise RuntimeError("Invalid Direction") # SETUP ========================== # setup led matrix #led_matrix.init_grid(angle=270) led_matrix.init_matrices([(0, 8), (8, 8), (8, 0), (0, 0)]) # notify of progress print("P60") sys.stdout.flush() HEIGHT = led_matrix.height() WIDTH = led_matrix.width() if WIDTH > 8: LEFT_EDGE = 3 RIGHT_EDGE = 12 else: LEFT_EDGE = -1 RIGHT_EDGE = WIDTH # initialize variables curr_state = State.IDLE # current state used for state machine blocks = [] # current block elements on screen start_width = 3 # pixel width of block on start start_speed = 5 # current speed on start (in pixel/sec) change_level = int(HEIGHT * (1 / 3.)) # number of blocks before upping difficulty
else: row.append(0x0) # add a dead pixel grid.append(row) return grid def draw_grid(): """Draws the current generation to led_matrix.""" for y in range(num_rows): for x in range(num_cols): led_matrix.point(x, y, curr_gen[y][x]) # whole game loop while True: # variables num_rows = led_matrix.height() num_cols = led_matrix.width() # 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()
if sidebar is not None: sidebar.draw() led_matrix.show() blinking_clock -= 1 time.sleep(.1) elif curr_state == State.IDLE: # display scrolling virtical text y_pos = - title.height while y_pos < led_matrix.height(): # if state changes stop scrolling and go to that state if curr_state != State.IDLE: break # display title in the center of the screen led_matrix.erase() led_matrix.sprite(title, (int(led_matrix.width()/2) - int(title.width/2), y_pos)) led_matrix.show() y_pos += 1 time.sleep(.1) elif curr_state == State.RESET: score = 0 stack = None if led_matrix.width() < 16: stack = Stack() else: stack = Stack(8) # if screen too width only use left half for stack sidebar = None sidebar = Sidebar(8) curr_piece = Piece(random.choice(SHAPES)) next_piece = Piece(random.choice(SHAPES))
# set up gpio inputs GPIO.setmode(GPIO.BCM) for g in [A, LEFT, DOWN, UP, RIGHT, START, SELECT]: GPIO.setup(g, GPIO.IN, pull_up_down = GPIO.PUD_UP) GPIO.add_event_detect(g, GPIO.FALLING, callback=button_handler, bouncetime=100) # notify of progress print("P70") sys.stdout.flush() # set up led matrix #led_matrix.init_grid(2,2) led_matrix.init_matrices([(0,8),(8,8),(8,0),(0,0)]) WIDTH = led_matrix.width() HEIGHT = led_matrix.height() # define walls wall_params = [ { # WALL_SCENE 0 "more_cols_min":5, "more_cols_max":8, "tunnel_min":5, "tunnel_max":HEIGHT - 3, "start_rate":2, # slow "period":5, }, { # WALL_SCENE 1 "more_cols_min":3,
for g in [A, LEFT, DOWN, UP, RIGHT, START, SELECT]: GPIO.setup(g, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.add_event_detect(g, GPIO.FALLING, callback=button_handler, bouncetime=100) # notify of progress print("P70") sys.stdout.flush() # set up led matrix #led_matrix.init_grid(2,2) led_matrix.init_matrices([(0, 8), (8, 8), (8, 0), (0, 0)]) WIDTH = led_matrix.width() HEIGHT = led_matrix.height() # define walls wall_params = [ { # WALL_SCENE 0 "more_cols_min": 5, "more_cols_max": 8, "tunnel_min": 5, "tunnel_max": HEIGHT - 3, "start_rate": 2, # slow "period": 5, }, { # WALL_SCENE 1
curr_state = State.WIN continue # if snake has got the apple, set up a new apple and start growing if snake.head() == field.apple: field.new_apple(snake) # create new apple score += 1 snake.growing = True # snake starts growing snake.grow_clock = GROW_CYCLES # reset grow clock time.sleep(.20) elif curr_state == State.IDLE: # display horizontal scrolling title title = led_matrix.LEDText("SNAKE", font_name="large") x_pos = led_matrix.width() - 1 y_pos = led_matrix.height() / 2 - title.height / 2 while x_pos > -title.width - 1: # break if state has changed, so we don't have to wait for it to finish if curr_state != State.IDLE: break led_matrix.erase() led_matrix.sprite(title, (x_pos, 1)) led_matrix.show() time.sleep(.1) x_pos -= 1 elif curr_state == State.RESET: snake = Snake() field = Field(led_matrix.width(), led_matrix.height()) score = 0
self.origin = [self.origin[0], self.origin[1]-1] else: raise RuntimeError("Invalid Direction") # SETUP ========================== # setup led matrix #led_matrix.init_grid(angle=270) led_matrix.init_matrices([(0,8),(8,8),(8,0),(0,0)]) # notify of progress print("P60") sys.stdout.flush() HEIGHT = led_matrix.height() WIDTH = led_matrix.width() if WIDTH > 8: LEFT_EDGE = 3 RIGHT_EDGE = 12 else: LEFT_EDGE = -1 RIGHT_EDGE = WIDTH # initialize variables curr_state = State.IDLE # current state used for state machine blocks = [] # current block elements on screen start_width = 3 # pixel width of block on start start_speed = 5 # current speed on start (in pixel/sec) change_level = int(HEIGHT*(1/3.)) # number of blocks before upping difficulty curr_width, curr_speed = start_width, start_speed
if curr_state == IN_MENU: led_matrix.erase() menu.draw() led_matrix.show() time.sleep(0.01) elif curr_state == IN_GAME: menu.run_selected_item() # run game and wait for it to die curr_state = IN_MENU elif curr_state == KONAMI: from random import shuffle, randint words = ["Brian", "Jason", "Jon", "Joe", "Steph", "Jed", "Tess"] shuffle(words) for name in words: sprite = led_matrix.LEDText(name, font_name="large") y_pos = randint(0, led_matrix.height() - sprite.height) x_pos = led_matrix.width() while x_pos >= -sprite.width: led_matrix.erase() led_matrix.sprite(sprite, (x_pos, y_pos)) led_matrix.show() x_pos -= 1 time.sleep(.05) logo = led_matrix.LEDText("Ready Set STEM", font_name="large") y_pos = int(led_matrix.height() / 2) - int(logo.height / 2) x_pos = led_matrix.width() while x_pos >= -logo.width: led_matrix.erase() led_matrix.sprite(logo, (x_pos, y_pos)) led_matrix.show() x_pos -= 1
curr_state = State.WIN continue # if snake has got the apple, set up a new apple and start growing if snake.head() == field.apple: field.new_apple(snake) # create new apple score += 1 snake.growing = True # snake starts growing snake.grow_clock = GROW_CYCLES # reset grow clock time.sleep(.20) elif curr_state == State.IDLE: # display horizontal scrolling title title = led_matrix.LEDText("SNAKE", font_name="large") x_pos = led_matrix.width() - 1 y_pos = led_matrix.height()/2 - title.height/2 while x_pos > -title.width - 1: # break if state has changed, so we don't have to wait for it to finish if curr_state != State.IDLE: break led_matrix.erase() led_matrix.sprite(title, (x_pos, 1)) led_matrix.show() time.sleep(.1) x_pos -= 1 elif curr_state == State.RESET: snake = Snake() field = Field(led_matrix.width(), led_matrix.height()) score = 0
field.draw() led_matrix.show() # check for collisions if field.player_collided_with_striker(): state = State.SCORE elif field.player_collided_with_apple(): field.new_apple() ret = field.add_striker() if ret == False: state = State.SCORE time.sleep(.1) elif state == State.IDLE: x = led_matrix.width() while x > -title.width: # break if state has changed, (don't wait for scroll to finish) if state != State.IDLE: break led_matrix.erase() led_matrix.sprite(title, (x, led_matrix.height() / 2 - (title.height / 2))) led_matrix.show() x -= 1 time.sleep(.05) elif state == State.SCORE: led_matrix.erase() led_matrix.text(str(len(field.strikers))) # led_matrix.text(str(len(field.horizontal_strikers) + len(field.vertical_strikers)))
led_matrix.show() blinking_clock -= 1 time.sleep(.1) elif curr_state == State.IDLE: # display scrolling virtical text y_pos = -title.height while y_pos < led_matrix.height(): # if state changes stop scrolling and go to that state if curr_state != State.IDLE: break # display title in the center of the screen led_matrix.erase() led_matrix.sprite( title, (int(led_matrix.width() / 2) - int(title.width / 2), y_pos)) led_matrix.show() y_pos += 1 time.sleep(.1) elif curr_state == State.RESET: score = 0 stack = None if led_matrix.width() < 16: stack = Stack() else: stack = Stack( 8) # if screen too width only use left half for stack sidebar = None sidebar = Sidebar(8) curr_piece = Piece(random.choice(SHAPES))
grid.append(row) return grid def draw_grid(): """Draws the current generation to led_matrix.""" for y in range(num_rows): for x in range(num_cols): led_matrix.point(x, y, curr_gen[y][x]) # whole game loop while True: # variables num_rows = led_matrix.height() num_cols = led_matrix.width() # 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()
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)) # Show the text on the screen led_matrix.show()
if moving_right: # show the sprite as normal (facing right) led_matrix.sprite(current_sprite, (x,0)) else: # show the sprite flipped vertical (faceing left) flipped_sprite = current_sprite.flipped_vertical() led_matrix.sprite(flipped_sprite, (x,0)) # Show sprite on screen led_matrix.show() # Update the x value to move it left or right if moving_right: x = x + 1 # increase the x if we are moving right else: x = x - 1 # decrease the x if we are moving left # if the sprite has hit the right side of the display and we are moving right, the sprite should switch to moving left if moving_right and x > (led_matrix.width() - sprite.width): moving_right = False # switch to moving left # else if the sprite has hit the left side of the display and is moving left, the sprite should switch to moving right elif not moving_right and x == 0: moving_right = True # Delay to show the frame for a fraction of a second time.sleep(.2)