class LineGraph(Graph): xMax = NumericProperty(60.0) yMax = NumericProperty(1000.0) yMin = NumericProperty(0.0) xMin = NumericProperty(0.0) xLabel = Property("Time (s)") yLabel = Property("Altitude (m)") plot_1 = MeshLinePlot(color=[1, 0, 0, 1]) plot_2 = MeshLinePlot(color=[0, 1, 0, 1]) yVal_1 = NumericProperty(0.0) yVal_2 = NumericProperty(0.0) xVal = NumericProperty(0.0) def update(self, myflightdata): if not myflightdata.hasStarted: return m, s = divmod(myflightdata.TheTime.seconds, 60) milliseconds = myflightdata.TheTime.microseconds / 1000.0 self.xVal = m * 60.0 + s + milliseconds / 1000.0 self.yVal_1 = myflightdata.altitude_1 self.plot_1.points.append((self.xVal, self.yVal_1)) self.xMax = max(self.xMax, self.xVal + 5) self.yMax = max(self.yMax, self.yVal_1 + 30, self.yVal_2 + 30) self.add_plot(self.plot_1) if (myflightdata.parachute_1): self.yVal_2 = myflightdata.altitude_2 self.plot_2.points.append((self.xVal, self.yVal_2)) self.add_plot(self.plot_2)
class Exibir(BoxLayout): """Componente Exibir.""" textoBotaoAtualizar = StringProperty("Atualizar") textoBotaoExcluir = StringProperty("Excluir") texto = StringProperty() att = Property(lambda x:...) deletar = Property(lambda x:...)
class PongPaddle(Widget): score = NumericProperty(0) time = Property(0.0) highscore = Property(0.0) def bounce_ball(self, ball): if self.collide_widget(ball): vx, vy = ball.velocity offset = (ball.center_y - self.center_y) / (self.height / 2) bounced = Vector(-1 * vx, vy) vel = bounced * 1.05 ball.velocity = vel.x, vel.y + offset
class PongPaddle(Widget): time = Property(0.0) highscore = Property(0.0) ''' If the ball has collided with the paddle, the ball changes y direction, as well as x direction based on the offset of the ball from the center ''' def bounce_ball(self, ball): if self.collide_widget(ball): vx, vy = ball.velocity offset = (ball.center_x - self.center_x) / (self.height / 2) bounced = Vector(vx, -1 * vy) vel = bounced * 1.05 ball.velocity = vel.x + offset, vel.y
class PopupError(Popup): """Componente Popup.""" textoBotao = StringProperty('Fechar') titulo = StringProperty('') texto = StringProperty('') funcao = Property(lambda x: x.dismiss())
class MainWidget(Widget): current = NumericProperty(0) prob_0 = NumericProperty(0) prob_1 = NumericProperty(0) prob_2 = NumericProperty(0) prob_3 = NumericProperty(0) prob_4 = NumericProperty(0) prob_5 = NumericProperty(0) prob_6 = NumericProperty(0) prob_7 = NumericProperty(0) prob_8 = NumericProperty(0) prob_9 = NumericProperty(0) max_prob = NumericProperty(1) log = Property("") def set_pred(self, pred): self.current = int(pred) def write_log(self, path): self.log = str(path) def draw_prob_rect(self, pred_arr): self.prob_0 = pred_arr[0] self.prob_1 = pred_arr[1] self.prob_2 = pred_arr[2] self.prob_3 = pred_arr[3] self.prob_4 = pred_arr[4] self.prob_5 = pred_arr[5] self.prob_6 = pred_arr[6] self.prob_7 = pred_arr[7] self.prob_8 = pred_arr[8] self.prob_9 = pred_arr[9] self.max_prob = max(pred_arr)
class PopupFile(Popup): """Componente Popup.""" textoBotao = StringProperty('Fechar') textoBotaoSel = StringProperty('Selecionar') titulo = StringProperty('Procurar:') funcao = Property(lambda x: x.dismiss()) path = StringProperty('') def __init__(self, *args, **kwargs): """.""" super().__init__(*args, **kwargs) self.path = App.get_running_app().pathDown def _att_down(self, func): self.func = func def selecionar(self): """.""" App.get_running_app().pathDown = self.ids.fc.path self.func(self.ids.fc.path) self.dismiss()
class GomokuRooms(Screen): username = Property('') userid = -1 def init(self): client.refresh() def setUsername(self, user): self.username = user def getUsername(self): return username def setUserid(self, userid): self.userid = userid def setRoomAmount(self, amount): self.roomAmount = amount def printRoom(self, rooms): roomAmount = len(rooms) self.ids.rooms.clear_widgets() if roomAmount > 0: for room in rooms: print room[1][1] #Init roomName = Label(text="[color=F41D4E]"+ room[1][1] +"[/color]", markup= True, font_size='20sp') tag1 = Label(text="[color=ffffff]Player[/color]", markup=True) mainGrid = GridLayout(cols= 2) #Setting Background - not function yet - #if i == 0: # mainGrid.canvas.add(Color(0.06,0.537,0.98,1)) # mainGrid.canvas.add(Rectangle(pos=self.pos, size=self.size)) #Process #adding roomname titleGrid = GridLayout(rows=2, padding=[5,10]) titleGrid.add_widget(roomName) #adding button for room buttonGrid = GridLayout(rows=2, padding=[250,0]) joinButton = Button(text='[color=F41D4E]Join[/color]',on_press= lambda instance: game_screen(instance, room[0][1], self.userid), markup= True, background_color=[2.8,2.8,2.8,1]) #joinButton.bind(on_press=change_screen('game')) watchButton = Button(text='[color=F41D4E]Watch[/color]', markup= True, background_color=[2.8,2.8,2.8,1]) buttonGrid.add_widget(joinButton) buttonGrid.add_widget(watchButton) titleGrid.add_widget(buttonGrid) #adding playername playerGrid = GridLayout(rows=2, padding=[100,0]) playerGrid.add_widget(tag1) playerGridInner = GridLayout(cols=2) for player in room[2][1]: playerGridInner.add_widget(Button(text='[color=eeeeee]'+ player[1][1] +'[/color]', markup=True, background_color=[2.953,1.67,0.471,1])) # PLAYER_NAME playerGrid.add_widget(playerGridInner) #including roomname and playername mainGrid.add_widget(titleGrid) mainGrid.add_widget(playerGrid) #Render self.ids.rooms.add_widget(mainGrid) else: self.ids.rooms.add_widget(Label(text="No rooms available"))
class Board(Widget): __events__ = ('on_move', ) pieces = Property([]) move = StringProperty('') def __init__(self, **kwargs): super().__init__(**kwargs) self.margin = 10 self.style = Style() self.calc_size() self.bind(size=self.redraw) self.bind(pieces=self.redraw_pieces) def calc_size(self): self.grid_size = min(i - 2 * self.margin for i in self.size) self.cell_size = self.grid_size / 8 self.xyo = [(i - self.grid_size) / 2 for i in self.size] Logger.info('{}.Board: {:.2f}, {:.2f}x8x8'.format( __name__, self.grid_size, self.cell_size)) def on_move(self, *_): pass def on_touch_down(self, touch): Logger.trace('{}.Board: on_touch_down({} {})'.format( __name__, touch.pos, self.xyo)) x, y = [(i - j) / self.cell_size for i, j in zip(touch.pos, self.xyo)] if 0 <= x < 8 and 0 <= y < 8: move = 'abcdefgh'[int(x)] + str(1 + int(y)) self.move += move if len(self.move) < 4: self.select(move) else: self.dispatch('on_move', self.move) self.move = '' def redraw_board(self): self.canvas.before.clear() with self.canvas.before: Color(0, 0, 0, 1) Rectangle(pos=[i - 4 for i in self.xyo], size=2 * [8 + self.grid_size]) Color(1, 1, 1, 1) Rectangle(pos=self.xyo, size=2 * [self.grid_size], source=self.style.background) Rectangle(pos=self.xyo, size=2 * [self.grid_size], source=self.style.board_source) def redraw_pieces(self, *_): self.canvas.clear() with self.canvas: for p, file, rank in self.pieces: x, y = self.xy(file, rank) w, h = 2 * [self.cell_size] texture = self.style.piece_texture(p) Rectangle(pos=(x + 16, y + 2), size=(w - 32, h - 4), source=texture) def redraw(self, *args): Logger.info('{}.Board: redraw {}'.format(__name__, args)) self.calc_size() self.redraw_board() self.redraw_pieces() # select square(s) in the move -- in uci notation def select(self, move: str): self.redraw_pieces() color = [(0.5, 0.65, 0.5, 1), (0.65, 0.75, 0.65, 1)] for i, pos in enumerate( [move[i:i + 2] for i in range(0, min(4, len(move)), 2)]): with self.canvas: x, y = [j for j in self.xy(*pos)] w, h = 2 * [self.cell_size] Color(*color[i]) Line(points=[x, y, x + w, y, x + w, y + h, x, y + h, x, y], width=2) def xy(self, file, rank): col, row = 'abcdefgh'.index(file), int(rank) - 1 return [o + i * self.cell_size for o, i in zip(self.xyo, [col, row])]
class cScrollableLabelLargeInner(RecycleView): """ The "real' scrollable label (without background) """ # to have similar properties as a Label font_size = Property('20sp') text = StringProperty('') oOrcaWidget = Property(None) # Internal Property which handles fonmt resizing (not working as RecycleView can't manage change of cached widget) fFontSize = BoundedNumericProperty(dpi2px(20, 'sp'), min=4.0, max=96.0, errorhandler=lambda x: 96.0 if x > 96.0 else 4.0) def __init__(self, **kwargs): #we create a new class on the fly top ass the font args to the creation process, as the view adapter creates without arguments self.cLineLayout = type('cLineLayout', cLineLayoutBase.__bases__, dict(cLineLayoutBase.__dict__)) # passes myself to the embedded class. Not good style but Recycleview limits passing customized parameters self.cLineLayout.oScrollableLabelLargeInner = self self.oOrcaWidget = kwargs.get('ORCAWIDGET', None) # maximal len (in chars) of a single ine of the given text self.iMaxLen = 0 # Setting the scrolltypes / bars for the Recycleview self.scroll_type = ['bars', 'content'] self.scroll_wheel_distance = dp(114) self.bar_width = dp(10) # The original passed Data array self.aData = [] # Internal Flag to distinguish between first show and (re) setting text self.bInit = False # The maximum width of a char self.iMaxCharwidth = 0 # The maximum characters per line self.iMaxCharsPerLine = 0 if "font_size" in kwargs: self.on_font_size(None, kwargs["font_size"]) # Retieving the genuine font propertes of a label to pass only those arguments to the label (removing pos, hints, background colors , etc self.aFontProperties = Label._font_properties + ("background_color", ) # standard font args, if nothing is given self.kwFontArgs = { "halign": "left", "valign": "top", "max_lines": 1, "font_size": 20 } # add / update the font args to be passed to the Label for k in kwargs: if k in self.aFontProperties: self.kwFontArgs[k] = kwargs[k] self.kwFontArgs["font_size"] = self.fFontSize self.kwFontArgs.pop("text", None) # Parameter Flag to disable horizontal scrolling self.bNoXScroll = kwargs.get("noxscroll", False) self.bMarkup = kwargs.get("markup", False) #A dummy label to get th width a the larges character self.oLabel = Label(**RemoveNoClassArgs(self.kwFontArgs, Label)) super(self.__class__, self).__init__(**RemoveNoClassArgs(kwargs, RecycleView)) # This manages the distance between lines self.layout_manager.default_size = ( None, self.oLabel._label.get_extents('W')[1]) #self.layout_manager.default_size = (None, self.fFontSize*1.1) self.layout_manager.orientation = 'vertical' # we need to handle size changes self.bind(size=self.update_size) self.bind(text=self.on_textinner) self.text = kwargs.get("text", "") def on_fFontSize(self, instance, value): """ Will handle font size changes """ if self.layout_manager is not None: self.kwFontArgs["font_size"] = self.fFontSize self.oLabel.font_size = self.fFontSize self.layout_manager.default_size = ( None, self.oLabel._label.get_extents('W')[1]) self.SetData(self.aData) def on_font_size(self, instance, value): """Helper function to manage strings with metrics passed as arguments (eg '12dp') """ try: fValue = float(value) except: fValue = dpi2px(value[:-2], value[-2:]) self.fFontSize = fValue def on_textinner(self, instance, value): """ helper to have a Label like funtionality to set the caption """ self.update_size(None, None) def IncreaseFontSize(self, *args): """ Increase the Font size """ self.fFontSize += 1.0 def DecreaseFontSize(self, *args): """ Decrease the Font size """ self.fFontSize -= 1.0 def SetData(self, aData): """ Passes the data to the Recycle view and sets the layout manager size """ self.data = [{ 'text': ToUnicode(x), "font_size": self.fFontSize } for x in aData] if self.bNoXScroll: self.layout_manager.width = self.width else: self.layout_manager.width = ( self.iMaxCharwidth) * self.iMaxCharsPerLine self.viewclass = self.cLineLayout self.refresh_from_data() def update_size(self, instance, value): """ Fits the text into layout_manager line. If noxscroll, all line with be split up to fit to the widget size. if x scrolling is enabled, we look, if the the maximum line lenght exceed the TEXTURE SIZE. In that case we split the lines as well and set the scrolling window size to the texture size. if x scrolling is enabled, and all lines fit to the texture size, we pass the unchanged array """ if self.size == [100, 100]: return bDoLineBreak = False self.iMaxCharwidth = self.oLabel._label.get_extents('W')[0] self.iMaxCharsPerLine = int(self.width / self.iMaxCharwidth) if not self.bNoXScroll: self.aData = self.text.split('\n') self.iMaxLen = len(max(self.aData, key=len)) if (self.iMaxCharwidth * self.iMaxLen) > GL_MAX_TEXTURE_SIZE: self.iMaxCharsPerLine = int(GL_MAX_TEXTURE_SIZE / self.iMaxCharwidth) bDoLineBreak = True else: self.iMaxCharsPerLine = self.iMaxLen else: bDoLineBreak = True if bDoLineBreak: if self.oLabel is not None: if len(self.text) > 10000: aData = self.text.split('\n') i = 0 iEnd = len(aData) while i < iEnd: if len(aData[i]) > self.iMaxCharsPerLine: aData.insert(i + 1, aData[i][self.iMaxCharsPerLine:]) aData[i] = aData[i][:self.iMaxCharsPerLine] iEnd += 1 i += 1 else: self.oLabel.size = self.size self.oLabel.text_size = (self.width, None) self.oLabel.text = self.text self.oLabel._label.render() aData = [] for oLine in self.oLabel._label._cached_lines: if len(oLine.words) > 0: uText = u'' for oWord in oLine.words: if self.bMarkup: uText += self.AddMarkUps(oWord) else: uText += oWord.text aData.append(uText) else: aData.append(u'') self.oLabel.text = "" self.aData = aData self.SetData(aData) else: self.SetData(self.aData) def AddMarkUps(self, oWord): uText = oWord.text if oWord.options["bold"]: uText = self.AddMarkUp(uText, "b") if oWord.options["italic"]: uText = self.AddMarkUp(uText, "i") if oWord.options["underline"]: uText = self.AddMarkUp(uText, "u") if oWord.options["strikethrough"]: uText = self.AddMarkUp(uText, "s") if oWord.options["font_name"] != "Roboto": uText = self.AddMarkUp(uText, "font", oWord.options["font_name"]) if oWord.options["font_size"] != self.fFontSize: uText = self.AddMarkUp(uText, "size", ToUnicode(oWord.options["font_size"])) if oWord.options["color"] != [1, 1, 1, 1]: uHexColor = u'' for iColor in oWord.options["color"]: uHexColor += ToHex(int(iColor * 255)) uText = self.AddMarkUp(uText, "color", '#' + uHexColor) return uText def AddMarkUp(self, uText, uMarkUp, uValue=None): if uValue is None: return "[{1}]{0}[/{1}]".format(uText, uMarkUp) else: return "[{1}={2}]{0}[/{1}]".format(uText, uMarkUp, uValue)
class PopupDownload(Popup): """Componente Popup.""" textoBotao = StringProperty('Fechar') titulo = StringProperty('Iniciando...') texto = StringProperty('Procurando Titulo') funcao = Property(lambda x: x.dismiss()) def __init__(self, *args, **kwargs): """.""" super().__init__(*args, **kwargs) self.pathDown = App.get_running_app().pathDown def _sanitizestring(self, palavra): """.""" # Unicode normalize transforma um caracter em seu equivalente em latin. nfkd = normalize('NFKD', palavra) palavrasemacento = u"".join([c for c in nfkd if not combining(c)]) # Usa expressão regular para retornar a palavra apenas com números, letras e espaço return sub('[^a-zA-Z0-9 ]', '', palavrasemacento) def baixar(self, tipo, link): """.""" if tipo == 'episodio': self.thr = Thread(target=self._download_video, args=[link]) elif tipo == 'capitulo': self.thr = Thread(target=self._download_capitulo, args=[link]) elif tipo == 'video': self.thr = Thread(target=self._download_video_youtube, args=[link]) self.thr.parar = False self.thr.start() def _baixar_callback(self, current, total, width): """.""" t = current_thread() if t.parar: exit(0) self.ids.barra.value = (current / total) * 100 self.ids.tamanho.text = ('%.2f' % ((total / 1024) / 1024)) self.ids.baixado.text = ('%.2lf' % ((current / 1024) / 1024)) def _baixar_video_callback(self, total, recvd, ratio, rate, eta): """.""" t = current_thread() if t.parar: exit(0) self.ids.barra.value = (recvd / total) * 100 self.ids.tamanho.text = ('%.2f' % ((total / 1024) / 1024)) self.ids.baixado.text = ('%.2lf' % ((recvd / 1024) / 1024)) self.lvel1.text = ('%.2f' % (rate / 1024)) self.ltemp1.text = str(int(eta)) def cancelar(self): """.""" self.thr.parar = True self.dismiss() def _req_link(self, u): """.""" try: resul = get(u) except (Exception, RequestException): resul = self._req_link(u) return resul def _pega_link(self, href, header): """.""" s = get(href, allow_redirects=False, headers=header) return s.headers['location'] def _download_video(self, link): """.""" try: link = link if ('http' or 'https') in link else "https:" + link r = self._req_link(link) b = bs(r.content, 'html.parser') nome = b.find("h1", itemprop='name').text.split()[-1] + '-' nome += b.find("h2", itemprop='alternativeHeadline').text bb = b.find("source") nome = nome + ".mp4" self.texto = nome headers = {'Referer': link} if bb: ll = bb.get("src") if ( 'http' or 'https') in bb.get('src') else "https:" + bb.get('src') r = get(ll, allow_redirects=False, headers=headers) self.titulo = "Baixando..." download(r.headers['location'], self.pathDown + "/" + nome, bar=self._baixar_callback) else: bb = b.find('a', title="Baixar Video") if bb: r = self._req_link( bb.get("href") if ('http' or 'https' ) in bb.get('href') else "https:" + bb.get('href')) b = bs(r.content, 'html.parser') bb = b.find("a", "bt-download") if bb: head = \ self._pega_link( bb.get("href") if ('http' or 'https') in bb.get('href') else "https:" + bb.get('href'), headers) self.titulo = "Baixando..." download(head, self.pathDown + "/" + nome, bar=self._baixar_callback) self.titulo = "Download Concluido!" btn = Button() btn.size_hint_y = None btn.height = dp(50) btn.text = self.textoBotao btn.on_press = lambda: self.funcao(self) self.ids.box.remove_widget(self.ids.cancelar) self.ids.box.add_widget(btn) except (Exception, AttributeError) as exp: print(link, exp) def _download_video_youtube(self, video): """.""" boxVel = BoxLayout() lvel = Label() lvel.text = 'Velocidade: ' self.lvel1 = Label() self.lvel1.text = '0' lvel2 = Label() lvel2.text = 'Mbps' boxVel.add_widget(lvel) boxVel.add_widget(self.lvel1) boxVel.add_widget(lvel2) self.ids.down.add_widget(boxVel) boxTemp = BoxLayout() ltemp = Label() ltemp.text = 'Tempo Restante: ' self.ltemp1 = Label() self.ltemp1.text = '0' ltemp2 = Label() ltemp2.text = 'Segundos' boxTemp.add_widget(ltemp) boxTemp.add_widget(self.ltemp1) boxTemp.add_widget(ltemp2) self.ids.down.add_widget(boxTemp) vInfo = video[0] vDown = video[1] arquivo = self.pathDown + "/" +\ self._sanitizestring(vInfo.title) + "." +\ vDown.extension self.titulo = "Baixando..." self.texto = vInfo.title[:50] if video[2].active: vDown.download(filepath=arquivo, quiet=True, callback=self._baixar_video_callback) if vDown.mediatype == 'audio': self.ids.box.remove_widget(self.ids.cancelar) self.titulo = "Convertendo..." FFmpeg( global_options=['-v quiet'], inputs={ arquivo: None }, outputs={ self.pathDown + "/" + self._sanitizestring(vInfo.title) + '.mp3': None }).run() remove(arquivo) else: vDown = vInfo.getbestaudio() arquivo = self.pathDown + "/" + \ self._sanitizestring(vInfo.title) + "."+vDown.extension vDown.download(filepath=arquivo, quiet=True, callback=self._baixar_video_callback) self.ids.box.remove_widget(self.ids.cancelar) self.titulo = "Convertendo..." FFmpeg( global_options=['-v quiet'], inputs={ arquivo: None }, outputs={ self.pathDown + "/" + self._sanitizestring(vInfo.title) + '.mp3': None }).run() remove(arquivo) self.titulo = "Download Concluido!" btn = Button() btn.size_hint_y = None btn.height = dp(50) btn.text = self.textoBotao btn.on_press = lambda: self.funcao(self) self.ids.box.add_widget(btn) def _download_capitulo(self, url): """.""" self.ids.box.remove_widget(self.ids.cancelar) self.ids.tamanho.text = '' self.ids.textoTamanho.text = '' self.ids.mb.text = '' self.ids.mbps.text = 'Paginas' caminho = self.pathDown urls = url.split('/') st = self._sanitizestring(str(urls[urls.__len__() - 2])) pasta = caminho + '/' + st + "_" + urls[urls.__len__() - 1] bb = bs(self._req_link(url).content, 'html.parser') self.criapasta(pasta) i = 1 self.texto = st + "_" + urls[urls.__len__() - 1] imagens = bb.find_all('img', pag=True) for node in imagens: if str(node.get("src")).find("leitor") == -1: imagens.remove(node) self.titulo = "Baixando..." self.ids.baixado.text = "00/" + str(len(imagens)) self.i = 1 self.total = str(len(imagens)) self.q = Queue() [ self.q.put([ pasta, '0' + str(i + 1) if len(str(i + 1)) < 2 else i + 1, str(imagens[i].get('src') if "http:" in imagens[i].get("src") or "https:" in imagens[i].get("src") else 'http:' + imagens[i].get("src")).split("."), imagens[i].get('src') if "http:" in imagens[i].get("src") or "https:" in imagens[i].get("src") else 'http:' + imagens[i].get("src") ]) for i in range(len(imagens)) ] p = [Thread(target=self.baixarimg) for i in range(5)] [i.start() for i in p] [i.join() for i in p] # p = p.map_async(lambda x: self.baixarimg(*x), [ # [ # pasta, # '0'+str(i+1) if len(str(i+1)) < 2 else i+1, # str(imagens[i].get('src') # if "http:" in imagens[i].get("src") or # "https:" in imagens[i].get("src") # else 'http:' + imagens[i].get("src")).split("."), # imagens[i].get('src') # if "http:" in imagens[i].get("src") or # "https:" in imagens[i].get("src") # else 'http:' + imagens[i].get("src") # ] for i in range(len(imagens)) # ]) # p.wait() self.titulo = "Download Concluido!" btn = Button() btn.size_hint_y = None btn.height = dp(50) btn.text = self.textoBotao btn.on_press = lambda: self.funcao(self) self.ids.box.add_widget(btn) def criapasta(self, pasta): """.""" if not path.isdir(pasta): mkdir(pasta) def baixarimg(self): """.""" while not self.q.empty(): pasta, i, n, url_img = self.q.get() rr = self._req_link(str(url_img)) with open(pasta + "/" + str(i) + "." + n[n.__len__() - 1], 'wb') as code: code.write(rr.content) open_image(pasta + "/" + str(i) + "." + n[n.__len__() - 1]).save(pasta + "/" + str(i) + "." + n[n.__len__() - 1]) self.ids.baixado.text = str('0'+str(self.i) if len(str(self.i)) < 2 else self.i) + \ "/" + self.total self.ids.barra.value = self.i / int(self.total) * 100 self.i += 1
class MapDrawer(Widget): action = Property(CurrentAction.none) grid_step = Property(6) max_time = Property(120) map_width = Property(60) map_height = Property(36) def __init__(self, **kwargs): super(MapDrawer, self).__init__(**kwargs) self.bind(pos=self.draw) self.bind(size=self.draw) self.x0_pos = 0 self.y0_pos = 0 self.x1_pos = 0 self.y1_pos = 0 self.camx = 0 self.camy = 0 self.zoom = 1 / 10 self.selection_r = 7.5 self.faulted_click = True self.colors = {'bg': (0, 0, 0), 'grid': (0.2, 0.2, 0.2), 'wall': (0.68, 1, 0.6), 'main_line': (0.05, 0.2, 0.28), 'selected_car': (0.86, 0.78, 0.65), 'finish': (0.6, 0.65, 0.8), 'selection': (0.9, 0.9, 0.9)} self._keyboard = Window.request_keyboard(self._keyboard_closed, self) self._keyboard.bind(on_key_down=self._on_keyboard_up) self.sel = None def fs(self, x, y): return x * self.zoom - self.camx, y * self.zoom - self.camy def set_action(self, action): if action == CurrentAction.wall: app.map.start_new_wall() elif action == CurrentAction.headline: app.map.headline.clear() elif action == CurrentAction.car: pass elif action == CurrentAction.edit: self.sel = None self.move_sel = False elif action == CurrentAction.none: pass self.action = action self.draw() def select_wall(self, x, y): sel_r = self.selection_r * self.zoom for i in range(len(app.map.walls)): wall = app.map.walls[i] for j in range(len(wall)): point = wall[j] if (point[0] - x) ** 2 + (point[1] - y) ** 2 < sel_r ** 2: return 'wall', i, j def select_headline(self, x, y): sel_r = self.selection_r * self.zoom for i in range(len(app.map.headline)): point = app.map.headline[i] if (point[0] - x) ** 2 + (point[1] - y) ** 2 < sel_r ** 2: return 'headline', i def select_finish(self, x, y): sel_r = self.selection_r * self.zoom for i in range(len(app.map.finish)): point = app.map.finish[i] if (point[0] - x) ** 2 + (point[1] - y) ** 2 < sel_r ** 2: return 'finish', i def select_car(self, x, y): sel_r2 = app.map.car_size[0] ** 2 + app.map.car_size[1] ** 2 for i in range(len(app.map.cars)): car = app.map.cars[i] if (car[0] - x) ** 2 + (car[1] - y) ** 2 < sel_r2: return 'car', i def select_something(self, x, y): car = self.select_car(x, y) if car: return car headline = self.select_headline(x, y) if headline: return headline wall = self.select_wall(x, y) if wall: return wall finish = self.select_finish(x, y) if finish: return finish def on_button_left_down(self, touch): self.x0_pos, self.y0_pos = touch.pos[0] - self.pos[0], -touch.pos[1] - self.pos[1] + self.size[1] if self.action == CurrentAction.edit: x, y = self.fs(self.x0_pos, self.y0_pos) self.sel = self.select_something(x, y) self.draw() def on_button_left_move(self, touch): self.x1_pos, self.y1_pos = touch.pos[0] - self.pos[0], -touch.pos[1] - self.pos[1] + self.size[1] if self.action == CurrentAction.none or (self.action == CurrentAction.edit and self.sel is None): self.camx += (self.x1_pos - self.x0_pos) * self.zoom self.camy += (self.y1_pos - self.y0_pos) * self.zoom self.camx = max(min(self.camx, self.width * self.zoom), -app.map.size[0]) self.camy = max(min(self.camy, self.height * self.zoom), -app.map.size[1]) elif self.action == CurrentAction.edit and self.sel is not None: x, y = self.fs(self.x1_pos, self.y1_pos) if self.sel[0] == 'wall': app.map.walls[self.sel[1]][self.sel[2]] = (x, y) elif self.sel[0] == 'headline': app.map.headline[self.sel[1]] = (x, y) elif self.sel[0] == 'finish': app.map.finish[self.sel[1]] = (x, y) elif self.sel[0] == 'car': app.map.cars[self.sel[1]] = (x, y, app.map.cars[self.sel[1]][2]) self.x0_pos = self.x1_pos self.y0_pos = self.y1_pos self.draw() def on_button_left_up(self, touch): self.x1_pos, self.y1_pos = touch.pos[0] - self.pos[0], -touch.pos[1] - self.pos[1] + self.size[1] x, y = self.fs(self.x1_pos, self.y1_pos) if self.action == CurrentAction.none: pass elif self.action == CurrentAction.wall: app.map.append_wall_point(x, y) elif self.action == CurrentAction.headline: app.map.append_headline_point(x, y) elif self.action == CurrentAction.car: app.map.create_car(x, y) elif self.action == CurrentAction.finish: app.map.append_finish_point(x, y) self.draw() def on_button_right_up(self, touch): if self.sel is None: return if self.sel[0] == 'wall' or self.sel[0] == 'headline': app.root.ids.context_on_point.show(*touch.pos) elif self.sel[0] == 'car': app.root.ids.context_on_car.show(*touch.pos) def on_button_right_down(self, touch): if self.action != CurrentAction.edit: return self.on_button_left_down(touch) def on_scrolldown(self, touch): if self.zoom < 0.01: return self.zoom /= 1.05 self.camx -= self.zoom * 0.05 * (touch.pos[0] - self.pos[0]) self.camy -= self.zoom * 0.05 * (-touch.pos[1] - self.pos[1] + self.size[1]) self.draw() def on_scrollup(self, touch): if self.zoom > 100: return self.zoom *= 1.05 self.camx += self.zoom * (0.05 / 1.05) * (touch.pos[0] - self.pos[0]) self.camy += self.zoom * (0.05 / 1.05) * (-touch.pos[1] - self.pos[1] + self.size[1]) self.draw() def on_touch_down(self, touch): if not (self.pos[0] < touch.pos[0] < self.pos[0] + self.size[0] and self.pos[1] < touch.pos[1] < self.pos[1] + self.size[1]): return self.faulted_click = False if touch.button == 'left': self.on_button_left_down(touch) elif touch.button == 'right': self.on_button_right_down(touch) elif touch.button == 'scrolldown': self.on_scrolldown(touch) elif touch.button == 'scrollup': self.on_scrollup(touch) def on_touch_up(self, touch): if self.faulted_click: return if touch.button == 'left': self.on_button_left_up(touch) elif touch.button == 'right': self.on_button_right_up(touch) self.faulted_click = True def on_touch_move(self, touch): if self.faulted_click: return if touch.button == 'left': self.on_button_left_move(touch) def _keyboard_closed(self): self._keyboard.unbind(on_key_up=self._on_keyboard_up) self._keyboard = None def _on_keyboard_up(self, keyboard, keycode, text, modifiers): if keycode[1] == 'w': app.map.start_new_wall() self.set_action(CurrentAction.wall) elif keycode[1] == 'h': self.set_action(CurrentAction.headline) elif keycode[1] == 'c': self.set_action(CurrentAction.car) elif keycode[1] == 'f': self.set_action(CurrentAction.finish) elif keycode[1] == 'e': self.set_action(CurrentAction.edit) elif keycode[1] == 'escape': self.set_action(CurrentAction.none) elif keycode[1] == 'numpadadd' and self.sel is not None and self.sel[0] == 'car': app.map.cars[self.sel[1]] = ( app.map.cars[self.sel[1]][0], app.map.cars[self.sel[1]][1], app.map.cars[self.sel[1]][2] + 0.1) elif keycode[1] == 'numpadsubstract' and self.sel is not None and self.sel[0] == 'car': app.map.cars[self.sel[1]] = ( app.map.cars[self.sel[1]][0], app.map.cars[self.sel[1]][1], app.map.cars[self.sel[1]][2] - 0.1) self.draw() return True def draw(self, *_): self.canvas.clear() with self.canvas: ScissorPush(x=self.pos[0], y=self.pos[1], width=self.size[0], height=self.size[1]) Color(*self.colors['bg']) Translate(self.pos[0], self.pos[1] + self.size[1]) Scale(1 / self.zoom, -1 / self.zoom, 1) Rectangle(pos=(0, 0), size=self.size) Translate(self.camx, self.camy) self.inner_draw() Translate(-self.camx, -self.camy) Scale(self.zoom, self.zoom, 1) Color(0, 0, 0) Scale(1, -1, 1) Translate(-self.pos[0], -self.pos[1] - self.size[1]) ScissorPop() def inner_draw(self): sel_r = self.selection_r * self.zoom show_selection_areas = self.action == CurrentAction.edit Color(*self.colors['grid']) for i in range(0, app.map.size[0], self.grid_step): Line(points=(i, 0, i, app.map.size[1])) for i in range(0, app.map.size[1], self.grid_step): Line(points=(0, i, app.map.size[0], i)) Color(*self.colors['finish'], 0.8) if len(app.map.finish) == 2: Rectangle(pos=app.map.finish[0], size=(app.map.finish[1][0] - app.map.finish[0][0], app.map.finish[1][1] - app.map.finish[0][1])) if show_selection_areas: Color(*self.colors['finish'], 0.3) for point in app.map.finish: Ellipse(pos=(point[0] - sel_r, point[1] - sel_r), size=(sel_r * 2, sel_r * 2)) Color(*self.colors['wall']) Line(rectangle=(0, 0, app.map.size[0], app.map.size[1])) for wall in app.map.walls: for i in range(len(wall) - 1): Line(points=(wall[i][0], wall[i][1], wall[i + 1][0], wall[i + 1][1])) if show_selection_areas: Color(*self.colors['wall'], 0.3) for wall in app.map.walls: for point in wall: Ellipse(pos=(point[0] - sel_r, point[1] - sel_r), size=(sel_r * 2, sel_r * 2)) Color(*self.colors['main_line']) for i in range(len(app.map.headline) - 1): Line(points=( app.map.headline[i][0], app.map.headline[i][1], app.map.headline[i + 1][0], app.map.headline[i + 1][1])) if show_selection_areas: Color(*self.colors['main_line'], 0.3) for point in app.map.headline: Ellipse(pos=(point[0] - sel_r, point[1] - sel_r), size=(sel_r * 2, sel_r * 2)) Color(*self.colors['selected_car']) sz = app.map.car_size for x, y, a in app.map.cars: Quad(points=( x + sz[0] * math.cos(a) - sz[1] * math.sin(a), y - sz[0] * math.sin(a) - sz[1] * math.cos(a), x - sz[0] * math.cos(a) - sz[1] * math.sin(a), y + sz[0] * math.sin(a) - sz[1] * math.cos(a), x - sz[0] * math.cos(a) + sz[1] * math.sin(a), y + sz[0] * math.sin(a) + sz[1] * math.cos(a), x + sz[0] * math.cos(a) + sz[1] * math.sin(a), y - sz[0] * math.sin(a) + sz[1] * math.cos(a)) ) Color(*self.colors['bg'], 0.5) for x, y, a in app.map.cars: Ellipse(pos=(x - sz[1] * math.sin(a) / 2 - 0.15, y - sz[1] * math.cos(a) / 2 - 0.15), size=(0.3, 0.3)) if self.action == CurrentAction.edit and self.sel is not None: def draw_selected_point(point, color): Color(*color, 0.5) Ellipse(pos=(point[0] - sel_r, point[1] - sel_r), size=(sel_r * 2, sel_r * 2)) Color(*self.colors['selection'], 1) Line(ellipse=(point[0] - sel_r, point[1] - sel_r, sel_r * 2, sel_r * 2)) if self.sel[0] == 'wall': draw_selected_point(app.map.walls[self.sel[1]][self.sel[2]], self.colors['wall']) if self.sel[0] == 'headline': draw_selected_point(app.map.headline[self.sel[1]], self.colors['main_line']) if self.sel[0] == 'finish': draw_selected_point(app.map.finish[self.sel[1]], self.colors['finish']) if self.sel[0] == 'car': x, y, a = app.map.cars[self.sel[1]] Color(*self.colors['selection'], 1) Line(points=( x + sz[0] * math.cos(a) - sz[1] * math.sin(a), y - sz[0] * math.sin(a) - sz[1] * math.cos(a), x - sz[0] * math.cos(a) - sz[1] * math.sin(a), y + sz[0] * math.sin(a) - sz[1] * math.cos(a), x - sz[0] * math.cos(a) + sz[1] * math.sin(a), y + sz[0] * math.sin(a) + sz[1] * math.cos(a), x + sz[0] * math.cos(a) + sz[1] * math.sin(a), y - sz[0] * math.sin(a) + sz[1] * math.cos(a)), width=1.3 * self.zoom, close=True ) def on_context_remove_point(self, *_): if self.sel is None: return if self.sel[0] == 'wall': app.map.walls[self.sel[1]].pop(self.sel[2]) elif self.sel[0] == 'headline': app.map.headline.pop(self.sel[1]) self.sel = None self.draw() def on_context_remove_object(self, *_): if self.sel is None: return if self.sel[0] == 'wall': app.map.walls.pop(self.sel[1]) elif self.sel[0] == 'headline': app.map.headline = [] self.sel = None self.draw() def on_context_add_point(self, *_): if self.sel is None: return if self.sel[0] == 'wall': app.map.walls[self.sel[1]].insert(self.sel[2], app.map.walls[self.sel[1]][self.sel[2]]) elif self.sel[0] == 'headline': app.map.headline.insert(self.sel[1], app.map.headline[self.sel[1]]) self.draw() def on_context_remove_car(self, *_): if self.sel is None: return if self.sel[0] != 'car': return app.map.cars.pop(self.sel[1]) self.sel = None self.draw()
def test_observer(self): from kivy.properties import Property a = Property(-1) a.link(wid, 'a') a.link_deps(wid, 'a') self.assertEqual(a.get(wid), -1) global observe_called observe_called = 0 def observe(obj, value): global observe_called observe_called = 1 a.bind(wid, observe) a.set(wid, 0) self.assertEqual(a.get(wid), 0) self.assertEqual(observe_called, 1) observe_called = 0 a.set(wid, 0) self.assertEqual(a.get(wid), 0) self.assertEqual(observe_called, 0) a.set(wid, 1) self.assertEqual(a.get(wid), 1) self.assertEqual(observe_called, 1)
class PopupProcura(Popup): """Componente Popup.""" textoBotao = StringProperty('Fechar') titulo = StringProperty('Procurando...') texto = StringProperty('Procurando Titulo') funcao = Property(lambda x: x.dismiss()) def __init__(self, *args, **kwargs): """.""" super().__init__(*args, **kwargs) self.path = App.get_running_app().user_data_dir + '/' self.base = "https://www.superanimes.site/" def _req_link(self, u, dados={}): try: resul = get(u, data=dados) except (Exception, RequestException): resul = self._req_link(u, dados) return resul def _req_link_post(self, u, info): try: resul = post(u, data=info) except (Exception, RequestException): resul = self._req_link_post(u, info) return resul def _sanitizestring(self, palavra): """.""" # Unicode normalize transforma um caracter em seu equivalente em latin. nfkd = normalize('NFKD', palavra) palavrasemacento = u"".join([c for c in nfkd if not combining(c)]) # Usa expressão regular para retornar a palavra apenas com números, letras e espaço return sub('[^a-zA-Z0-9 ]', '', palavrasemacento) def procura(self, tipo, nome, link, rv): """.""" if tipo == 'anime': Thread(target=self._pagina_anime, args=[nome, link, rv]).start() else: Thread(target=self._pagina_manga, args=[nome, link, rv]).start() def atualizar(self, tipo, func): """.""" self.titulo = 'Atualizando...' self.texto = '' if tipo == 'animes': Thread(target=self._atualizar_pagina_animes, args=[func]).start() else: Thread(target=self._atualizar_pagina_mangas, args=[func]).start() def _atualizar_pagina_animes(self, func): """.""" link = f"{self.base}inc/paginator.inc.php" total = 99 atual = 1 ani = {'nome': [], 'link': []} lista_animes = [] self.tam = str(total) while atual <= total: data = { 'type_url': "lista", 'page': atual, 'limit': 1000, 'total_page': total, 'type': 'lista', 'filters': '{"filter_data":"filter_letter=0&filter_type_content=100' '&filter_genre_model=0&filter_order=0&filter_rank=0' '&filter_status=0&filter_idade=&filter_dub=0' '&filter_size_start=0&filter_size_final=0&filter_date=0' '&filter_viewed=0",' '"filter_genre_add":[],"filter_genre_del":[]}' } e = self._req_link_post(link, data) body = loads(e.content) total = body['total_page'] self.tam = str(total) self.ids.paginas.text = (self.tam) self.ids.procuradas.text = ('%d' % atual) self.ids.barra.value = atual / total * 100 atual += 1 for I in range(len(body['body'])): novo_ani = dict(ani) b = bs(body['body'][I], 'html.parser') a = b.find('h1', 'grid_title').find('a') novo_ani['nome'] = a.text novo_ani['link'] = (a.get('href') if ('http' or 'https') in a.get('href') else "https:" + a.get('href')) lista_animes.append(novo_ani) for I in sorted(lista_animes, key=itemgetter('nome')): ani['nome'].append(I['nome']) ani['link'].append(I['link']) io = StringIO() dump(ani, io) json_s = io.getvalue() arq = open(self.path + "PaginasAnimes.json", 'w') arq.write(json_s) arq.close() self.dismiss() func() def _atualizar_pagina_mangas(self, func): """Refatorar essa Merda.""" r = self._req_link("https://unionmangas.top/lista-mangas") b = bs(r.text, 'html.parser') paginacao = b.find("ul", "pagination").find_all('span', "sr-only") link = "https://unionmangas.top/lista-mangas/a-z/%s/*" self.tam = 0 self.per = 1 for i in paginacao: if i.text == 'End': self.tam = int( compile('([0-9]+)').findall(i.parent.get("href"))[0]) self.ids.paginas.text = str(self.tam) self.q = Queue() [self.q.put(link % i) for i in range(1, self.tam + 1)] self.resQ = [] p = [Thread(target=self._busca_pag, args=[self.q]) for i in range(5)] [i.start() for i in p] [i.join() for i in p] self._junta([i[1] for i in sorted(self.resQ, key=lambda x: x[0])]) self.dismiss() func() def _junta(self, paginas): """.""" dic = dict({'nome': [], 'link': []}) for i in paginas: js = i dic['nome'] += js['nome'] dic['link'] += js['link'] io = StringIO() dump(dic, io) json_s = io.getvalue() arq = open(self.path + "PaginasMangas.json", 'w') arq.write(json_s) arq.close() def _busca_pag(self, fila, direcao=True, maximo=0): """.""" while not fila.empty(): link = fila.get() info = {'nome': [], 'link': []} r = self._req_link(link) b = bs(r.text, 'html.parser') mangas = b.find_all('div', 'bloco-manga') for i in mangas: lin = i.find_all('a')[-1] info['nome'].append( self._sanitizestring( lin.get("href").split('/')[-1].replace('-', ' ').title())) info['link'].append(lin.get("href")) self.ids.barra.value = self.per / self.tam * 100 self.ids.procuradas.text = ('%d' % self.per) self.per += 1 self.resQ.append((int(compile('([0-9]+)').findall(link)[0]), info)) def _pagina_anime(self, nome, link, rv): """.""" try: dic = dict({'ep': [], 'link': []}) link = link if ('http' or 'https') in link else "https:" + link r = self._req_link(link) b = bs(r.content, 'html.parser') id_cat = b.find('div', attrs={ "data-id-cat": True }).get("data-id-cat") self.texto = nome atual = 1 self.tam = 20 link = f"{self.base}inc/paginatorVideo.inc.php" while atual <= self.tam: data = { 'id_cat': int(id_cat), 'page': int(atual), 'limit': 100, 'total_page': int(self.tam), 'order_video': 'asc' } e = self._req_link_post(link, data) body = loads(e.content) self.tam = body['total_page'] self.ids.paginas.text = str(self.tam) self.ids.procuradas.text = ('%d' % atual) self.ids.barra.value = atual / self.tam * 100 atual += 1 if self.tam > 0: for II in range(len(body['body'])): bb = bs(body['body'][II], 'html.parser') a = bb.find('div', 'epsBoxSobre').find('a') dic['ep'].append(a.text) dic['link'].append( a.get('href') if ('http' or 'https') in a.get('href') else "https:" + a.get('href')) box = b.find_all("div", 'boxBarraInfo js_dropDownBtn active') if box: for K in box: par = K.parent ova = par.find_all('div', 'epsBox') if ova: for kk in ova: dic['ep'].append("OVA: " + kk.find("h3").a.text) dic['link'].append( kk.find("h3").a.get("href") if ( 'http' or 'https') in kk.find("h3").a.get("href") else "https:" + kk.find("h3").a.get("href")) fil = par.find_all('div', 'epsBoxFilme') if fil: for L in fil: dic['ep'].append("FILME: " + L.find("h4").text) dic['link'].append( L.find("a").get("href") if ( 'http' or 'https' ) in L.find("a").get("href") else "https:" + L.find("a").get("href")) self.dismiss() rv.data = [{ 'titulo': dic['ep'][i], 'link': dic['link'][i], 'tituloBotao': 'Baixar', 'tipo': 'episodio' } for i in range(len(dic['ep']))] except (Exception, AttributeError) as exception: print(link, exception) def _pagina_manga(self, nome, link, rv): """.""" info = {'titulo': [], 'link': []} r = self._req_link(link) b = bs(r.text, 'html.parser') cap = b.find_all('div', 'row lancamento-linha') for i in cap: info['titulo'].append(i.a.text) info['link'].append(i.a.get("href")) self.dismiss() rv.data = [{ 'titulo': info['titulo'][i], 'link': info['link'][i], 'tituloBotao': 'Baixar', 'tipo': 'capitulo' } for i in range(len(info['titulo']))]
class Playground(Widget): engine = ObjectProperty() game_widgets = ListProperty() grid = ObjectProperty() target_field_widgets = ListProperty() is_target_field = BooleanProperty(False) rules_scroll_view = Property(None) update_event = ObjectProperty(None, allownone=True) storage = ObjectProperty() sound_handler = ObjectProperty() scroll_views = DictProperty() selected_box = ObjectProperty(allownone=True) def start(self, lvl): self.engine = Engine(lvl, self.sound_handler) self.init_storage_star() self.add_missing_game_widgets() self.draw_field() self.set_target_field_widgets() self.scroll_views = {} self.make_rules_scroll_view(self.engine.get_all_rules(), lambda _: None, id(self)) self.update_event = Clock.schedule_interval(self.update, FRAME_RATE_SEC) def update(self, _): self.engine.tick() self.add_missing_game_widgets() self.update_all_game_widgets() self.check_win() def update_all_game_widgets(self): for game_widget in self.game_widgets: corresponding_game_obj = next( (obj for obj in self.engine.all_game_objects() if obj.game_id == game_widget.game_id), None) if corresponding_game_obj is None: self.remove_widget(game_widget) self.game_widgets.remove(game_widget) continue self.update_game_widget(game_widget, corresponding_game_obj) @staticmethod def update_game_widget(game_widget, game_object): game_widget.box = game_object for attr, value in game_object.__dict__.items(): if hasattr(game_widget, attr): setattr(game_widget, attr, value) def add_missing_game_widgets(self): for obj in self.engine.all_game_objects(): if any(widg.game_id == obj.game_id for widg in self.game_widgets): continue wimg = BoxWidget(obj) self.game_widgets.append(wimg) self.add_widget(wimg) def check_win(self): if self.engine.win and not self.engine.any_animation_in_progress(): self.manage_star_after_win() self.update_storage(f'lvl{self.engine.lvl}', status='Passed') if self.storage.get('lvl' + str(self.engine.lvl + 1))['status'] == 'Locked': self.update_storage(f'lvl{self.engine.lvl + 1}', status='Unlocked') self.update_event.cancel() self.parent.show_winning_widget() def manage_star_after_win(self): if self.engine.min_moves and self.engine.moves_done <= self.engine.min_moves and \ not self.storage.get(f'lvl{self.engine.lvl}')['got_star']: self.update_storage(f'lvl{self.engine.lvl}', got_star=True) cur_module = str(get_module(self.engine.lvl)) module_stars = self.storage.get('module_stars') module_stars[cur_module] += 1 self.storage.put('module_stars', **module_stars) def draw_field(self): with self.canvas.before: Color(0.992, 0.925, 0.863, 1) Rectangle(pos=self.engine.screen_utils.start, size=self.engine.screen_utils.size) self.grid = InstructionGroup() points = self.engine.screen_utils.create_grid() self.grid.add(Color(rgba=(0.29, 0, 0.153, 1))) for a, b in points: self.grid.add(Line(points=[a[0], a[1], b[0], b[1]])) border_width = 5 dl = self.engine.screen_utils.start width, height = self.engine.screen_utils.size self.grid.add( Line(points=[ dl[0] - border_width, dl[1] - border_width, dl[0] - border_width, dl[1] + height + border_width, dl[0] + width + border_width, dl[1] + height + border_width, dl[0] + width + border_width, dl[1] - border_width ], width=border_width, close=True)) self.canvas.before.add(self.grid) def set_target_field_widgets(self): for box in self.engine.get_target_field_boxes(): box_wimg = Image() for attr, value in box.__dict__.items(): if hasattr(box_wimg, attr): setattr(box_wimg, attr, value) self.target_field_widgets.append(box_wimg) def switch_field(self): self.show_all_rules() self.unselect_box() if not self.is_target_field: for widg in self.game_widgets: self.remove_widget(widg) for box_wimg in self.target_field_widgets: self.add_widget(box_wimg) else: for widg in self.target_field_widgets: self.remove_widget(widg) for widg in self.game_widgets: self.add_widget(widg) self.is_target_field = not self.is_target_field def show_all_rules(self): self.unselect_box() self.make_rules_scroll_view(self.engine.get_all_rules(), lambda _: None, id(self)) def make_rules_scroll_view(self, rules, click_on_rule_function, obj_hash): if self.rules_scroll_view is not None: self.remove_widget(self.rules_scroll_view) if obj_hash in self.scroll_views: self.rules_scroll_view = self.scroll_views[obj_hash] self.add_widget(self.rules_scroll_view) return self.rules_scroll_view = RulesScrollViewWidget() if obj_hash == id(self): ''' That means we're working with all rules, so no need in all rules button''' self.rules_scroll_view.remove_widget( self.rules_scroll_view.all_rules_btn) self.add_widget(self.rules_scroll_view) if len(rules) == 0: from src.LanguageUtils import LanguageUtils img = Image(source=LanguageUtils().set_texture('no_rules'), size_hint=(1, None)) self.rules_scroll_view.ids.grid.add_widget(img) else: max_right_side_len = max( [len(rule.result_box_kinds) for rule in rules] + [1]) for rule in rules: rule_widget = RuleWidget(rule, click_on_rule_function, max_right_side_len) self.rules_scroll_view.ids.grid.add_widget(rule_widget) self.scroll_views[obj_hash] = self.rules_scroll_view def undo(self): if self.is_target_field: return self.engine.undo() self.unselect_box() self.show_all_rules() def on_touch_down(self, touch): if self.engine.any_animation_in_progress(): self.engine.finish_all_animations() return True return super(Playground, self).on_touch_down(touch) def init_storage_star(self): if self.engine.min_moves is None: return lvl_dict = self.storage.get(f'lvl{self.engine.lvl}') if 'got_star' not in lvl_dict.keys(): lvl_dict['got_star'] = False self.storage.put(f'lvl{self.engine.lvl}', **lvl_dict) def update_storage(self, key, **kwargs): d = self.storage.get(key) for key, value in kwargs.items(): d[key] = value self.storage.put(key, **d) def select_box(self, box_widg): if box_widg not in self.game_widgets: return if self.selected_box is not None: self.selected_box.unselect() box_widg.select() self.selected_box = box_widg def unselect_box(self): if self.selected_box is None: return self.selected_box.unselect() self.selected_box = None
class GomokuRooms(Screen): username = Property('') def setUsername(self, user): self.username = user def getUsername(self): return username def setRoomAmount(self, amount): self.roomAmount = amount def printRoom(self): roomAmount = 0 self.ids.rooms.clear_widgets() if roomAmount > 0: for i in range(0, roomAmount): #Init roomName = Label(text="[color=F41D4E]Room 1[/color]", markup=True, font_size='20sp') tag1 = Label(text="[color=ffffff]Player[/color]", markup=True) mainGrid = GridLayout(cols=2) #Setting Background - not function yet - #if i == 0: # mainGrid.canvas.add(Color(0.06,0.537,0.98,1)) # mainGrid.canvas.add(Rectangle(pos=self.pos, size=self.size)) #Process #adding roomname titleGrid = GridLayout(rows=2, padding=[5, 10]) titleGrid.add_widget(roomName) #adding button for room buttonGrid = GridLayout(rows=2, padding=[250, 0]) joinButton = Button(text='[color=F41D4E]Join[/color]', on_press=game_screen, markup=True, background_color=[2.8, 2.8, 2.8, 1]) #joinButton.bind(on_press=change_screen('game')) watchButton = Button(text='[color=F41D4E]Watch[/color]', markup=True, background_color=[2.8, 2.8, 2.8, 1]) buttonGrid.add_widget(joinButton) buttonGrid.add_widget(watchButton) titleGrid.add_widget(buttonGrid) #adding playername playerGrid = GridLayout(rows=2, padding=[100, 0]) playerGrid.add_widget(tag1) playerGridInner = GridLayout(cols=2) playerGridInner.add_widget( Button(text='[color=eeeeee]fauzan[/color]', markup=True, background_color=[2.953, 1.67, 0.471, 1])) playerGridInner.add_widget( Button(text='[color=eeeeee]ahmad[/color]', markup=True, background_color=[2.953, 1.67, 0.471, 1])) playerGridInner.add_widget( Button(text='[color=eeeeee]azwar[/color]', markup=True, background_color=[2.953, 1.67, 0.471, 1])) playerGridInner.add_widget( Button(text='[color=eeeeee]adli[/color]', markup=True, background_color=[2.953, 1.67, 0.471, 1])) playerGridInner.add_widget( Button(text='[color=eeeeee]naufal[/color]', markup=True, background_color=[2.953, 1.67, 0.471, 1])) playerGrid.add_widget(playerGridInner) #including roomname and playername mainGrid.add_widget(titleGrid) mainGrid.add_widget(playerGrid) #Render self.ids.rooms.add_widget(mainGrid) else: self.ids.rooms.add_widget(Label(text="No rooms available"))
class DirectionArrow(Widget): direction = OptionProperty("None", options=list(map(lambda x: x.name, MovementType))) pressed_callback = Property(None)
def test_base(self, set_name): from kivy.properties import Property a = Property(-1) if set_name: a.set_name(wid, 'a') a.link_eagerly(wid) else: a.link(wid, 'a') a.link_deps(wid, 'a') self.assertEqual(a.get(wid), -1) a.set(wid, 0) self.assertEqual(a.get(wid), 0) a.set(wid, 1) self.assertEqual(a.get(wid), 1)
def test_base(self): from kivy.properties import Property a = Property(-1) a.link(wid, 'a') a.link_deps(wid, 'a') self.assertEqual(a.get(wid), -1) a.set(wid, 0) self.assertEqual(a.get(wid), 0) a.set(wid, 1) self.assertEqual(a.get(wid), 1)
class ToggleButtons(BoxLayout): """docstring for Sequence.""" instance = None selected = Property(None) index = None # index of the selected in widgets def __init__(self, **kwargs): super(ToggleButtons, self).__init__(**kwargs) ToggleButtons.instance = self self.widgets = [] # all the sequence is in there! self.loadWidgets() self.updateUI() def updateUI(self): self.clear_widgets() grid = GridLayout(rows=1, size_hint=(None, None)) grid.bind(minimum_width=grid.setter('width')) for i in self.widgets: grid.add_widget( WidgetSequenceur(i, text=i["name"], size_hint=(None, 1), group="SequenceItem")) scroll = ScrollView(size_hint=(1, 1), do_scroll_x=True, do_scroll_y=False) scroll.add_widget(grid) self.add_widget(scroll) def updateEntity(self, clicked): if (clicked.state == "down"): ToggleButtons.selected = clicked #find a way to get the index selectedIndex = None for i, wid in enumerate(self.widgets): print(wid) if (wid["name"] == clicked.nom): selectedIndex = i ToggleButtons.index = selectedIndex PanelItem.instance.updatePanel(clicked) else: ToggleButtons.selected = None ToggleButtons.index = None PanelItem.instance.updatePanel( WidgetSequenceur({ "name": "", "type": 0, "descr": "" })) print(ToggleButtons.selected) def loadWidgets(self): for i in range(0): obj = {"name": "fez" + str(i), "type": 0, "descr": ""} self.widgets.append(obj) @staticmethod def addItem(widget): obj = {"name": "", "type": 0, "descr": ""} ToggleButtons.instance.widgets.append(obj) ToggleButtons.instance.updateUI()
class MultiStateBehavior(Widget): """ Changes properties of widget based on :attr:`current_state` and the corresponding entry in :attr:`state_dict`. The properties in :attr:`animated_properties` change via animation. """ current_state = Property(None) """:class:`~kivy.properties.Property` current state of the widget.""" default_state = Property(None) """:class:`~kivy.properties.Property` current state of the widget.""" state_dicts = DictProperty({}) """ :class:`~kivy.properties.DictProperty`. E.g., :: state_dicts = { state_1 : {"some_property": some_value, ...}, ... } """ animated_properties = ListProperty() """:class:`~kivy.properties.ListProperty` containing the list of property-names that get changed via animation.""" animation_kwargs = DictProperty({"duration": 0.5, "t": "out_circ"}) def _get_current_property(self): defaults = (self.state_dicts[self.default_state] if self.default_state in self.state_dicts else {}) current = (self.state_dicts[self.current_state] if self.current_state in self.state_dicts else {}) return {**defaults, **current} current_properties = AliasProperty( _get_current_property, bind=["state_dicts", "current_state", "default_state"], ) def _get_properties_to_update(self): props = self.properties() props = { key for key, val in self.current_properties.items() if key in props and val != getattr(self, key) } animated = set(self.animated_properties) return props & animated, props - animated def _animated_update(self, keys): if keys: animation = Animation( **{key: self.current_properties[key] for key in keys}, **self.animation_kwargs) animation.start(self) def update_properties(self, *_): """Update properties if they differ from the corresponding entry in :attr:`current_properties`.""" animated, not_animated = self._get_properties_to_update() for key in not_animated: setattr(self, key, self.current_properties[key]) self._animated_update(animated) def __init__(self, **kwargs): super().__init__(**kwargs) self.bind(current_properties=self.update_properties) Clock.schedule_once(self.update_properties)
class MyActionBar(ActionBar): """Customização da ActionBar.""" textoLogo = StringProperty("SYML") textoUsuarios = StringProperty("Usuarios") textoAcervo = StringProperty("Acervo") textoReservas = StringProperty("Reservas") textoEmprestimos = StringProperty("Emprestimos") textoSair = StringProperty("Sair") listaOpcoesUsuarios = ListProperty(['Ver Todos', 'Cadastrar']) listaOpcoesAcervo = ListProperty( ['Livros', 'Exemplares', 'Cadastrar Livro', 'Cadastrar Exemplar']) listaOpcoesReservas = ListProperty(['Ver Todas']) listaOpcoesEmprestimos = ListProperty( ['Ver Todos', "Devoluções", "Emprestar Livro"]) prev = BooleanProperty(False) func = Property(lambda:...) def usuario(self, args): """Função para escolher opção do botão Usuario.""" if args[1] != 'Usuarios': root = App.get_running_app().root root.current = args[1].replace(' ', '') + "usuarios" self.ids.usuarios.text = 'Usuarios' if root.current == 'Cadastrarusuarios': root.current_screen.ids.nome.text = '' root.current_screen.ids.email.text = '' root.current_screen.ids.cpf.text = '' root.current_screen.ids.telefone.text = '' root.current_screen.ids.senha.text = '' root.current_screen.ids.bib.active = False root.current_screen.ids.user.active = True root.current_screen.ids.nomeBotao.text = "Cadastrar" else: root.current_screen.on_pre_enter() def acervo(self, args): """Função para escolher opção do botão Acervo.""" if args[1] != 'Acervo': root = App.get_running_app().root root.current = args[1].replace(' ', '') + "acervo" self.ids.acervo.text = 'Acervo' root.current_screen.on_pre_enter() def reserva(self, args): """Função para escolher opção do botão Reserva.""" if args[1] != 'Reservas': root = App.get_running_app().root root.current = args[1].replace(' ', '') + "reservas" self.ids.reservas.text = 'Reservas' root.current_screen.on_pre_enter() def emprestimo(self, args): """Função para escolher opção do botão Emprestimo.""" if args[1] != 'Emprestimos': root = App.get_running_app().root root.current = args[1].replace(' ', '') + "emprestimos" self.ids.emprestimos.text = 'Emprestimos' root.current_screen.on_pre_enter() def sair(self): """Função para Sair do Aplicativo.""" p = PopupError() p.titulo = "Deseja Realmente Sair?" p.size_hint_y = .2 p.ids.box.clear_widgets() sim = Button(text='sim') sim.size_hint_y = None sim.height = sp(40) sim.on_release = (lambda: self._sair_func(p)) sim.background_color = (0.1607843137254902, 0.7137254901960784, 0.9647058823529412, 1) nao = Button(text='não') nao.size_hint_y = None nao.height = sp(40) nao.on_release = p.dismiss nao.background_color = (0.1607843137254902, 0.7137254901960784, 0.9647058823529412, 1) p.ids.box.orientation = 'horizontal' p.ids.box.add_widget(sim) p.ids.box.add_widget(nao) p.open() def _sair_func(self, p): """Função Auxiliar para Sair.""" p.dismiss() root = App.get_running_app().root root.current = 'login' root.current_screen.ids.email.text = '' root.current_screen.ids.senha.text = ''
check = True client.subscribe(topic_cars_tot) client.subscribe(topic_Places) else: check = False return check # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. client.on_connect = on_connect Cars_TOT = Property(1) Places = Property(1) # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): global Cars_TOT, Places if msg.topic == topic_cars_tot: Cars_TOT = msg.payload.decode() if msg.topic == topic_Places: Places = msg.payload.decode() return str(Cars_TOT), str(Places) def publish(client): msg = "update" result = client.publish("saleh_shalabi/feeds/App", msg) status = result[0]