def app_status(self, val): logging.debug('Changing application status to %s' % val) # if old status(before this one) was NEED_UPDATE, # we should to erase notification text about updates if self._app_status == constants.STATUS_NEED_UPDATE: self.hide_install_updates() if val is None: if not self.check_internet_connection(): val = constants.STATUS_NO_INTERNET elif self.check_for_new_updates(): val = constants.STATUS_NEED_UPDATE else: val = constants.STATUS_UP_TO_DATE if val == constants.STATUS_UP_TO_DATE: font = get_font(bold=True) self.change_background_color(constants.background_color_green) self.upper_widget_label.setFont(font) elif val == constants.STATUS_NO_INTERNET: font = get_font(size=18, weight=65, bold=True) self.change_background_color(constants.background_color_red) self.upper_widget_label.setFont(font) elif val == constants.STATUS_NEED_UPDATE: font = get_font(size=16, weight=62, bold=True) self.change_background_color(constants.background_color_yellow) self.upper_widget_label.setFont(font) self.bottom_widget_label.setText( constants.LABEL_NOTIFICATION_TEXT['new_updates_available']) self.installUpdates.show() self._app_status = val status_text = constants.STATUS_TEXT[val] self.tray_icon.show_notification.setText(status_text) self.upper_widget_label.setText(status_text)
def __init__(self, statemanager): super(State, self).__init__() #TODO: just use state def in lambda. if we don't init outside lambda, the exception is squelched for some baffling reason. self.options = [ (get_font("New Game", "good times rg.ttf", 240, (252, 240, 15)), addgamestate), #(get_font("Settings", "good times rg.ttf", 240, (252, 240, 15)), lambda x: x.statemanager.addnextstate(s)), (get_font(" Exit ", "good times rg.ttf", 240, (252, 240, 15)), lambda x: x) ] self.is_done = False self.selected_option = 0 self.statemanager = statemanager
def render(self): font = get_font() text_color = graphics.Color(255, 235, 59) if self.canvas.width > 32: long_word = 'scheduled' else: long_word = 'today' while True: time_now = time.strftime("%-I:%M%p") self.canvas.Fill(7, 14, 25) no_games_text = 'No games scheduled today' no_games_x = center_text_position(no_games_text, self.canvas.width / 2, 4) graphics.DrawText(self.canvas, font, no_games_x, 8, text_color, no_games_text) today_text = long_word today_x = center_text_position(today_text, self.canvas.width / 2, 4) graphics.DrawText(self.canvas, font, today_x, 15, text_color, today_text) time_text = time_now time_x = center_text_position(time_text, self.canvas.width / 2, 4) graphics.DrawText(self.canvas, font, time_x, 26, text_color, time_text) self.matrix.SwapOnVSync(self.canvas) time.sleep(15) pass
def __init__(self, canvas, game, scoreboard, scroll_pos): self.canvas = canvas self.font = get_font() self.game = game self.scoreboard = scoreboard self.text_color = graphics.Color(*ledcolors.scoreboard.text) self.scroll_pos = scroll_pos
def render(matrix, canvas, division): font = get_font() text_color = graphics.Color(*ledcolors.standings.text) canvas.Fill(*ledcolors.standings.fill) stat = 'w' starttime = time.time() while True: offset = 6 graphics.DrawText(canvas, font, 28, offset, text_color, stat.upper()) for team in division.teams: abbrev = '{:3s}'.format(team.team_abbrev) team_text = '%s' % abbrev stat_text = '%s' % getattr(team, stat) graphics.DrawText(canvas, font, 1, offset, text_color, team_text) graphics.DrawText(canvas, font, 15, offset, text_color, stat_text) for x in range(0, canvas.width): canvas.SetPixel(x, offset, *ledcolors.standings.divider) for y in range(0, canvas.height): canvas.SetPixel(13, y, *ledcolors.standings.divider) offset += 6 matrix.SwapOnVSync(canvas) time.sleep(5.0 - ((time.time() - starttime) % 5.0)) canvas.Fill(*ledcolors.standings.fill) stat = 'w' if stat == 'l' else 'l'
def __init__(self, canvas, game, scoreboard, scroll_pos): self.canvas = canvas self.font = get_font() self.game = game self.scoreboard = scoreboard self.text_color = graphics.Color(*ledcolors.scoreboard.text) self.scroll_pos = scroll_pos
def render(self): font = get_font() text_color = graphics.Color(*ledcolors.scoreboard.text) self.canvas.Fill(*ledcolors.scoreboard.fill) no_text = 'No' no_x = center_text_position(no_text, self.canvas.width) graphics.DrawText(self.canvas, font, no_x, 8, text_color, no_text) games_text = 'games' games_x = center_text_position(games_text, self.canvas.width) graphics.DrawText(self.canvas, font, games_x, 15, text_color, games_text) today_text = 'today' today_x = center_text_position(today_text, self.canvas.width) graphics.DrawText(self.canvas, font, today_x, 22, text_color, today_text) frown_text = ':(' frown_x = center_text_position(frown_text, self.canvas.width) graphics.DrawText(self.canvas, font, frown_x, 29, text_color, frown_text) self.matrix.SwapOnVSync(self.canvas) while True: pass # I hate the offseason and off days.
def __init__(self, canvas, game, coords, probable_starter_pos): self.canvas = canvas self.game = game self.coords = coords self.font = get_font() self.text_color = graphics.Color(*ledcolors.scoreboard.text) self.probable_starter_pos = probable_starter_pos
def __init__(self, canvas, home_team, away_team): self.canvas = canvas self.home_team = home_team self.away_team = away_team self.colors = json.load(open(get_file('Assets/colors.json'))) self.font = get_font()
def render(matrix, canvas, division): font = get_font() text_color = graphics.Color(*ledcolors.standings.text) canvas.Fill(*ledcolors.standings.fill) stat = 'w' starttime = time.time() while True: offset = 6 graphics.DrawText(canvas, font, 28, offset, text_color, stat.upper()) for team in division.teams: abbrev = '{:3s}'.format(team.team_abbrev) team_text = '%s' % abbrev stat_text = '%s' % getattr(team, stat) graphics.DrawText(canvas, font, 1 , offset, text_color, team_text) graphics.DrawText(canvas, font, 15, offset, text_color, stat_text) for x in range(0, canvas.width): canvas.SetPixel(x, offset, *ledcolors.standings.divider) for y in range(0, canvas.height): canvas.SetPixel(13, y, *ledcolors.standings.divider) offset += 6 matrix.SwapOnVSync(canvas) time.sleep(5.0 - ((time.time() - starttime) % 5.0)) canvas.Fill(*ledcolors.standings.fill) stat = 'w' if stat == 'l' else 'l'
def __init__(self, canvas, home_team, away_team): self.canvas = canvas self.home_team = home_team self.away_team = away_team self.colors = json.load(open(get_file('Assets/colors.json'))) self.font = get_font()
def web_identify(): form = IdentifyForm(request.form) if request.method == 'POST': if len(request.files) > 0: file = request.files['file'] if utils.is_picture(file.filename): try: pilimage = Image.open(file.stream, 'r').convert('RGB') except Exception as e: flash("Error: {}".format(e)) return render_template('identify.html', form=form) try: faces = dlib_api.detect_and_identify_faces( np.array(pilimage)) except Exception as e: flash("Error: {}".format(e)) return render_template('identify.html', form=form) font = utils.get_font(1024) draw = ImageDraw.Draw(pilimage) for p, rect, shape in faces: s = font.getsize(p.name) utils.draw_rectangle(draw, rect, 5, color=128) draw.text( ((rect.right() - rect.left()) / 2 + rect.left() - int(s[0] / 2), rect.top() - s[1] - 20), p.name, fill=128, font=font) del draw tmpfile = os.path.join('static/tmp', '{}.jpg'.format(uuid.uuid4())) # resize pilimage = utils.resize_image(pilimage, 1024) with open(tmpfile, 'wb+') as fp: pilimage.save(fp, 'JPEG') flash('found {} faces... '.format(len(faces)) + '\n'.join(("id: {}, name: {}".format(p.id, p.name) for p, _, _ in faces))) return render_template('identify.html', form=form, proc_image=tmpfile) else: flash('Error: Only images allowed!') else: flash('Error: All the form fields are required. ') return render_template('identify.html', form=form)
def __init__(self, canvas, home_team, away_team, config): self.canvas = canvas self.home_team = home_team self.away_team = away_team self.coords = config.coords["teams"] self.display_full_team_names = config.display_full_team_names self.colors = json.load(open(get_file('Assets/colors.json'))) self.font = get_font()
def render(matrix, canvas, division): font = get_font() text_color = graphics.Color(*ledcolors.standings.text) canvas.Fill(*ledcolors.standings.fill) if canvas.width > 32: render_static_wide_standings(matrix, canvas, division, font, text_color) else: render_rotating_standings(matrix, canvas, division, font, text_color)
def __init__(self, text, fadeinms, fadeoutms, totalms, fontname, color): super(Fader, self).__init__() self.label = get_font(text, fontname, 240, color) self.fadeinms = fadeinms self.fadeoutms = fadeoutms self.totalms = totalms self.currentms = 0 self.is_done = False #start with a width of 60% self.width = .8 self.alpha = 0
def render(matrix, canvas): font = get_font() text_color = graphics.Color(*ledcolors.scoreboard.text) canvas.Fill(*ledcolors.scoreboard.fill) graphics.DrawText(canvas, font, 12, 8, text_color, 'No') graphics.DrawText(canvas, font, 6, 15, text_color, 'games') graphics.DrawText(canvas, font, 6, 22, text_color, 'today') graphics.DrawText(canvas, font, 12, 29, text_color, ':(') matrix.SwapOnVSync(canvas) while True: pass # I hate the offseason and off days.
def render(matrix, canvas): font = get_font() text_color = graphics.Color(*ledcolors.scoreboard.text) canvas.Fill(*ledcolors.scoreboard.fill) graphics.DrawText(canvas, font, 12, 8, text_color, 'No') graphics.DrawText(canvas, font, 6, 15, text_color, 'games') graphics.DrawText(canvas, font, 6, 22, text_color, 'today') graphics.DrawText(canvas, font, 12, 29, text_color, ':(') matrix.SwapOnVSync(canvas) while True: pass # I hate the offseason and off days.
def render(matrix, canvas, error_strings): font = get_font() text_color = graphics.Color(255, 235, 59) current_y = 9 offset = 7 canvas.Fill(7, 14, 25) error_text = 'ERROR' error_x = center_text_position(error_text, canvas.width/2, 4) graphics.DrawText(canvas, font, error_x, 7, text_color, error_text) for error_string in error_strings: current_y += offset text = error_string text_x = center_text_position(text, canvas.width/2, 4) graphics.DrawText(canvas, font, text_x, current_y, text_color, text) matrix.SwapOnVSync(canvas)
def render(matrix, canvas, error_strings): font = get_font() text_color = graphics.Color(*ledcolors.scoreboard.text) current_y = 9 offset = 7 canvas.Fill(*ledcolors.scoreboard.fill) error_text = 'ERROR' error_x = center_text_position(error_text, canvas.width) graphics.DrawText(canvas, font, error_x, 7, text_color, error_text) for error_string in error_strings: current_y += offset text = error_string text_x = center_text_position(text, canvas.width) graphics.DrawText(canvas, font, text_x, current_y, text_color, text) matrix.SwapOnVSync(canvas)
def __init__(self): super(Game, self).__init__() width, height = self.back_screen.get_size() self.background_left = Background(width/2, height) self.background_right = Background(width/2, height) self.position = (960,0) self.bright_star = StarObject(["sprites/star1.png", "sprites/star2.png", "sprites/star3.png"], self.position, width/2, height, 0) self.dark_star = StarObject(["sprites/dark1.png", "sprites/dark2.png", "sprites/dark3.png"], self.position, width/2, height, 0) self.right_platforms = [] self.left_platforms = [] y = 0 x = 200 manager = PlatformManager() for i in range(0, 100): y += random.randint(250,450) x += random.randint(-450, 450) if (x < 0): x = 0 if x > config.GAME_WIDTH - 500: x = config.GAME_WIDTH - 500 z = random.choice([True, False]) size = random.randint(3, 9) plat = PlatformObject(manager, z, (x, y), size, width/2, height, 0) if not z: self.left_platforms.append(plat) else: self.right_platforms.append(plat) #plat = PlatformObject(True, (600, 600), 8, width/2, height, 0) self.__sizetextures() self.displacement = 0 self.is_displacing = False self.keyvector = (0,0) self.movement_speed = 1 self.vertical_speed = 0 self.is_done = False self.moving_left = False self.moving_right = False self.active_player = 0 self.gravity = -15 self.score = 0 self.ramprate = 1 self.scorefont = utils.get_font("Hi Score: " + str(config.highscores[0][1]).zfill(10) + " Score: " + str(self.score).zfill(10), "good times rg.ttf", 35, (255,255,255), None)
def draw(self, draw): for line in self.lines: #fill = colors[idx % len(colors)] if colortext else "black" fill = "black" draw.text(line.pos, line.text, font=utils.get_font(line.text, line.size[0]), fill=fill) draw.text( line.pos, "%.2f" % line.count, fill=TEXT_COUNT_COLOR)
def plot_ngon(bal_mass, bal_diam, nbals, side_len, dmin, payload=0.0, plot_show=False, plot_save_as=''): """ Функция построения эскиза размеров плоской платформы-многоугольника (с указанием максимально достижимой высоты подъёма) - с метеошарами на каждом углу - с центральным отверстием не менее заданного диаметра --------------------------------------------------------------------------- :param bal_mass: масса метеошара, кг :param bal_diam: диаметр метеошара без растяжения, м :param nbals: число углов / число метеошаров, шт (не менее 3) :param side_len: длина стороны многоугольника / расстояние между шарами, м :param dmin: минимальный диаметр центрального отверстия, м :param payload: масса платформы и полезной нагрузки на платформе, кг :param plot_show: True/False отображение графика (эскиза) :param plot_save_as: путь к сохраняемому файлу графика, с расширением. '' - пустая строка - не сохранять изображение (по умолчанию) --------------------------------------------------------------------------- :return: exit_status: 0 - успешное завршение 1 - некорректные входные данные 2 - ошибка создания объекта метеошара 4 - ошибка создания графика решения Примеры вызова: >>> plot_ngon(bal_mass=3, ... bal_diam=2.164, ... nbals=3, ... side_len=2.7, ... dmin=0.5, ... payload=1.05, ... plot_show=True, ... plot_save_as='doctest.png') 0 """ # Check inputs. # ----------------------------------------------------------- try: # Confirm input numeric types bal_mass = float(bal_mass) if bal_mass <= 0: raise ValueError('bal_mass must be positive') bal_diam = float(bal_diam) if bal_diam <= 0: raise ValueError('bal_diam must be positive') nbals = int(nbals) if nbals < 2: raise ValueError('nbals must be integer greater than 2') side_len = float(side_len) if side_len <= 0: raise ValueError('side_len must be positive') dmin = float(dmin) if dmin <= 0: raise ValueError('dmin must be positive') payload = float(payload) if payload < 0: raise ValueError('payload must be non-negative') except ValueError as err: print(err, file=sys.stderr) return 1 # Create balloon instance # ----------------------------------------------------------- try: balloon = BalloonStatic(bal_mass=bal_mass, bal_mat=material.RUBBER, gas=gas.HELIUM, bal_diam=bal_diam) except Exception as err: print(err, file=sys.stderr) return 2 # Create geometrical-condition checker function # ----------------------------------------------------------- # Calc radius of a circumscribed circle (over N-gon) rcs = side_len / (2 * math.sin(const.pi / nbals)) def geom_check(alt, bal=balloon, rcs=rcs, l=side_len, dmin=dmin): bal_d = bal.get_diam(alt) if bal_d > l: # Balloons contact return False # Check dmin if (bal_d / 2.0 + dmin / 2.0) > rcs: # Balloons overlap central shaft return False return True # Create platform plot-function # ----------------------------------------------------------- def plot(ax, alt, bal=balloon, n=nbals, rcs=rcs, l=side_len, dmin=dmin): ax.set_aspect('equal') # ax.set_title(u'H = ' + str(round(alt/1000, 1)) + u' км') # Plot dmin-shaft circle circle_shaft = plt.Circle((0, 0), radius=dmin / 2.0, edgecolor='k', facecolor='k', fill=True, linestyle='-', linewidth=1.0) ax.add_artist(circle_shaft) # Polar coordinate <theta> [radians] of platform corners corners_theta = np.arange(0.0, 2 * math.pi, 2 * math.pi / n) # Polar coordinate <rho> [meters] is equal to radius # of a circumscribed circle (over N-gon) corners_rho = [rcs] * n # Plot N=gon for i in range(0, n): x_end, y_end = utils.pol2cart(corners_theta[i], corners_rho[i]) x_beg, y_beg = utils.pol2cart(corners_theta[i - 1], corners_rho[i - 1]) ax.plot([x_beg, x_end], [y_beg, y_end], color='b', linestyle='-', linewidth=2.0) # Plot balloons bal_rad = bal.get_radius(alt) for theta, rho in zip(corners_theta, corners_rho): x_cnt, y_cnt = utils.pol2cart(theta, rho) circle_bal = plt.Circle((x_cnt, y_cnt), radius=bal_rad, edgecolor='r', facecolor=None, fill=False, linestyle='--', linewidth=1.0) ax.add_artist(circle_bal) ax.set_xlim([-(l + bal_rad), (l + bal_rad)]) ax.set_ylim([-(l + bal_rad), (l + bal_rad)]) # ======================================================================== # Now we need to detect maximum altitude where geom_check() returns True. # Cycle-variable: alt = 0 # Commentary txt_alt_limiter = u"Высота ограничена " # Cycle step alt_step = 100 # step of altitude checking # Run iter-cycle weight_payload = payload * const.g while geom_check(alt): f_arh = balloon.get_forces_sum(alt) f_sum = f_arh - weight_payload if f_sum <= 0: txt_alt_limiter += u"подъёмной силой" break if balloon.is_burst(alt): txt_alt_limiter += u"предельным растяжением шара" break alt += alt_step txt_alt_limiter += u"геометрическими параметрами платформы" alt_max = alt # ======================================================================== # Create 2 subplots: (1) at H=0 and (2) at H=Hmax try: if plot_show or plot_save_as: matplotlib.rcParams['font.size'] = 12 matplotlib.rcParams['font.family'] = utils.get_font() matplotlib.rcParams["axes.grid"] = True f, (ax1, ax2) = plt.subplots(1, 2) # at H=0 plot(ax1, alt=0) ax1.set_title(u'Исходное состояние:\nH = 0 км') # at Hmax plot(ax2, alt=alt_max) ax2.set_title(u'Макс. высота:\nH = ' + str(round(alt / 1000, 1)) + u' км' + '\n' + txt_alt_limiter) if plot_show: plt.show() if plot_save_as: f.set_size_inches(18.5, 10.5) f.savefig(plot_save_as, dpi=100, bbox_inches='tight') plt.close() else: warnings.warn("All output's disabled.") except Exception as err: print(err, file=sys.stderr) return 4 return 0
def __init__(self, canvas, inning): self.canvas = canvas self.inning = inning self.font = get_font()
def __init__(self, canvas, pitches): self.canvas = canvas self.pitches = pitches self.font = get_font()
def __init__(self, canvas, inning): self.canvas = canvas self.inning = inning self.font = get_font()
def model_free_lift(duration, bal_mass, bal_diam, bal_mat='rubber', bal_gas='helium', payload=0, plot_show=False, plot_save_as='', show_debug_msg=False, ): """ Моделирование процесса свободного подъёма для шара с полезной нагрузкой Функция создаёт изображение-график, если в аргументе <plot_save_as> для него передано имя --------------------------------------------------------------------------- :param duration: продолжительность моделируемого процесса, с :param bal_mass: масса метеошара, кг :param bal_diam: диаметр метеошара в состоянии без растяжения, м :param bal_mat: наименование материала метеошара. Варианты: {'rubber', } (см пакет <material>) :param bal_gas: наименование наполняющего газа метеошара. Варианты: {'helium', } (см пакет <gas>) :param payload: полезная нагрузка, поднимаемая метеошаром, кг :param plot_show: True/False отображение графика процесса :param plot_save_as: путь к сохраняемому файлу графика, с расширением. '' - пустая строка - не сохранять изображение :param show_debug_msg: отображать отладочные сообщения выводом print() --------------------------------------------------------------------------- :return: exit_status: 0 - успешное завршение 1 - некорректные входные данные 2 - ошибка создания объекта метеошара 3 - ошибка интегрирования системы ОДУ 4 - ошибка создания графика решения Примеры вызова: >>> model_free_lift(duration=180*60, ... bal_mass=3.0, ... bal_diam=2.164, ... payload=1.05, ... plot_save_as='doctest.png', ... plot_show=True, ... show_debug_msg=True) Called function: model_free_lift( duration=10800, bal_mass=3.0, bal_diam=2.164, bal_mat=rubber, bal_gas=helium, payload=1.05, plot_show=True, plot_save_as=doctest.png, show_debug_msg=True) RK4 terminated at t=7018 Successfull end. 0 >>> kwargs = {'duration': 180*60, ... 'bal_mass': 3.0, ... 'bal_diam':2.164, ... 'payload': 1.05, ... 'plot_save_as': 'doctest.png'} >>> model_free_lift(**kwargs) RK4 terminated at t=7018 0 """ # Send inputs to log if show_debug_msg: log_msg = "Called function:\n" \ " model_free_lift(\n" \ " duration={0},\n" \ " bal_mass={1},\n" \ " bal_diam={2},\n" \ " bal_mat={3},\n" \ " bal_gas={4},\n" \ " payload={5},\n" \ " plot_show={6},\n" \ " plot_save_as={7},\n" \ " show_debug_msg={8})".\ format(duration, bal_mass, bal_diam, bal_mat, bal_gas, payload, plot_show, plot_save_as, show_debug_msg) print(log_msg) # Create ODE-function for model def odefun(y, time, balloon, payload): """ Дифф. закон Ньютона - уравнение процесса свободного подъёма для шара с полезной нагрузкой В форме Коши: dy/dt = f(y, t) Внимание! Условие разрыва шара должно проверяться извне функции. """ alt = y[0] vel = y[1] # Model equations f_sum_bal = balloon.get_forces_sum(alt, vel) f_sum_pl = - payload*const.g f_sum = f_sum_bal + f_sum_pl mass = balloon.get_mass() + payload return [vel, f_sum/mass] def terminator(y, t, step_no): # Функция, останавливающая интегрирование при разрыве метеошара h = y[step_no][0] tf = balloon.is_burst(h) return tf # Check inputs. # ----------------------------------------------------------- try: # Confirm input numeric types duration = float(duration) if duration <= 0: raise ValueError('duration must be positive') bal_mass = float(bal_mass) if bal_mass <= 0: raise ValueError('bal_mass must be positive') bal_diam = float(bal_diam) if bal_diam <= 0: raise ValueError('bal_diam must be positive') payload = float(payload) if payload < 0: raise ValueError('payload must be non-negative') # Define material if not (bal_mat in material.__all__): raise ValueError("Unknown balloon material name ", bal_mat) # Define gas if not (bal_gas in gas.__all__): raise ValueError("Unknown gas name ", bal_gas) except ValueError as err: print(err, file=sys.stderr) return 1 # Create balloon instance # ----------------------------------------------------------- try: balloon = BalloonStatic( bal_mass=bal_mass, bal_diam=bal_diam, bal_mat=material.BY_NAME[bal_mat], gas=gas.BY_NAME[bal_gas]) except Exception as err: print(err, file=sys.stderr) return 2 # Шаг детализации процесса по времени, с tstep = duration/100.0 if duration < 100.0 else 1 time_points = np.arange(0, duration, tstep) # solve the DEs # ----------------------------------------------------------- try: # Create solver (Runge-Kutta, 4th order) solver = odespy.RK4( odefun, f_args=(balloon, payload), rtol=1E-2) solver.set_initial_condition([0, 0]) y_sln, time = solver.solve( time_points, terminate=terminator) alt = y_sln[:, 0] vel = y_sln[:, 1] # Максимальная высота alt_max = max(alt) # Момент достижения макс. высоты time_alt_max = time[np.where(alt == alt_max)][0] # Индекс высшей точки в массиве ind_max = np.argmax(alt) # Скрыть некорректные точки расчёта после разрыва шара time = time[:ind_max] alt = alt[:ind_max] vel = vel[:ind_max] except Exception as err: print(err, file=sys.stderr) return 3 # Plot # ----------------------------------------------------------- if plot_show or plot_save_as: try: # масштаб отображения scale_v = 1.0 # скорости scale_h = 1.0/1000.0 # высоты scale_t = 1.0/60.0 # времени time *= scale_t time_alt_max *= scale_t alt *= scale_h alt_max *= scale_h vel *= scale_v # Построение графика matplotlib.rcParams['font.size'] = 14 matplotlib.rcParams['font.family'] = utils.get_font() matplotlib.rcParams["axes.grid"] = True plt.figure() plt.plot( time, alt, 'b-', linewidth=2.0, label=u'Высота, км') plt.plot( time, vel, 'r-', linewidth=2.0, label=u'Скорость, м/с') plt.xlabel(u'Время, мин') matplotlib.pyplot.ylim([0.0, alt_max*1.2]) plt.legend(loc='upper left', shadow=True) plt.title( u"Полёт метеошара\n" u"(m = {0} кг; Ø = {1} м, нагрузка {2} кг)\n" u"Макс. высота {3} км достигнута спустя {4} мин".format( balloon.bal_mass, balloon.d0, payload, round(alt_max), round(time_alt_max) )) if plot_save_as: plt.savefig(plot_save_as, bbox_inches='tight') if plot_show: plt.show() plt.close() except Exception as err: print(err, file=sys.stderr) return 4 else: warnings.warn("All output's disabled.") if show_debug_msg: print('Successfull end.') return 0
def __init__(self, canvas, scoreboard): self.canvas = canvas self.scoreboard = scoreboard self.font = get_font() self.text_color = graphics.Color(*ledcolors.scoreboard.text)
def __init__(self, canvas, game, probable_starter_pos): self.canvas = canvas self.game = game self.font = get_font() self.text_color = graphics.Color(*ledcolors.scoreboard.text) self.probable_starter_pos = probable_starter_pos
def update(self, dt): width, height = self.back_screen.get_size() # TODO: implement gravity # dt / 1000 to get fractional seconds and / 2 to get proper integration https://www.niksula.hut.fi/~hkankaan/Homepages/gravity.html self.vertical_speed += self.gravity * (dt / 1000.0) #scroll the screen if self.is_displacing: self.displacement += (dt / 3.0) + (self.displacement / 3000.0) self.score = self.displacement #only check this if the star is moving negative so we don't stick the star to stuff if self.vertical_speed < 0 and self.activesun_on_platform(): self.vertical_speed = 0 # reset vertical speed since we're on a platform that's currently active. if self.moving_left: self.keyvector = (-1, self.vertical_speed) elif self.moving_right: self.keyvector = (1, self.vertical_speed) else: self.keyvector = (0,self.vertical_speed) #collect all our dirty rects (must be done before player moves) dirty_rects = [self.bright_star.getscreenrect((width/2, height))] #reposition the player self.position = (self.position[0] + dt * self.keyvector[0] * self.movement_speed, self.position[1] + dt * self.keyvector[1] * self.movement_speed) if self.vertical_speed <= 0 and self.activesun_on_platform(): self.position = (self.position[0], self.get_sun_platform_offset()) self.position = self.bright_star.move((self.position[0], max(self.position[1], 1)), dt) # start scrolling once past halfway point. if (self.position[1] > config.GAME_HEIGHT / 2): self.is_displacing = True self.dark_star.move(self.position, dt) #set our state to done if player is dead if (self.bright_star.isdead()): #save our score. #TODO: make this less ghetto newscores = [] has_scored = False for hiscore in config.highscores: if not has_scored and hiscore[1] < int(self.score): #we have a score higher than this one so insert now. has_scored = True newscores.append(("XXX", self.score)) newscores.append(hiscore) if not has_scored: newscores.append(("XXX", self.score)) config.update_scores(newscores) self.is_done = True dirty_rects.append(pygame.rect.Rect(0, 20, width/2, self.scorefont.get_size()[1] + 30)) for platform in self.left_platforms: if platform.is_onscreen(self.displacement): dirty_rects.append(platform.getscreenrect((width/2, height))) for platform in self.right_platforms: if platform.is_onscreen(self.displacement): dirty_rects.append(platform.getscreenrect((width/2, height))) #redraw background updateall = self.background_left.update(self.back_screen.subsurface(0, 0, width/2, height), dirty_rects) self.background_right.update(self.back_screen.subsurface(width/2, 0, width/2, height), dirty_rects) #draw platforms #TODO: make dirty_rects an screen_dirty 2 separate lists, and then extend them. for platform in self.left_platforms: if platform.is_onscreen(self.displacement): platform.update(self.back_screen.subsurface(0, 0, width/2, height), self.displacement, dt) dirty_rects.append(platform.getscreenrect((width/2, height))) for platform in self.right_platforms: if platform.is_onscreen(self.displacement): platform.update(self.back_screen.subsurface(width/2, 0, width/2, height), self.displacement, dt) dirty_rects.append(platform.getscreenrect((width/2, height))) if (self.active_player == 0): self.bright_star.update(self.back_screen.subsurface(0, 0, width/2, height), self.displacement, dt) self.dark_star.update(self.back_screen.subsurface(width/2, 0, width/2, height), self.displacement, dt) else: self.bright_star.update(self.back_screen.subsurface(width/2, 0, width/2, height), self.displacement, dt) self.dark_star.update(self.back_screen.subsurface(0, 0, width/2, height), self.displacement, dt) #draw score temphi = int(config.highscores[0][1]) if self.score > temphi: temphi = self.score self.scorefont = utils.get_font("Hi Score: " + str(int(temphi)).zfill(10) + " Score: " + str(int(self.score)).zfill(10), "monofonto.ttf", 32, (255,255,255), None) destrect = pygame.rect.Rect(self.back_screen.get_size()[0] - self.scorefont.get_size()[0] - 20, 20, self.scorefont.get_size()[0], self.scorefont.get_size()[1] + 20) #make a platform on the left side. #destrect = pygame.rect.Rect(0, 0, plat5.get_size()[0], plat5.get_size()[1]) #dirty_rects.append(destrect) #self.back_screen.blit(plat5, destrect) #self.left_platforms.append(self.platformmanager.getplatformimage(5)) #draw font self.back_screen.blit(self.scorefont, destrect) #TODO: add all current positions to dirty rects so we can pass all to display update. dirty_rects.append(self.bright_star.getscreenrect((width/2, height))) #double all dirty rects that are in both windows #this is really not optimal because the platforms are not on both sides but no time to make better final_rects = [] for rect in dirty_rects: final_rects.append(rect) final_rects.append(rect.move(self.back_screen.get_size()[0] / 2, 0)) #Trigger a full screen redraw if anything needs it. if updateall: return None return final_rects
def __init__(self, canvas, pitches): self.canvas = canvas self.pitches = pitches self.font = get_font()
def __init__(self, canvas, inning, coords): self.canvas = canvas self.inning = inning self.coords = coords self.font = get_font()