def one_round(): ball = Ball() topPaddle = Paddle(0) bottomPaddle = Paddle(1) ugfx.clear(bgColor) ugfx.backlight(100) ugfx.set_default_font(ugfx.FONT_TITLE) while True: topPaddle.update() bottomPaddle.update() ball.update(topPaddle, bottomPaddle) if ball.isDead(): if(ball.y > SCREEN_HEIGHT/2): return [1,0] else: return [0,1] topPaddle.draw() bottomPaddle.draw() ball.draw() #draw the net for i in range(0,7): ugfx.area(int(i*2*SCREEN_WIDTH/13), int(SCREEN_HEIGHT/2-1), int(SCREEN_WIDTH/13), 3, netColor) ugfx.orientation(0) ugfx.text(130, 0, "%d " % (points[0]),netColor) ugfx.text(170, 0, "%d " % (points[1]),netColor) ugfx.orientation(270) time.sleep_ms(1)
def render_ui(): ugfx.clear(ugfx.html_color(0xffffff)) # draw squares current_row = int( (time.ticks_ms() - start_time) / time_per_row) % total_rows for row in range(total_rows): for col in range(total_cols): colour = inactive_colour if active and row == current_row: if active_states[row][col] == True: colour = current_active_colour else: colour = current_inactive_colour elif active_states[row][col] == True: colour = active_colour ugfx.area(col_width * col + line_width, row_height * row + line_width, col_width - line_width, row_height - line_width, colour) # highlight working area ugfx.area(active_h_block * block_width, active_v_block * block_height, line_width, block_height, ugfx.RED) ugfx.area((active_h_block + 1) * block_width, active_v_block * block_height, line_width, block_height, ugfx.RED) ugfx.area(active_h_block * block_width, active_v_block * block_height, block_width, line_width, ugfx.RED) ugfx.area(active_h_block * block_width, (active_v_block + 1) * block_height, block_width + line_width, line_width, ugfx.RED)
def loading_screen(): logo = 'praise_horse_worship_melon/loading.gif' ugfx.area(0,0,ugfx.width(),ugfx.height(),0xFFFF) ugfx.display_image(2,2,logo) ugfx.set_default_font(ugfx.FONT_SMALL) ugfx.text(60, 145, "Praise Horse (A)", ugfx.GREY) ugfx.text(55, 305, "Worship Melon (B)", ugfx.GREY)
def display_datetime(): ugfx.area(0, 215, 320, 25, 0xFFFF) ugfx.set_default_font(ugfx.FONT_MEDIUM_BOLD) (date, day) = format_selected_date() time = format_selected_time() ugfx.text(5, 220, time, ugfx.RED) ugfx.text(60, 220, "%s, %s" % (day, date), ugfx.GREY)
def loop(): sta_if = network.WLAN(network.STA_IF) sta_if.active(True) # Activate standalone interface sta_if.scan() # Scan for available access points sta_if.connect("SHA2017-insecure" ) # Connect to the public SHA2017 AP without a password sta_if.isconnected() # Check for successful connection sta_if.ifconfig() # Print connection information r = urequests.get( 'https://br-gpsgadget-new.azurewebsites.net/data/raintext/?lat=52.28&lon=5.52' ) lines = r.text.splitlines() raindata = [int(lines[i].split('|')[0]) for i in range(len(lines))] if sum(raindata) > 0: # Plot graph ugfx.clear(ugfx.WHITE) for i in range(len(raindata)): ugfx.area(12 * i, 127 - (raindata[i] // 2), 11, 127, ugfx.BLACK) ugfx.flush() badge.leds_init() badge.leds_send_data(bytes([0, 0, raindata[0] // 2, 0] * 6), 24) # all blue with intensity of current rain badge.vibrator_init() badge.vibrator_activate(9) time.sleep(2) badge.leds_disable() return 15 * 60 * 1000
def viewmsg(): msgid = db.get('msgseq') msg = inbox.get(msgid) if msg == None: ugfx.set_default_font(ugfx.FONT_SMALL) ugfx.area(0,0,ugfx.width(),ugfx.height(),0x0000) ugfx.text(40,100,"NO MESSAGES",ugfx.BLUE) pyb.delay(1000) return else: data = json.loads(msg) printmsg(data['sender'], data['payload'], data['ts']) while True: if buttons.is_triggered("JOY_UP"): print(msgid) msgid -= 1 msg = inbox.get(msgid) if msg != None: data = json.loads(msg) printmsg(data['sender'], data['payload'], data['ts']) else: msgid += 1 if buttons.is_triggered("JOY_DOWN"): print(msgid) msgid += 1 msg = inbox.get(msgid) if msg != None: data = json.loads(msg) printmsg(data['sender'], data['payload'], data['ts']) else: msgid -= 1 if buttons.is_triggered("BTN_B"): display() return
def msg(message, title='Still Loading Anyway...', reset=False): """Show a terminal style loading screen with title title can be optionaly set when resetting or first call """ global messageHistory try: messageHistory if reset: raise exception except: ugfx.clear(ugfx.WHITE) ugfx.string(0, 0, title, "PermanentMarker22", ugfx.BLACK) messageHistory = [] if len(messageHistory) < 6: ugfx.string(0, 30 + (len(messageHistory) * 15), message, "Roboto_Regular12", ugfx.BLACK) messageHistory.append(message) else: messageHistory.pop(0) messageHistory.append(message) ugfx.area(0, 30, 296, 98, ugfx.WHITE) for i, message in enumerate(messageHistory): ugfx.string(0, 30 + (i * 15), message, "Roboto_Regular12", ugfx.BLACK) ugfx.flush(ugfx.LUT_FASTER)
def display(): for x in range(0, width-1): for y in range(0, height-1): if grid[x][y] == 1: ugfx.area((x-1)*cell_width+1,(y-1)*cell_height, cell_width, cell_height, ugfx.BLACK) else: ugfx.area((x-1)*cell_width+1,(y-1)*cell_height, cell_width, cell_height, ugfx.WHITE)
def msg_nosplit(message, title='Loading...', reset=False): global NUM_LINES """Show a terminal style loading screen with title title can be optionaly set when resetting or first call """ global messageHistory try: messageHistory if reset: raise exception except: ugfx.clear(ugfx.WHITE) ugfx.string(0, 0, title, version.font_header, ugfx.BLACK) messageHistory = [] if len(messageHistory) < NUM_LINES: ugfx.string(0, 19 + (len(messageHistory) * 13), message, version.font_default, ugfx.BLACK) messageHistory.append(message) else: messageHistory.pop(0) messageHistory.append(message) ugfx.area(0, 15, ugfx.width(), ugfx.height() - 15, ugfx.WHITE) for i, message in enumerate(messageHistory): ugfx.string(0, 19 + (i * 13), message, version.font_default, ugfx.BLACK) ugfx.flush(ugfx.LUT_FASTER)
def loading_screen(): logo = 'lobstervision/lobsterpictures.gif' ugfx.area(0, 0, ugfx.width(), ugfx.height(), 0xFFFF) ugfx.display_image(0, 50, logo) ugfx.set_default_font(ugfx.FONT_SMALL) ugfx.text(15, 305, "lobstervision.tv/emf2018", ugfx.GREY) display_loading()
def draw_everything(): # We draw the bird at X, and pipes every X*10 locations. ugfx.area(0,0,ugfx.width(), ugfx.height(), back_colour) draw_bird(10,y) for i in range(0,len(pipe_heights)): draw_pipe(10+i*10-x,pipe_heights[i]) #ugfx.text(30,10, "Bird %d,%d Pipe: %d,%d" % (x,y,pipe_heights[x//10],pipe_heights[x//10]+gap), ugfx.WHITE) ugfx.text(30,10, "Score %d" % (score), ugfx.WHITE)
def draw_background(self, colour): logo = 'apps/emf_hub_mon/emf_hub_mon.gif' ugfx.area(0, 0, ugfx.width(), ugfx.height(), colour) ugfx.area(0, 0, ugfx.width(), 25, ugfx.GREY) ugfx.display_image(10, 30, logo)
def draw(self): if self.needsRedraw: ugfx.area(int(self.previousX - self.width / 2), int(self.y - self.height / 2), int(self.width), int(self.height), bgColor) self.needsRedraw = False ugfx.area(int(self.x - self.width / 2), int(self.y - self.height / 2), int(self.width), int(self.height), paddleColor)
def display(): logo = 'apps/nexmo~messages/nexmo_logo.gif' ugfx.area(0,0,ugfx.width(),ugfx.height(),0xFFFF) ugfx.set_default_font(ugfx.FONT_MEDIUM_BOLD) ugfx.text(20,20,"My Number is...",ugfx.BLACK) ugfx.text(20,130,"Powered By, ",ugfx.GREY) ugfx.display_image(15,150,logo) ugfx.set_default_font(ugfx.FONT_TITLE) ugfx.text(40,75,mynumber+" ",ugfx.BLUE)
def room_6(): ###Room 6 - exits EW room=6 ugfx.clear(ugfx.BLACK) setup_right_menu() build_room_walls(0,1,0,1) ugfx.area(90,100,20,20,ugfx.BLUE) ugfx.fill_circle(80,100,5,ugfx.YELLOW)
def reset(): global i global j i = int(ugfx.width() / 2) j = int(ugfx.height() / 2) ugfx.area(0, 0, ugfx.width(), ugfx.height(), ugfx.BLACK) ugfx.area((i - 1) if i > 0 else 0, (j - 1) if j > 0 else 0, 3 if (i > 0 and i < (ugfx.width() - 1)) else 2, 3 if (j > 0 and j < (ugfx.height() - 1)) else 2, ugfx.GREY)
def dash(): if AF: ch1 = t4.channel(1, pyb.Timer.PWM, pin=pyb.Pin("BUZZ"), pulse_width=(t4.period() + 1) // 2) ugfx.area(25,75,270,90,ugfx.BLACK) pyb.delay(SIGN_SCALING*DASH) if AF: pyb.Pin("BUZZ",pyb.Pin.OUT).low() ugfx.area(0,0,320,240,ugfx.html_color(0x00FF00)) pyb.delay(SIGN_SCALING*PAUSE_ELEMENT)
def display(): for x in range(0, width): for y in range(0, height): if grid[x][y] == 1: ugfx.area(x * cell_width, y * cell_height, cell_width - 1, cell_height - 1, ugfx.BLACK) else: ugfx.area(x * cell_width, y * cell_height, cell_width - 1, cell_height - 1, ugfx.WHITE) ugfx.flush()
def getdata(): server = 'badge.emf.camp' #url = 'http://'+server+':9002/schedule' #url = 'http://hackspace-leaderboard-scollins.c9users.io/schedule' url = 'http://api.ipify.org/' resp = get(url).text ugfx.area(0,0,ugfx.width(),ugfx.height(),0x0000) while True: ugfx.text(30,30,resp,ugfx.WHITE) return json.loads(resp)
def updateGeneralInfo(currentTimeMs): global timeLastInfoRefresh, hookStatus if (currentTimeMs - timeLastInfoRefresh > 10000): ugfx.area(5, 5, 120, 20, ugfx.GRAY) ugfx.text(5, 5, "Batt " + str(battery()) + "%", ugfx.WHITE) connBtDeviceNames = list(map(lambda e: e[1], sim800.btconnected())) ugfx.area(5, 30, 235, 20, ugfx.GRAY) ugfx.text(5, 30, "Bt Cn " + str(connBtDeviceNames), ugfx.WHITE) ugfx.text(120, 30, "Hk " + str(hookStatus), ugfx.WHITE) timeLastInfoRefresh = currentTimeMs
def draw_flag(colours): # Orientation for other people to see ugfx.orientation(90) # Draw each "band" of colour in the flag colour_width = ugfx.width() / len(colours) for num, colour in enumerate(colours): width_loc = int(num * colour_width) flag_height = ugfx.height() - (name_height + info_height) ugfx.area(width_loc, info_height, int(colour_width), flag_height, ugfx.html_color(colour))
def display(): for x in range(0, width): for y in range(0, height): if grid[x][y]: ugfx.area(x * cell_width, y * cell_height, cell_width - 1, cell_height - 1, ugfx.BLACK) else: ugfx.area(x * cell_width, y * cell_height, cell_width - 1, cell_height - 1, ugfx.WHITE) badge.eink_busy_wait() ugfx.flush()
def updateHook(currentTimeMs): global hookStatus, hookTimeLastToggle, currentNumber if (currentTimeMs - hookTimeLastToggle > 100): newHookStatus = bool(pinHook.value()) if (newHookStatus != hookStatus): hookStatus = newHookStatus currentNumber = "" #reset number dialed ugfx.area(5, 90, 235, 20, ugfx.WHITE) hookTimeLastToggle = currentTimeMs print("Hook: " + str(hookStatus))
def doScroll(): global yPos, maxHeight, logo # Blank previous logo location ugfx.area(0, yPos, ugfx.width(), yPos + logo_height, 0) # Move up and wrap yPos -= 20 if (yPos <= -logo_height): yPos = maxHeight # Draw logo ugfx.display_image(int((ugfx.width() - logo_width) / 2), int(yPos), logo)
def showColourChangeMenu(): global shades global hues global scroll global huesToShow global maxHeight boxHeight = int((ugfx.height() - maxHeight) / huesToShow) boxWidth = int(ugfx.width() / shades) for x in range(shades): for y in range(scroll, scroll + huesToShow): (r, g, b) = getColour(x / shades, y / hues) ugfx.area(x * boxWidth, maxHeight + int( (y - scroll) * boxHeight), boxWidth, boxHeight, (int(31 * r) << 11) + (int(63 * g) << 5) + int(31 * b))
def show_scanner(): global current_color_map, scanner image = color_images[current_color_map] scanner = color_maps[image] scanner.brightness = settings_get_brightness( ) if 0 < settings_get_brightness() < 1 else 0.1 scanner.decay = settings_get_decay( ) if 0 < settings_get_decay() < 1 else 0.6 try: ugfx.area(0, 0, 176, 128, ugfx.WHITE) ugfx.flush() badge.eink_png(0, 0, LARSON_LIB + image) ugfx.flush() except: pass
def showPage(): global current_page # avoid out of bounds errors current_page = max(1, min(current_page, total_pages)) start = (current_page - 1) * APPS_PER_PAGE end = start + APPS_PER_PAGE apps_on_current_page = all_apps[start:end] # Refresh page ugfx.clear(ugfx.html_color(EMF_PURPLE)) # Write current page number and arrows ugfx.Label(0, 20, ugfx.width(), 20, "Page {} of {}".format(current_page, total_pages), justification=ugfx.Label.CENTER) if current_page > 1: ugfx.fill_polygon(10, 16, [[0, 10], [15, 20], [15, 0]], ugfx.WHITE) if current_page < total_pages: ugfx.fill_polygon(ugfx.width() - 30, 16, [[0, 0], [15, 10], [0, 20]], ugfx.WHITE) # Write app numbers and names i = 0 yOffset = 45 xOffset = 0 for a in apps_on_current_page: # xOffset = (i % 3) * 8 # offset lines to match the physical layout of the keypad ugfx.area(20 + xOffset, yOffset + 2, 20, 20, ugfx.WHITE) ugfx.text(23 + xOffset, yOffset + 3, keypadLabels[i] + " ", EMF_PURPLE) ugfx.Label(46 + xOffset, yOffset + 3, ugfx.width(), 20, a['title'], justification=ugfx.Label.LEFT) yOffset = yOffset + 22 i = i + 1 while True: for key in keypad: keyIndex = keypad.index(key) if buttons.is_pressed(key) and (keyIndex < len(apps_on_current_page)): apps_on_current_page[keyIndex]['app'].boot() break if buttons.is_triggered(Buttons.JOY_Right) and (current_page is not total_pages): current_page = current_page + 1 return if buttons.is_triggered(Buttons.JOY_Left) and (current_page is not 1): current_page = current_page - 1 return
def disp_body_straight(x,y,rotation,colour): if (rotation == 0): ugfx.area((x+1)*grid_size+1, (y+1)*grid_size+1, grid_size-2, grid_size, colour) elif (rotation == 90): ugfx.area((x+1)*grid_size+1, (y+1)*grid_size+1, grid_size, grid_size-2, colour) elif (rotation == 180): ugfx.area((x+1)*grid_size+1, (y+1)*grid_size-1, grid_size-2, grid_size, colour) else: ugfx.area((x+1)*grid_size-1, (y+1)*grid_size+1, grid_size, grid_size-2, colour)
def printmsg(sender, text, ts): ugfx.set_default_font(ugfx.FONT_SMALL) ugfx.area(0,0,ugfx.width(),ugfx.height(),0x0000) ugfx.text(10,10,"From: "+sender,ugfx.BLUE) timestamp = timestring(ts) linelen = 40 lines = int(math.ceil(len(text)/linelen)) for l in range(0, lines): pixels = l*25+35 start = l*linelen end = l*linelen+linelen if end>len(text): end = len(text) linetext = text[start:end] ugfx.text(10,pixels,linetext,0xFFFF) ugfx.text(10,200,timestamp,ugfx.GREEN) return
def display_badge(self): x = 0 y = 0 x_pixel = 0 y_pixel = 0 block_idx = 0 block_idx_limit = self._cells_display.size_bytes cells = self._cells_display width = self._width colour_fore = self._colour_fore colour_back = self._colour_back pixel_width = self._pixel_width pixel_height = self._pixel_height hash_val = 0 while block_idx < block_idx_limit: cell_block = cells.get_block(block_idx) hash_val ^= cell_block mask = 1 mask_idx = 0 while mask_idx < 8: cell_alive = mask & cell_block colour = colour_fore if cell_alive else colour_back ugfx.area( x_pixel, y_pixel, pixel_width, pixel_height, colour ) mask <<= 1 mask_idx += 1 x += 1 x_pixel += pixel_width if x == width: x = 0 x_pixel = 0 y += 1 y_pixel += pixel_height block_idx += 1 return hash_val
def disp_body_straight(x, y, rotation, colour): if (rotation == 0): ugfx.area((x + 1) * grid_size + 1, (y + 1) * grid_size + 1, grid_size - 2, grid_size, colour) elif (rotation == 90): ugfx.area((x + 1) * grid_size + 1, (y + 1) * grid_size + 1, grid_size, grid_size - 2, colour) elif (rotation == 180): ugfx.area((x + 1) * grid_size + 1, (y + 1) * grid_size - 1, grid_size - 2, grid_size, colour) else: ugfx.area((x + 1) * grid_size - 1, (y + 1) * grid_size + 1, grid_size, grid_size - 2, colour)
def orc_kicking(strength, orc, hp): ugfx.area(190,30,300,180, ugfx.BLACK) damage_orc = (pyb.rng()%6) ugfx.text(190, 30, "You kick the orc!", ugfx.WHITE) ugfx.text(190, 50, "The orc takes", ugfx.WHITE) ugfx.text(190, 70, str(damage_orc)+" damage.", ugfx.WHITE) orc = orc-damage_orc tone(155.563,250,30) pyb.delay(1000) damage = (pyb.rng()%strength) ugfx.text(190, 100, "The orc kicks you!", ugfx.WHITE) ugfx.text(190, 120, "You take "+str(damage)+" damage.", ugfx.WHITE) hp = hp-damage tone(174.614,250,30) ugfx.text(190, 150, "A: Kick again", ugfx.RED) ugfx.text(190, 170, "B: Run away", ugfx.RED) ugfx.area(30,200,180,250, ugfx.BLACK) ugfx.text(30, 200, "HP: "+str(hp), ugfx.BLUE) return orc,hp
def draw_user_info(): # Draw for the user to see ugfx.orientation(270) # Calc width center of screen center_width = int(ugfx.width() / 2) ugfx.set_default_font(ugfx.FONT_SMALL) ugfx.area(0, ugfx.height() - info_height, ugfx.width(), info_height, ugfx.WHITE) wifi_strength_value = homescreen.wifi_strength() if wifi_strength_value: wifi_message = 'WiFi: %s%%' % int(wifi_strength_value) ugfx.text(center_width, ugfx.height() - info_height, wifi_message, ugfx.BLACK) battery_value = homescreen.battery() if battery_value: battery_message = 'Battery: %s%%' % int(battery_value) ugfx.text(0, ugfx.height() - info_height, battery_message, ugfx.BLACK)
def show_screen(type=None): if type == "horse": img = "praise_horse_worship_melon/horse.gif" color = ugfx.RED text = "HORSE!" elif type == "melon": img = "praise_horse_worship_melon/melon.gif" color = ugfx.BLUE text = "MELON!" else: return ugfx.area(0,0,ugfx.width(),ugfx.height(), color) ugfx.display_image(0, 0,img) ugfx.set_default_font(ugfx.FONT_MEDIUM_BOLD) for y_offset in range(8): ugfx.Label(0, 42 * y_offset, ugfx.width(), 20, text, parent=None, style=None, justification=ugfx.Label.CENTER) utime.sleep_ms(100) utime.sleep_ms(1000) loading_screen()
def updateDial(currentTimeMs): global timeFirstPulse, timeLastPulse, timeLastStart, dialing, currentNumber, lastDigit, hookStatus, calling if (currentTimeMs - timeLastStart > 300 and currentTimeMs - timeLastPulse > 200): if (pinDialStart.value() == 1 and dialing == False): dialing = True lastDigit = -1 timeLastStart = currentTimeMs elif (pinDialStart.value() == 0 and dialing == True and lastDigit >= 0): dialing = False lastDigit = lastDigit + 1 if (lastDigit >= 10): lastDigit = lastDigit - 10 # check the digit digitDurationMs = timeLastPulse - timeFirstPulse durationBasedLastDigit = digitByDuration(digitDurationMs) # DURATION based digit is much more RELIABLE ! (all interrupts/callback code for not much... :) ) currentNumber = currentNumber + str(durationBasedLastDigit) timeLastStart = currentTimeMs print("Dialled DIGIT: " + str(lastDigit)) if (lastDigit != durationBasedLastDigit): print(" !!!! Digit mismatch. From duration: " + str(durationBasedLastDigit) + " / " + str(digitDurationMs) + "ms") print("# " + currentNumber) ugfx.area(5, 90, 120, 20, ugfx.WHITE) ugfx.text(5, 90, currentNumber, ugfx.RED) #returns 0=ready, 2=unknown, 3=ringing, 4=call in progress # after 3 secs from starting a number, take whatever we have and try dialing if ((not calling) and hookStatus and sim800.getstatus() == 0 and len(currentNumber) > 0 and currentTimeMs - timeLastStart > 3000): calling = True ugfx.area(120, 90, 240, 20, ugfx.WHITE) ugfx.text(120, 90, "Calling...", ugfx.RED) print("Calling... " + str(currentNumber)) sim800.call(currentNumber)
def showevent(stage, event): start = event['start_date'] end = event['end_date'] speaker = event['speaker'] text = event['title'] ugfx.set_default_font(ugfx.FONT_MEDIUM) ugfx.area(0, 0, ugfx.width(), ugfx.height(), 0x0000) ugfx.text(10, 10, stage, ugfx.GREY) ugfx.text(10, 35, "Start: " + start, ugfx.GREEN) ugfx.text(10, 60, "End: " + end, ugfx.RED) ugfx.text(10, 85, "Speaker: " + speaker, ugfx.BLUE) linelen = 25 lines = int(math.ceil(len(text) / linelen)) for l in range(0, lines): pixels = l * 25 + 110 start = l * linelen end = l * linelen + linelen if end > len(text): end = len(text) linetext = text[start:end] ugfx.text(10, pixels, linetext, 0xFFFF) return
def show_trains(self): ugfx.clear() ugfx.area(0, 0, 240, 25, ugfx.RED if self.has_error else ugfx.GRAY) title = get_title(self.station_data['locationName'], self.has_error) ugfx.text(5, 5, title, ugfx.WHITE if self.has_error else ugfx.BLACK) ugfx.text(195, 5, time_as_string(), ugfx.BLUE) names = self._get_names_container() names.show() row_num = 0 for service in self.station_data['trainServices']: departure = get_departure(service) if departure: names.text(5, 15 * row_num, service['destination'][0]['locationName'], ugfx.BLACK) ugfx.text(195, 25 + (15 * row_num), departure, ugfx.RED if is_red(service) else ugfx.BLUE) row_num += 1 ugfx.display_image(0, 300, 'trains/bottom.gif') self.should_redraw = False
def showevent(stage, event): start = event['start_date'] end = event['end_date'] speaker = event['speaker'] text = event['title'] ugfx.set_default_font(ugfx.FONT_MEDIUM) ugfx.area(0,0,ugfx.width(),ugfx.height(),0x0000) ugfx.text(10,10,stage,ugfx.GREY) ugfx.text(10,35,"Start: "+start,ugfx.GREEN) ugfx.text(10,60,"End: "+end,ugfx.RED) ugfx.text(10,85,"Speaker: "+speaker,ugfx.BLUE) linelen = 25 lines = int(math.ceil(len(text)/linelen)) for l in range(0, lines): pixels = l*25+110 start = l*linelen end = l*linelen+linelen if end>len(text): end = len(text) linetext = text[start:end] ugfx.text(10,pixels,linetext,0xFFFF) return
def battery(vUsb, vBatt, charging): vMin = badge.nvs_get_u16('batt', 'vmin', 3500) # mV vMax = badge.nvs_get_u16('batt', 'vmax', 4100) # mV if charging and vUsb > 4000: try: badge.eink_png(0, 0, '/lib/resources/chrg.png') except: ugfx.string(0, 0, "CHRG", 'Roboto_Regular12', ugfx.BLACK) elif vUsb > 4000: try: badge.eink_png(0, 0, '/lib/resources/usb.png') except: ugfx.string(0, 0, "USB", 'Roboto_Regular12', ugfx.BLACK) else: width = round((vBatt - vMin) / (vMax - vMin) * 44) if width < 0: width = 0 elif width > 38: width = 38 ugfx.box(2, 2, 46, 18, ugfx.BLACK) ugfx.box(48, 7, 2, 8, ugfx.BLACK) ugfx.area(3, 3, width, 16, ugfx.BLACK)
def redraw_bg_range(x: int, y: int, to_x: int, to_y: int): if x < 0: x = 0 if y < 0: y = 0 if to_x > 319: to_x = 319 if to_y > 239: to_y = 239 if to_y < 190: # This is just sky ugfx.area(x, y, to_x-x, to_y-y, SKIES[level]) complex_draw = False elif to_y > 190 and y < 190: # Partial sky coverage ugfx.area(x, y, to_x-x, 190-y, SKIES[level]) y = 190 complex_draw = True else: complex_draw = True if complex_draw: ugfx.stream_start(x, y, to_x-x, to_y-y) for x_value in range(x, to_x): for y_value in range(y, to_y): ugfx.stream_color(get_background_pixel(x_value, y_value)) ugfx.stream_stop()
def draw(self): if not self.crashing: self.crashing = not (pyb.rng() % 500) ugfx.area(self.x-QUADCOPTER_BODY_SIZE, self.y-QUADCOPTER_BODY_SIZE, QUADCOPTER_BODY_SIZE*2, QUADCOPTER_BODY_SIZE*2, self.color) self.animation_frame += 1 self.animation_frame %= 4 for armature_x, armature_y in ( (-QUADCOPTER_BODY_SIZE*3, -QUADCOPTER_BODY_SIZE*2), (QUADCOPTER_BODY_SIZE*3, -QUADCOPTER_BODY_SIZE*2), (-QUADCOPTER_BODY_SIZE*3, QUADCOPTER_BODY_SIZE*2), (QUADCOPTER_BODY_SIZE*3, QUADCOPTER_BODY_SIZE*2) ): rotor_center_x = self.x + armature_x rotor_center_y = self.y + armature_y ugfx.thickline(rotor_center_x, rotor_center_y, self.x, self.y, self.color, 2, False) if self.animation_frame == 0: ugfx.line(rotor_center_x - int(QUADCOPTER_BODY_SIZE*0.7), rotor_center_y - int(QUADCOPTER_BODY_SIZE*0.7), rotor_center_x + int(QUADCOPTER_BODY_SIZE*0.7), rotor_center_y + int(QUADCOPTER_BODY_SIZE*0.7), ugfx.BLACK) elif self.animation_frame == 1: ugfx.line(rotor_center_x, rotor_center_y - QUADCOPTER_BODY_SIZE, rotor_center_x, rotor_center_y + QUADCOPTER_BODY_SIZE, ugfx.BLACK) elif self.animation_frame == 2: ugfx.line(rotor_center_x + int(QUADCOPTER_BODY_SIZE*0.7), rotor_center_y - int(QUADCOPTER_BODY_SIZE*0.7), rotor_center_x - int(QUADCOPTER_BODY_SIZE*0.7), rotor_center_y + int(QUADCOPTER_BODY_SIZE*0.7), ugfx.BLACK) elif self.animation_frame == 3: ugfx.line(rotor_center_x + QUADCOPTER_BODY_SIZE, rotor_center_y, rotor_center_x - QUADCOPTER_BODY_SIZE, rotor_center_y, ugfx.BLACK) draw_crosshair(crosshair_x, crosshair_y)
def print_page(self): self.content = ["xxxxxxxxxxxxxxxxxxx xxxxxxxxx xxxxxxxxx", "xxxxxxxxxxxx x x x x x", "xxxxxxxxxxxx xxxxx xxxxxxxxxxxxx x xxxx xxxxxxx x x x xxxxxxxxxxxxxxxxxxxxxx", "xxxxxxxxxxxx xxx x xxx x x xx x x x x x x xxxxxxxxxxxxxxxx", "xxxxxxxxxxxx xxxxx x x x x x x xxxx x xxxx x x x x x xxxxxxxxxxxxxxxx", "xxxxxxxxxxxx x x xx xx x x xxxx x xx x x x xx xxxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxxxxx x xxxxxxx x xxxxxxx x xxxx xxxxxxx x x xxxxxxxxxxxxxxxx", " x xxxxxxx x x xxxx x x xxxxxxxxxxxxxxxx", " xxxxxxxxxxxxxxx xxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxx"] ugfx.clear(ugfx.BLACK) ugfx.area(0, 5, 320, 45, ugfx.BLUE) for i,line in enumerate(self.content): for j,c in enumerate(line): if c=="x": ugfx.area(4*j, 5*i+5, 4, 5, ugfx.YELLOW) ugfx.area(0, 220, 320, 15, ugfx.YELLOW) ugfx.text(35, 221, "EMFFAX: The World at Your Fingertips", ugfx.BLUE)
def print_page(self): ugfx.clear(ugfx.BLACK) ugfx.area(0, 5, 320, 45, ugfx.BLUE) ugfx.area(0, 220, 320, 15, ugfx.YELLOW) ugfx.text(35, 221, "EMFFAX: The World at Your Fingertips", ugfx.BLUE)
def mainscreen(): ugfx.area(0,0,ugfx.width(),ugfx.height(),0x0000) ugfx.set_default_font(ugfx.FONT_MEDIUM_BOLD) ugfx.text(30,30,"EMF Schedule Now & Next ",ugfx.GREY) ugfx.text(40,75,"Press [A] to get events ",ugfx.BLUE) return
game_over("The orc gobbled you up!") break else: room=6 room_6() elif room==6: room=7 room_7() elif room==7: room=8 room_8() if buttons.is_triggered("BTN_A"): btn_a_presses+=1 if room == 2: ugfx.area(190,30,300,180, ugfx.BLACK) if btn_a_presses==1: ugfx.text(190, 30, "With which leg?", ugfx.RED) ugfx.text(190, 50, "A: Left", ugfx.RED) ugfx.text(190, 70, "B: Right", ugfx.RED) ugfx.text(190, 90, "Joy Press: Middle", ugfx.RED) elif (btn_a_presses>1 and orc1 > 0 and hp >0): orc1,hp=orc_kicking(6, orc1, hp) if orc1<=0: ugfx.fill_circle(130,70,10,ugfx.RED) elif (orc1<=0 and hp>0): ugfx.text(190, 30, "The orc is dead.", ugfx.RED) ugfx.text(190, 50, "It would be mean ", ugfx.RED) ugfx.text(190, 70, "to kick it again.", ugfx.RED)
b = 3.0 * (y/size[1] - 0.50) z = 0 for n in range(32): z = z**2 + a + b*1j if abs(z) > 4: break return 31-n ugfx.clear(ugfx.GREY) ugfx.text(30, int(size[1])-30, 'Computing...', ugfx.BLACK) for y in range(size[1]): for x in range(size[0]): c = m(x, y) ugfx.area(x, y, 1, 1, get_color(c)) if buttons.is_triggered("BTN_B"): break while playing: ugfx.text(30, int(size[1])-30, 'Mandelbrot done :)', ugfx.WHITE) while True: # pyb.wfi() # Some low power stuff if buttons.is_triggered("BTN_A"): break if buttons.is_triggered("BTN_MENU"): playing = 0 #pyb.hard_reset() break
def home_main(): global orientation, next_tick, tick ugfx.area(0,0,320,240,sty_tb.background()) ugfx.set_default_font(ugfx.FONT_MEDIUM) win_bv = ugfx.Container(0,0,80,25, style=sty_tb) win_wifi = ugfx.Container(82,0,60,25, style=sty_tb) win_name = ugfx.Container(0,25,320,240-25-60, style=dialogs.default_style_badge) win_text = ugfx.Container(0,240-60,320,60, style=sty_tb) windows = [win_bv, win_wifi, win_text] obj_name = apps.home.draw_name.draw(0,25,win_name) buttons.init() gc.collect() ugfx.set_default_font(ugfx.FONT_MEDIUM_BOLD) hook_feeback = ugfx.List(0, 0, win_text.width(), win_text.height(), parent=win_text) win_bv.show() win_text.show() win_wifi.show() min_ctr = 28 # Create external hooks so other apps can run code in the context of # the home screen. # To do so an app needs to have an external.py with a tick() function. # The tick period will default to 60 sec, unless you define something # else via a "period" variable in the module context (use milliseconds) # If you set a variable "needs_wifi" in the module context tick() will # only be called if wifi is available # If you set a variable "needs_icon" in the module context tick() will # be called with a reference to a 25x25 pixel ugfx container that you # can modify external_hooks = [] icon_x = 150 for path in get_external_hook_paths(): try: module = __import__(path) if not hasattr(module, "tick"): raise Exception("%s must have a tick function" % path) hook = { "name": path[5:-9], "tick": module.tick, "needs_wifi": hasattr(module, "needs_wifi"), "period": module.period if hasattr(module, "period") else 60 * 1000, "next_tick_at": 0 } if hasattr(module, "needs_icon"): hook["icon"] = ugfx.Container(icon_x, 0, 25, 25) icon_x += 27 external_hooks.append(hook) except Exception as e: # Since we dont know what exception we're looking for, we cant do much print ("%s while parsing background task %s. This task will not run! " % (type(e).__name__, path[5:-9])) sys.print_exception(e) continue # If the module fails to load or dies during the setup, skip it backlight_adjust() inactivity = 0 last_rssi = 0 ## start connecting to wifi in the background wifi_timeout = 30 #seconds wifi_reconnect_timeout = 0 try: wifi.connect(wait = False) except OSError: print("Creating default wifi settings file") wifi.create_default_config() while True: pyb.wfi() ugfx.poll() if (next_tick <= pyb.millis()): tick = True next_tick = pyb.millis() + 1000 #if wifi still needs poking if (wifi_timeout > 0): if wifi.nic().is_connected(): wifi_timeout = -1 #wifi is connected, but if becomes disconnected, reconnect after 5 sec wifi_reconnect_timeout = 5 else: wifi.nic().update() if tick: tick = False ledg.on() if (wifi_timeout > 0): wifi_timeout -= 1; # change screen orientation ival = imu.get_acceleration() if ival['y'] < -0.5: if orientation != 0: ugfx.orientation(0) elif ival['y'] > 0.5: if orientation != 180: ugfx.orientation(180) if orientation != ugfx.orientation(): inactivity = 0 ugfx.area(0,0,320,240,sty_tb.background()) orientation = ugfx.orientation() for w in windows: w.hide(); w.show() apps.home.draw_name.draw(0,25,win_name) #if wifi timeout has occured and wifi isnt connected in time if (wifi_timeout == 0) and not (wifi.nic().is_connected()): print("Giving up on Wifi connect") wifi_timeout = -1 wifi.nic().disconnect() #give up wifi_reconnect_timeout = 30 #try again in 30sec wifi_connect = wifi.nic().is_connected() #if not connected, see if we should try again if not wifi_connect: if wifi_reconnect_timeout>0: wifi_reconnect_timeout -= 1 if wifi_reconnect_timeout == 0: wifi_timeout = 60 #seconds wifi.connect(wait = False) ledg.on() # display the wifi logo rssi = wifi.nic().get_rssi() if rssi == 0: rssi = last_rssi else: last_rssi = rssi draw_wifi(sty_tb.background(),rssi, wifi_connect,wifi_timeout>0,win_wifi) battery_percent = onboard.get_battery_percentage() draw_battery(sty_tb.background(),battery_percent,win_bv) inactivity += 1 # turn off after some period # takes longer to turn off in the 'used' position if ugfx.orientation() == 180: inactivity_limit = 120 else: inactivity_limit = 30 if battery_percent > 120: #if charger plugged in if ugfx.backlight() == 0: ugfx.power_mode(ugfx.POWER_ON) ugfx.backlight(100) elif inactivity > inactivity_limit: low_power() else: backlight_adjust() ledg.off() for hook in external_hooks: try: if hook["needs_wifi"] and not wifi.nic().is_connected(): continue; if hook["next_tick_at"] < pyb.millis(): text = None if "icon" in hook: text = hook["tick"](hook["icon"]) else: text = hook["tick"]() hook["next_tick_at"] = pyb.millis() + hook["period"] if text: if hook_feeback.count() > 10: hook_feeback.remove_item(0) hook_feeback.add_item(text) if hook_feeback.selected_index() >= (hook_feeback.count()-2): hook_feeback.selected_index(hook_feeback.count()-1) except Exception as e: # if anything in the hook fails to work, we need to skip it print ("%s in %s background task. Not running again until next reboot! " % (type(e).__name__, hook['name'])) sys.print_exception(e) external_hooks.remove(hook) continue if buttons.is_pressed("BTN_MENU"): pyb.delay(20) break if buttons.is_pressed("BTN_A"): inactivity = 0 tick = True if buttons.is_pressed("BTN_B"): inactivity = 0 tick = True for hook in external_hooks: if "icon" in hook: hook["icon"].destroy() for w in windows: w.destroy() apps.home.draw_name.draw_destroy(obj_name) win_name.destroy() hook_feeback.destroy() if ugfx.backlight() == 0: ugfx.power_mode(ugfx.POWER_ON) ugfx.backlight(100) ugfx.orientation(180) #if we havnt connected yet then give up since the periodic function wont be poked if wifi_timeout >= 0: # not (wifi.nic().is_connected()): wifi.nic().disconnect()
### Author: core ### Description: Simple visual morse widget ### Category: morse ### License: MIT ### Appname: cw_flash import ugfx, pyb, buttons ugfx.init() ugfx.clear() ugfx.area(0,0,320,240,ugfx.html_color(0x00FF00)) buttons.init() ugfx.set_default_font(ugfx.FONT_NAME) t4 = pyb.Timer(4, freq=300, mode=pyb.Timer.CENTER) SIGN_SCALING = 100 DOT = 1 DASH = 3 PAUSE_ELEMENT = DOT PAUSE_CHARACTER = 3 * DOT - DOT PAUSE_WORD = 7 * DOT - DOT AF = True def dot(): if AF: ch1 = t4.channel(1, pyb.Timer.PWM, pin=pyb.Pin("BUZZ"), pulse_width=(t4.period() + 1) // 2) ugfx.area(100,75,90,90,ugfx.BLACK) pyb.delay(SIGN_SCALING*DOT) if AF:
def one_round(): grid_size = 8; body_colour = ugfx.RED back_colour = 0; food_colour = ugfx.YELLOW wall_colour = ugfx.BLUE score = 0; edge_x = math.floor(ugfx.width()/grid_size)-2; edge_y = math.floor(ugfx.height()/grid_size)-2; def disp_square(x,y,colour): ugfx.area((x+1)*grid_size, (y+1)*grid_size, grid_size, grid_size, colour) def disp_body_straight(x,y,rotation,colour): if (rotation == 0): ugfx.area((x+1)*grid_size+1, (y+1)*grid_size+1, grid_size-2, grid_size, colour) elif (rotation == 90): ugfx.area((x+1)*grid_size+1, (y+1)*grid_size+1, grid_size, grid_size-2, colour) elif (rotation == 180): ugfx.area((x+1)*grid_size+1, (y+1)*grid_size-1, grid_size-2, grid_size, colour) else: ugfx.area((x+1)*grid_size-1, (y+1)*grid_size+1, grid_size, grid_size-2, colour) def disp_eaten_food(x,y,colour): ugfx.area((x+1)*grid_size, (y+1)*grid_size, grid_size, grid_size, colour) def randn_square(): return [pyb.rng()%edge_x, pyb.rng()%edge_y] body_x = [12,13,14,15,16] body_y = [2,2,2,2,2] ugfx.area(0,0,ugfx.width(),ugfx.height(),0) ugfx.area(0,0,grid_size*(edge_x+1),grid_size,wall_colour) ugfx.area(0,0,grid_size,grid_size*(edge_y+1),wall_colour) ugfx.area(grid_size*(edge_x+1),0,grid_size,grid_size*(edge_y+1),wall_colour) ugfx.area(0,grid_size*(edge_y+1),grid_size*(edge_x+2),grid_size,wall_colour) keepgoing = 1; food = [20,20] dir_x = 1 dir_y = 0 orient = 270 #for i in range(0,len(body_x)): # disp_body_straight(body_x[i],body_y[i],orient,body_colour) while keepgoing: disp_square(food[0],food[1],food_colour) if buttons.is_pressed("JOY_RIGHT"): if orient != 90: dir_x = 1; dir_y = 0; orient = 270 elif buttons.is_pressed("JOY_LEFT"): if orient != 270: dir_x = -1; dir_y = 0; orient = 90 elif buttons.is_pressed("JOY_DOWN"): if orient != 0: dir_y = 1; dir_x = 0; orient = 180 elif buttons.is_pressed("JOY_UP"): if orient != 180: dir_y = -1; dir_x = 0; orient = 0 body_x.append(body_x[-1]+dir_x) body_y.append(body_y[-1]+dir_y) for i in range(0,len(body_x)-1): if (body_x[i] == body_x[-1]) and (body_y[i] == body_y[-1]): keepgoing = 0 if not((body_x[-1] == food[0]) and (body_y[-1] == food[1])): x_del = body_x.pop(0) y_del = body_y.pop(0) disp_eaten_food(x_del,y_del,back_colour) else: disp_eaten_food(food[0],food[1],body_colour) food = randn_square() disp_square(food[0],food[1],food_colour) score = score + 1 disp_body_straight(body_x[-1],body_y[-1],orient,body_colour) if ((body_x[-1] >= edge_x) or (body_x[-1] < 0) or (body_y[-1] >= edge_y) or (body_y[-1] < 0)): break pyb.delay(100) return score
import pyb import math import ugfx # Example of how a simple animation can be done # ToDo: This is quite flickery. It would work a lot better with # Pixmaps, but I couldn't get them to work :( ugfx.init() ugfx.enable_tear() tear = pyb.Pin("TEAR", pyb.Pin.IN) ugfx.set_tear_line((int(320/2)+0)) ugfx.area(0,0,ugfx.width(), ugfx.height(), 0) sec = 0; def draw_hand(cx, cy, angle, length, thickness, color): x = int(math.cos(angle) * length + cx); y = int(math.sin(angle) * length + cy); ugfx.thickline(cx, cy, x, y, color, thickness, 1) while True: # Center cx = int(ugfx.width() / 2); cy = int(ugfx.height() / 2); # Hand: hours angel_hour = math.pi * 2 * sec / 60 / 60 / 12 - math.pi / 2
def mainscreen(): ugfx.area(0,0,ugfx.width(),ugfx.height(),0x0000) ugfx.set_default_font(ugfx.FONT_MEDIUM_BOLD) ugfx.text(30,30,"Whats My IP",ugfx.YELLOW) ugfx.text(40,75,"Press [A] to continue",ugfx.YELLOW) return
break pyb.delay(100) return score playing = 1 while playing: score = one_round() new_high_score = False with Database() as db: high_score = db.get("improved_snake-high-score", 0) if score > high_score: db.set("improved_snake-high-score", score) new_high_score = True ugfx.area(0,0,ugfx.width(),ugfx.height(),0) ugfx.text(30, 30, "GAME OVER Score: %d" % (score), 0xFFFF) if new_high_score: ugfx.text(30, 60, "NEW HIGH SCORE!", 0xFFFF) else: ugfx.text(30, 60, "High score: %d" % (high_score), 0xFFFF) ugfx.text(30, 90, "Press A to play again", 0xFFFF) ugfx.text(30, 120, "Press MENU to quit" , 0xFFFF) while True: pyb.wfi() if buttons.is_triggered("BTN_A"): break if buttons.is_triggered("BTN_MENU"): playing = 0 #pyb.hard_reset() break
def disp_square(x,y,colour): ugfx.area((x+1)*grid_size, (y+1)*grid_size, grid_size, grid_size, colour)
left = 1 def callback_arrow_left(line): global right right = 1 buttons.init() buttons.enable_interrupt("JOY_UP", callback_arrow_up) buttons.enable_interrupt("JOY_DOWN", callback_arrow_down) buttons.enable_interrupt("JOY_LEFT", callback_arrow_left) buttons.enable_interrupt("JOY_RIGHT", callback_arrow_right) while True: if up: up = 0 ugfx.area(40,0,20,20,0) #else: # ugfx.area(40,0,20,20,0xFFFF) # up = 0 if down: down = 0 ugfx.area(40,50,20,20,0) #else: # down = 0 # ugfx.area(40,50,20,20,0xFFFF) if right: right = 0 ugfx.area(70,25,20,20,0) # else:
### Author: Lars Weiler ### Description: progress bar ### Category: fun ### License: THE NERD-WARE LICENSE (Revision 2) ### Appname: progressbar import pyb import ugfx ugfx.init() h = ugfx.height() w = ugfx.width() ugfx.clear(ugfx.BLACK) lw = 240 # progress bar width lh = 40 # progress bar height m = 5 # margin s = 1 # step ugfx.box((w//2)-(lw//2), (h//2)-(lh//2), lw, lh, ugfx.WHITE) for i in range(m, lw-2*m, s): # use the 30bit random number, bitshift by 24 bits, which will give 0-65 # and use this number for the delay in milliseconds pyb.delay(pyb.rng()>>24) ugfx.area((w//2)-(lw//2-m), (h//2)-(lh//2-m), i, (lh-2*m), ugfx.WHITE) # wait 500ms and blank the screen pyb.delay(500) ugfx.clear(ugfx.BLACK)
keepgoing = 1 tgl_menu = pyb.Pin("BTN_MENU", pyb.Pin.IN) tgl_menu.init(pyb.Pin.IN, pyb.Pin.PULL_UP) ugfx.enable_tear() tear = pyb.Pin("TEAR", pyb.Pin.IN) wi = ugfx.width() hi = ugfx.height() while(keepgoing): while(tear.value() == 0): 2+2 while(tear.value()): 2+2 ugfx.area(0,0,wi,hi,ugfx.RED) pyb.delay(60) while(tear.value() == 0): 2+2 while(tear.value()): 2+2 ugfx.area(0,0,wi,hi,ugfx.GREEN) pyb.delay(60) while(tear.value() == 0): 2+2 while(tear.value()): 2+2 ugfx.area(0,0,wi,hi,ugfx.YELLOW) pyb.delay(60)
def disp_eaten_food(x,y,colour): ugfx.area((x+1)*grid_size, (y+1)*grid_size, grid_size, grid_size, colour)