class Login_Screen(Screen): port = kyprops.ObjectProperty(None) host = kyprops.ObjectProperty(None) def btn(self): #s.settimeout(3) if_show = True try: port_no = int(port.text) s.connect((host.text, port_no)) except: if_show = False self.port.text = "" self.host.text = "" show = Login_Failure() popupWindow = Popup(title="Login Result", content=show, size_hint=(0.4, 0.4), pos_hint={ "x": 0.3, "y": 0.3 }) popupWindow.open() if if_show: self.port.text = "" self.host.text = "" show = Login_Success() popupWindow = Popup(title="Login Result", content=show, size_hint=(0.8, 0.8), pos_hint={ "x": 0.1, "y": 0.1 }) popupWindow.open()
class DeckWidget(Label): deck = prop.ObjectProperty() game_widget = prop.ObjectProperty() def __init__(self, deck, **kwargs): super(DeckWidget, self).__init__(**kwargs) self.deck = deck self.register_event_type('on_remove_card') def on_touch_down(self, touch, *args): if self.deck.number_of_cards > 0: if self.collide_point(*touch.pos): card = self.game_widget.game.make_dummy_card() cw = card.make_widget(game_widget=self.game_widget) cw.size_hint_y = None cw.size = self.size cw.center = self.center cw.origin = ui_namespace.card_types.FROM_DECK self.game_widget.add_widget(cw) touch.grab(cw) return True return super(DeckWidget, self).on_touch_down(touch, *args) def on_remove_card(self, card): pass
class PongGame(Widget): ball = kv.ObjectProperty(None) player1 = kv.ObjectProperty(None) player2 = kv.ObjectProperty(None) def serve_ball(self, vel=(4, 0)): self.ball.center = self.center self.ball.velocity = vel def update(self, dt): self.ball.move() # bounce of paddles self.player1.bounce_ball(self.ball) self.player2.bounce_ball(self.ball) # bounce ball off bottom or top if (self.ball.y < self.y) or (self.ball.top > self.top): self.ball.velocity_y *= -1 # went of to a side to score point? if self.ball.x < self.x: self.player2.score += 1 self.serve_ball(vel=(4, 0)) if self.ball.x > self.width: self.player1.score += 1 self.serve_ball(vel=(-4, 0)) def on_touch_move(self, touch): if touch.x < self.width / 3: self.player1.center_y = touch.y if touch.x > self.width - self.width / 3: self.player2.center_y = touch.y
class PongGame(Widget): ball = kp.ObjectProperty(None) player1 = kp.ObjectProperty(None) player2 = kp.ObjectProperty(None) def serve_ball(self): self.ball.velocity = Vector(4,0).rotate(random.randint(0,360)) def update(self,dt): self.ball.move() if(self.ball.y < 0) or (self.ball.y > self.height -50): self.ball.velocity_y *= -1 if self.ball.x < 0: self.ball.velocity_x *= -1 self.player1.score += 1 if self.ball.x > self.width -50: self.ball.velocity_x *= -1 self.player2.score += 1 self.player1.bounce_ball(self.ball) self.player2.bounce_ball(self.ball) def on_touch_move(self,touch): if touch.x < self.width/ 1/4: self.player1.center_y = touch.y if touch.x > self.width * 3/4: self.player2.center_y = touch.y
class HandWidget(blayout.BoxLayout): hand = prop.ObjectProperty() game_widget = prop.ObjectProperty() player_widget = prop.ObjectProperty() def __init__(self, hand, **kwargs): super(HandWidget, self).__init__(**kwargs) self.hand = hand self.register_event_type('on_get_cards') def on_get_cards(self, *cards): for card in cards: card = self.game_widget.game.view_card(card) card_widget = card.make_widget(game_widget=self.game_widget) is_our_hand = ( self.game_widget.player_name == self.player_widget.player.name) card_widget.origin = ui_namespace.card_types.FROM_OUR_HAND if is_our_hand else ui_namespace.card_types.FROM_ANOTHER_HAND self.ui_add_card_widget(card_widget) def try_to_get_card(self, card_widget, touch_pos): if card_widget.origin == ui_namespace.card_types.FROM_OUR_HAND: self.ui_add_card_widget(card_widget, touch_pos) # пытаемся взять карту из колоды, если можно elif card_widget.origin == ui_namespace.card_types.FROM_DECK: if self.game_widget.is_our_turn( ) and self.game_widget.is_our_tab_active(): #TODO: это выглядит неправильно. g = self.game_widget.game atable = g.get_category( game_component_types.TABLE)['game_action_table'] dca_class = filter(lambda x: x.name == 'draw_cards', atable.actions)[0] draw_card = dca_class(source=self.game_widget.deck_widget.deck, target=self.hand, number=1, author=self.game_widget.player_name) if draw_card.check(): self.game_widget.send_actions(draw_card) card_widget.origin = ui_namespace.card_types.FROM_OUR_HAND elif not self.game_widget.is_our_turn(): self.game_widget.notify("It's not your turn now") card_widget.size_hint_y = 1 def ui_add_card_widget(self, card, touch_pos=None): if touch_pos: for i, c in enumerate(self.ids.card_stack.children): if c.collide_point(*touch_pos): self.ids.card_stack.add_widget(card, i) return self.ids.card_stack.add_widget(card)
class MyWidget(Widget): firstName = kivyProp.ObjectProperty(None) lastName = kivyProp.ObjectProperty(None) email = kivyProp.ObjectProperty(None) def submitButton(self): print('Name: ', self.firstName.text, 'Last name: ', self.lastName.text, 'Email: ', self.email.text)
class AbstractMenu(object): cancel_handler_widget = kp.ObjectProperty(None) bounding_box_widget = kp.ObjectProperty(None) def __init__(self, *args, **kwargs): self.clock_event = None def add_item(self, widget): self.add_widget(widget) def add_text_item(self, text, on_release=None): item = ContextMenuTextItem(text=text) if on_release: item.bind(on_release=on_release) self.add_item(item) def get_height(self): height = 0 for widget in self.children: height += widget.height return height def hide_submenus(self): for widget in self.menu_item_widgets: widget.hovered = False widget.hide_submenu() def self_or_submenu_collide_with_point(self, x, y): raise NotImplementedError() def on_cancel_handler_widget(self, obj, widget): self.cancel_handler_widget.bind(on_touch_down=self.hide_app_menus) def hide_app_menus(self, obj, pos): raise NotImplementedError() @property def menu_item_widgets(self): """ Return all children that are subclasses of ContextMenuItem """ return [ w for w in self.children if issubclass(w.__class__, AbstractMenuItem) ] def _setup_hover_timer(self): if self.clock_event is None: self.clock_event = Clock.schedule_interval( partial(self._check_mouse_hover), 0.05) def _check_mouse_hover(self, obj): self.self_or_submenu_collide_with_point(*Window.mouse_pos) def _cancel_hover_timer(self): if self.clock_event: self.clock_event.cancel() self.clock_event = None
class TerminalSpace(ResizableBehavior, BoxLayout): manager = prop.ObjectProperty(None) ''' Instance of screen manager used ''' tab_container = prop.ObjectProperty(None) ''' instance of a gridlayout where tha tab lays''' state = prop.OptionProperty('open', options=['open', 'close']) def __init__(self, **k): super(TerminalSpace, self).__init__(**k) self.logger = ErrorLogger() self.add_widget(self.logger, title='Logs') self.terminal = CommandTerminal() self.add_widget(self.terminal, title='Terminal') def add_widget(self, widget, title=''): if len(self.children) > 1: tab = TerminalTab() tab.text=title tab.name=title tab.bind(state=self.tab_state) self.tab_container.add_widget(tab) Clock.schedule_once(lambda dt: setattr(tab, 'state', 'down')) screen = Screen(name=title) screen.add_widget(widget) self.manager.add_widget(screen) else: super(TerminalSpace, self).add_widget(widget) def tab_state(self, tab, state): panel = self.manager.get_screen(tab.name).children[0] if state=='down': self.manager.current = tab.name for item in panel.top_pannel_items: self.top_pannel.add_widget(item, 2) else: for item in panel.top_pannel_items: if item in self.top_pannel.children: self.top_pannel.remove_widget(item) def on_state(self, *args): if self.state=='open': self.height = self.norm_height else: self.height='48dp' def toggle_state(self): if self.state=='open': self.state='close' else: self.state='open'
class TextInputDialog(fl.FloatLayout): validate_callback = prop.ObjectProperty(None) cancel = prop.ObjectProperty(None) def __init__(self, caption='', validate_callback=None, dismiss_on_validate=True, focus=True, **kwargs): super(TextInputDialog, self).__init__(**kwargs) self.ids.textinput.hint_text = caption self.ids.textinput.focus = focus self.dismiss_on_validate = dismiss_on_validate self.validate_callback = validate_callback
class app(Widget): pongball = properties.ObjectProperty(None) player = properties.ObjectProperty(None) opponent = properties.ObjectProperty(None) score = properties.NumericProperty(0) game = properties.ObjectProperty(None) def serve(self): self.game = "off" def on_touch_down(self, touch): if touch.x <= self.width and self.game == "off": self.pongball.velocity = Vector(0, 0) def on_touch_up(self, touch): if touch.x <= self.width and self.game == "off": self.pongball.velocity = Vector(10, 0).rotate(random.randint(60, 300)) self.game = "on" def update(self, dt): self.pongball.move() if (self.pongball.y <= 30) or (self.pongball.y >= self.height - 45): self.pongball.velocity_y *= -1 if (self.pongball.x <= 0) or (self.pongball.x >= self.width - 25): self.score += 1 self.pongball.velocity_x *= -1 if (self.player.y <= 0): self.player.y += 20 if (self.player.y >= self.height - 125): self.player.y -= 20 if (self.opponent.y <= 0): self.opponent.y += 20 if (self.opponent.y >= self.height - 125): self.opponent.y -= 20 self.player.collision(self.pongball) self.opponent.collision(self.pongball) def on_touch_move(self, touch): if touch.x <= self.width / 4: self.player.center_y = touch.y if touch.x >= self.width - self.width / 4: self.opponent.center_y = touch.y
class ConnectionScreen(Screen): app = prop.ObjectProperty() def __init__(self, app, **kwargs): super(ConnectionScreen, self).__init__(**kwargs) self.app = app def connect(self, host, port, name): if not host or not port or not name: l = [] if not host: l.append('host') if not port: l.append('port') if not name: l.append('name') err = 'The following fields are empty: {fields}'.format( fields=', '.join(l)) self.app.notify(err) return nm = self.app.network_manager self.app.player_name = name nm.host = host nm.port = int(port) self.app.connect() # self.app.connect_to_server(host=host, port=int(port)) def cancel(self): self.app.stop()
class LobbyScreen(Screen): app = prop.ObjectProperty() def __init__(self, app, **kwargs): super(LobbyScreen, self).__init__(**kwargs) self.app = app self.ids.ready_checkbox.bind(state=self.on_ready_clicked) self.ids.online_users.adapter = sla.SimpleListAdapter( \ data=self.ids.online_users.item_strings, cls=ListItemButton, ) # Обработка событий с виджетов def on_ready_clicked(self, checkbox, state): if state == 'down': self.app.send_lobby_ready() else: self.app.send_lobby_not_ready() def notify(self, text): """ Показывает уведомление вверху экрана. """ self.nm.notify(text) def update_users(self, users): self.ids.online_users.item_strings = sorted(users)
class AppMenuTextItem(ToggleButton, AbstractMenuItem): label = kp.ObjectProperty(None) text = kp.StringProperty('') font_size = kp.NumericProperty(14) color = kp.ListProperty([1, 1, 1, 1]) def on_release(self): submenu = self.get_submenu() if self.state == 'down': root = self._root_parent submenu.bounding_box_widget = root.bounding_box if root.bounding_box else root.parent submenu.bind(visible=self.on_visible) submenu.show(self.x, self.y - 1) for sibling in self.siblings: if sibling.get_submenu() is not None: sibling.state = 'normal' sibling.get_submenu().hide() self.parent._setup_hover_timer() else: self.parent._cancel_hover_timer() submenu.hide() def on_visible(self, *args): submenu = self.get_submenu() if self.width > submenu.get_max_width(): submenu.width = self.width def _check_submenu(self): super(AppMenuTextItem, self)._check_submenu() self.disabled = (self.get_submenu() is None)
class Apple(Widget): coord = props.ListProperty([250, 300]) body = props.ObjectProperty(None) def __init__(self, canvas): super().__init__() self.canvas = canvas with self.canvas: Color(1, 0, 0) self.body = Ellipse(pos=self.coord, size=(SIZE, SIZE)) def check_collision(self, coord): print(self.coord, coord) if coord[0] <= self.coord[0] + SIZE/2 <= coord[0] + SIZE \ and coord[1] <= self.coord[1] + SIZE/2 <= coord[1] + SIZE: print("check_collision") return True return False def new_position(self, snake): print("new_position") while True: apple_x = random.randint(SIZE, Window.size[0] - SIZE) apple_y = random.randint(SIZE, Window.size[1] - SIZE) apple_x -= apple_x % SIZE apple_y -= apple_y % SIZE for segment in snake.body: if [apple_x, apple_y] == segment.pos: continue self.coord = [apple_x, apple_y] self.body.pos = [apple_x, apple_y] return
class AbstractMenuItem(object): submenu = kp.ObjectProperty(None) def get_submenu(self): return self.submenu if self.submenu != "" else None def show_submenu(self, x=None, y=None): if self.get_submenu(): self.get_submenu().show(*self._root_parent.to_local(x, y)) def hide_submenu(self): submenu = self.get_submenu() if submenu: submenu.visible = False submenu.hide_submenus() def _check_submenu(self): if self.parent is not None and len(self.children) > 0: submenus = [w for w in self.children if issubclass(w.__class__, ContextMenu)] if len(submenus) > 1: raise Exception('Menu item (ContextMenuItem) can have maximum one submenu (ContextMenu)') elif len(submenus) == 1: self.submenu = submenus[0] @property def siblings(self): return [w for w in self.parent.children if issubclass(w.__class__, AbstractMenuItem) and w != self] @property def content_width(self): return None @property def _root_parent(self): return self.parent.get_context_menu_root_parent()
class StableModelDialog(fl.FloatLayout): cancel = prop.ObjectProperty(None) def __init__(self, solver, **kwargs): super(StableModelDialog, self).__init__(**kwargs) self.solver = solver self.index = 0 number = [str(self.index + 1), str(len(self.solver.get_models()))] self.ids.number.text = '/'.join(number) def previous_model(self): if self.index < 1: return self.index -= 1 model = self.solver.get_models()[self.index] self.solver.generate_graph(model) self.ids.img.reload() number = [str(self.index + 1), str(len(self.solver.get_models()))] self.ids.number.text = '/'.join(number) def next_model(self): models = self.solver.get_models() if self.index > (len(models) - 2): return self.index += 1 model = models[self.index] self.solver.generate_graph(model) self.ids.img.reload() number = [str(self.index + 1), str(len(models))] self.ids.number.text = '/'.join(number)
class ScatterImage(Scatter): source = Properties.StringProperty() anim_delay = Properties.NumericProperty() saveOnDBEvent = Properties.ObjectProperty() imagenId = Properties.NumericProperty() def on_pos(self, instance, value): try: self.saveOnDBEvent.cancel() except: logging.info('Gifs: No previous event') self.saveOnDBEvent = Clock.schedule_once(self.saveOnDB, 5) def bringToFront(self): parent = self.parent children = parent.children childOnTop = children[0] if (self != childOnTop): parent.remove_widget(self) parent.add_widget(self) def saveOnDB(self, dt): gifToSave = Gifs( _id=self.imagenId, source=self.source, posX=self.pos[0], posY=self.pos[1], scale=self.scale, rotation=self.rotation, delay=self.anim_delay) gifToSave.save() logging.info('DB: Updated gif with id: ' + str(self.imagenId))
class TabletKeyApp(App): """ The core app of TabletKeyApp. """ app = kp.ObjectProperty(None) def build(self) -> AppFrame: """ Builds the widget tree based on tabletkey.kv. :return: An AppFrame object. """ self.app = AppFrame() return self.app def load_last_bset(self, bset_name: str) -> None: """ If TabletKeyApp has been run before, this method will automatically load the last bindset file into the window. :param bset_name: A string, a file name found in bindsets. :return: None """ print(f'Attempting to load the last used bindset {bset_name}...') load_result = self.app.load(bset_name) if load_result: print(f'Load of {bset_name}.json successful.') else: self.app.config.pop('last_bindset') self.app.save_config() print(f'Load failed. bindsets/{bset_name}.json no ' f'longer exists.') @staticmethod def setup_basics() -> None: """ Simple method to ensure that the expected file structure is in place. :return: None """ if not os.path.exists('bindsets/'): os.mkdir('bindsets') def on_start(self) -> None: """ A collection of methods to run and properties to change after build. :return: None """ self.setup_basics() self.root_window.borderless = True print('Performing TabletKey startup...') result = self.app.from_json('ref.json') for k, v in result.items(): self.app.config[k] = v last_bset = self.app.config.get('last_bindset') if last_bset: self.load_last_bset(last_bset)
class ScatterColoredLabel(Scatter): background_color = Properties.ListProperty((0, 0, 0, 1)) visible = Properties.BooleanProperty() saveOnDBEvent = Properties.ObjectProperty() noteId = Properties.NumericProperty() text = Properties.StringProperty() def on_pos(self, instance, value): try: self.saveOnDBEvent.cancel() except: logging.info('Notes: No previous event') self.saveOnDBEvent = Clock.schedule_once(self.saveOnDB, 5) def saveOnDB(self, dt): noteToSave = Notes( _id=self.noteId, pinned=self.visible, text=self.text, posX=self.pos[0], posY=self.pos[1], scale=self.scale, rotation=self.rotation, rgb=[ self.background_color[0]*255, self.background_color[1]*255, self.background_color[2]*255, self.background_color[3], ], ) noteToSave.save() logging.info('DB: Updated note with id: ' + str(self.noteId))
class ShmupApp(App): screen_manager = kp.ObjectProperty(None) highscore = kp.NumericProperty(0) game_over_msg = kp.StringProperty("") score = kp.NumericProperty(0) def build(self): # self.game = Game() # Clock.schedule_interval(self.game.update, 1.0/FPS) # return self.game self.screen_manager = MetaGame() return self.screen_manager def new_game(self): if self.screen_manager.game_screen.game.over: self.screen_manager.game_screen.game.new() self.screen_manager.current = "game_screen" Clock.schedule_interval(self.screen_manager.game_screen.game.update, 1.0/FPS) def update_score(self): self.score = self.screen_manager.game_screen.game.score self.highscore = max(self.highscore, self.score) def quit_game(self): self.update_score() self.screen_manager.game_screen.game.quit_game() self.screen_manager.current = "game_over_screen"
class AboutDialog(fl.FloatLayout): cancel = prop.ObjectProperty(None) def __init__(self, **kwargs): super(AboutDialog, self).__init__(**kwargs) self.ids.title.text = __title__ self.ids.version.text = 'Version ' + __version__ self.ids.copyright.text = __copyright__ self.ids.license.text = __license__
class Sprite(Image): vel = kp.ObjectProperty(Vector(0, 0)) acc = kp.ObjectProperty(Vector(0, 0)) touch_the_ground = kp.BooleanProperty(True) last_moving = kp.StringProperty("right") have_the_key = kp.BooleanProperty(False) def __init__(self, game, source, **kwargs): super().__init__() self.source = source self.game = game self.width = kwargs.get("width", self.game.tile_size) self.height = kwargs.get("height", self.game.tile_size) self.x = kwargs.get("x", 0) self.y = kwargs.get("y", 0) index = kwargs.get("index", 1) self.game.add_widget(self, index=index) self._pos = Vector(*self.pos)
class ContextMenuItem(RelativeLayout, AbstractMenuItem): submenu_arrow = kp.ObjectProperty(None) def _check_submenu(self): super(ContextMenuItem, self)._check_submenu() if self.get_submenu() is None: self.submenu_arrow.opacity = 0 else: self.submenu_arrow.opacity = 1
class GameOverScreen(Screen): app = prop.ObjectProperty() winner_name = prop.StringProperty() def __init__(self, app, winner_name=None, **kwargs): super().__init__(**kwargs) self.app = app self.winner_name = winner_name or ""
class MenuButton(MenuItem, but.Button, HoverBehavior): icon = prop.StringProperty(None, allownone=True) menubar = prop.ObjectProperty(None) def on_release(self): print("Button", self.text, "triggered") if isinstance(self.parent.parent, MenuDropDown): self.menubar.selected = False self.parent.parent.dismiss()
class SettingsScreen(Screen): image = Properties.StringProperty(dbWrapper.getSaveScreen().image) showNotes = Properties.ObjectProperty(None) refreshImagesSchedule = Properties.ObjectProperty(None) def __init__(self, **kwargs): super(SettingsScreen, self).__init__(**kwargs) self.pos_hint = {'center_y': 0.5, 'center_x': 0.5} self.showNotes.bind(minimum_height=self.showNotes.setter('height')) self.showSaveScreenFunc() Clock.schedule_interval(self.showSaveScreenFunc, 20) def showSaveScreenFunc(self, *args): imagenes = dbWrapper.getAllSaveScreen() try: children = self.showNotes.children.copy() for child in children: self.showNotes.remove_widget(child) except: pass for imagen in imagenes: selected = imagen.image == self.image fondo = Fondo(imagen=imagen.image, state="down" if selected else "normal") self.ids.showNotes.add_widget(fondo) def refreshImageList(self): imageName = dbWrapper.getSaveScreen().image self.fondo = "images/saveScreen/" + imageName def pressedBack(self, widget): anim = Animation(pos_hint={"center_x": .5, "y": -.03}, duration=.1) anim += Animation(pos_hint={"center_x": .5, "y": 0}, duration=.1) anim.bind(on_complete=partial(self.goToMenuScreen)) anim.start(widget) def goToMenuScreen(self, widget, selected): #self.saveConfig() App.get_running_app().root.transition = FadeTransition(duration=.3) App.get_running_app().root.current = "menu"
class TestApp(App): addition = kp.ObjectProperty(Addition()) def build(self): return Button(text=str(self.addition.xp), on_press=self.change_button()) def change_button(self): self.addition.xp += 1
class GameScreen(Screen): app = prop.ObjectProperty() def __init__(self, app, game, network_manager, username="", **kwargs): super().__init__(**kwargs) self.app = app self.game = game self.username = username self.add_widget(self.game.make_widget(network_manager=network_manager))
class GameApp(App): game = kp.ObjectProperty(Game()) def build(self): self.width = Window.width self.height = Window.height self.game = Game() self.game.new() Clock.schedule_interval(self.game.update, 1.0 / FPS) return self.game
class TelaCandidatura(Screen): candidatos = [] registro = Registros() nCandidato = kyprops.ObjectProperty() numCandidato = kyprops.ObjectProperty() def iniciar(self): try: with open("/tmp/registros.json", 'r') as f: print(f) self.registro.importar(f) except IOError: print("Arquivo não localizado") def novoCandidato(self): candidato = Candidato(self.nCandidato.text, self.numCandidato.text) self.candidatos.append(candidato) self.registro.inserir(candidato) self.registro.exportar('/tmp/registros.json') for c in self.candidatos: print(c.paraJson())