class mainApp(App): _layout = None #This holds the root layout widget _labels = [None] * 15 #This will hold all our labels def build(self): #Create the layout to hold all the widgets self._layout = FloatLayout(size=(800, 480)) return self._layout def on_start(self): #Schedule a timer Clock.schedule_interval(self._update, 0.1) def _update(self, delta_time): #If GPIO40 is triggered, add the widget if pi.read(40): self._labels[0] = Label(text="Hello!", font_size=150) self._layout.add_widget(self._labels[0]) #If GPIO41 is triggered, remove the widget if pi.read(41): self._layout.remove_widget(self._labels[0])
class ChooserTest(App): def build(self): # This is our application self.top_layout = FloatLayout() self.msg_label= Label(text="LABEL") self.top_layout.add_widget(self.msg_label) # OH! We want a directory chooser! Let's add a chooser in a Popup... self.chooser= KivyFileChooserLayout(ok=self.ok, cancel=self.cancel, filter=self.is_dir) for directory in ['/home']: self.chooser.add_entry(directory) self.popup = Popup(title="Choose Directories", content=self.chooser) # Add the Popup self.top_layout.add_widget(self.popup) return self.top_layout def is_dir(self, directory, filename): return os.path.isdir(os.path.join(directory, filename)) def ok(self, directories): print ("APP: OK", directories) self.top_layout.remove_widget(self.popup) self.msg_label.text = "DIRECTORIES: " + ', '.join(directories) def cancel(self, directories): print ("APP: CANCEL", directories) self.top_layout.remove_widget(self.popup)
class ScatterLayout(Scatter): '''RelativeLayout class, see module documentation for more information. ''' content = ObjectProperty() def __init__(self, **kw): self.content = FloatLayout() super(ScatterLayout, self).__init__(**kw) if self.content.size != self.size: self.content.size = self.size super(ScatterLayout, self).add_widget(self.content) self.bind(size=self.update_size) def update_size(self, instance, size): self.content.size = size def add_widget(self, *l): self.content.add_widget(*l) def remove_widget(self, *l): self.content.remove_widget(*l) def clear_widgets(self): self.content.clear_widgets()
class ScatterLayout(Scatter): '''ScatterLayout class, see module documentation for more information. ''' content = ObjectProperty() def __init__(self, **kw): self.content = FloatLayout() super(ScatterLayout, self).__init__(**kw) if self.content.size != self.size: self.content.size = self.size super(ScatterLayout, self).add_widget(self.content) self.bind(size=self.update_size) def update_size(self, instance, size): self.content.size = size def add_widget(self, *l): self.content.add_widget(*l) def remove_widget(self, *l): self.content.remove_widget(*l) def clear_widgets(self): self.content.clear_widgets()
def __init__(self, **kwargs): super(ScrambledPicture, self).__init__(**kwargs) self.tile_list = [] self.grid_pos = [] self.image_list = [] self.tile_list_array = [[164.0, 436.0], [228.0, 436.0], [292.0, 436.0], [356.0, 436.0], [164.0, 372.0], [228.0, 372.0], [292.0, 372.0], [356.0, 372.0], [164.0, 308.0], [228.0, 308.0], [292.0, 308.0], [356.0, 308.0], [164.0, 244.0], [228.0, 244.0], [292.0, 244.0], [356.0, 244.0]] self.correct_grid_pos = [[164.0, 436.0], [228.0, 436.0], [292.0, 436.0], [356.0, 436.0], [164.0, 372.0], [228.0, 372.0], [292.0, 372.0], [356.0, 372.0], [164.0, 308.0], [228.0, 308.0], [292.0, 308.0], [356.0, 308.0], [164.0, 244.0], [228.0, 244.0], [292.0, 244.0]] #shuffle the tile positions shuffle(self.tile_list_array) f = FloatLayout(size_hint=(0.1, 0.1)) f.add_widget(Label(text='hi')) for i in range(1, 5): for j in range(1, 5): btn = Button(name=str('btn' + str(i * 4 + j - 4)), id=str('btn' + str(i * 4 + j - 4)), size=(64, 64), pos=(self.tile_list_array[i * 4 + j - 5][0], self.tile_list_array[i * 4 + j - 5][1]), on_release=self.move_tile) self.image_list.append( str('squareimage_0' + str(i) + '_0' + str(j) + '.png')) self.tile_list.append(btn) self.grid_pos.append(btn.pos) f.add_widget(btn) self.add_widget(f) f.add_widget( Button(text='Solve', pos=(292.5, 0), on_release=self.do_you_win)) f.remove_widget( self.tile_list[15]) #the same picture will always be popped self.tile_list.pop(15) self.grid_pos.pop(15) self.image_list.pop(15) self.score = 0
class HelpGuideApp(App): def build(self): self.root = FloatLayout() self.home = HomePage(self) self.home.show() return self.root def remove_widget(self, widget): """Remove a widget from the app.""" self.root.remove_widget(widget) def add_widget(self, widget): """Add a widget to the app.""" self.root.add_widget(widget)
class FileBrowserApp(App): def build(self): self.root = FloatLayout() button = Button(text='Select Files', pos_hint={ 'x': 0, 'y': 0 }, size_hint=(0.2, 0.1)) button.bind(on_press=self.do_select) self.root.add_widget(button) return self.root def do_select(self, *args): homeDir = None if platform == 'win': homeDir = os.environ["HOMEPATH"] elif platform == 'android': homeDir = os.path.dirname(os.path.abspath(__file__)) elif platform == 'linux': homeDir = os.environ["HOME"] elif platform == 'macosx': homeDir = os.environ["HOME"] self.fbrowser = filebrowser.FileBrowser(select_string='Select', multiselect=True, filters=['*.wav'], path=homeDir) self.root.add_widget(self.fbrowser) self.fbrowser.bind(on_success=self._fbrowser_success, on_canceled=self._fbrowser_canceled, on_submit=self._fbrowser_success) def _fbrowser_success(self, fbInstance): if len(fbInstance.selection) == 0: return selected = [] for file in fbInstance.selection: selected.append(os.path.join(fbInstance.path, file)) df = pd.DataFrame(data=selected) df.to_csv('filepath.csv', index=False) self.root.remove_widget(self.fbrowser) self.fbrowser = None App.get_running_app().stop() def _fbrowser_canceled(self, instance): self.root.remove_widget(self.fbrowser) self.fbrowser = None
class FileBrowserApp(App): def build(self): self.root = FloatLayout() button = Button(text='Select Files', pos_hint={ 'x': 0, 'y': 0 }, size_hint=(0.2, 0.1)) button.bind(on_press=self.do_select) self.root.add_widget(button) return self.root def do_select(self, *args): homeDir = None if platform == 'win': homeDir = os.environ["HOMEPATH"] elif platform == 'android': homeDir = os.path.dirname(os.path.abspath(__file__)) elif platform == 'linux': homeDir = os.environ["HOME"] self.fbrowser = kivy.garden.filebrowser.FileBrowser( select_string='Select', multiselect=True, filters=['*.png'], path=homeDir) self.root.add_widget(self.fbrowser) self.fbrowser.bind(on_success=self._fbrowser_success, on_canceled=self._fbrowser_canceled, on_submit=self._fbrowser_success) def _fbrowser_success(self, fbInstance): if len(fbInstance.selection) == 0: return selected = [] for file in fbInstance.selection: selected.append(os.path.join(fbInstance.path, file)) print('selected: ' + str(selected)) self.root.remove_widget(self.fbrowser) self.fbrowser = None def _fbrowser_canceled(self, instance): self.root.remove_widget(self.fbrowser) self.fbrowser = None
class RelativeLayout(Scatter): """RelativeLayout class, see module documentation for more information. """ content = ObjectProperty() def __init__(self, **kw): self.content = FloatLayout() super(RelativeLayout, self).__init__(**kw) super(RelativeLayout, self).add_widget(self.content) self.bind(size=self.update_size) def update_size(self, instance, size): self.content.size = size def add_widget(self, *l): self.content.add_widget(*l) def remove_widget(self, *l): self.content.remove_widget(*l)
class Layer(): def __init__(self, img): self.points = [] self.src = img self.layout = FloatLayout(size=(width-150, height)) self.layout.add_widget(Image(source=img)) self.setTransform(Matrix()) def getSource(self): return self.src def addPoint(self, point): self.points.append(point) self.layout.add_widget(point.getDisplay()) def deletePoint(self, point): self.points.remove(point) self.layout.remove_widget(point.getDisplay()) def getContents(self): return self.layout def setTransform(self, transform): self.transform = transform def getTransform(self): return self.transform
class BaseGrid(Screen): def __init__(self, **kwargs): super().__init__(**kwargs) self.screens = [] self.screen_index = 0 self.right_nav_btn = None self.left_nav_btn = None self.layout = FloatLayout() def go_next(self, instance): if self.right_nav_btn.disabled: return self.layout.remove_widget(self.screens[self.screen_index]) self.screen_index += 1 self.layout.add_widget(self.screens[self.screen_index]) self.add_nav_buttons() def go_prev(self, instance): if self.left_nav_btn.disabled: return self.layout.remove_widget(self.screens[self.screen_index]) self.screen_index -= 1 self.layout.add_widget(self.screens[self.screen_index]) self.add_nav_buttons() def add_nav_buttons(self): self.right_nav_btn = MDIconButton(icon='chevron-right') self.right_nav_btn.md_bg_color = (1, 1, 1, 1) self.right_nav_btn.disabled = False if self.screen_index + 1 < len( self.screens) else True self.right_nav_btn.pos_hint = {'center_x': .6, 'center_y': .15} self.right_nav_btn.bind(on_press=self.go_next) self.layout.add_widget(self.right_nav_btn) self.left_nav_btn = MDIconButton(icon='chevron-left') self.left_nav_btn.md_bg_color = (1, 1, 1, 1) self.left_nav_btn.disabled = True if self.screen_index == 0 else False self.left_nav_btn.pos_hint = {'center_x': .4, 'center_y': .15} self.left_nav_btn.bind(on_press=self.go_prev) self.layout.add_widget(self.left_nav_btn)
class CameraExample(App): def build(self): self.clicked = False self.layout = FloatLayout(orientation='vertical') # Create a camera object self.cameraObject = Camera(play=False, pos=(0,346)) self.cameraObject.play = True self.cameraObject.resolution = (1000, 600) # Specify the resolution # Create a button for taking photograph self.cameraClick = Button(text="Take Photo and Evaluate", pos=(0, 440), font_size='60dp') self.cameraClick.size_hint=(1, .2) # bind the button's on_press to onCameraClick self.cameraClick.bind(on_press=self.onCameraClick) # add camera and button to the layout self.layout.add_widget(self.cameraObject) self.layout.add_widget(self.cameraClick) return self.layout def delete_output_pngs(self): import glob, os, multiprocessing p = multiprocessing.Pool(4) p.map(os.remove, glob.glob("output*.png")) # Take the current frame of the video as the photo graph def onCameraClick(self, *args): Cache.remove('kv.image') Cache.remove('kv.texture') self.delete_output_pngs() if self.clicked == True: self.layout.remove_widget(self.output) self.clicked = True self.cameraObject.export_to_png('output.png') latex_string = image_to_latex('output.png') #latex_string = u'\\left. \\begin{array} { l } { 4 x ^ { 3 } + \\int _ { 0 } ^ { x } x ^ { 2 } d x } \\\\ { = 4 x ^ { 3 } + 3 x ^ { 3 } } \\\\ { = 7 x ^ { 3 } } \\end{array} \\right.' print latex_string.__repr__() latex_equations = split_into_equations(latex_string) print latex_equations self.output = Output(latex_equations, size_hint=(1, .35)) self.layout.add_widget(self.output)
class MainApp(App): def build(self): self.parent = FloatLayout() self.titre = Label(text='[color=2ecc71]Le Sept[/color]', markup= True, font_size= 50, pos_hint={'x': 0, 'center_y': 0.8}) self.bouton = Button(text='[color=2ecc71]Rechercher un horaire[/color]', font_size_hint= 0.1, markup= True, size_hint=(0.3,0.1), pos_hint={'x': 0.35, 'center_y': 0.3}) self.bouton.bind(on_press=self.ville_depart) self.parent.add_widget(self.titre) self.parent.add_widget(self.bouton) return self.parent def ville_depart(self, value): self.parent.remove_widget(self.titre) self.parent.remove_widget(self.bouton) liste_ville = ListeVille(self.parent) self.parent.add_widget(liste_ville.list_view)
class Board(RelativeLayout): """A graphical view onto a :class:`LiSE.Character`, resembling a game board. """ engine = ObjectProperty() character = ObjectProperty() wallpaper_path = StringProperty() spot = DictProperty({}) pawn = DictProperty({}) arrow = DictProperty({}) kvlayoutback = ObjectProperty() arrowlayout = ObjectProperty() spotlayout = ObjectProperty() pawnlayout = ObjectProperty() kvlayoutfront = ObjectProperty() wids = ReferenceListProperty( kvlayoutback, arrowlayout, spotlayout, pawnlayout, kvlayoutfront ) spots_unposd = ListProperty([]) layout_tries = NumericProperty(5) new_spots = ListProperty([]) tracking_vel = BooleanProperty(False) branch = StringProperty('trunk') tick = NumericProperty(0) selection_candidates = ListProperty([]) selection = ObjectProperty(allownone=True) keep_selection = ObjectProperty(False) adding_portal = BooleanProperty(False) reciprocal_portal = BooleanProperty(False) grabbing = BooleanProperty(True) grabbed = ObjectProperty(None, allownone=True) @property def widkwargs(self): return { 'size_hint': (None, None), 'size': self.size, 'pos': (0, 0) } def on_touch_down(self, touch): """Check for collisions and select an appropriate entity.""" if hasattr(self, '_lasttouch') and self._lasttouch == touch: return if not self.collide_point(*touch.pos): return if self.selection: self.selection.hit = self.selection.collide_point(*touch.pos) if self.selection.hit: Logger.debug("Board: hit selection") touch.grab(self.selection) pawns = list(self.pawns_at(*touch.pos)) if pawns: Logger.debug("Board: hit {} pawns".format(len(pawns))) self.selection_candidates = pawns if self.selection in self.selection_candidates: self.selection_candidates.remove(self.selection) return True spots = list(self.spots_at(*touch.pos)) if spots: Logger.debug("Board: hit {} spots".format(len(spots))) self.selection_candidates = spots if self.adding_portal: self.origspot = self.selection_candidates.pop(0) self.protodest = Dummy( name='protodest', pos=touch.pos, size=(0, 0) ) self.add_widget(self.protodest) self.protodest.on_touch_down(touch) self.protoportal = ArrowWidget( origin=self.origspot, destination=self.protodest ) self.add_widget(self.protoportal) if self.reciprocal_portal: self.protoportal2 = ArrowWidget( destination=self.origspot, origin=self.protodest ) self.add_widget(self.protoportal2) return True if not self.selection_candidates: arrows = list(self.arrows_at(*touch.pos)) if arrows: Logger.debug("Board: hit {} arrows".format(len(arrows))) self.selection_candidates = arrows return True def on_touch_move(self, touch): """If an entity is selected, drag it.""" if hasattr(self, '_lasttouch') and self._lasttouch == touch: return if self.selection in self.selection_candidates: self.selection_candidates.remove(self.selection) if self.selection: if not self.selection_candidates: self.keep_selection = True return self.selection.dispatch('on_touch_move', touch) elif self.selection_candidates: for cand in self.selection_candidates: if cand.collide_point(*touch.pos): if hasattr(self.selection, 'selected'): self.selection.selected = False if hasattr(self.selection, 'hit'): self.selection.hit = False self.selection = cand cand.hit = cand.selected = True touch.grab(cand) return cand.dispatch('on_touch_move', touch) def portal_touch_up(self, touch): """Try to create a portal between the spots the user chose.""" try: # If the touch ended upon a spot, and there isn't # already a portal between the origin and this # destination, create one. destspot = next(self.spots_at(*touch.pos)) orig = self.origspot.remote dest = destspot.remote if not( orig.name in self.character.portal and dest.name in self.character.portal[orig.name] ): port = self.character.new_portal( orig.name, dest.name ) self.arrowlayout.add_widget( self.make_arrow(port) ) # And another in the opposite direction if needed if ( hasattr(self, 'protoportal2') and not( orig.name in self.character.preportal and dest.name in self.character.preportal[orig.name] ) ): deport = self.character.new_portal( dest.name, orig.name ) self.arrowlayout.add_widget( self.make_arrow(deport) ) except StopIteration: pass self.remove_widget(self.protoportal) if hasattr(self, 'protoportal2'): self.remove_widget(self.protoportal2) del self.protoportal2 self.remove_widget(self.protodest) del self.protoportal del self.protodest def on_touch_up(self, touch): """Delegate touch handling if possible, else select something.""" if hasattr(self, '_lasttouch') and self._lasttouch == touch: return self._lasttouch = touch if hasattr(self, 'protodest'): Logger.debug("Board: on_touch_up making a portal") touch.ungrab(self) return self.portal_touch_up(touch) if hasattr(self.selection, 'on_touch_up'): self.selection.dispatch('on_touch_up', touch) while self.selection_candidates: candidate = self.selection_candidates.pop(0) if candidate.collide_point(*touch.pos): Logger.debug("Board: selecting " + repr(candidate)) if hasattr(self.selection, 'selected'): self.selection.selected = False if hasattr(self.selection, 'hit'): self.selection.hit = False if hasattr(self.selection, '_start'): self.selection.pos = self.selection._start del self.selection._start self.selection = candidate if hasattr(self.selection, 'selected'): self.selection.selected = True if hasattr(self.selection, 'hit'): self.selection.hit = True if ( hasattr(self.selection, 'thing') and not hasattr(self.selection, '_start') ): self.selection._start = tuple(self.selection.pos) self.keep_selection = True if not self.keep_selection: Logger.debug("Board: deselecting " + repr(self.selection)) if hasattr(self.selection, 'selected'): self.selection.selected = False if hasattr(self.selection, 'hit'): self.selection.hit = False self.selection = None self.keep_selection = False touch.ungrab(self) return def on_parent(self, *args): """Create some subwidgets and trigger the first update.""" if not self.parent or hasattr(self, '_parented'): return self._parented = True self.kvlayoutback = KvLayoutBack( wallpaper_path=self.wallpaper_path, pos=(0, 0) ) self.bind(wallpaper_path=self.kvlayoutback.setter('wallpaper_path')) self.size = self.kvlayoutback.size self.kvlayoutback.bind(size=self.setter('size')) self.arrowlayout = FloatLayout(**self.widkwargs) self.spotlayout = FloatLayout(**self.widkwargs) self.pawnlayout = FloatLayout(**self.widkwargs) self.kvlayoutfront = KvLayoutFront(**self.widkwargs) for wid in self.wids: if wid != self.kvlayoutback: self.bind(size=wid.setter('size')) self.add_widget(wid) if hasattr(self.parent, 'effect_x'): self.parent.effect_x.bind(velocity=self.track_vel) if hasattr(self.parent, 'effect_y'): self.parent.effect_y.bind(velocity=self.track_vel) self.trigger_update() def on_character(self, *args): if self.character is None: return if self.parent is None: Clock.schedule_once(self.on_character, 0) return if hasattr(self.parent, 'scroll_x'): self.parent.scroll_x = self.character.stat.setdefault( '_scroll_x', 0.0 ) if hasattr(self.parent, 'scroll_y'): self.parent.scroll_y = self.character.stat.setdefault( '_scroll_y', 0.0 ) self.wallpaper_path = self.character.stat.setdefault('wallpaper', 'wallpape.jpg') if '_control' not in self.character.stat or 'wallpaper' not in self.character.stat['_control']: control = self.character.stat.setdefault('_control', {}) control['wallpaper'] = 'textinput' self.character.stat['_control'] = control self.character.stat.connect(self._trigger_pull_wallpaper) def pull_wallpaper(self, *args): self.wallpaper_path = self.character.stat.setdefault('wallpaper', 'wallpape.jpg') def _trigger_pull_wallpaper(self, *args, **kwargs): if kwargs['key'] != 'wallpaper': return Clock.unschedule(self.pull_wallpaper) Clock.schedule_once(self.pull_wallpaper, 0) @trigger def kv_updated(self, *args): self.unbind(wallpaper_path=self.kvlayoutback.setter('wallpaper_path')) for wid in self.wids: self.remove_widget(wid) self.kvlayoutback = KvLayoutBack(pos=(0, 0), wallpaper_path=self.wallpaper_path) self.bind(wallpaper_path=self.kvlayoutback.setter('wallpaper_path')) self.kvlayoutfront = KvLayoutFront(**self.widkwargs) self.size = self.kvlayoutback.size self.kvlayoutback.bind(size=self.setter('size')) for wid in self.wids: self.add_widget(wid) def make_pawn(self, thing): """Make a :class:`Pawn` to represent a :class:`Thing`, store it, and return it. """ if thing["name"] in self.pawn: raise KeyError("Already have a Pawn for this Thing") r = Pawn( board=self, thing=thing ) self.pawn[thing["name"]] = r return r def make_spot(self, place): """Make a :class:`Spot` to represent a :class:`Place`, store it, and return it. """ if place["name"] in self.spot: raise KeyError("Already have a Spot for this Place") r = Spot( board=self, place=place ) self.spot[place["name"]] = r if '_x' in place and '_y' in place: r.pos = ( self.width * place['_x'], self.height * place['_y'] ) return r def make_arrow(self, portal): """Make an :class:`Arrow` to represent a :class:`Portal`, store it, and return it. """ if ( portal["origin"] not in self.spot or portal["destination"] not in self.spot ): raise ValueError( "An :class:`Arrow` should only be made after " "the :class:`Spot`s it connects" ) if ( portal["origin"] in self.arrow and portal["destination"] in self.arrow[portal["origin"]] ): raise KeyError("Already have an Arrow for this Portal") r = Arrow( board=self, portal=portal ) if portal["origin"] not in self.arrow: self.arrow[portal["origin"]] = {} self.arrow[portal["origin"]][portal["destination"]] = r return r def track_vel(self, *args): """Track scrolling once it starts, so that we can tell when it stops. """ if not self.parent: return if ( not self.tracking_vel and ( self.parent.effect_x.velocity > 0 or self.parent.effect_y.velocity > 0 ) ): self.upd_pos_when_scrolling_stops() self.tracking_vel = True def upd_pos_when_scrolling_stops(self, *args): """Wait for the scroll to stop, then store where it ended.""" if not self.parent: return if self.parent.effect_x.velocity \ == self.parent.effect_y.velocity == 0: self.character.stat['_scroll_x'] = self.parent.scroll_x self.character.stat['_scroll_y'] = self.parent.scroll_y self.tracking_vel = False return Clock.schedule_once(self.upd_pos_when_scrolling_stops, 0.001) def rm_arrows_to_and_from(self, name): origs = list(self.arrow.keys()) if name in origs: origs.remove(name) for dest in list(self.arrow[name].keys()): self.rm_arrow(name, dest) for orig in origs: if name in self.arrow[orig]: self.rm_arrow(orig, name) def rm_pawn(self, name, *args): """Remove the :class:`Pawn` by the given name.""" if name not in self.pawn: raise KeyError("No Pawn named {}".format(name)) # Currently there's no way to connect Pawns with Arrows but I # think there will be, so, insurance self.rm_arrows_to_and_from(name) pwn = self.pawn[name] pwn.parent.remove_widget(pwn) for canvas in ( self.pawnlayout.canvas.after, self.pawnlayout.canvas.before, self.pawnlayout.canvas ): if pwn.group in canvas.children: canvas.remove(pwn.group) pwn.canvas.clear() del self.pawn[name] def _trigger_rm_pawn(self, name): Clock.schedule_once(partial(self.rm_pawn, name), 0) def rm_spot(self, name, *args): """Remove the :class:`Spot` by the given name.""" if name not in self.spot: raise KeyError("No Spot named {}".format(name)) spot = self.spot[name] pawns_here = list(spot.children) self.rm_arrows_to_and_from(name) self.spotlayout.remove_widget(spot) spot.canvas.clear() del self.spot[name] for pawn in pawns_here: self.rm_pawn(pawn.name) def _trigger_rm_spot(self, name): part = partial(self.rm_spot, name) Clock.unschedule(part) Clock.schedule_once(part, 0) def rm_arrow(self, orig, dest, *args): """Remove the :class:`Arrow` that goes from ``orig`` to ``dest``.""" if ( orig not in self.arrow or dest not in self.arrow[orig] ): raise KeyError("No Arrow from {} to {}".format(orig, dest)) self.arrowlayout.remove_widget(self.arrow[orig][dest]) del self.arrow[orig][dest] def _trigger_rm_arrow(self, orig, dest): part = partial(self.rm_arrow, orig, dest) Clock.unschedule(part) Clock.schedule_once(part, 0) def graph_layout(self, graph): from networkx.drawing.layout import spring_layout return normalize_layout(spring_layout(graph)) def discard_pawn(self, thingn, *args): if thingn in self.pawn: self.rm_pawn(thingn) def _trigger_discard_pawn(self, thing): part = partial(self.discard_pawn, thing) Clock.unschedule(part) Clock.schedule_once(part, 0) def remove_absent_pawns(self, *args): Logger.debug( "Board: removing pawns absent from {}".format( self.character.name ) ) for pawn_name in list(self.pawn.keys()): if pawn_name not in self.character.thing: self.rm_pawn(pawn_name) def discard_spot(self, placen, *args): if placen in self.spot: self.rm_spot(placen) def _trigger_discard_spot(self, place): Clock.schedule_once(partial(self.discard_spot, place), 0) def remove_absent_spots(self, *args): Logger.debug( "Board: removing spots absent from {}".format( self.character.name ) ) for spot_name in list(self.spot.keys()): if spot_name not in self.character.place: self.rm_spot(spot_name) def discard_arrow(self, orign, destn, *args): if ( orign in self.arrow and destn in self.arrow[orign] ): self.rm_arrow(orign, destn) def _trigger_discard_arrow(self, orig, dest): Clock.schedule_once(partial(self.discard_arrow, orig, dest), 0) def remove_absent_arrows(self, *args): Logger.debug( "Board: removing arrows absent from {}".format( self.character.name ) ) for arrow_origin in list(self.arrow.keys()): for arrow_destination in list(self.arrow[arrow_origin].keys()): if ( arrow_origin not in self.character.portal or arrow_destination not in self.character.portal[arrow_origin] ): self.rm_arrow(arrow_origin, arrow_destination) def add_spot(self, placen, *args): if ( placen in self.character.place and placen not in self.spot ): self.spotlayout.add_widget( self.make_spot(self.character.place[placen]) ) def _trigger_add_spot(self, placen): Clock.schedule_once(partial(self.add_spot, placen), 0) def add_new_spots(self, *args): Logger.debug( "Board: adding new spots to {}".format( self.character.name ) ) spots_added = [] nodes_patch = {} for place_name in self.character.place: if place_name not in self.spot: place = self.character.place[place_name] spot = self.make_spot(place) patch = {} if '_image_paths' in place: zeroes = [0] * len(place['_image_paths']) else: patch['_image_paths'] = spot.default_image_paths zeroes = [0] if '_offxs' not in place: patch['_offxs'] = zeroes if '_offys' not in place: patch['_offys'] = zeroes if '_stackhs' not in place: patch['_stackhs'] = zeroes if patch: nodes_patch[place_name] = patch self.spotlayout.add_widget(spot) spots_added.append(spot) if nodes_patch: self.engine.handle( 'update_nodes', char=self.character.name, patch=nodes_patch, ) for spot in spots_added: spot.finalize() self.new_spots = spots_added def add_arrow(self, orign, destn, *args): if not ( orign in self.character.portal and destn in self.character.portal[orign] ): raise ValueError("No portal for arrow {}->{}".format(orign, destn)) if not ( orign in self.arrow and destn in self.arrow[orign] ): self.arrowlayout.add_widget( self.make_arrow( self.character.portal[orign][destn] ) ) assert self.arrow[orign][destn] in self.arrowlayout.children def _trigger_add_arrow(self, orign, destn): part = partial(self.add_arrow, orign, destn) Clock.unschedule(part) Clock.schedule_once(part, 0) def add_new_arrows(self, *args): Logger.debug( "Board: adding new arrows to {}".format( self.character.name ) ) for arrow_orig in self.character.portal: for arrow_dest in self.character.portal[arrow_orig]: if ( arrow_orig not in self.arrow or arrow_dest not in self.arrow[arrow_orig] ): self.arrowlayout.add_widget( self.make_arrow( self.character.portal[arrow_orig][arrow_dest] ) ) def add_pawn(self, thingn, *args): if ( thingn in self.character.thing and thingn not in self.pawn ): pwn = self.make_pawn(self.character.thing[thingn]) locn = pwn.thing['location'] nextlocn = pwn.thing['next_location'] if nextlocn is None: self.add_spot(nextlocn) whereat = self.spot[locn] else: self.add_arrow(locn, nextlocn) whereat = self.arrow[locn][nextlocn] whereat.add_widget(pwn) self.pawn[thingn] = pwn def _trigger_add_pawn(self, thingn): part = partial(self.add_pawn, thingn) Clock.unschedule(part) Clock.schedule_once(part, 0) def add_new_pawns(self, *args): Logger.debug( "Board: adding new pawns to {}".format( self.character.name ) ) nodes_patch = {} pawns_added = [] for (thing_name, thing) in self.character.thing.items(): if thing_name not in self.pawn: pwn = self.make_pawn(thing) pawns_added.append(pwn) patch = {} if '_image_paths' in thing: zeroes = [0] * len(thing['_image_paths']) else: patch['_image_paths'] = Pawn.default_image_paths zeroes = [0] * len(Pawn.default_image_paths) if '_offxs' not in thing: patch['_offxs'] = zeroes if '_offys' not in thing: patch['_offys'] = zeroes if '_stackhs' not in thing: patch['_stackhs'] = zeroes if patch: nodes_patch[thing_name] = patch try: whereat = self.arrow[ pwn.thing['location'] ][ pwn.thing['next_location'] ] except KeyError: whereat = self.spot[pwn.thing['location']] whereat.add_widget(pwn) self.pawn[thing_name] = pwn if nodes_patch: self.engine.handle( 'update_nodes', char=self.character.name, patch=nodes_patch, silent=True ) for pwn in pawns_added: pwn.finalize() @trigger def trigger_update(self, *args): """Force an update to match the current state of my character. This polls every element of the character, and therefore causes me to sync with the LiSE core for a long time. Avoid when possible. """ # remove widgets that don't represent anything anymore Logger.debug("Board: updating") self.remove_absent_pawns() self.remove_absent_spots() self.remove_absent_arrows() # add widgets to represent new stuff self.add_new_spots() self.add_new_arrows() self.add_new_pawns() self.spots_unposd = [ spot for spot in self.spot.values() if not ('_x' in spot.remote and '_y' in spot.remote) ] def update_from_diff(self, chardiff, *args): """Apply the changes described in the dict ``chardiff``.""" for (place, extant) in chardiff['places'].items(): if extant and place not in self.spot: self.add_spot(place) spot = self.spot[place] if '_x' not in spot.place or '_y' not in spot.place: self.new_spots.append(spot) self.spots_unposd.append(spot) elif not extant and place in self.spot: self.rm_spot(place) for (thing, extant) in chardiff['things'].items(): if extant and thing not in self.pawn: self.add_pawn(thing) elif not extant and thing in self.pawn: self.rm_pawn(thing) for (node, stats) in chardiff['node_stat'].items(): if node in self.spot: spot = self.spot[node] if '_x' in stats: spot.x = stats['_x'] * self.width if '_y' in stats: spot.y = stats['_y'] * self.height if '_image_paths' in stats: spot.paths = stats['_image_paths'] elif node in self.pawn: pawn = self.pawn[node] if 'location' in stats: pawn.loc_name = stats['location'] if 'next_location' in stats: pawn.next_loc_name = stats['next_location'] if '_image_paths' in stats: pawn.paths = stats['_image_paths'] else: raise ValueError( "Diff tried to change stats of " "nonexistent node {}".format(node) ) for ((orig, dest), extant) in chardiff['portals'].items(): if extant and (orig not in self.arrow or dest not in self.arrow[orig]): self.add_arrow(orig, dest) elif not extant and orig in self.arrow and dest in self.arrow[orig]: self.rm_arrow(orig, dest) def trigger_update_from_diff(self, chardiff, *args): part = partial(self.update_from_diff, chardiff) Clock.unschedule(part) Clock.schedule_once(part, 0) def on_spots_unposd(self, *args): # TODO: If only some spots are unpositioned, and they remain # that way for several frames, put them somewhere that the # user will be able to find. if not (self.spots_unposd and self.new_spots) or len(self.spots_unposd) != len(self.new_spots): return for spot in self.new_spots: if spot not in self.spots_unposd: self.new_spots = self.spots_unposd = [] return # No spots have positions; # do a layout. try: bounds = detect_2d_grid_layout_bounds(spot.name for spot in self.new_spots) Clock.schedule_once(partial(self.grid_layout, *bounds), 0) except ValueError: Clock.schedule_once(self.nx_layout, 0) def _apply_node_layout(self, l): node_upd = {} for spot in self.new_spots: (x, y) = l[spot.name] assert 0 <= x <= 0.98 assert 0 <= y <= 0.98 node_upd[spot.name] = { '_x': x, '_y': y } spot.pos = ( int(x * self.width), int(y * self.height) ) if node_upd: self.engine.handle( 'update_nodes', char=self.character.name, patch=node_upd, silent=True ) self.new_spots = self.spots_unposd = [] def grid_layout(self, minx, miny, maxx, maxy, *args): l = normalize_layout( {spot.name: spot.name for spot in self.new_spots}, minx, miny, maxx, maxy ) self._apply_node_layout(l) def nx_layout(self, *args): for spot in self.new_spots: if not (spot.name and spot.remote): Clock.schedule_once(self.nx_layout, 0) return spots_only = self.character.facade() for thing in list(spots_only.thing.keys()): del spots_only.thing[thing] self._apply_node_layout(self.graph_layout(spots_only)) def arrows(self): """Iterate over all my arrows.""" for o in self.arrow.values(): for arro in o.values(): yield arro def pawns_at(self, x, y): """Iterate over pawns that collide the given point.""" for pawn in self.pawn.values(): if pawn.collide_point(x, y): yield pawn def spots_at(self, x, y): """Iterate over spots that collide the given point.""" for spot in self.spot.values(): if spot.collide_point(x, y): yield spot def arrows_at(self, x, y): """Iterate over arrows that collide the given point.""" for arrow in self.arrows(): if arrow.collide_point(x, y): yield arrow
class KvWindow(KvWidget, ProxyWindow): """ A Qt implementation of an Enaml ProxyWindow. """ #: A reference to the toolkit widget created by the proxy. widget = Instance(Widget) #-------------------------------------------------------------------------- # Initialization API #-------------------------------------------------------------------------- def create_widget(self): """ Create the QWindow widget. """ app = KvApplication.instance() self.widget = FloatLayout() app.root = self.widget def init_widget(self): """ Initialize the widget. """ super(KvWindow, self).init_widget() d = self.declaration if d.title: self.set_title(d.title) if -1 not in d.initial_size: self.widget.size = d.initial_size if -1 not in d.initial_position: self.widget.position = d.initial_position if d.modality != 'non_modal': self.set_modality(d.modality) if d.icon: self.set_icon(d.icon) #-------------------------------------------------------------------------- # Public API #-------------------------------------------------------------------------- def central_widget(self): """ Find and return the central widget child for this widget. Returns ------- result : QWidget or None The central widget defined for this widget, or None if one is not defined. """ d = self.declaration.central_widget() if d is not None: return d.proxy.widget #-------------------------------------------------------------------------- # Child Events #-------------------------------------------------------------------------- def child_added(self, child): """ Handle the child added event for a QtWindow. """ super(KvWindow, self).child_added(child) if isinstance(child, KvWidget): self.widget.add_widget(child.widget) def child_removed(self, child): """ Handle the child added event for a QtWindow. """ super(KvWindow, self).child_removed(child) if isinstance(child, KvWidget): self.widget.remove_widget(child.widget) #-------------------------------------------------------------------------- # ProxyWindow API #-------------------------------------------------------------------------- def set_title(self, title): """ Set the title of the window. """ app = KvApplication.instance() app.proxy.title = str(title) def set_modality(self, modality): """ Set the modality of the window. """ return def set_icon(self, icon): """ Set the window icon. """ app = KvApplication.instance() app.proxy.icon = str(icon) def position(self): """ Get the position of the of the window. """ return Pos(*self.widget.position) def set_position(self, pos): """ Set the position of the window. """ self.widget.move(*pos) def size(self): """ Get the size of the window. """ return self.widget.size def set_size(self, size): """ Set the size of the window. """ self.widget.size = size def geometry(self): """ Get the geometry of the window. """ return Rect(self.widget.x, self.widget.y, self.widget.width, self.widget.height) def set_geometry(self, rect): """ Set the geometry of the window. """ rect = QRect(*rect) if rect.isValid(): self.widget.setGeometry(rect) def frame_geometry(self): """ Get the geometry of the window. """ rect = self.widget.frameGeometry() return Rect(rect.x(), rect.y(), rect.width(), rect.height()) def maximize(self): """ Maximize the window. """ self.widget.maximize() def is_maximized(self): """ Get whether the window is maximized. """ return bool(self.widget.windowState() & Qt.WindowMaximized) def minimize(self): """ Minimize the window. """ self.widget.minimize() def is_minimized(self): """ Get whether the window is minimized. """ return bool(self.widget.windowState() & Qt.WindowMinimized) def restore(self): """ Restore the window after a minimize or maximize. """ self.widget.restore() def send_to_front(self): """ Move the window to the top of the Z order. """ self.widget.raise_window() def send_to_back(self): """ Move the window to the bottom of the Z order. """ #self.widget.lo pass def activate_window(self): """ Activate the underlying window widget. """ pass #self.widget.activateWindow() #if sys.platform == 'win32': # # For some reason, this needs to be called twice on Windows # # in order to get the taskbar entry to flash. # self.widget.activateWindow() def center_on_screen(self): """ Center the window on the screen. """ widget = self.widget rect = QRect(QPoint(0, 0), widget.frameGeometry().size()) geo = QApplication.desktop().screenGeometry(widget) widget.move(geo.center() - rect.center()) def center_on_widget(self, other): """ Center the window on another widget. """ widget = self.widget rect = QRect(QPoint(0, 0), widget.frameGeometry().size()) other_widget = other.proxy.widget if other_widget.isWindow(): geo = other_widget.frameGeometry() else: size = other_widget.size() point = other_widget.mapToGlobal(QPoint(0, 0)) geo = QRect(point, size) widget.move(geo.center() - rect.center()) def close(self): """ Close the window. """ self.widget.close()
class ebotsScreen(Screen): '''this class is written without real time function for monitoring the ebots location due to the limitations of our knowledge on the ebots. hence, the information is superimposed with pictures instead. however, should self.intruder == True , this screen will be triggered to example display how guards will be alerted by the app after pressing the refresh button''' def __init__(self, **kwargs): Screen.__init__(self, **kwargs) self.tryout = StackLayout(orientation ='lr-bt') self.floatt = FloatLayout() #variable for gettinginformation() self.counter = 0 # Title of the screen self.floatt.add_widget(Label(text='[color=000000][size=40][font=yorkwhiteletter]EBOTS INFORMATION[/font][/size][/color]', size_hint=(0.5,0.2),markup=True,pos_hint={'x':0.05,'y':0.8})) #information on ebots with 'good' status self.ebotgoodpic = Image(source='C:\Users\The Gt Zan\Pictures\ebotinfo.PNG') self.floatt.add_widget(self.ebotgoodpic) #buttons at the bottom self.switchtomenu = Button(text='[size=50][font=yorkwhiteletter][color=000000]MENU[/font][/size][/color]',markup=True, size_hint=(0.2,0.2),background_color=(1,1,1,0),on_press=self.changeToMenu) self.switchtoebot = Button(text='[size=50][font=yorkwhiteletter][color=000000]EBOTS[/font][/size][/color]', markup=True,size_hint=(0.2,0.2),background_color=(1,1,1,0),on_press=self.changeToebots) self.switchtopersonal = Button(text='[size=50][font=yorkwhiteletter][color=000000]INDIVIDUAL[/font][/size][/color]', markup=True,size_hint=(0.2,0.2),background_color=(1,1,1,0),on_press=self.changeToPersonal) self.tryout.add_widget(self.switchtoebot) self.tryout.add_widget(self.switchtopersonal) self.tryout.add_widget(self.switchtomenu) #getting information self.refresh=Button(text='[size=50][font=yorkwhiteletter][color=000000]REFRESH[/font][/size][/color]', markup = True, size_hint=(0.2,0.2),background_color=(1,1,1,0),on_press=self.gettinginformation) self.tryout.add_widget(self.refresh) #add layouts self.add_widget(self.tryout) self.add_widget(self.floatt) def gettinginformation(self,value): self.intruder = fire.get('/intruder/') #actual # self.intruder = True #variable for testing only if self.intruder == True: if self.counter == 0: self.refresh.text = '[size=50][font=yorkwhiteletter][color=000000]CLEAR[/font][/size][/color]' self.ebotgoodpic.pos_hint={'x':0.0,'y':0.15} #to move the image upwards self.ebotintruderfound= Image(source='C:\Users\The Gt Zan\Pictures\ebotinforbad.PNG',pos_hint={'x':0.0,'y':-0.1}) self.floatt.add_widget(self.ebotintruderfound) else: #upon clearing, the ebot page will only show info of the robots in 'normal' status self.ebotgoodpic.pos_hint = {'x':0.0,'y':0.0} self.floatt.remove_widget(self.ebotintruderfound) #to clear intruder status ebot when the button in state 'clear' is pressed self.refresh.text = '[size=50][font=yorkwhiteletter][color=000000]REFRESH[/font][/size][/color]' else: #self.intruder == False , there isn't a need to display the warning 'intruder detected' ebot alert if self.counter ==0: self.refresh.text = '[size=50][font=yorkwhiteletter][color=000000]CLEAR[/font][/size][/color]' self.ebotgoodpic.pos_hint={'x':0.0,'y':0.0} else: self.refresh.text = '[size=50][font=yorkwhiteletter][color=000000]REFRESH[/font][/size][/color]' self.counter +=1 #is to increase self.counter = self.counter % 2 #mod two so that counter remains at 0 or 1 only # print self.intruder #for monitoring on command prompt only return self.refresh.text def changeToMenu(self,value): self.manager.transition.direction = 'right' self.manager.current= 'menu' def changeToebots(self,value): self.manager.transition.direction = 'right' self.manager.current= 'bots' def changeToPersonal(self,value): self.manager.transition.direction = 'right' self.manager.current= 'individual'
class TwistedClientApp(App): ''' ''' connection = None user_os = None user = None labelmsg = "" chat_online_details = "" haha = [] y=0 notify_events = [] available_users = [] def build(self): root = self.initialise_setup() self.start_thread() return root def initialise_setup(self): '''variable initialisation''' self.layout = FloatLayout(size=(800,800)) self.Mainlabel = Label(text="SharePy",color=(0.6,0.7,0.2,1),font_size="65sp",pos=(280,450),size_hint=(.3,.3)) self.layout.add_widget(self.Mainlabel) self.cont_but = Button(text="Cont...",background_color=(0.2,0.3,0.88,1),pos=(700,30),size_hint=(.12,.1)) self.layout.add_widget(self.cont_but) self.INFO = Label(size_hint=(.3,.3),pos=(230,300),color=(0.6,0.3,0.1,1),font_size="21dp") self.INFO2 = Label(size_hint=(.3,.3),pos=(230,150),color=(0.3,0.3,0.7,1),font_size="21dp") self.INFO.text = "SharePy is a project based on File Sharing.\nIts a project developed in Kivy using Python.\n\nBasic Features include:\n " self.INFO2.text = self.INFO2.text + "\n-> Zero Configuration\n-> File Transfering\n-> File Syncing\n-> File Searching\n-> Notification Broadcasting on File Events\n-> ChatBot for communication between Clients\n-> File Listing" self.INFO3 = Label(text="Members:\nVarun Malhotra\nMayank Bhola\nHarsh Bhatia",color=(0.7,0.1,0.1,1),pos=(150,40),size_hint=(0.2,0.2),font_size="21dp") self.layout.add_widget(self.INFO) self.layout.add_widget(self.INFO2) self.layout.add_widget(self.INFO3) self.anim_info2 = Animation(x=80,y=150, opacity=0.4, d=0.4,t ='in_quad') +\ Animation(x=230,y=150, opacity=1, d=0.5) self.anim_info2.start(self.INFO2) self.anim_info3 = Animation(x=80,y=20, opacity=0.4, d=0.6,t ='in_quad') +\ Animation(x=150,y=20, opacity=1, d=0.8) self.anim_info3.start(self.INFO3) self.cont_but.bind(on_press=self.setup_gui) return self.layout def setup_gui(self,object): ''' The layout for the app goes here ''' global user user = getpass.getuser() global user_os user_os = platform.system() self.Mainlabel = Label(text="SharePy",color=(0.6,0.7,0.2,1),font_size="65sp",pos=(280,450),size_hint=(.3,.3)) self.label = TextInput(hint_text='Connecting...\n',size_hint=(.68,.5),pos=(20,120),readonly=True,focus=True) self.dir_loc = TextInput(hint_text='Your root directory is: ',size_hint=(.68,.07),pos=(20,430),readonly=True,background_color=(192,192,192,0.3),foreground_color=(255,255,255,1)) self.button =Button(text="Start Client",size_hint=(.2,.2),background_color=(0.7,0.2,0.3,1),pos=(50,100)) self.ctexthost = TextInput(text="localhost",hint_text="Enter host",size_hint=(.2,.1),pos=(-150,350),multiline=False,background_color=(0.4,0.5,1,0.9),foreground_color=(255,255,255,1)) self.ctextport = TextInput(text="8000",hint_text="Enter port",size_hint=(.2,.1),pos=(-150,250),multiline=False,background_color=(0.4,0.5,1,.9),foreground_color=(255,255,255,1)) self.button1 = ToggleButton(text="Search a File",size_hint=(.2,.2),pos=(10,500),group="file_share",font_size='18sp') self.button2 = ToggleButton(text="Get a File",size_hint=(.2,.2),pos=(210,500),group="file_share",font_size="18sp") self.button3 = Button(text="Search a File",size_hint=(.17,.15),pos=(20,520),background_color=(0.5,0.7,1,1),font_size="18sp") self.button4 = Button(text="List Directory",size_hint=(.17,.15),pos=(150,520),background_color=(0.4,1,0.3,1),font_size="18sp") self.button4.bind(on_press=self.opentextinput) self.closeclient = Button(text="Close Client",pos=(425,520),size_hint=(0.17,0.15),background_color=(0.8,0.3,0.1,1),font_size="18sp") self.closeclient.bind(on_press=self.CloseClient) self.notify_ground = TextInput(text="I notify events",pos=(600,0),background_color=(0.7,0.5,0.9,1),size_hint=(.3,1),readonly=True,scroll_y=10) self.chat_ground = TextInput(text="CHAT BOX",pos=(600,0),background_color=(0.7,0.5,0.9,1),size_hint=(.3,1),readonly=True,scroll_y=10) self.chatbox = Button(text="Chat Box",pos=(563,520),size_hint=(0.17,0.15),background_color=(0.3,0.3,0.7,1),font_size="18sp") self.chatbox.bind(on_press=self.chathistory) self.reponame = TextInput(text="Hellosnp",hint_text="Enter RepoName",pos=(200,300),size_hint=(0.5,0.1),multiline=False,focus=True) self.button.bind(on_press=self.connect_to_server) self.label_info = TextInput(text="Hi i'm a alebe;",pos=(0,610),background_color=(0.7,0,0,1),size_hint=(1,.2),readonly=True) self.notify_but = Button(text="Recent events",size_hint=(.17,.15),pos=(290,520),background_color=(0.8,0.2,0.3,1),font_size="18sp") self.notify_but.bind(on_press=self.recent_act) self.cancel_event = Button(text="Close",size_hint=(0.27,0.06),pos=(600,0),background_color=(255,0,0,0.6)) self.cancel_chat = Button(text="Close",size_hint=(0.27,0.06),pos=(600,0),background_color=(255,0,0,0.6)) self.repolabel = Label(text="Create your own Repository/New Folder by providing the name below",pos=(210,320),size_hint=(0.5,0.5),color=(0.6,0.3,0.1,1),font_size="20dp") self.update = Button(text="Update",background_color=(0.3,0.3,0.9,1),size_hint=(.25,.1),pos=(600,550)) self.fetching_server() return self.layout def fetching_server(self): ''' Start server on desired port''' self.layout.clear_widgets() self.layout.add_widget(self.button) self.layout.add_widget(self.Mainlabel) self.layout.add_widget(self.ctexthost) self.layout.add_widget(self.ctextport) self.anim_host = Animation(x=280,y=550, opacity=0.4, d=0.2,t ='in_quad') +\ Animation(x=280,y=450, opacity=1, d=0.2) self.anim_host.start(self.Mainlabel) self.anim_host = Animation(x=0,y=350, opacity=0.4, d=0.5,t ='in_quad') +\ Animation(x=50,y=350, opacity=1, d=0.6) self.anim_host.start(self.ctexthost) self.anim_port = Animation(x=0,y=250, opacity=0.4, d=0.5,t ='in_quad') +\ Animation(x=50,y=250, opacity=1, d=0.6) self.anim_port.start(self.ctextport) self.anim_startbut = Animation(x=0,y=100, opacity=0.4, d=0.5,t ='in_quad') +\ Animation(x=50,y=100, opacity=1, d=0.6) self.anim_startbut.start(self.button) def repo_creation(self): ''' creation of repo to work in''' self.layout.clear_widgets() self.layout.add_widget(self.repolabel) self.layout.add_widget(self.reponame) self.reponame.bind(on_text_validate=self.building_utilities) return self.layout def building_utilities(self, *args): ''' providing the services to the client''' root_dirname = self.reponame.text if not os.path.exists(root_dirname): os.makedirs(root_dirname) os.chdir(root_dirname) self.dir_loc.text = os.getcwd() self.layout.clear_widgets() self.layout.add_widget(self.button3) self.layout.add_widget(self.button4) self.layout.add_widget(self.closeclient) self.layout.add_widget(self.notify_but) self.layout.add_widget(self.chatbox) self.layout.add_widget(self.label) self.layout.add_widget(self.dir_loc) self.layout.add_widget(self.label_info) self.anim_host = Animation(x=20,y=520, opacity=0.4, d=0.5,t ='in_quad') +\ Animation(x=20,y=480, opacity=1, d=0.6) self.anim_host.start(self.button3) self.anim_port = Animation(x=155,y=520, opacity=0.1, d=0.5,t ='in_quad') +\ Animation(x=155,y=480, opacity=1, d=0.6) self.anim_port.start(self.button4) self.anim_button = Animation(x=290,y=520, opacity=0.1, d=0.5,t ='in_quad') +\ Animation(x=290,y=480, opacity=1, d=0.6) self.anim_button.start(self.notify_but) self.anim_close = Animation(x=425,y=520, opacity=0.1, d=0.5,t ='in_quad') +\ Animation(x=425,y=480, opacity=1, d=0.6) self.anim_close.start(self.closeclient) self.anim_chat = Animation(x=563,y=520, opacity=0.1, d=0.5,t ='in_quad') +\ Animation(x=563,y=480, opacity=1, d=0.6) self.anim_chat.start(self.chatbox) return self.layout def connect_to_server(self,*args): ''' connection establishing (handshaking)''' if((self.ctextport.text).isdigit()): self.conn = reactor.connectTCP(str(self.ctexthost.text), int(self.ctextport.text), EchoFactory(self)) self.label.text = "Connecting...\n" else: self.label.text = "Not Connected...\nPlease enter valid port" def on_connection(self, connection): ''' on successful establishment with server''' self.print_message("Connected Succesfully!") self.connection = connection self.repo_creation() def send_message(self,connection): ''' client demands resources ''' msg = self.textbox.text if msg and self.connection: msg = "2$#" + user + "@" + user_os + ": " + msg self.connection.write(str(msg)) self.textbox.text = "" def print_message(self, msg): ''' the processed output client gets on demanding resources ''' copr = msg.split("$#")[0] if copr.isdigit(): if (int(copr)==2): self.label.text = msg.split("$#")[1] + "\n" #print msg.split("$#")[1] elif (int(copr)==8): self.sendarea.text = self.sendarea.text + msg.split("8$#")[1] + "\n" print "recveived msg - " + (msg.split("8$#")[1]).split("##")[1] + " from ip add" + (msg.split("8$#")[1]).split("##")[0] elif (int(copr)==4): msg = msg.split("$#")[1] g = msg.split(": <")[1] o = g.split(": ")[0] if o=="FileMovedEvent": d = g.split(": src_path=")[1] e = d.split(", ")[0] f = d.split(", ")[1] f1 = f.split(">")[0] msg = "A file at\n" + e + "\nis moved to\n" + f1 else: of = g.split(": ")[1] print o f = g.split("src_path=")[1] f1 = f.split(">")[0] msg = "A file at\n" + f1 + "\n is " + o self.layout.remove_widget(self.label_info) self.layout.add_widget(self.label_info) self.label_info.text = str(msg) self.anim = Animation(x=0,y=550, opacity=0, d=1, t='in_back') +\ Animation(x=0,y=480, d=1, opacity=0.8) +\ Animation(x=0,y=480, d=4,opacity=1) +\ Animation(x=0,y=650, opacity=0, d=2) self.anim.start(self.label_info) self.notify_events.append(str(msg)) elif (int(copr)==5): msg = msg.split("$#")[1] msg = msg.split(',') self.chat_ground.text = " " self.haha = [0]*30 self.y = 0 for on in range (0,len(msg)-1): self.haha[on] = Button(text=str(msg[on]),background_color=(0,1,0,1),pos=(600,515-self.y),size_hint=(0.25,0.07)) self.layout.add_widget(self.haha[on]) self.haha[on].bind(on_press= partial(self.open_chat_for,msg[on])) self.y=self.y+45 self.layout.add_widget(self.update) return self.layout else: self.label.text = msg + "\n" def opentextinput(self, *args): ''' for sending a message to server or searching for ''' self.textbox = TextInput(size_hint=(.9,.1),pos=(0,0), multiline=False,focus=True) self.textbox.bind(on_text_validate=self.send_message) self.closebutton = Button(text="Close",size_hint=(.1,.1),pos=(720,0),background_color=(255,0,0,1)) self.closebutton.bind(on_press=self.close_input_editor) self.layout.add_widget(self.textbox) self.layout.add_widget(self.closebutton) def close_input_editor(self, *args): ''' closing the requester -- textbox ''' self.layout.remove_widget(self.closebutton) self.layout.remove_widget(self.textbox) def CloseClient(self, *args): ''' client wants to disconnect with the server ''' self.conn.disconnect() self.layout.clear_widgets() #os.chdir(cd..) self.repo_creation() path = os.path.dirname(os.getcwd()) os.chdir(path) #output = subprocess.Popen(["cd.."],stdout=subprocess.PIPE).communicate()[0] print os.getcwd() return self.layout def chathistory(self, *args): ''' maintaining conversational history ''' self.layout.remove_widget(self.chatbox) self.layout.clear_widgets() self.sendarea = Label(text=" ",size_hint=(.2,.2),pos=(80,400),font_size="19dp",color=(0.7,0.5,0.6,1)) self.layout.add_widget(self.sendarea) self.update.bind(on_press=self.cancel_chat_box) self.layout.add_widget(self.chat_ground) self.backbutton = Button(text="Back <-",background_color=(1,0.1,0.1,1),size_hint=(.11,.1),pos=(30,500),font_size="20dp") self.layout.add_widget(self.backbutton) self.backbutton.bind(on_press=self.building_utilities) #self.layout.add_widget(self.cancel_chat) #self.cancel_chat.bind(on_press=self.cancel_chat_box) self.chat_online_details = "5$#" + user + "@" + user_os + ": " + "Ready to chat" #print self.chat_online_details self.connection.write(str(self.chat_online_details)) #return self.layout def stimulate_on_repo_changes(self): ''' checking for any file events in the current repo ''' while True: #self.logging.basicConfig(level=logging.INFO,format='%(asctime)s - %(message)s',datefmt='%Y-%m-%d %H:%M:%S') self.path = sys.argv[1] if len(sys.argv) > 1 else os.getcwd() self.event_handler = ChangeHandler(self) self.observer = Observer() self.observer.schedule(self.event_handler, self.path, recursive=True) self.observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: self.observer.stop() self.observer.join() def start_thread(self): t = Thread(target=self.stimulate_on_repo_changes) t.start() def notify(self,textevent): textevent1 = "4$#" + user + "@" + user_os + ": " + str(textevent) #textevent = "4$#" + textevent self.connection.write(str(textevent1)) return self.layout def dismiss_popup(instance): return False def recent_act(self, textevent): self.layout.remove_widget(self.notify_but) self.layout.add_widget(self.notify_ground) self.anim_ground = Animation(x=700,y=0, opacity=0.3, d=0.2,t ='in_quad') +\ Animation(x=600,y=0, opacity=1, d=0.2) self.anim_ground.start(self.notify_ground) self.layout.add_widget(self.cancel_event) self.cancel_event.bind(on_press=self.cancel_event_window) self.notify_ground.text = "" for l in self.notify_events: self.notify_ground.text = self.notify_ground.text + str(l) + '\n' return self.layout def cancel_event_window(self,*args): self.layout.remove_widget(self.notify_ground) self.layout.remove_widget(self.cancel_event) self.layout.add_widget(self.notify_but) return self.layout def cancel_chat_box(self,args): self.layout.clear_widgets() self.chathistory() return self.layout def open_chat_for(self,ipadd,args): self.chat_lid = TextInput(hint_text="Send msg",pos=(100,50),size_hint=(.6,.1),multiline=False,focus=True) self.layout.add_widget(self.chat_lid) self.chat_lid.bind(on_text_validate=partial(self.send_to_ip,ipadd)) def send_to_ip(self,ipadd,args): print "send msg - '" + self.chat_lid.text +"' to ip address - "+ipadd self.connection.write("8$#"+str(ipadd)+"##"+str(self.chat_lid.text)) self.chat_lid.text = "" self.chat_lid.focus = True
class RemoveUser(Popup): ## # Class Constructor: __init__ # --------------------------- # This method is called during creation of the RemoveUser class. # This function creates the layout for the popup as well as initializes all the # popup attributes. # # @params # (RemoveUser) self This instance of RemoveUser # (Various) **kwargs Arguments for constuction of internal Popup object ## def __init__(self, **kwargs): self.layout = FloatLayout(size=(Window.width, 200)) super(RemoveUser, self).__init__(title='Remove User', content=self.layout, size_hint=(None,None), size=(400,200), background=BKGD_DCHRC, pos_hint={"center_x":.5, 'top':.7}, auto_dismiss=False, **kwargs) ## # Class Method: draw_layout # ------------------------- # This method creates the entire layout for the remove user popup including # the dropdown from which to select group users to remove # # @params # (RemoveUser) self This instance of RemoveUser ## def draw_layout(self): self.button_x = .5 if manager.CURRENT_GROUP != None: self.button_x = .3 self.dropdown = DropDown(auto_width=False, width=180, max_height=180) self.dropdown.main_button = HoverButton(text="Select User", size=(180,40), size_hint=(None,None), pos_hint={"center_x":.5, 'top':.8}, button_down=DD_DCHRC[1], button_up=DD_DCHRC[0], on_release=self.dropdown.open) self.layout.add_widget(self.dropdown.main_button) self.remove_user_dropdown() self.layout.add_widget(HoverButton(text="Remove", button_down=BTN_DCHRC[1], button_up=BTN_DCHRC[0], font_size=14, size_hint=(None,None), size=(100,40), pos_hint={"center_x":.7, 'top':.35}, on_press=self.remove_from_group)) else: self.layout.add_widget(Label(text="No Group Selected", font_size=14, pos_hint={"center_x":.5, 'top':1.2})) self.layout.add_widget(HoverButton(text="Cancel", button_down=BTN_DCHRC[1], button_up=BTN_DCHRC[0], font_size=14, size_hint=(None,None), size=(100,40), pos_hint={"center_x":self.button_x, 'top':.35}, on_press=self.dismiss)) ## # Class Method: select_user # ------------------------- # This method sets the main button to the user selected and closes the dropdown # # @params # (RemoveUser) self This instance of RemoveUser # (HoverButton) instance The button of the user that has been selected ## def select_user(self, instance): self.dropdown.dismiss() self.dropdown.main_button.text = instance.text if len(self.group_members) == 1: for child in self.layout.children: if type(child) == Label and child.text == "Please Select a User to Remove" or\ child.text == "Deleting this user will delete the Group! Proceed with caution": self.layout.remove_widget(child) self.layout.add_widget(Label(text="Deleting this user will delete the Group! Proceed with caution", color = (1, 0, 0, 1), font_size = 11, pos_hint={"center_x":.5, "top":1.95})) ## # Class Method: remove_user_dropdown # ---------------------------------- # This method adds all of the current grop members to the dropdown to be selected # for removal # # @params # (RemoveUser) self This instance of RemoveUser ## def remove_user_dropdown(self): self.group_members = database.get_group_members(manager.CURRENT_GROUP) for user in self.group_members: self.dropdown.add_widget(HoverButton(text=user[0], button_up=DD_DCHRC[0], button_down=DD_DCHRC[1], font_size=12, size=(180,30), size_hint=(None,None), on_release=self.select_user)) ## # Class Method: remove_from_group # ------------------------------- # This method removes the selected user from the group. In the case where no user is selected, # an error message is provided to inform the end user. # # @params # (RemoveUser) self This instance of RemoveUser # (HoverButton) instance The button that triggers the call to remove_from_group ## def remove_from_group(self, instance): user = self.dropdown.main_button.text if user == 'Select User': for child in self.layout.children: if type(child) == Label and child.text == "Please Select a User to Remove" or\ child.text == "Deleting this user will delete the Group! Proceed with caution": self.layout.remove_widget(child) self.layout.add_widget(Label(text="Please Select a User to Remove", color = (1, 0, 0, 1), font_size = 11, pos_hint={"center_x":.5, "top":1.95})) return database.remove_group_member(user, manager.CURRENT_GROUP) if len(self.group_members) == 1: manager.menu.show_groups() manager.menu.info_panel.clear() else: manager.menu.display_group_info(manager.CURRENT_GROUP) self.dismiss() ## # Class Method: open_popup # ------------------------ # This method is called to clear the widgets of the current popup layout and redraw the # layout according to the current situation. # # @params # (RemoveUser) self This instance of RemoveUser ## def open_popup(self): self.layout.clear_widgets() self.draw_layout() self.open()
class GmApp(App): #kivy's run calls build. def build(self): self.initialize() self.layout = FloatLayout(size=(cfg.GRID_SIZE * cfg.BLOCK_SIZE, cfg.GRID_SIZE * cfg.BLOCK_SIZE + (2 * cfg.BLOCK_SIZE))) height = cfg.GRID_SIZE - 1 while height >= 0: width = 0 while width < cfg.GRID_SIZE: # Create the button button = Button( text='%d,%d' % (width, height), font_size=6, size_hint=((1 / cfg.GRID_SIZE), (1 / cfg.GRID_SIZE)), pos=((width * cfg.BLOCK_SIZE), (height * cfg.BLOCK_SIZE + (2 * cfg.BLOCK_SIZE))), # pos=((width * (1 / cfg.GRID_SIZE)), (height * (1 / cfg.GRID_SIZE) + (2 * (1 / cfg.GRID_SIZE)))), background_color=[0, 1, 0, 1]) self.layout.add_widget(button, 10) self.gmGrid[width][height].button = button width += 1 height -= 1 play_button = Button( text='ply', font_size=6, size_hint=(((1 / cfg.GRID_SIZE) * 8), ((1 / cfg.GRID_SIZE) * 1.5)), pos_hint={'center_x': .5, 'y': .0}, background_color=[1, 0, 0, 1]) play_button.bind(on_press=self.callback) self.layout.add_widget(play_button) return self.layout def callback(self, instance): print('The <%s> button was pressed' % instance.text) if instance.text is 'ply': Clock.schedule_interval(self.ply, cfg.SLEEP_TIME) def AddWidget(self, widget): self.layout.add_widget(widget, 0) self.layout.do_layout() def RemoveWidget(self, widget): self.layout.remove_widget(widget) self.layout.do_layout() def ply(self, whoAmI): # print(whoAmI) # done = 0 counter = 1 print('Begin ply') counter += 1 self.AdvancePlrs() if self.GmDone(): Clock.unschedule(self.ply) self.UpdateBlots() self.CheckForHits() def AdvancePlrs(self): for plr in self.plrs: # Do nothing if done or hit if plr.status == cfg.PLR_DONE or plr.status == cfg.PLR_HIT: continue # Remove the current player button if plr.status == cfg.PLR_GOING: self.RemoveWidget(plr.getButton()) # Advance plr.x += 1 plr.y += 1 # Test for done if plr.x == cfg.GRID_SIZE: plr.status = cfg.PLR_DONE self.plrsMadeIt += 1 elif plr.x == 0: plr.status = cfg.PLR_GOING if plr.status == cfg.PLR_GOING: # Update the players button then the grid plr.setButton() self.AddWidget(plr.getButton()) def initialize(self): self.logger = logging.getLogger('driver.modules.Gm.GmApp') self.logger.info('Initializing Grid') self.grid = [[GridPoint() for _ in range(0, cfg.GRID_SIZE)] for _ in range(0, cfg.GRID_SIZE)] self.gmGrid = [[GridPoint() for _ in range(0, cfg.GRID_SIZE)] for _ in range(0, cfg.GRID_SIZE)] self.logger.info('Initializing Plrs') self.plrs = [Plr(_) for _ in range(0, cfg.PLR_NUM)] self.blots = [Blot() for _ in range(0, cfg.BLOT_NUM)] self.blotCounter = 0 self.plrsMadeIt = 0 self.plrsHit = 0 self.totalPos = 0 def GmDone(self): for plr in self.plrs: if(plr.status != cfg.PLR_DONE): if(plr.status != cfg.PLR_HIT): return False # Assume done return True def PrintStats(self): print('Plrs : %s' % len(self.plrs)) print('Plrs who made it : %s' % self.plrsMadeIt) print('Plrs hit : %s' % self.plrsHit) print('Percentage safe : %0.2f%%' % (float(self.plrsMadeIt) / float(len(self.plrs)) * float(100))) print('Avg Distance : %s' % self.avgPos) def GetStats(self): for plr in self.plrs: self.totalPos += plr.x self.avgPos = self.totalPos / len(self.plrs) def CheckForHits(self): print('Checking for hits') for plr in self.plrs: print('Checking player %s' % plr.num) if(plr.status != cfg.PLR_GOING): print('Player is not going, skipping') continue else: print('Checking blots') for blot in self.blots: if(blot.status == cfg.BLOT_ACTIVE): distance = Util.Distance(plr, blot) print('distance = %s' % distance) if(distance < blot.size): plr.status = cfg.PLR_HIT self.RemoveWidget(plr.getButton()) self.plrsHit += 1 print('Distance : %s' % distance) print('Player Hit: %s' % plr.PrintPlr()) print('Blot : %s' % blot.PrintBlot()) continue def AddBlot(self, blot): with self.layout.canvas: Line(circle=(blot.x, blot.y, blot.size)) def RemoveBlot(self, blot): with self.layout.canvas.remove(): print('Removing %s, %s' % blot.x, blot.y) Line(circle=(blot.x, blot.y, blot.size)) def UpdateBlots(self): # Get the new blot index newBlotIndex = self.blotCounter % cfg.BLOT_NUM # Get the old blot at that index oldBlot = self.blots[newBlotIndex] # If the old blot is active, remove it from the grid if(oldBlot.status == cfg.BLOT_ACTIVE): print('Removing the old blot') self.RemoveWidget(oldBlot.GetCircle()) pass # Create a new blot, add it to blots and update the grid newBlot = Blot() newBlot.activate() self.blots[newBlotIndex] = newBlot self.AddWidget(newBlot.GetCircle()) print('Added %s, %s, %s' % (newBlot.x, newBlot.y, newBlot.size)) self.blotCounter += 1 for blot in self.blots: # Skip blot if it's not active if blot.status != cfg.BLOT_ACTIVE: continue # Remove blot if it's timer is up if blot.timer < 0: print('Timer up, removing blot') self.RemoveWidget(blot.GetCircle()) # self.RemoveBlot(blot) blot.status = cfg.BLOT_INACTIVE continue blot.timer = blot.timer - 1
class Crear(Screen): def __init__(self, **Kwargs): super(Crear, self).__init__(**Kwargs) self.orientation = "vertical" S = Image(source='imagenes/fondoRojo.jpeg', allow_stretch=True) self.add_widget(S) #añade la imagen al widget self.my_box1 = FloatLayout(size=(300, 300)) # label del PIN self.btnPin = Button(text="Generar PIN", font_size=24, size_hint=(0.3, 0.1), background_color=[0, 1, 0.6, 0.8], pos=(250, 350)) self.btnPin.bind(on_press=self.generarPin) #Boton para ingresar al juego self.btn = Button(text="Inicio", font_size=24, size_hint=(0.1, 0.1), background_color=[0, 1, 0.6, 0.8], pos=(350, 120)) self.btn.bind(on_press=self.changerJuego) self.my_box1.add_widget(self.btn) self.my_box1.add_widget(self.btnPin) self.add_widget(self.my_box1) def generarPin(self, btn): s.sendall(b'PIN') num = s.recv(1024).decode() # reemplazar por el numero de sala varg.setnum(num) my_label = Label(text='[color=ffffff] El PIN es: [/color]' + varg.getnum(), markup=True, font_size="40dp", font_name="Times", size_hint=(0.3, 0.3), pos=(100, 150)) self.my_box1.add_widget(my_label) def changerJuego(self, btn): #Cambiar de pantalla self.my_box1.remove_widget(self.btn) self.my_box1.remove_widget(self.btnPin) my_label = Label(text='[color=ffffff] Esperando... [/color]', markup=True, font_size="40dp", font_name="Times", size_hint=(0.3, 0.3), pos=(150, 100)) self.my_box1.add_widget(my_label) join = "join " + varg.getnum() s.sendall(join.encode()) print(varg.getnum()) message = s.recv(1024).decode() print(message) if (message == "joined room successfully"): esperando = True while (esperando == True): time.sleep(1) s.sendall(b'sala') a = s.recv(1024).decode() if (a != "no"): print(a) info = a.split() users = info[0].split(',') cartas = info[1].split(',') # orden de los usuarios varg.setorden(users) #turno varg.setprimerTurno(users[0]) # nombres de los demás jugadores jugadores = [] for a in users: if (a != varg.getplayer_name()): jugadores.append(a) varg.setjugadores(jugadores) # mis cartas print(users) index = users.index(varg.getplayer_name()) if (index == 0): miscartas = cartas[0:14] varg.setmisCartas(miscartas) varg.setnameTurno("p1") elif (index == 1): miscartas = cartas[14:27] varg.setmisCartas(miscartas) varg.setnameTurno("p2") elif (index == 2): miscartas = cartas[27:40] varg.setmisCartas(miscartas) varg.setnameTurno("p3") elif (index == 3): miscartas = cartas[40:53] varg.setmisCartas(miscartas) varg.setnameTurno("p4") esperando = False print(varg.getnameTurno()) self.manager.current = "Juego"
class AutoPen(App): ''' def __init__(self, **kwargs): super(App, self).__init__(**kwargs) with self.canvas: welcome = Label(text='Welcome to Autopen', size_hint=(.6,.3), pos_hint={'x':.2,'y':.7}, background_color=[1,0,1,0]) self.mainpage.add_widget(welcome) ''' def build(self): self.mainpage = FloatLayout() #btn = Button(text='Back', on_release=self.callback, size_hint=(0.15, 0.1), pos_hint={'x': 0, 'y': .9}) #car = Image(source='AutoPen.png') def MainPage(instance): self.mainpage.clear_widgets( ) #going to have to overwrite this function later self.can = Button(text='CAN', size_hint=(.2, .1), pos_hint={ 'x': .1, 'y': .2 }) self.wifi_SDR = Button(text='Wi-fi/SDR', size_hint=(.2, .1), pos_hint={ 'x': .1, 'y': .6 }) self.bluetooth = Button(text='Bluetooth', size_hint=(.2, .1), pos_hint={ 'x': .7, 'y': .2 }) self.miscellaneous = Button(text='Miscellaneous', size_hint=(.2, .1), pos_hint={ 'x': .7, 'y': .6 }) self.back = Button(text='Back', size_hint=(.1, .05), pos_hint={ 'x': 0, 'y': 0 }) tools_title = Button(text='Tools', size_hint=(.6, .3), pos_hint={ 'x': .2, 'y': .8 }, background_color=[1, 0, 1, 0]) self.mainpage.add_widget(tools_title) #adding buttons to main tools self.mainpage.add_widget(self.can) self.mainpage.add_widget(self.wifi_SDR) self.mainpage.add_widget(self.bluetooth) self.mainpage.add_widget(self.miscellaneous) self.mainpage.add_widget(self.back) self.can.bind(on_press=canPage) self.bluetooth.bind(on_press=bluetoothPage) self.wifi_SDR.bind(on_press=wifi_SDRPage) self.miscellaneous.bind(on_press=miscellaneousPage) def databasePage(instance): self.mainpage.remove_widget(self.welcome) self.mainpage.remove_widget(self.database) self.mainpage.remove_widget(self.howto) self.mainpage.remove_widget(self.terms) self.mainpage.remove_widget(self.tools) self.mainpage.remove_widget(self.search) database_title = Button(text='Database', size_hint=(.6, .3), pos_hint={ 'x': .2, 'y': .7 }, background_color=[1, 0, 0, 0]) self.mainpage.add_widget(database_title) self.create = Button(text='Create New Car', size_hint=(.2, .1), pos_hint={ 'x': .1, 'y': .5 }) self.load = Button(text='Load Car', size_hint=(.2, .1), pos_hint={ 'x': .1, 'y': .4 }) self.back = Button(text='Back', size_hint=(.1, .05), pos_hint={ 'x': 0, 'y': 0 }) self.cont = Button(text='Continue', size_hint=(.1, .05), pos_hint={ 'x': .9, 'y': 0 }) self.mainpage.add_widget(self.create) self.mainpage.add_widget(self.load) self.mainpage.add_widget(self.back) self.mainpage.add_widget(self.cont) #self.tools = Button(text='Tools', size_hint=(.3,.1), pos_hint={'x':.35, 'y':.5}) self.create.bind(on_press=createCarButton) self.load.bind(on_press=loadCarButton) #self.back.bind(on_press=self.mainpage) self.cont.bind(on_press=MainPage) def on_text(instance, value): print('The widget', instance, 'have:', value) def createCarButton(button): layout = button.parent model = TextInput(text='Input Car Model', background_color=[1, 1, 0, 0.5], size_hint=(.3, .1), pos_hint={ 'x': .3, 'y': .5 }) make = TextInput(text='Input Car Make', background_color=[1, 1, 0, 0.5], size_hint=(.3, .1), pos_hint={ 'x': .3, 'y': .4 }) year = TextInput(text='Input Car Year', background_color=[1, 1, 0, 0.5], size_hint=(.3, .1), pos_hint={ 'x': .3, 'y': .3 }) creat = Button(text='Create', size_hint=(.3, .1), pos_hint={ 'x': .3, 'y': .2 }) self.mainpage.add_widget(model) self.mainpage.add_widget(make) self.mainpage.add_widget(year) self.mainpage.add_widget(creat) # print (textinput) def loadCarButton(button): layout = button.parent self.welcome = Button(text='Welcome to Autopen', size_hint=(.6, .3), pos_hint={ 'x': .2, 'y': .7 }, background_color=[1, 0, 1, 1]) self.mainpage.add_widget(self.welcome) self.howto = Button(text='How-To', size_hint=(.3, .1), pos_hint={ 'x': .35, 'y': .4 }) self.search = Button(text='Search', size_hint=(.3, .1), pos_hint={ 'x': .35, 'y': .3 }) self.terms = Button(text='Terms and Conditions', size_hint=(.3, .1), pos_hint={ 'x': .35, 'y': .2 }) self.mainpage.add_widget(self.howto) self.mainpage.add_widget(self.search) self.mainpage.add_widget(self.terms) self.database = Button(text='Register Vehicle', size_hint=(.3, .1), pos_hint={ 'x': .35, 'y': .6 }) self.mainpage.add_widget(self.database) self.database.bind(on_press=databasePage) self.tools = Button(text='Tools', size_hint=(.3, .1), pos_hint={ 'x': .35, 'y': .5 }) self.mainpage.add_widget(self.tools) self.tools.bind(on_press=MainPage) def canutilsPage(instance): self.install = Button(text='Install', size_hint=(.2, .1), pos_hint={ 'x': .4, 'y': .1 }) self.mainpage.add_widget(self.install) #self.install.bind(on_press=test_install.test()) def canPage(instance): self.mainpage.remove_widget(self.can) self.mainpage.remove_widget(self.wifi_SDR) self.mainpage.remove_widget(self.bluetooth) self.mainpage.remove_widget(self.miscellaneous) tools_title = Button(text='Tools', size_hint=(.6, .3), pos_hint={ 'x': .2, 'y': .8 }, background_color=[1, 0, 1, 0]) self.mainpage.add_widget(tools_title) #l = Label(text='CAN Tools', font_size='20sp', halign='left', valign='top', size=(2,2)) can_title = Button(text='CAN Tools', size_hint=(.2, .1), pos_hint={ 'x': .05, 'y': .85 }, background_color=[1, 0, 0, 0.5]) self.mainpage.add_widget(can_title) self.canutils = Button(text='Can-utils', size_hint=(.2, .1), pos_hint={ 'x': .05, 'y': .75 }) canbus_utils = Button(text='Canbus-utils', size_hint=(.2, .1), pos_hint={ 'x': .05, 'y': .65 }) kayak = Button(text='Kayak', size_hint=(.2, .1), pos_hint={ 'x': .05, 'y': .55 }) caringcaribou = Button(text='Caring Caribou', size_hint=(.2, .1), pos_hint={ 'x': .05, 'y': .45 }) c0f = Button(text='c0f', size_hint=(.2, .1), pos_hint={ 'x': .05, 'y': .35 }) UDSim = Button(text='UDSim', size_hint=(.2, .1), pos_hint={ 'x': .05, 'y': .25 }) DO = Button(text='PyOBD', size_hint=(.2, .1), pos_hint={ 'x': .05, 'y': .15 }) O2OO = Button(text='O2OO', size_hint=(.2, .1), pos_hint={ 'x': .05, 'y': .05 }) self.mainpage.add_widget(self.canutils) self.mainpage.add_widget(canbus_utils) self.mainpage.add_widget(c0f) self.mainpage.add_widget(kayak) self.mainpage.add_widget(caringcaribou) self.mainpage.add_widget(UDSim) self.mainpage.add_widget(DO) self.mainpage.add_widget(O2OO) self.back.bind(on_press=MainPage) self.canutils.bind(on_press=canutilsPage) def bluetoothPage(instance): self.mainpage.remove_widget(self.can) self.mainpage.remove_widget(self.wifi_SDR) self.mainpage.remove_widget(self.bluetooth) self.mainpage.remove_widget(self.miscellaneous) tools_title = Button(text='Tools', size_hint=(.6, .3), pos_hint={ 'x': .2, 'y': .8 }, background_color=[1, 0, 1, 0]) self.mainpage.add_widget(tools_title) bluetooth_title = Button(text='Bluetooth Tools', size_hint=(.25, .1), pos_hint={ 'x': .05, 'y': .85 }, background_color=[1, 0, 0, 0.5]) self.mainpage.add_widget(bluetooth_title) bluelog = Button(text='Bluelog', size_hint=(.25, .1), pos_hint={ 'x': .05, 'y': .75 }) bluemaho = Button(text='Bluemaho', size_hint=(.25, .1), pos_hint={ 'x': .05, 'y': .65 }) btscanner = Button(text='BTScanner', size_hint=(.25, .1), pos_hint={ 'x': .05, 'y': .55 }) bluetooth_tools = Button(text='Bluetooth Tools Package', size_hint=(.25, .1), pos_hint={ 'x': .05, 'y': .45 }) install = Button(text='Install', size_hint=(.2, .1), pos_hint={ 'x': .4, 'y': .1 }) self.mainpage.add_widget(bluelog) self.mainpage.add_widget(bluemaho) self.mainpage.add_widget(btscanner) self.mainpage.add_widget(bluetooth_tools) self.mainpage.add_widget(install) self.back.bind(on_press=MainPage) def wifi_SDRPage(instance): self.mainpage.remove_widget(self.can) self.mainpage.remove_widget(self.wifi_SDR) self.mainpage.remove_widget(self.bluetooth) self.mainpage.remove_widget(self.miscellaneous) tools_title = Button(text='Tools', size_hint=(.6, .3), pos_hint={ 'x': .2, 'y': .8 }, background_color=[1, 0, 1, 0]) self.mainpage.add_widget(tools_title) title = Button(text='Wi-fi/SDR Tools', size_hint=(.25, .1), pos_hint={ 'x': .05, 'y': .85 }, background_color=[1, 0, 0, 0.5]) self.mainpage.add_widget(title) aircrack = Button(text='Aircrack-ng', size_hint=(.25, .1), pos_hint={ 'x': .05, 'y': .75 }) gnuradio = Button(text='GNU Radio', size_hint=(.25, .1), pos_hint={ 'x': .05, 'y': .65 }) install = Button(text='Install', size_hint=(.2, .1), pos_hint={ 'x': .4, 'y': .1 }) self.mainpage.add_widget(aircrack) self.mainpage.add_widget(gnuradio) self.mainpage.add_widget(install) self.back.bind(on_press=MainPage) def miscellaneousPage(instance): self.mainpage.remove_widget(self.can) self.mainpage.remove_widget(self.wifi_SDR) self.mainpage.remove_widget(self.bluetooth) self.mainpage.remove_widget(self.miscellaneous) tools_title = Button(text='Tools', size_hint=(.6, .3), pos_hint={ 'x': .2, 'y': .8 }, background_color=[1, 0, 1, 0]) self.mainpage.add_widget(tools_title) miscel_title = Button(text='Miscellaneous Tools', size_hint=(.25, .1), pos_hint={ 'x': .05, 'y': .85 }, background_color=[1, 0, 0, 0.5]) self.mainpage.add_widget(miscel_title) katoolin = Button(text='Katoolin', size_hint=(.25, .1), pos_hint={ 'x': .05, 'y': .75 }) romraider = Button(text='Romraider', size_hint=(.25, .1), pos_hint={ 'x': .05, 'y': .65 }) install = Button(text='Install', size_hint=(.2, .1), pos_hint={ 'x': .4, 'y': .1 }) self.mainpage.add_widget(katoolin) self.mainpage.add_widget(romraider) self.mainpage.add_widget(install) self.back.bind(on_press=MainPage) return self.mainpage
class GameScreen(Screen): def __init__(self, game_session, **kwargs): super(GameScreen, self).__init__(**kwargs) self.time_label = None self.current_load_label = None self.load_plot = None self.locations = [(0.15, 0.15), (0.25, 0.15), (0.38, 0.15), (0.5, 0.15), (0.62, 0.15), (0.73, 0.15)] self.layout = FloatLayout() self.game_session = game_session self.current_load_label = Label( text=str(self.game_session.current_load)) def display(self): background = Image(source="images/background2.png") clinic = Image(source="images/clinic.png", pos_hint={ 'x': .15, 'y': -0.05 }, size_hint=(.7, .7)) sun = Image(source="images/sun.png", size_hint=(.7, .7)) sun.pos_hint = { 'x': .15, 'y': 0.3 } self.layout.add_widget(background) self.layout.add_widget(clinic) self.layout.add_widget(sun) if self.game_session.level.battery > 0: battery = Image(source="images/battery.png", size_hint=(.3, .38), pos_hint={ 'x': .1, 'y': .2 }) self.layout.add_widget(battery) self.time_label = Label(text="00:00:00", font_size='24dp', pos_hint={ 'x': .4, 'y': .01 }, size_hint=(.2, .1)) self.layout.add_widget(self.time_label) back_button = Button(text="<< Menu", font_size='18dp', pos_hint={ 'x': .01, 'y': 0.01 }, size_hint=(.15, .075), on_press=self.callpopup) self.layout.add_widget(back_button) for i, appliance in enumerate(self.game_session.level.appliances): appliance.pos_hint = { 'x': self.locations[i][0], 'y': self.locations[i][1] } appliance.size_hint = (.12, .12) self.layout.add_widget(appliance) self.layout.add_widget(self.current_load_label) self.add_widget(self.layout) Clock.schedule_interval(self.update, 1) Clock.schedule_interval(self.add_drop, 1 / 20) Clock.schedule_interval(self.move_rain, 1 / 20) def add_drop(self, dt): drop = Drop() time = self.game_session.current_time() if self.game_session.level.rain[time[0]] > 0: self.game_session.rain.append(drop) self.layout.add_widget(drop) def move_rain(self, dt): for i, drop in enumerate(self.game_session.rain): drop.pos_hint = { 'y': drop.pos_hint.get('y') - .01, 'x': drop.pos_hint.get('x') } if drop.pos_hint.get('y') < 0: self.layout.remove_widget(drop) del self.game_session.rain[i] del drop def update(self, dt): current_time = self.game_session.current_time() current_supply = self.game_session.level.supply[current_time[0]] current_load = self.game_session.current_load balance = current_supply - current_load hour = ("0" + str(current_time[0]))[-2:] min = ("0" + str(current_time[1]))[-2:] sec = ("0" + str(current_time[2]))[-2:] self.time_label.text = "%s:%s:%s" % (hour, min, sec) self.game_session.time += (12 * 60) / self.game_session.duration self.game_session.set_current_load() self.current_load_label.text = str(self.game_session.current_load) rect_width = 5 rect_height = 100 full_height = 480 space = 1 with self.layout.canvas: # plot supply Color(0, 1, 0, 1.0, mode='rgba') Rectangle(pos=(self.game_session.iteration * (rect_width + space), full_height - rect_height), size=(rect_width, self.game_session.level.supply[current_time[0]] / rect_height)) # plot load Color(0, 0, 1, 1.0, mode='rgba') Rectangle(pos=(self.game_session.iteration * (rect_width + space), full_height - rect_height), size=(rect_width, self.game_session.current_load / rect_height)) # plot overload (battery used) Color(1, 0, 1, 1.0, mode='rgba') if balance < 0: Rectangle(pos=(self.game_session.iteration * (rect_width + space), full_height - rect_height + current_load / rect_height), size=(rect_width, balance / rect_height)) self.game_session.iteration += 1 def callpopup(self, event): MessageBox(self, titleheader="Confirm", message="Are sure you want to quit the game", options={ "YES": "yes()", "NO": "no()" }) def yes(self): self.game_session.level = None self.manager.current = 'welcome_screen' # Todo: Clock unschedule self.manager.remove_widget(self) def no(self): pass
class GamesScreen(Screen): def __init__(self, **kwargs): Screen.__init__(self, **kwargs) with self.canvas: self.rectangle = Rectangle (source = 'game-06.png', size = self.size, pos_hint = self.pos) self.bind(pos = self.update_rect, size = self.update_rect) # Window.bind(on_key_up=self._keyup) Window.bind(on_key_down=self._keydown) self.layout= FloatLayout() self.sm = Typing_sm() self.sm.start() self.diff_lvl = Label(text = 'Level: ' + difficulty[difficulty['choice']], font_size = 24,size_hint = (.1,.1),pos_hint = {'x':0.1, 'y': 0}) self.layout.add_widget(self.diff_lvl) self.life_indicator = Label(text = 'Lives left: 0' + str(life['hearts']), font_size = 24, size_hint = (.1,.1), pos_hint = {'x':0.1, 'y': 0.9}) self.layout.add_widget(self.life_indicator) self.timer = Countdown(font_size = 48, pos_hint = {'x':0, 'y': 0.1}) self.layout.add_widget(self.timer) self.label = Label(text = 'Start', font_size = 24,size_hint =(.1,.1), pos_hint = {'x':.4, 'y': .75}) self.layout.add_widget(self.label) self.reminder = Label (text = 'DOUBLE CLICK TEXTBOX!!', font_size = 24, pos_hint = {'x':0, 'y': 0.1}) self.layout.add_widget(self.reminder) self.total_words = '' self.inp = MyInput(hint_text = "type here", pos_hint = {'x':.4, 'y': .65}, on_double_tap = self.startCountdown) self.layout.add_widget(self.inp) self.add_widget(self.layout) def update_rect(self, *args): self.rectangle.pos = self.pos self.rectangle.size = self.size # def _keyup(self,*args): # print('key up!!', args) def startCountdown(self, *args): self.layout.remove_widget(self.reminder) self.timer.start() def _keydown(self,*args): diff_name = difficulty[difficulty['choice']] word_dic = dictionaries[diff_name] if self.sm.state == 'norm': if args[3] == None and args[1] == 13 and args[2] == 40: #'enter key' user = self.inp.text.strip() word = self.label.text self.sm.step(user, word) self.total_words += user self.inp.text = ' ' self.inp.focus = True num = random.randrange(0, len(word_dic)) word = word_dic[num] self.label.text = word elif self.sm.state == 'wrong' and life['hearts'] > 0: #removing hearts self.remove_widget(self.heartlayout) #update lives and state life['hearts']-= 1 self.sm.state = 'norm' self.life_indicator.text = 'Lives left: 0' + str(life['hearts']) #adding hearts self.heartlayout = FloatLayout() for i in range(life['hearts']): self.hearts = HeartButtons(text = '',pos =(30+ 70*i,500)) self.heartlayout.add_widget(self.hearts) self.add_widget(self.heartlayout) if life['hearts'] == 0: #access the Main widget Screen Manager self.manager.transition.direction = 'up' # modify the current screen to a different "name" fail = sm.get_screen('fail') characters = str(len(self.total_words)) stat = Label(text = 'you typed ' + characters + ' characters per minute.', size_hint=(.1,.1), pos_hint = {'x':.3, 'y': .5}) fail.layout.add_widget(stat) self.manager.current = 'fail' return True
class Transmut(App): def build(self): self.ether = [] self.universe = [] self.data_path = os.path.realpath(os.path.dirname(sys.argv[0])) + os.sep + "Data" + os.sep self.load_ether() #self.test() #self.solution() self.root = FloatLayout() self.screen_menu = Menu(app=self) self.screen_splash = Splash(app=self) sound_intro = SoundLoader.load(filename= self.data_path + '42286__erh__f-eh-angelic-3.ogg') self.sound_find = SoundLoader.load(filename= self.data_path + '30342__junggle__waterdrop25.ogg') sound_intro.play() self.show('splash') def show(self, *args): name = args[0] screen = getattr(self, 'screen_%s' % name) self.root.clear_widgets() self.root.add_widget(screen) def new_game(self): self.elements_found = ['Air', 'Earth', 'Fire', 'Water'] self.game() def restore_game(self): try: g = open(self.data_path + 'savegame', 'rb') self.elements_found = pickle.load(g) g.close() self.game() except: self.new_game() def game(self): self.root.clear_widgets() a = AnchorLayout() i = Image(source = 'Data/space.jpg', allow_stretch = True, keep_ratio = False) a.add_widget(i) g1 = GridLayout(size_hint = (1,1), cols = 2, rows = 1) a.add_widget(g1) s = ScrollView(size_hint = (.25, 1), do_scroll_x = False, size_hint_y = None) g1.add_widget(s) self.g2 = GridLayout(size_hint = (1, None), height = len(self.elements_found)*35, cols = 1, spacing = 2) s.add_widget(self.g2) self.l = Label(text="0/"+str(len(self.ether)+4), size_hint = (None, None), height = 35) self.g2.add_widget(self.l) for e in self.elements_found: self.update_elements_menu(e) self.root.add_widget(a) def update_elements_menu(self,e): b = Button(size_hint = (None, None), height = 30, text = e) b.bind(on_press = partial(self.add_element_to_universe,e)) self.g2.add_widget(b) self.g2.height = len(self.elements_found)*30 self.l.text = "%d / %d" % (len(self.elements_found), len(self.ether)+4) def add_element_to_universe(self,*args): e = args[0] if len(self.universe) > 0: #let's roll a = 2*math.pi/len(self.universe) c = 0 r = 150 + 100*len(self.universe)/10 for x in self.universe: A = Animation( center_x = Window.center[0] + math.cos(c*a)*r, center_y = Window.center[1] + math.sin(c*a)*r, transition = 'out_back', duration = 1 ) c = c + 1 A.start(x) f = Element(text = e, center=Window.center) f.bind(on_touch_up=partial(self.check_position,f)) self.universe.append(f) self.root.add_widget(f) def check_position(self,*args): f = args[1] if f in self.universe and (f.x <0.1*Window.width or f.x>0.9*Window.width or f.y<0.1*Window.height or f.y>0.9*Window.height): self.universe.remove(f) self.root.remove_widget(f) return 1 for e in self.universe: if e == f: continue if f.collide_widget(e): b = self.transmute(e.text,f.text) if b: self.sound_find.play() self.universe.remove(e) self.universe.remove(f) self.root.remove_widget(e) self.root.remove_widget(f) self.add_element_to_universe(b) if b not in self.elements_found: self.elements_found.append(b) output = open(self.data_path + 'savegame', 'wb') pickle.dump(self.elements_found, output) output.close() self.update_elements_menu(b) return 1 def load_ether(self): f = open(self.data_path + "ether.dat", 'r') c = 0 for line in f: c = c + 1 if re.match("#",line): continue a = re.match("(\d+)\s+(.*?)\s+\=\s+(.*?)\s+\+\s+(.*?)\s+",line) if a != None: self.ether.append( [int(a.group(1)), a.group(2), a.group(3), a.group(4)] ) else: print "Error building ether [%d] " % c def transmute(self, item1, item2): for formula in self.ether: if (formula[2] == item1 and formula[3] == item2) or (formula[3] == item1 and formula[2] == item2): return formula[1] return None def test(self): print "%d %s = %s + %s" %(self.ether[5][0], self.ether[5][1], self.ether[5][2], self.ether[5][3]) print "transmute Storm & Snow => %s" % self.transmute('Storm','Snow') print "transmute Bread & Snow => %s" % self.transmute('Bread','Snow') # doesn't work def solution(self): s = ['Air', 'Earth', 'Fire', 'Water'] count = 4 def solution_rec(e,l): for x in l: n = self.transmute(e,x) if n and n not in s: #count = count + 1; print "%s + %s = %s" %(e,x,n) l.append(n) solution_rec(n,l) for e in s: solution_rec(e,s)
class AddUser(Popup): ## # Class Constructor: __init__ # --------------------------- # This method is called during creation of the AddUser class. # This function creates the layout for the popup as well as initializes all the # popup attributes. # # @params # (AddUser) self This instance of AddUser # (Various) **kwargs Arguments for constuction of internal Popup object ## def __init__(self, **kwargs): self.layout = FloatLayout(size=(Window.width, 200)) super(AddUser, self).__init__(title='Add Users', content=self.layout, size_hint=(None,None), size=(400,200), background=BKGD_DCHRC, pos_hint={"center_x":.5, 'top':.7}, auto_dismiss=False, **kwargs) self.num_not_in_group = 0 ## # Class Method: draw_layout # ------------------------- # This method draws the layout of the popup by adding the button and the add and cancel buttons. # This method has the functionality to see if a group is selected and responds accordingly # # @params # (AddUser) self This instance of AddUser ## def draw_layout(self): self.button_x = .5 if manager.CURRENT_GROUP != None: self.button_x = .3 self.dropdown = DropDown(auto_width=False, width=180, max_height=180, on_dismiss=self.display_num_down) self.dropdown.main_button = HoverButton(text="Select Users", size=(180,40), size_hint=(None,None), pos_hint={"center_x":.5, 'top':.8}, button_down=DD_DCHRC[1], button_up=DD_DCHRC[0], on_release=self.display_label) self.layout.add_widget(self.dropdown.main_button) self.add_user_dropdown(self.dropdown) self.layout.add_widget(HoverButton(text="Add", button_down=BTN_DCHRC[1], button_up=BTN_DCHRC[0], font_size=14, size_hint=(None,None), size=(100,40), pos_hint={"center_x":.7, 'top':.35}, on_press=self.add_user_to_group)) else: self.layout.add_widget(Label(text="No Group Selected", font_size=14, pos_hint={"center_x":.5, 'top':1.2})) self.layout.add_widget(HoverButton(text="Cancel", button_down=BTN_DCHRC[1], button_up=BTN_DCHRC[0], font_size=14, size_hint=(None,None), size=(100,40), pos_hint={"center_x":self.button_x, 'top':.35}, on_press=self.dismiss)) ## # Class Method: display_layout # ---------------------------- # This method displays the priority label above the priority text boxes to give an # indication of what the text box is for # # @params # (AddUser) self This instance of AddUser # (HoverButton) instance This is the button which triggers the creation of # the priority label and the dropdown ## def display_label(self, instance): self.dropdown.open(self.dropdown.main_button) if self.num_not_in_group != 0: self.layout.add_widget(Label(text="Priority", size_hint=(None,None), size = (40,20), font_size=9, pos_hint={'center_x':.7, 'top':.65})) else: self.dropdown.main_button.text = 'No More Users' ## # Class Method: add_user_dropdown # ------------------------------- # This method fills the dropdown with UserToggle objects # that are not already in the group # # @params # (AddUser) self This instance of AddUser # (DropDown) instance This is the dropdown which is being filled up ## def add_user_dropdown(self, instance): all_users = database.get_all_users() current_group = database.get_group_members(manager.CURRENT_GROUP) members = [] for member in current_group: members.append(member[0]) for user in all_users: if user not in members: self.num_not_in_group += 1 user_tog = UserToggle(user) self.dropdown.add_widget(user_tog) ## # Class Method: open_popup # ------------------------ # This method is called to open the popup and create the layout for the popup # # @params # (AddUser) self This instance of AddUser ## def open_popup(self): self.layout.clear_widgets() self.draw_layout() self.open() ## # Class Method: display_num_down # ------------------------------ # This method updates the main button to display the number of users that are selected to add into # the group # # @params # (AddUser) self This instance of AddUser # (DropDown) instance The dropdown that on dismiss causes the main button to be updated ## def display_num_down(self, instance): if self.num_not_in_group == 0: return num_down = 0 for user_panel in self.dropdown.container.children: for user in user_panel.children: if type(user) == ToggleButton: if user.state == 'down': num_down += 1 if num_down == 1: self.dropdown.main_button.text = str(num_down) + " User Selected" else: self.dropdown.main_button.text = str(num_down) + " Users Selected" for child in self.layout.children: if type(child) == Label and child.text == 'Priority': self.layout.remove_widget(child) ## # Class Method: add_user_to_group # ------------------------------- # This method adds all of the selected users in the dropdown to the group. # The method also has a check to see if users are actually selected and sends # an error message if none are selected. # # @params # (AddUser) self This instance of AddUser # (HoverButton) instance This is the add button that closes the popup # and commits all of the changes ## def add_user_to_group(self, instance): self.num_not_in_group = 0 names_selected = False for user_panel in self.dropdown.container.children: for user in user_panel.children: if type(user) == ToggleButton and user.state == 'down': names_selected = True database.add_group_member(user.text, manager.CURRENT_GROUP, user_panel.priority_text.text) if not names_selected: for child in self.layout.children: if type(child) == Label and child.text == "Please Select Group Members": self.content.remove_widget(child) self.content.add_widget(Label(text="Please Select Group Members", size_hint=(None,None), font_size=12, color=(1,0,0,1), pos_hint={'center_x':.5, 'top':1.8})) else: manager.menu.display_group_info(manager.CURRENT_GROUP) self.dismiss()
class Application(App): def build(self): Window.clearcolor = (1, 1, 1, 0) #Window.size=(320,480) self.connection = Connection() self.img = Image(source='net.jpeg', size_hint=(None, None)) self.img.allow_stretch = True self.img.opacity = 1 self.password = TextInput(text="password", multiline=False, size_hint=(None, None)) self.loginbutton = Button(text="Unlock", size_hint=(None, None)) self.loginbutton.bind(on_press=self.login) self.registerbutton = Button(text="Register", size_hint=(None, None)) self.registerbutton.bind(on_press=self.register) #creating layout based on conditions cols = self.connection.size("pwmanager") self.master = FloatLayout() if cols is not 1: self.master.add_widget(self.registerbutton) else: self.master.add_widget(self.loginbutton) self.master.add_widget(self.img) self.master.add_widget(self.password) self.master.bind(size=self.on_rotate) return self.master def login(self, event): passwordtext = self.connection.getvalues("*", "pwmanager") userentry = "" for i in passwordtext.fetchone(): userentry = i if (userentry == self.password.text): self.master.remove_widget(self.loginbutton) self.master.remove_widget(self.img) self.master.remove_widget(self.password) self.connection.conn.close() self.viewer = Viewer(self.master) else: self.password.text = "Retry" global choice choice = 2 def register(self, event): if (self.password.text is not ""): values = "('{}')".format(str(self.password.text)) columnname = "('{}')".format("password") self.connection.insertintotable("pwmanager", columnname, values) self.master.remove_widget(self.registerbutton) self.master.add_widget(self.loginbutton) self.password.text = "" def on_rotate(self, event, event1): global screenheight global screenwidth global choice screenheight = Window.height screenwidth = Window.width if (choice == 1): self.img.pos = (WXY(60), HXY(263)) self.img.width = WXY(207) self.img.height = HXY(164) self.password.pos = (WXY(53), HXY(180)) self.password.width = WXY(208) self.password.height = HXY(37) self.password.font_size = HXY(18) self.loginbutton.pos = (WXY(82), HXY(117)) self.loginbutton.width = WXY(146) self.loginbutton.height = HXY(40) self.loginbutton.font_size = HXY(18) self.registerbutton.pos = (WXY(82), HXY(117)) self.registerbutton.width = WXY(146) self.registerbutton.height = HXY(40) elif (choice == 2): self.viewer.on_rotate() elif (choice == 3): self.viewer.notepad.on_rotate()
class Juego(Screen): def __init__(self, **Kwargs): super(Juego, self).__init__(**Kwargs) self.orientation = "vertical" S = Image(source='imagenes/juego.jpeg', allow_stretch=True) self.add_widget(S) #añade la imagen al widget self.option = "" self.botones = [] self.my_box1 = FloatLayout(size=(300, 300)) labelTitle = Label(text='[color=000000] CENTINELA [/color]', markup=True, font_size="70dp", font_name="Times", size_hint=(0.3, 0.3), pos=(120, 450)) labelChat = Label(text='[color=000000] CHAT [/color]', markup=True, font_size="50dp", font_name="Times", size_hint=(0.3, 0.3), pos=(500, 450)) SP1 = Image(source='imagenes/moneda.png', size_hint=(0.2, 0.1), pos=(30, 370)) SP2 = Image(source='imagenes/moneda.png', size_hint=(0.2, 0.1), pos=(150, 370)) SP3 = Image(source='imagenes/moneda.png', size_hint=(0.2, 0.1), pos=(270, 370)) labelPunto1 = Label(text='[color=000000] ' + varg.getPuntos1() + '[/color]', markup=True, font_size="30dp", font_name="Times", size_hint=(0.3, 0.3), pos=(55, 350)) labelPunto2 = Label(text='[color=000000] ' + varg.getPuntos2() + '[/color]', markup=True, font_size="30dp", font_name="Times", size_hint=(0.3, 0.3), pos=(175, 350)) labelPunto3 = Label(text='[color=000000] ' + varg.getPuntos3() + '[/color]', markup=True, font_size="30dp", font_name="Times", size_hint=(0.3, 0.3), pos=(295, 350)) #Acción de iniciar self.btnIniciar = Button(text="INICIAR", font_size=85, size_hint=(0.5, 0.5), background_color=[0, 166, 0, 38], pos=(100, 30)) self.btnIniciar.bind(on_press=self.iniciar) #Acción de atacar self.btnAtacar = Button(text="Atacar", font_size=24, size_hint=(0.1, 0.1), background_color=[0, 1, 0.6, 0.8], pos=(100, 10)) self.btnAtacar.bind(on_press=self.changerA) #Acción de sumar self.btnSumar = Button(text="Sumar", font_size=24, size_hint=(0.1, 0.1), background_color=[0, 1, 0.6, 0.8], pos=(200, 10)) self.btnSumar.bind(on_press=self.changer) #Acción de Robar self.btnRobar = Button(text="Robar", font_size=24, size_hint=(0.1, 0.1), background_color=[0, 1, 0.6, 0.8], pos=(300, 10)) self.btnRobar.bind(on_press=self.changerR) self.labelPunto = Label(text='[color=000000] ' + varg.getPuntos() + '[/color]', markup=True, font_size="30dp", font_name="Times", size_hint=(0.3, 0.3), pos=(375, -10)) self.puntosImg = Image(source='imagenes/moneda.png', size_hint=(0.2, 0.1), pos=(350, 10)) #Chat self.messageInput = TextInput(size_hint=(0.2, 0.1), pos=(550, 10)) #Boton para enviar mensaje btn = Button(text="Enviar", font_size=24, size_hint=(0.1, 0.1), background_color=[0, 1, 0.6, 0.8], pos=(720, 10)) btn.bind(on_press=self.sendMessage) self.my_box1.add_widget(labelTitle) self.my_box1.add_widget(labelChat) self.my_box1.add_widget(self.messageInput) self.my_box1.add_widget(SP1) self.my_box1.add_widget(SP2) self.my_box1.add_widget(SP3) self.puntosImg.add_widget(self.labelPunto) self.puntosImg.add_widget(labelPunto1) self.puntosImg.add_widget(labelPunto2) self.puntosImg.add_widget(labelPunto3) self.my_box1.add_widget(btn) self.my_box1.add_widget(self.btnAtacar) self.my_box1.add_widget(self.btnRobar) self.my_box1.add_widget(self.btnSumar) self.my_box1.add_widget(self.puntosImg) self.my_box1.add_widget(self.btnIniciar) self.add_widget(self.my_box1) def sendMessage(self, btn): requestmsg = varg.getplayer_name() + " chat " + self.messageInput.text print(requestmsg) self.my_box1.remove_widget(self.messageInput) self.my_box1.add_widget(self.messageInput) s.sendall(requestmsg.encode()) def escucharTurno(self): while (varg.getturno() != varg.getplayer_name()): time.sleep(1) s.sendall(b'turno') data = s.recv(1024).decode() varg.setturno(data) print(data) print(varg.getturno()) self.my_box1.remove_widget(self.labelTurno) self.labelTurno = Label(text='[color=165B03] Es turno de: ' + varg.getprimerTurno() + '[/color]', markup=True, font_size="20dp", font_name="Times", size_hint=(0.3, 0.3), pos=(120, 380)) self.my_box1.add_widget(self.labelTurno) self.my_box1.remove_widget(self.labelTurno) self.labelTurno = Label(text='[color=165B03] Es turno de: ' + varg.getprimerTurno() + '[/color]', markup=True, font_size="20dp", font_name="Times", size_hint=(0.3, 0.3), pos=(120, 380)) self.my_box1.add_widget(self.labelTurno) def jugada(self, btn): print("boton", btn.text) if (self.option == "S"): print(varg.getnameTurno()) requestS = "S " + btn.text + " " + varg.getnameTurno() print(requestS) s.sendall(requestS.encode()) data = s.recv(1024).decode() print(requestS) print("respuesta de suma:", data) varg.setPuntos(data) # TODO: ACTUALIZAR LABEL DE PUNTOS self.puntosImg.remove_widget(self.labelPunto) self.labelPunto = Label(text='[color=000000] ' + varg.getPuntos() + '[/color]', markup=True, font_size="30dp", font_name="Times", size_hint=(0.3, 0.3), pos=(375, -10)) self.puntosImg.add_widget(self.labelPunto) print("antes de las cartas") misCartasAct = varg.getmisCartas() index = misCartasAct.index(btn.text) newarray = [] for carta in misCartasAct: if (index != misCartasAct.index(carta)): newarray.append(carta) varg.setmisCartas(newarray) print("mis cartas", varg.getmisCartas()) #self.escucharTurno() elif (self.option == "A"): namePlayer = self.Jugador.text orden = varg.getorden() indeP = orden.index(namePlayer) if (indeP == 0): elPlayer = "p1" elif (indeP == 1): elPlayer = "p2" elif (indeP == 2): elPlayer = "p3" elif (indeP == 3): elPlayer = "p4" requestA = "S" + " -" + btn.text + " " + elPlayer print(requestA) s.sendall(requestA.encode()) misCartas = varg.getmisCartas() index = misCartas.index(btn.text) newarray = [] for carta in misCartas: if (index != misCartas.index(carta)): newarray.append(carta) varg.setmisCartas(newarray) elif (self.option == "R"): requestS = "R" print("antes del for") for a in self.botones: self.my_box1.remove_widget(a) self.my_box1.add_widget(self.btnAtacar) self.my_box1.add_widget(self.btnRobar) self.my_box1.add_widget(self.btnSumar) def generarCartas(self, cartas): x = 30 y = 100 cont = 0 for a in cartas: self.btnC = Button(text=a, font_size=24, size_hint=(0.05, 0.08), background_color=[0, 1, 0.6, 0.8], pos=(x, y)) self.btnC.bind(on_press=self.jugada) self.my_box1.add_widget(self.btnC) self.botones.append(self.btnC) cont = cont + 1 if (cont < 7): x = x + 50 elif (cont == 7): y = 50 x = 30 else: x = x + 50 def threaded_msg(self): while True: time.sleep(1) data = s.recv(1024).decode() print(data) def iniciar(self, btn): self.my_box1.remove_widget(self.btnIniciar) jugadores = varg.getjugadores() labelPin = Label(text='[color=165B03] Estas en la sala: ' + varg.getnum() + '[/color]', markup=True, font_size="20dp", font_name="Times", size_hint=(0.3, 0.3), pos=(120, 400)) self.labelTurno = Label(text='[color=165B03] Es turno de: ' + varg.getprimerTurno() + '[/color]', markup=True, font_size="20dp", font_name="Times", size_hint=(0.3, 0.3), pos=(120, 380)) labelP1 = Label(text='[color=165B03] ' + jugadores[0] + '[/color]', markup=True, font_size="20dp", font_name="Times", size_hint=(0.3, 0.3), pos=(-20, 270)) labelP2 = Label(text='[color=165B03] ' + jugadores[1] + '[/color]', markup=True, font_size="20dp", font_name="Times", size_hint=(0.3, 0.3), pos=(110, 270)) labelP3 = Label(text='[color=165B03] ' + jugadores[2] + '[/color]', markup=True, font_size="20dp", font_name="Times", size_hint=(0.3, 0.3), pos=(220, 270)) self.my_box1.add_widget(labelPin) self.my_box1.add_widget(self.labelTurno) self.my_box1.add_widget(labelP1) self.my_box1.add_widget(labelP2) self.my_box1.add_widget(labelP3) #start_new_thread(self.threaded_msg, ()) def cartas(self): if (self.option == "A" or self.option == "R"): self.my_box1.remove_widget(self.btnCon) self.my_box1.remove_widget(self.Jugador) self.my_box1.remove_widget(self.labelJ) if (self.option == "A"): self.generarCartas(varg.getmisCartas()) elif (self.option == "R"): self.generarCartas([ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13" ]) elif (self.option == "S"): self.generarCartas(varg.getmisCartas()) def changerAR(self): #Cambiar de pantalla self.my_box1.remove_widget(self.btnAtacar) self.my_box1.remove_widget(self.btnRobar) self.my_box1.remove_widget(self.btnSumar) self.labelJ = Label(text='[color=165B03] Jugador: [/color]', markup=True, font_size="30dp", font_name="Times", size_hint=(0.3, 0.3), pos=(10, 10)) self.my_box1.add_widget(self.labelJ) self.Jugador = TextInput(size_hint=(0.2, 0.1), pos=(40, 10)) self.btnCon = Button(text="continuar", font_size=24, size_hint=(0.17, 0.1), background_color=[0, 1, 0.6, 0.8], pos=(210, 15)) self.btnCon.bind(on_press=self.change) self.my_box1.add_widget(self.btnCon) self.my_box1.add_widget(self.Jugador) def changerA(self, btn): self.option = "A" self.changerAR() def changerR(self, btn): self.option = "R" self.changerAR() def change(self, btn): self.cartas() def changer(self, btn): #Cambiar de pantalla self.option = "S" self.my_box1.remove_widget(self.btnAtacar) self.my_box1.remove_widget(self.btnRobar) self.my_box1.remove_widget(self.btnSumar) self.cartas()
class GameView(ScreenManager): def __init__ (self, app): super(GameView, self).__init__(transition=WipeTransition()) self.app = app self.graphics_widget = FloatLayout() image = Image(source = PATH + "splash.png", keep_ratio=False, allow_stretch=True,\ size=(SCREEN_WIDTH, SCREEN_HEIGHT), size_hint=(None, None), pos=(0,0)) self.graphics_widget.add_widget(image) screen = Screen(name="0") screen.add_widget(self.graphics_widget) self.add_widget(screen) self.current = "0" # self.load_sounds() self.load_textures() #self.load_sprites() self.load_gems() # self.schedules = [] self.image_hero = None # self.image_score = MyImage(source = PATH + "score_bg.png", allow_stretch=True) self.image_score.set_score(0) self.image_score.set_shadow(False) self.image_score.set_font_size(30) self.image_score.set_label_position(3,4) self.image_score.size_hint = (.2, .2) self.image_score.pos_hint = {'x':.8, 'y':.8} # self.button_reset = MyButton(source=PATH + "restart.png", on_press=self.reset, opacity=0.5,\ background_color = (0,0,0,0), size = (X_BLOCK, Y_BLOCK), border=(0,0,0,0)) self.button_reset.size_hint = (.1, .1) self.button_reset.pos_hint = {'x': 0, 'y':.9} self.progress_bar = ProgressBar(max=500, opacity=0) #CURRENTLY HIDDEN with self.progress_bar.canvas: Color(0,0,0,0) self.progress_bar.size_hint = (.6, .05) self.progress_bar.pos_hint = {'x': 0.2, 'y': 0} self.progress_bar.value = 0 self.schedule(self.reset_level, 3) def unschedule_all(self): for s in self.schedules: Clock.unschedule(s) self.schedules = [] def unschedule_single(self, dt=None): self.schedules = self.schedules[1:] def schedule(self, func, delay): if func not in self.schedules: self.schedules.append(func) Clock.schedule_once(func, delay) Clock.schedule_once(self.unschedule_single, delay) def reset(self, widget=None): print "Reset" #save_state(1) #self.reset_level() self.level = 1 save_state(1) self.app.stop() def reset_level(self, dt=None): self.level = int(get_state()) try: Animation.cancel_all(self.scatter_hero) except: pass try: Animation.cancel_all(self.scatter_baddy) except: pass Animation.cancel_all(self.progress_bar) self.unschedule_all() self.setup_battle() def get_level_data(self): data = get_level_data(self.level) self.baddy_points_for_level = int(data[0]) self.weapons = [int(x) for x in data[1].split(",")] self.score_threshold = int(data[2]) self.maximum_attacks = int(data[3]) self.time_limit = int(data[4]) self.baddy_image = data[5] self.baddy_ratio_for_level = int(data[6]) self.baddy_label_deltax = int(data[7]) self.baddy_label_deltay = int(data[8]) self.level_potions = [int(x) for x in data[9].split(",") if x] self.textures_data = data[10].split(";") #self.sprites_data = data[11].split(";") #if self.sprites_data == ['']: # self.sprites_data = [] def setup_battle(self, dt=None): self.graphics_widget.remove_widget(self.button_reset) self.graphics_widget.remove_widget(self.image_score) self.graphics_widget.remove_widget(self.progress_bar) if self.level == 11: graphics_widget = FloatLayout() image = Image(source = PATH + "end.png", keep_ratio=False, allow_stretch=True,\ size=(SCREEN_WIDTH, SCREEN_HEIGHT), size_hint=(None, None), pos=(0,0)) graphics_widget.add_widget(image) graphics_widget.add_widget(self.button_reset) screen = Screen(name="end") screen.add_widget(graphics_widget) self.add_widget(screen) self.current=screen.name else: self.get_level_data() graphics_widget = self.set_background() screen = Screen(name=str(self.level)) screen.add_widget(graphics_widget) self.graphics_widget = graphics_widget self.add_widget(screen) self.current=screen.name if self.score_threshold > 0: self.level_score = - self.score_threshold else: self.level_score = 0 self.image_score.set_score(self.level_score) if self.level < 3: self.start_battle() else: self.schedule(self.start_battle, 0) #WAS 2 self.graphics_widget.add_widget(self.button_reset) self.graphics_widget.add_widget(self.progress_bar) self.graphics_widget.add_widget(self.image_score) def repeat_battle(self, dt=None): self.image_hero = None self.level_score = 0 self.image_score.set_score(self.level_score) self.start_battle() def start_battle(self, dt=None): self.attacks_tried = 0 self._picked_gems = [] if self.level_potions: self.create_potions(self.level_potions) else: self.potion_buttons = [] self.create_gems(self.weapons) # min_wait = 0 #WAS 3 if self.level < 3: min_wait = 0 self.schedule(self.introduce_hero, min_wait) if self.level == 1: self.schedule(self.introduce_baddy, min_wait) else: self.schedule(self.introduce_baddy, min_wait + 2) self.schedule(self.talk_baddy, min_wait + 4) self.schedule(self.talk_hero, min_wait + 5.5) self.schedule(self.talk_baddy, min_wait + 6.5) if self.level == 1: self.schedule(self.show_gems, 0) else: self.schedule(self.show_gems, min_wait + 8) if self.score_threshold > 0: self.image_score.flash(10) self.schedule(self.show_potions, min_wait + 8) self.schedule(self.look_alive, min_wait + 8) self.schedule(self.handle_timed_battle, min_wait + 8) if self.level == 1: self.schedule(self.flash_gem, min_wait + 11) #self.schedule(self.flash_hero, min_wait + 15) def flash_gem(self, dt=None): for g in self.gems: if g: g.flash(10) def flash_hero(self, widget=None, event=None): self.image_hero.flash(10) def handle_timed_battle(self, dt=None): if self.time_limit > 0: anim1 = Animation(x = X_BLOCK, duration=self.time_limit) anim1.bind(on_complete = self.level_failed) anim1.start(self.scatter_baddy) self.progress_bar.value = self.progress_bar.max anim2 = Animation(value = 0, duration=self.time_limit) anim2.start(self.progress_bar) def create_gems(self, numbers): self.gems = [None] * 10 self.gem_values = [0] * 10 for i in range(len(numbers)): n = numbers[i] #gem = MyImage(keep_ratio=True, allow_stretch=False, color=(0,0,0,0), keep_data=True) #gem.set_shadow(False) #with gem.canvas: # gem.rectangle = Rectangle(texture=self.gem_sprites[n].texture, size = (X_BLOCK,Y_BLOCK)) gem = MyImage(source = self.gem_sources[n],keep_ratio=False, allow_stretch=True, keep_data=True) gem.set_shadow(False) self.gems[n] = gem self.gem_values[n] = n def drop_gem(self, widget=None, event=None): if widget not in self.graphics_widget.children: return True if widget.x > self.scatter_hero.x and widget.x < self.scatter_hero.x + self.image_hero.width * 2: if widget.y > self.scatter_hero.y and widget.y < self.scatter_hero.y + self.image_hero.height * 2: self.image_hero.stop_flash() self.handle_player_action(widget) return True else: self.hide_gems() self.show_gems() self.hide_potions() self.show_potions() else: self.hide_gems() self.show_gems() self.hide_potions() self.show_potions() return False def pick_gem(self, widget=None, event=None): self._picked_gems.append(widget) self.flash_hero() def hide_gems(self, dt=None, dummy=None): for scatter in self.gem_scatters: if scatter.children: scatter.remove_widget(scatter.children[-1]) self.graphics_widget.remove_widget(scatter) def show_gems(self, dt=None, dummy=None): self.gem_scatters = [] filler = (8 - len(self.weapons)) / 2.0 for i in range(len(self.weapons)): gem = self.gems[self.weapons[i]] scatter = Scatter(do_rotation=False, do_scale=False, color=(0,0,0,0), size_hint=(0.1,0.1)) scatter.add_widget(gem) gem.bind(on_touch_down=self.flash_hero) scatter.bind(on_touch_up=self.drop_gem) scatter.pos = ((filler + i) * X_BLOCK, 0) scatter.scale = 1 try: self.graphics_widget.add_widget(scatter) self.gem_scatters.append(scatter) except: pass def bring_to_front(self, widget): self.graphics_widget.remove_widget(widget) self.graphics_widget.add_widget(widget) def set_background(self): graphics_widget = FloatLayout() for td in self.textures_data: filename,xpos,ypos,width,height = td.split(":") xpos = float(xpos) ypos = float(ypos) image = MyImage(keep_ratio=True, allow_stretch=False, color=(0,0,0,0)) image.set_shadow(False) with image.canvas: Rectangle(texture=self.textures[filename].texture, size=(float(width) * X_BLOCK, float(height) * Y_BLOCK)) scatter = Scatter(do_rotation=False, do_scale=False, do_translation=False) scatter.pos = (xpos * X_BLOCK, ypos * Y_BLOCK) scatter.add_widget(image) graphics_widget.add_widget(scatter) #for td in self.sprites_data: # filename,xpos,ypos,width,height = td.split(":") # xpos = float(xpos) # ypos = float(ypos) # image = MyImage(texture = self.sprites[filename].texture, keep_ratio=True, allow_stretch=False) # image.set_shadow(False) # scatter = Scatter(do_rotation=False, do_scale=False, do_translation=False) # scatter.pos = (xpos * X_BLOCK, (ypos + 4) * Y_BLOCK / 2) # scatter.add_widget(image) # graphics_widget.add_widget(scatter) # scatter.scale = 6 - ypos * 1.5 return graphics_widget def introduce_hero(self, dt=None): self.image_hero = MyImage(source = PATH + "hero.png", keep_ratio=False, allow_stretch=True, keep_data=True) self.image_hero.set_label_position(-4, -12) self.image_hero.set_shadow(True) self.scatter_hero = Scatter(do_rotation=False, do_scale=False, do_translation=False) self.scatter_hero.add_widget(self.image_hero) self.scatter_hero.scale= 2 + (0.5 * SCREEN_DENSITY) if self.level < 3: self.hero_position = [X_BLOCK, Y_BLOCK] self.scatter_hero.pos = (self.hero_position[0], self.hero_position[1]) self.graphics_widget.add_widget(self.scatter_hero) else: self.schedule(self.sounds['hero_song'].play, 1.0) self.hero_position = [- 2 * X_BLOCK, Y_BLOCK] self.scatter_hero.pos = (self.hero_position[0], self.hero_position[1]) self.graphics_widget.add_widget(self.scatter_hero) # self.image_hero.walk(60, 2.4 * X_BLOCK) anim = Animation(x = X_BLOCK, duration=4) anim.start(self.scatter_hero) self.image_score.set_score(self.level_score) def introduce_baddy(self, dt=None): self.baddy_size_ratio = self.baddy_ratio_for_level self.baddy_points = self.baddy_points_for_level self.image_baddy = MyImage(source = PATH + self.baddy_image, keep_ratio=False, allow_stretch=True) self.image_baddy.set_label_position(self.baddy_label_deltax, self.baddy_label_deltay) self.image_baddy.set_score(self.baddy_points) self.scatter_baddy = Scatter(do_rotation=False, do_scale=False, do_translation=False) self.scatter_baddy.add_widget(self.image_baddy) self.baddy_size = [X_BLOCK, Y_BLOCK] self.baddy_step = (4 * X_BLOCK + 0.0) / self.maximum_attacks self.scatter_baddy.scale = self.baddy_size_ratio # * SCREEN_DENSITY self.scatter_baddy.pos = (8 * X_BLOCK, Y_BLOCK) self.graphics_widget.add_widget(self.scatter_baddy) self.image_baddy.walk(30, 60) anim = Animation(x=5 * X_BLOCK, duration=2) anim.start(self.scatter_baddy) self.baddy_position = [5 * X_BLOCK, Y_BLOCK] def create_potions(self, numbers): self.potion_buttons = [] self.potion_button_values = [] for n in numbers: button = MyButton(source=PATH + "potion.png",background_color=[0,0,0,0], label_text="-1", font_size = 30) self.potion_buttons.append(button) self.potion_button_values.append(n) button.pos_hint = {'x': .45,'y': .85} button.size_hint = (0.12, 0.12) button.bind(on_press=self.handle_potion) def show_potions(self, dt=None): for button in self.potion_buttons: self.graphics_widget.add_widget(button) def hide_potions(self): for button in self.potion_buttons: self.graphics_widget.remove_widget(button) def handle_potion(self, widget=None): value = self.potion_button_values[self.potion_buttons.index(widget)] self.image_baddy.flash(5) self.baddy_points = self.baddy_points + value self.image_baddy.set_score(self.baddy_points) self.graphics_widget.remove_widget(widget) self.potion_buttons.remove(widget) self.potion_button_values.remove(value) self.decide_next_stage() def handle_player_action(self, widget=None): # HANDLE MULTIPLE WIDGETS USING self._PICKED_GEMS AND THEN CLEAR IT! try: self.graphics_widget.remove_widget(widget) except: pass image = widget.children[-1] self.hide_gems() Clock.unschedule(self.image_hero.look_alive) Clock.unschedule(self.image_baddy.look_alive) # widget.pos = (X_BLOCK / (20.0 * (SCREEN_DENSITY **2) * SCREEN_RATIO ), Y_BLOCK / (16 * (SCREEN_DENSITY**2) * SCREEN_RATIO) ) # widget.scale = 0.3 widget.add_widget(image) self.current_gem = widget self.scatter_hero.add_widget(widget) self.image_hero.walk(40, 60) self.image_baddy.walk(40, 60) anim1 = Animation(x = 3 * X_BLOCK, t='out_quad') anim1.start(self.scatter_hero) anim2 = Animation(x = 3.1 * X_BLOCK, t='out_quad') anim2.start(self.scatter_baddy) self.attacks_tried = self.attacks_tried + 1 if self.maximum_attacks > 0: self.baddy_position[0] = self.baddy_position[0] - ((self.attacks_tried +0.0) / self.maximum_attacks) * self.baddy_step self.schedule(self.sounds['hero_charge'].play, 0.1) self.schedule(self.sounds['baddy_charge'].play, 0.5) #Handle hit hit_value = self.gems.index(widget.children[-1]) if self.baddy_points / (hit_value + 0.0) == self.baddy_points / hit_value: if self.baddy_size_ratio <= self.baddy_ratio_for_level: self.level_score = self.level_score + hit_value * self.baddy_points self.baddy_points = self.baddy_points / hit_value self.baddy_size_ratio = self.baddy_size_ratio - 1 if self.baddy_size_ratio == 0: self.baddy_size_ratio = 0.1 else: self.baddy_points = self.baddy_points * hit_value self.baddy_size_ratio = self.baddy_size_ratio + 1 anim1.bind(on_complete = self.update) def baddy_vanquished(self, widget=None, event=None): self.graphics_widget.remove_widget(self.progress_bar) Animation.cancel_all(self.progress_bar) Animation.cancel_all(self.scatter_baddy, 'x') self.celebrate() self.image_baddy.walk(20, 40) self.image_baddy.children[-1].text="" anim1 = Animation(size = (1,1)) anim1.start(self.image_baddy) self.hide_gems() if self.level_score < 0: print "NOTIFY USER ABOUT THRESHOLD!" self.image_score.flash(10) self.schedule(self.level_failed, 2) else: self.schedule(self.move_to_next_battle, 2) def level_failed(self, widget=None, event=None): self.graphics_widget.remove_widget(self.progress_bar) Animation.cancel_all(self.progress_bar) Animation.cancel_all(self.scatter_baddy, 'x') if self.baddy_points < 2 and self.level_score >= self.score_threshold: return self.hide_gems() anim = Animation(x = - 4 * X_BLOCK, duration = 2) self.image_hero.walk(10, 4 * X_BLOCK) anim.start(self.image_hero) self.image_baddy.celebrate(240,60) self.schedule(self.move_to_repeat_battle, 2) def move_to_repeat_battle(self, widget=None, event=None): self.graphics_widget.remove_widget(self.scatter_hero) anim = Animation(x = 8 * X_BLOCK, duration = 12) self.image_baddy.walk(30, 8 * X_BLOCK) anim.start(self.image_baddy) self.schedule(self.repeat_battle, 3) def move_to_next_battle(self, widget=None, event=None): self.graphics_widget.remove_widget(self.scatter_baddy) if self.level == 1: self.next_battle() else: self.schedule(self.sounds['hero_song'].play, .5) self.schedule(self.sounds['hero_song'].play, 3) anim = Animation(x = 8 * X_BLOCK, duration = 4.5) self.image_hero.walk(30, 6 * X_BLOCK) anim.start(self.scatter_hero) anim.bind(on_complete = self.next_battle) def keep_hero_in_same_position(self, dt=None): self.image_hero.x = self.image_hero.x + 0.0 def stop_hero_motion(self, event=None, widget=None): Clock.unschedule(self.keep_hero_in_same_position) def next_battle(self, widget=None, event=None): self.scatter_baddy.rotation = 0 if self.level > 1: self.graphics_widget.remove_widget(self.scatter_hero) self.level = self.level + 1 self.schedule(self.setup_battle, 2.0) def remove_item(self, animation=None, widget=None): self.graphics_widget.remove_widget(widget) widget.canvas.clear() widget = None def update(self, widget=None, event=None): self.image_hero.angle = 0 self.image_baddy.angle = 0 try: self.current_gem.remove_widget(self.current_gem.children[-1]) self.scatter_hero.remove_widget(self.current_gem) except: pass anim1 = Animation(scale=self.baddy_size_ratio) anim2 = Animation(y= self.baddy_position[1]) anim3 = Animation(x= self.baddy_position[0]) anim4 = Animation(x = X_BLOCK) anim1.start(self.scatter_baddy) anim2.start(self.scatter_baddy) if self.time_limit < 0: anim3.start(self.scatter_baddy) anim4.start(self.scatter_hero) self.image_baddy.set_score(self.baddy_points) self.image_score.set_score(self.level_score) if self.scatter_baddy.scale > self.baddy_size_ratio: self.hero_celebrate() else: self.baddy_celebrate() if self.level_score < 0: self.image_score.flash(10) anim4.bind(on_complete = self.decide_next_stage) def decide_next_stage(self, widget=None, event=None): if self.baddy_points == 1: self.baddy_vanquished() elif self.attacks_tried == self.maximum_attacks: self.level_failed() elif self.baddy_points > 1 and (self.is_impossible(self.baddy_points)) and not self.potion_buttons: self.level_failed() else: self.hide_gems() self.show_gems() def talk_hero(self, dt=None): self.sounds['hero_talk'].play() self.image_hero.jump(60, 60) def talk_baddy(self, dt=None): self.sounds['baddy_talk'].play() self.image_baddy.jump(60, 60) def look_alive(self, dt=None, dummy=None): Clock.schedule_interval(self.image_baddy.look_alive, 1.5) Clock.schedule_interval(self.image_hero.look_alive, 2.0) def celebrate(self): self.image_hero.celebrate(60, 60) def hero_celebrate(self, widget=None, event=None): self.image_hero.celebrate(60, 60) def baddy_celebrate(self, widget=None, event=None): self.image_baddy.celebrate(60, 60) def load_sounds(self): self.sounds = {} for f in ["hero_charge", "hero_song", "hero_talk", "baddy_charge", "baddy_talk", "sword1", "sword2", "sword3"]: sound = SoundLoader.load(PATH + "sounds/" + f + '.wav') self.sounds[f] = MySound(sound) def load_gems(self): self.gem_sprites = [None] * 10 self.gem_sources = [""] * 10 for i in range(2,10,1): self.gem_sources[i] = PATH + "gems/" +"gem_0"+str(i)+".png" self.gem_sprites[i] = CoreImage(PATH + "gems/" +"gem_0"+str(i)+".png", color=(0,0,0,1)) def load_textures(self): self.textures = {} for f in ["splash", "bg_1", "bg_2", "bg_3", "bg_4", "bg_5", "bg_6", "bg_7", "bg_8", "bg_9"]: self.textures[f] = CoreImage(PATH+f+".png") #def load_sprites(self): # self.sprites = {} # for f in ["tree_green","tree_red","tree_yellow", "castle", "moon"]: # self.sprites[f] = CoreImage(PATH+f+".png") def calc_baddy_points(self, numbers, n_multiplications): product = 1 for i in range(n_multiplications): product = product * random.choice(numbers) return product #def is_prime(self, num): # if divide(num): # return False # return True def is_impossible(self, num): for weapon in self.weapons: if num % weapon == 0: return False return True
class PersonalScreen(Screen): def __init__(self, **kwargs): Screen.__init__(self, **kwargs) Window.clearcolor = ( 1, 1, 1, 1 ) #change master bg colour, RGB in .% , last is a binary: 1 = On, 0 = Off . Currently the colour is white #Layouts self.tryout = StackLayout( orientation='lr-bt' ) #buttons would be placed from left to right first then bottom to top => the buttons would be stacked at the bottom from left to right first self.floatt = FloatLayout() #free size #variable for def gettinginformation() self.counter = 0 #title of the screen to be seen self.floatt.add_widget( Label( text= '[color=000000][size=40][font=yorkwhiteletter]Last Screened Individual[/size][/font][/color]', size_hint=(0.5, 0.2), halign='center', markup=True, pos_hint={ 'x': 0.05, 'y': 0.8 })) #information , left column. FIXED TEXT '''x is moving left right, y is moving up and down 0.0 for y is in the middle. to move down, use -ve column of the table is fixed at x=0.2, or 0.2 left relative to floatlayout''' self.Lname = Label( text= '[color=000000][size=40][font=Impact Label Reversed]Name\nBatch[/font][/size][/color]', markup=True, pos_hint={ 'x': -0.2, 'y': 0.1 }) self.Lid = Label( text= '[color=000000][size=40][font=Impact Label Reversed]Card ID[/font][/size][/color]', markup=True, pos_hint={ 'x': -0.2, 'y': 0.0 }) self.Llocation = Label( text= '[color=000000][size=40][font=Impact Label Reversed]Location[/font][/size][/color]', markup=True, pos_hint={ 'x': -0.2, 'y': -0.1 }) self.Ltime = Label( text= '[color=000000][size=40][font=Impact Label Reversed]Time\nDate[/font][/size][/color]', markup=True, pos_hint={ 'x': -0.2, 'y': -0.2 }) self.floatt.add_widget(self.Lname) self.floatt.add_widget(self.Lid) self.floatt.add_widget(self.Ltime) self.floatt.add_widget(self.Llocation) #widgets to get information, depending on the card ID received, RHS column of information #currently made RHS columns contain a '-' to show no information is being displayed self.namee = Label( text= '[color=000000][size=40][font=Impact Label Reversed]-[/size][/font][/color]', halign='center', markup=True, pos_hint={ 'x': 0.2, 'y': 0.1 }) self.Rid = Label( text= '[color=000000][size=40][font=Impact Label Reversed]-[/size][/font][/color]', markup=True, pos_hint={ 'x': 0.2, 'y': 0.0 }) self.Rlocation = Label( text= '[color=000000][size=40][font=Impact Label Reversed]-[/size][/font][/color]', markup=True, pos_hint={ 'x': 0.2, 'y': -0.1 }) self.Rtime = Label( text= '[color=000000][size=40][font=Impact Label Reversed]%s[/size][/font][/color]' % (time.strftime("%H:%M:%S\n%d/%m/%Y")), markup=True, pos_hint={ 'x': 0.2, 'y': -0.2 }) self.floatt.add_widget(self.namee) self.floatt.add_widget(self.Rid) self.floatt.add_widget(self.Rtime) self.floatt.add_widget(self.Rlocation) #fixed buttons at the bottom of the screen to navigate self.switchtomenu = Button( text= '[size=50][font=yorkwhiteletter][color=000000]MENU[/font][/size][/color]', markup=True, size_hint=(0.2, 0.2), background_color=(1, 1, 1, 0), on_press=self.changeToMenu) self.switchtoebot = Button( text= '[size=50][font=yorkwhiteletter][color=000000]EBOTS[/font][/size][/color]', markup=True, size_hint=(0.2, 0.2), background_color=(1, 1, 1, 0), on_press=self.changeToebots) self.switchtopersonal = Button( text= '[size=50][font=yorkwhiteletter][color=000000]INDIVIDUAL[/font][/size][/color]', markup=True, size_hint=(0.2, 0.2), background_color=(1, 1, 1, 0), on_press=self.changeToPersonal) self.tryout.add_widget(self.switchtoebot) self.tryout.add_widget(self.switchtopersonal) self.tryout.add_widget(self.switchtomenu) # button to trigger gettinginformation self.refresh = Button( text= '[size=50][font=yorkwhiteletter][color=000000]REFRESH[/font][/size][/color]', markup=True, size_hint=(0.2, 0.2), background_color=(1, 1, 1, 0), on_press=self.gettinginformation) self.tryout.add_widget(self.refresh) #add layouts self.add_widget(self.tryout) self.add_widget(self.floatt) def gettinginformation(self, value): #example dictionary acting as a database that kivy would check against self.known = { '162,180,172,117,207': 'Joshua Lim\nFreshmore', '345,456,567': 'Chua Ah Bheng\nSenior', '154,168,144,85,247': 'Hoo Jian Li\nFreshmore', '225,19,229,43,60': 'Donald Trump\nPOTUS Candidate' } #getting information from Firebase self.cardno = fire.get('/cardID/') #information is received in string self.intruder = fire.get('/intruder/') #actual ; received in boolean # self.intruder = False #<--- variable for testing # self.cardno = '345,456,67' #<--- variable for testing ''' from the raspberry pi , self.intruder is given a default state of False. so when the state remains false, kivy app will check against self.known to anlayse if the person is a registered user or not. if it is, self.intruder changes to True. False is sent over from raspberry pi when 1. Invalid card is scanned 2. Valid card is scanned occurs the only time that self.intruder is read as True from the raspberry pi would be when the intruder does not scan the card at all.''' if self.intruder == False: #if given that self.intruder is False for number in self.known: if self.cardno == number: self.intruder = False if self.cardno != number: self.intruder = True #guards will click the 'refresh' button to capture information if self.intruder == True: if self.counter == 0: self.refresh.text = '[size=50][font=yorkwhiteletter][color=000000]CLEAR[/font][/size][/color]' #to change the text of the button self.namee.text = '[color=ff0000][size=40][font=Impact Label Reversed]INTRUDER-\nNO CARD DETECTED[/color][/size][/font]' #no valid name thus "intruder" is displayed instead self.Rtime.text = '[color=000000][size=40][font=Impact Label Reversed]%s[/size][/font][/color]' % ( time.strftime("%H:%M:%S\n%d/%m/%Y")) #to update time self.angryface = Image( source='C:\Users\The Gt Zan\Pictures\leangryface.PNG', pos_hint={ 'x': 0.2, 'y': 0.3 }) #an angry face self.floatt.add_widget(self.angryface) self.Rlocation.text = '[color=ff0000][size=40][font=Impact Label Reversed]FAB LAB[/color][/size][/font]' fire.put( '/', 'veriFlag', 2 ) #placing into firebase to signal to ebot to play evil toned music print 'Gave firebase a 2!' # to check whether successful or not in the command prompt/ terminal #if-else case: if no card info is received, then a '-' is seen. if card info is received then the card info is displayed if self.cardno == '': self.Rid.text = '[color=000000][size=40][font=Impact Label Reversed]-[/font][/size][/color]' else: self.Rid.text = '[color=000000][size=35][font=Impact Label Reversed]%s[/font][/size][/color]' % ( self.cardno) else: #to revert back self.floatt.remove_widget(self.angryface) self.namee.text = '[color=000000][size=40]-[/size][/color]' self.Rid.text = '[color=000000][size=40][font=Impact Label Reversed]-[/size][/font][/color]' self.Rlocation.text = '[color=000000][size=40][font=Impact Label Reversed]-[/size][/font][/color]' self.Rtime.text = '[color=000000][size=40][font=Impact Label Reversed]%s[/size][/font][/color]' % ( time.strftime("%H:%M:%S\n%d/%m/%Y")) #to update time self.refresh.text = '[size=50][font=yorkwhiteletter][color=000000]REFRESH[/font][/size][/color]' fire.put( '/', 'intruder', False ) #to switch back the boolean from self.intruder to the default False else: if self.counter == 0: fire.put( '/', 'veriFlag', 1 ) #placing into firebase to signal to ebot to play happy toned music print 'Gave firebase a 1!' # to check whether successful or not self.refresh.text = '[size=50][font=yorkwhiteletter][color=000000]CLEAR[/font][/size][/color]' d = self.known c = self.cardno name = d[ c] #to retrieve information from database. the corresponding student info is retrieved self.happyface = Image( source='C:\Users\The Gt Zan\Pictures\lehappyface.PNG', pos_hint={ 'x': 0.2, 'y': 0.3 }) self.floatt.add_widget(self.happyface) self.Rtime.text = '[color=000000][size=40][font=Impact Label Reversed]%s[/size][/font][/color]' % ( time.strftime("%H:%M:%S\n%d/%m/%Y")) #to update time self.namee.text = '[color=007700][size=40][font=Impact Label Reversed]%s[/font][/color]' % ( name) self.Rid.text = '[color=000000][size=35][font=Impact Label Reversed]%s[/font][/color]' % ( self.cardno) self.Rlocation.text = '[color=007700][size=40][font=Impact Label Reversed]CC02[/font][/color]' else: #revert back to the initial '-' symbols self.floatt.remove_widget( self.happyface) #remove the happy face image when cleared self.namee.text = '[color=000000][size=40]-[/size][/color]' self.Rlocation.text = '[color=000000][size=40][font=Impact Label Reversed]-[/font][/color]' self.Rid.text = '[color=000000][size=40][font=Impact Label Reversed]-[/size][/font][/color]' self.Rtime.text = '[color=000000][size=40][font=Impact Label Reversed]%s[/size][/font][/color]' % ( time.strftime("%H:%M:%S\n%d/%m/%Y")) #to update time self.refresh.text = '[size=50][font=yorkwhiteletter][color=000000]REFRESH[/font][/size][/color]' self.counter += 1 #is to increase self.counter = self.counter % 2 #mod two so that counter remains at 0 or 1 only # print self.intruder #to check whether the correct information is received, seen in command prompt return self.refresh.text def changeToMenu(self, value): self.manager.transition.direction = 'right' self.manager.current = 'menu' def changeToebots(self, value): self.manager.transition.direction = 'right' self.manager.current = 'bots' def changeToPersonal(self, value): self.manager.transition.direction = 'right' self.manager.current = 'individual'
class Game(Widget): def __init__(self, **kwargs): super(Game, self).__init__(**kwargs) self.layout = FloatLayout(size=Window.size) self.add_widget(self.layout) self.background = Background() self.layout.add_widget(self.background) self.missileList = [] self.speed = 1 self.score = 0 self.scoreLabel = Label(text=str(self.score), font_size=45, font_name="font", pos_hint={ "x": .0, 'y': .4 }) self.layout.add_widget(self.scoreLabel) self.startButton = Button(text="Start", font_size=30, font_name="font", size_hint=[0.25, 0.15], pos_hint={ 'center_x': 0.5, 'center_y': 0.5 }) self.startButton.bind(on_press=self.start) self.layout.add_widget(self.startButton) self.running = False if store.exists('score'): best = store.get('score')['best'] self.best = Label(text="Best: " + str(best), font_size=45, font_name="font", pos_hint={ "x": -0.35, 'y': .4 }) self.layout.add_widget(self.best) else: store.put('score', best=0) self.best = Label(text="Best: 0", font_size=45, font_name="font", pos_hint={ "x": -0.35, 'y': .4 }) self.layout.add_widget(self.best) def start(self, instance): self.layout.remove_widget(self.startButton) self.layout.remove_widget(self.best) self.summon() self.running = True Clock.schedule_interval(self.update, 1.0 / 100.0) def summon(self): edgex = int((0.25 * game.layout.width) / 2) edgey = int((0.25 * game.layout.height) / 2) while 1: col = False locx = random.randint(edgex, game.layout.width - edgex) locy = random.randint(edgey, game.layout.height - edgey) for m in self.missileList: if ((m.pos[0] - 2 * edgex <= locx) and (locx <= (m.pos[0] + 2 * edgex))) and ( ((m.pos[1] - 2 * edgey) <= locy) and (locy <= (m.pos[1] + 2 * edgey))): col = True if not col: break loc = [locx, locy] startSize = 0.05 * self.layout.width msl = Missile([startSize, startSize], loc) self.missileList.append(msl) self.layout.add_widget(msl) def update(self, dt): global second global third global fourth global fifth global speedFlag1m global speedFlag2m global speedFlag3m global speedFlag4m global speedFlag5m global speedFlag3 global speedFlag4 if self.score >= 5 and speedFlag1m: self.speed = 2 speedFlag1m = False if self.score >= 10 and second: self.speed = 1 self.summon() second = False if self.score >= 20 and speedFlag2m: self.speed = 2 speedFlag2m = False if self.score >= 30 and third: self.speed = 1 self.summon() third = False if self.score >= 50 and speedFlag3m: self.speed = 2 speedFlag3m = False if self.score >= 70 and fourth: self.speed = 1 self.summon() fourth = False if self.score >= 100 and speedFlag4m: self.speed = 2 speedFlag4m = False if self.score >= 125 and fifth: self.speed = 1 self.summon() fifth = False if self.score >= 150 and speedFlag5m: self.speed = 2 speedFlag5m = False if self.score >= 200 and speedFlag3: self.speed = 3 speedFlag3 = False if self.score >= 250 and speedFlag4: self.speed = 4 speedFlag4 = False for m in self.missileList: m.move() if not self.running: return False def on_touch_down(self, touch): if self.running: self.clickx = touch.x self.clicky = touch.y for m in self.missileList: if m.image.collide_point(touch.x, touch.y): m.explode() sound.play() self.layout.remove_widget(m) self.missileList.remove(m) self.summon() self.score = self.score + 1 #self.layout.remove_widget(self.scoreLabel) self.scoreLabel.text = str(self.score) #self.layout.add_widget(self.scoreLabel) self.add_widget(Target(touch.x, touch.y)) break else: return super(Game, self).on_touch_down(touch) def over(self): with self.layout.canvas: Color(1., 0, 0, 0.3) self.redScreen = Rectangle(pos=(0, 0), size=self.layout.size) for m in self.missileList: if m.hit: self.layout.remove_widget(m) self.layout.add_widget(m) self.layout.remove_widget(self.scoreLabel) self.layout.add_widget(self.scoreLabel) self.overButton = Button(text="Play Again?", font_size=30, font_name="font", size_hint=[0.25, 0.15], pos_hint={ 'center_x': 0.5, 'center_y': 0.5 }) self.overButton.bind(on_press=self.restart) self.layout.add_widget(self.overButton) best = store.get('score')['best'] if self.score > best: store.put('score', best=self.score) best = self.score self.best = Label(text="Best: " + str(best), font_size=45, font_name="font", pos_hint={ "x": -0.35, 'y': .4 }) self.layout.add_widget(self.best) def restart(self, instance): global second global third global fourth global fifth global speedFlag1m global speedFlag2m global speedFlag3m global speedFlag4m global speedFlag5m global speedFlag3 global speedFlag4 self.layout.clear_widgets() self.layout.canvas.clear() self.clear_widgets() self.add_widget(self.layout) self.layout.add_widget(self.background) ## for m in self.missileList: ## self.layout.remove_widget(m) ## self.layout.remove_widget(self.overButton) self.missileList = [] self.speed = 1 self.score = 0 ## self.layout.remove_widget(self.scoreLabel) self.scoreLabel.text = str(self.score) self.layout.add_widget(self.scoreLabel) self.running = True self.summon() second = True third = True fourth = True fifth = True speedFlag1m = True speedFlag2m = True speedFlag3m = True speedFlag4m = True speedFlag5m = True speedFlag3 = True speedFlag4 = True ## self.layout.canvas.remove(self.redScreen) ## self.layout.remove_widget(self.best) Clock.schedule_interval(self.update, 1.0 / 100.0)
class ChangePassword(Popup): ## # Class Constructor: __init__ # --------------------------- # This method is called during creation of the ChangePassword class. # This function creates the layout for the popup as well as initializes all the # popup attributes. # # @params # (ChangePassword) self This instance of ChangePassword # (Various) **kwargs Arguments for constuction of internal Popup object ## def __init__(self, **kwargs): self.layout = FloatLayout(size=(Window.width, 200)) super(ChangePassword, self).__init__(title='Change Password', content=self.layout, size_hint=(None, None), size=(400, 200), background=BKGD_DCHRC, pos_hint={ "center_x": .5, 'top': .7 }, auto_dismiss=False, **kwargs) ## # Class Method: draw_layout # ------------------------- # This method creates the entire layout for the change password popup including # both the password box and the verify password box. The function can also detect # if a user is selected or not and responds accordingly. # # @params # (ChangePassword) self This instance of ChangePassword ## def draw_layout(self): if manager.CURRENT_USER == None: self.layout.add_widget( Label(text="No user currently selected", pos_hint={ "center_x": .5, 'top': 1.25 })) self.layout.add_widget( HoverButton(text="Cancel", button_up=BTN_DCHRC[0], button_down=BTN_DCHRC[1], font_size=14, size_hint=(None, None), size=(100, 40), pos_hint={ "center_x": .5, 'top': .35 }, on_press=self.dismiss)) if manager.CURRENT_USER: self.new_passwd = TextInput(size_hint=(.8, None), size=(0, 30), write_tab=False, pos_hint={ 'center_x': .5, 'top': .878 }, password=True, hint_text='new password', multiline=False) self.verify_new_passwd = TextInput(size_hint=(.8, None), size=(0, 30), write_tab=False, pos_hint={ 'center_x': .5, 'top': .62 }, password=True, hint_text='verify new password', multiline=False) self.layout.add_widget(self.new_passwd) self.layout.add_widget(self.verify_new_passwd) self.layout.add_widget( HoverButton(text="Update", background_normal=BKGD_LCHRC, font_size=14, button_up=BTN_DCHRC[0], button_down=BTN_DCHRC[1], size_hint=(None, None), size=(100, 40), pos_hint={ "center_x": .65, 'top': .35 }, on_press=self.update_password)) self.layout.add_widget( HoverButton(text="Cancel", button_up=BTN_DCHRC[0], button_down=BTN_DCHRC[1], font_size=14, size_hint=(None, None), size=(100, 40), pos_hint={ "center_x": .35, 'top': .35 }, on_press=self.dismiss)) ## # Class Method: open_popup # ------------------------ # This method is called to clear the widgets of the current popup layout and redraw the # layout according to the current situation. # # @params # (ChangePassword) self This instance of ChangePassword ## def open_popup(self): self.layout.clear_widgets() self.draw_layout() self.open() ## # Class Method: update_password # ----------------------------- # This method checks the password and verify password text inputs to see if both passwords match. # In the case that no password is provided or the passwords do not match, the function provides an # error message to let the user know their mistake. In the case that they do match, the function updates # the database with the new password and closes the popup # # @params # (ChangePassword) self This instance of ChangePassword # (HoverButton) instance The button that is used to call the update_password function ## def update_password(self, instance): for child in self.layout.children: if child.text == "Please Insert a New Password" or\ child.text == "Passwords Did Not Match!": self.layout.remove_widget(child) if self.new_passwd.text == '' and self.verify_new_passwd.text == '': self.layout.add_widget( Label(text="Please Insert a New Password", color=(1, 0, 0, 1), font_size=11, pos_hint={ "center_x": .5, "top": 1.95 })) return elif self.new_passwd.text != self.verify_new_passwd.text: self.new_passwd.text = '' self.verify_new_passwd.text = '' self.layout.add_widget( Label(text="Passwords Did Not Match!", color=(1, 0, 0, 1), font_size=11, pos_hint={ "center_x": .5, "top": 1.95 })) return pw = database.Attribute("Crypt-Password", ":=", database.hash_passwd(self.new_passwd.text), 'radcheck') database.modify_user_attr(manager.CURRENT_USER, pw) self.dismiss() manager.menu.display_user_info(manager.CURRENT_USER)
class SwipeBook( ScatterPlane ): """ Upgrades: 1. Deactivate un-viewed widgets. 2. Don't press buttons when swiped. """ PAGE_W, PAGE_H = Window.size SPACING = .2 * Window.width ##### Initialization def __init__(self, *args, **kwargs): """ScatterPlane that supports navigation between pages.""" # Don't allow any touch navigation. self.do_rotation, self.do_scale, self.do_translation = False, False, False super( SwipeBook, self).__init__(*args, **kwargs) #from kivy.uix.label import Label #self.add_widget( Label( text="***** WINDOW DIMENSIONS: {} x {} *****".format( self.PAGE_W, self.PAGE_H ) ) ) self.pages = [] # Only allow one animation loop at a time. self.animating = False # Sliding velocity. self.xvel = 0 # Rendering layers: widgets in self.top are rendered on top of widgets in self.bottom. self.top_layer = FloatLayout() self.bottom_layer = FloatLayout() # The widget (and the widget tree there rooted) added first is rendered first (meaning underneath any widgets added later). self.add_widget( self.bottom_layer ) self.add_widget( self.top_layer ) ##### Widget adding/removing with layer control # Any widget added to a layer 'above' another layer is rendered on top of all widgets in the 'lower' layer. def add_widget_to_layer( self, widg, layer ): if layer == 'top': self.top_layer.add_widget( widg ) if layer == 'bottom': self.bottom_layer.add_widget( widg ) def remove_widget_from_layer( self, widg, layer): if layer == 'top': self.top_layer.remove_widget( widg ) if layer == 'bottom': self.bottom_layer.remove_widget( widg ) # Create a new page and place the widget in it. # A page is a PAGE_W x PAGE_H box that is used for collision detection. def add_page( self, widget, extend=(0,0) ): extend_x, extend_y = extend x, y = len(self.pages) * ( self.PAGE_W + self.SPACING ), 0 page = Page( (x,y), (self.PAGE_W+extend_x, self.PAGE_H+extend_y) ) self.pages += [page] # Wrap widget in a BoxLayout before placing in the swipebook. page_wrapper = BoxLayout( pos=(x,y), size=(self.PAGE_W+extend_x, self.PAGE_H+extend_y) )#(self.PAGE_W, self.PAGE_H) ) page_wrapper.add_widget( widget ) self.add_widget_to_layer( page_wrapper, 'bottom' ) def current_page(self): """Return the current page we're looking at.""" return int(-self.x / self.PAGE_W) ##### Navigation methods # Swipe right to the next page. def swipe_right( self ): self.start_page_i = self.current_page() self.start_page = self.pages[ self.start_page_i ] self.start_inertia( -50 ) # Swipe left to the previous page. def swipe_left( self ): self.start_page_i = self.current_page() self.start_page = self.pages[ self.start_page_i ] self.start_inertia( 50 ) ##### Animation control # Start the animation def start_inertia(self, xvel): global SWIPING SWIPING = True self.animating, self.xvel = True, xvel Clock.schedule_interval(self.animate, 1/120.0) # Stop the animation def stop_inertia(self): self.animating, self.xvel = False, 0 Clock.unschedule(self.animate) # Check if self is colliding with a new page. def collide_page( self, page ): return page != self.start_page and \ page.x - abs(self.xvel) <= -self.x <= page.x + abs(self.xvel) # Translate self (the viewport) horizontally. def x_shift(self, x): self.apply_transform( self.transform.inverse().translate( x, 0, 0 ) ) ##### Animation def animate( self, dt ): for p in self.pages: if self.collide_page(p): self.stop_inertia() self.x_shift( -p.x ) return self.x += self.xvel self.x_shift( self.x )
class GameScreen(Screen): def __init__(self, game_session, **kwargs): super(GameScreen, self).__init__(**kwargs) self.time_label = None self.current_load_label = None self.load_plot = None self.locations = [(0.15, 0.15), (0.25, 0.15), (0.38, 0.15), (0.5, 0.15), (0.62, 0.15), (0.73, 0.15)] self.layout = FloatLayout() self.game_session = game_session self.current_load_label = Label(text=str(self.game_session.current_load)) def display(self): background = Image(source="images/background2.png") clinic = Image(source="images/clinic.png", pos_hint={'x': .15, 'y': -0.05}, size_hint=(.7, .7)) sun = Image(source="images/sun.png", size_hint=(.7, .7)) sun.pos_hint = {'x': .15, 'y': 0.3}; self.layout.add_widget(background) self.layout.add_widget(clinic) self.layout.add_widget(sun) if self.game_session.level.battery > 0: battery = Image(source="images/battery.png", size_hint=(.3, .38), pos_hint={'x': .1, 'y': .2}) self.layout.add_widget(battery) self.time_label = Label(text="00:00:00", font_size='24dp', pos_hint={'x': .4, 'y': .01}, size_hint=(.2, .1)) self.layout.add_widget(self.time_label) back_button = Button(text="<< Menu", font_size='18dp', pos_hint={'x': .01, 'y': 0.01}, size_hint=(.15, .075), on_press=self.callpopup) self.layout.add_widget(back_button) for i, appliance in enumerate(self.game_session.level.appliances): appliance.pos_hint = {'x': self.locations[i][0], 'y': self.locations[i][1]} appliance.size_hint = (.12, .12) self.layout.add_widget(appliance) self.layout.add_widget(self.current_load_label) self.add_widget(self.layout) Clock.schedule_interval(self.update, 1) Clock.schedule_interval(self.add_drop, 1/20) Clock.schedule_interval(self.move_rain, 1/20) def add_drop(self, dt): drop = Drop() time = self.game_session.current_time() if self.game_session.level.rain[time[0]] > 0: self.game_session.rain.append(drop) self.layout.add_widget(drop) def move_rain(self, dt): for i, drop in enumerate(self.game_session.rain): drop.pos_hint = {'y': drop.pos_hint.get('y') - .01, 'x': drop.pos_hint.get('x')} if drop.pos_hint.get('y') < 0: self.layout.remove_widget(drop) del self.game_session.rain[i] del drop def update(self, dt): current_time = self.game_session.current_time() current_supply = self.game_session.level.supply[current_time[0]] current_load = self.game_session.current_load balance = current_supply - current_load hour = ("0"+str(current_time[0]))[-2:] min = ("0"+str(current_time[1]))[-2:] sec = ("0"+str(current_time[2]))[-2:] self.time_label.text = "%s:%s:%s" % (hour, min, sec) self.game_session.time += (12 * 60) / self.game_session.duration self.game_session.set_current_load() self.current_load_label.text = str(self.game_session.current_load) rect_width = 5 rect_height = 100 full_height = 480 space = 1 with self.layout.canvas: # plot supply Color(0, 1, 0, 1.0, mode='rgba') Rectangle(pos=(self.game_session.iteration * (rect_width + space), full_height - rect_height), size=(rect_width, self.game_session.level.supply[current_time[0]]/rect_height)) # plot load Color(0, 0, 1, 1.0, mode='rgba') Rectangle(pos=(self.game_session.iteration * (rect_width + space), full_height - rect_height), size=(rect_width, self.game_session.current_load/rect_height)) # plot overload (battery used) Color(1, 0, 1, 1.0, mode='rgba') if balance < 0: Rectangle(pos=(self.game_session.iteration * (rect_width + space), full_height - rect_height + current_load / rect_height), size=(rect_width, balance/rect_height)) self.game_session.iteration += 1 def callpopup(self, event): MessageBox(self, titleheader="Confirm", message="Are sure you want to quit the game", options={"YES": "yes()", "NO": "no()"}) def yes(self): self.game_session.level = None self.manager.current = 'welcome_screen' # Todo: Clock unschedule self.manager.remove_widget(self) def no(self): pass
class SvgApp(App): def build(self): from kivy.garden.smaa import SMAA Window.bind(on_keyboard=self._on_keyboard_handler) self.smaa = SMAA() self.effects = [self.smaa, Widget()] self.effect_index = 0 self.label = Label(text='SMAA', top=Window.height) self.effect = effect = self.effects[0] self.root = FloatLayout() self.root.add_widget(effect) if 0: from kivy.graphics import Color, Rectangle wid = Widget(size=Window.size) with wid.canvas: Color(1, 1, 1, 1) Rectangle(size=Window.size) effect.add_widget(wid) if 1: #from kivy.uix.image import Image #root.add_widget(Image(source='data/logo/kivy-icon-512.png', # size=(800, 600))) filenames = sys.argv[1:] if not filenames: filenames = glob(join(dirname(__file__), '*.svg')) for filename in filenames: svg = SvgWidget(filename) effect.add_widget(svg) effect.add_widget(self.label) svg.scale = 5. svg.center = Window.center if 0: wid = Scatter(size=Window.size) from kivy.graphics import Color, Triangle, Rectangle with wid.canvas: Color(0, 0, 0, 1) Rectangle(size=Window.size) Color(1, 1, 1, 1) w, h = Window.size cx, cy = w / 2., h / 2. Triangle(points=[cx - w * 0.25, cy - h * 0.25, cx, cy + h * 0.25, cx + w * 0.25, cy - h * 0.25]) effect.add_widget(wid) if 0: from kivy.uix.button import Button from kivy.uix.slider import Slider effect.add_widget(Button(text='Hello World')) effect.add_widget(Slider(pos=(200, 200))) control_ui = Builder.load_string(smaa_ui) self.root.add_widget(control_ui) def _on_keyboard_handler(self, instance, key, *args): if key == 32: self.effect_index = (self.effect_index + 1) % 2 childrens = self.effect.children[:] self.effect.clear_widgets() self.root.remove_widget(self.effect) self.effect = self.effects[self.effect_index] self.root.add_widget(self.effect) for child in reversed(childrens): self.effect.add_widget(child) self.label.text = self.effect.__class__.__name__ Window.title = self.label.text
class MenuScreen(App): def build(self): self.layout = FloatLayout() with self.layout.canvas.before: # Adding background to the layout Color(0.784, 0.878, 0.984, 1) self.layout.rect = Rectangle(size=(800, 540), post=self.layout.pos) # Logo self.image0 = Image(source='logo.png', pos=(-230, 270)) # Adding labels and images self.label1 = Label(text="[b]Bin NO:[/b]" + "\n" + "1.3A", markup=True, color=(0, 0, 0, 1), font_size=32, pos=(-240, 0)) self.label2 = Label(text="[b]Building 1 Level 3[/b]", markup=True, color=(0, 0, 0, 1), font_size=36, pos=(230, 200)) self.label3 = Label(text='0 %', color=(0, 1, 0, 1), font_size=40, pos=(20, -220)) self.image1 = Image(source='happydust bin.png') self.image2 = Image(source='saddustbin.png') self.image3 = Image(source='filleddustbin1.png') self.image4 = Image(source='shocking-bubble1.png', pos=(250, -100)) self.image5 = Image(source='happy-bubble1.png', pos=(240, 0)) self.image6 = Image(source='sad-bubble1.png', pos=(240, 0)) # Adding a quit button so that app can be closed self.quitbutton = Button(text='Quit', size_hint=(0.1, 0.1), font_size=24, pos=(100, 120), on_press=self.quit_app) # Add widget to the layout self.layout.add_widget(self.label1) self.layout.add_widget(self.label2) self.layout.add_widget(self.label3) self.layout.add_widget(self.image1) self.layout.add_widget(self.image5) self.layout.add_widget(self.image0) self.layout.add_widget(self.quitbutton) # for the values to be updated every 0.1min Clock.schedule_interval(self.update, 2) return self.layout def update(self, instance): binstatus = read_level() # Update the current bin status to the app self.label3.text = str(round(binstatus, 1)) + " %" # Update the label3 # Display different image for different bin status if float(binstatus) < 50: # Remove all the widget(images) before adding new images self.layout.remove_widget(self.image1) self.layout.remove_widget(self.image2) self.layout.remove_widget(self.image3) self.layout.remove_widget(self.image4) self.layout.remove_widget(self.image5) self.layout.remove_widget(self.image6) # Change the label color self.label3.color = (0, 1, 0, 1) # Add new widget(images) self.layout.add_widget(self.image1) self.layout.add_widget(self.image5) elif 50 <= float(binstatus) < 80: # Remove all the widget(images) before adding new images self.layout.remove_widget(self.image1) self.layout.remove_widget(self.image2) self.layout.remove_widget(self.image3) self.layout.remove_widget(self.image4) self.layout.remove_widget(self.image5) self.layout.remove_widget(self.image6) # Change the label color self.label3.color = (1, 0.549, 0, 1) # Add new widget(images) self.layout.add_widget(self.image2) self.layout.add_widget(self.image6) elif float(binstatus) >= 80: # Remove all the widget(images) before adding new images self.layout.remove_widget(self.image1) self.layout.remove_widget(self.image2) self.layout.remove_widget(self.image3) self.layout.remove_widget(self.image4) self.layout.remove_widget(self.image5) self.layout.remove_widget(self.image6) # Change the label color self.label3.color = (1, 0, 0, 1) # Add new widget(images) self.layout.add_widget(self.image3) self.layout.add_widget(self.image4) def quit_app(self, value): # Quit app function App.get_running_app().stop()
class LoginScreen(Screen): ## # Class Constructor: __init__ # --------------------------- # This method is called during the creation of the LoginScreen object. # It initializes the internal Screen object and the various other widgets present # on the login screen. # # @params # (LoginScreen) self This instance of LoginScreen # (Various) **kwargs Arguments for construction of internal Screen object ## def __init__(self, **kwargs): super(LoginScreen, self).__init__(**kwargs) with self.canvas: Color(DARK_CHARCOAL[0], DARK_CHARCOAL[1], DARK_CHARCOAL[2], 1) self.rect = Rectangle() self.bind(pos=manager.update_rect, size=manager.update_rect) self.layout = FloatLayout(size_hint=(None, None), size=(800, 600), pos_hint={ 'center_x': .5, 'center_y': .5 }) self.layout.add_widget( Label(text="Log In", font_size=40, size_hint=(None, None), pos_hint={ 'center_x': .5, 'top': .8 }, color=(1, 1, 1, 1))) self.layout.add_widget( Label(text="Username", font_size=20, size_hint=(None, None), pos_hint={ 'center_x': .5, 'top': .71 }, color=(1, 1, 1, 1))) self.username_box = TextInput(hint_text="Username", size_hint=(None, None), multiline=False, write_tab=False, size=(300, 30), pos_hint={ 'center_x': .5, 'top': .59 }) self.layout.add_widget(self.username_box) self.layout.add_widget( Label(text="Password", font_size=20, size_hint=(None, None), pos_hint={ 'center_x': .5, 'top': .58 }, color=(1, 1, 1, 1))) self.password_box = TextInput(hint_text="Password", size_hint=(None, None), size=(300, 30), write_tab=False, multiline=False, password=True, pos_hint={ 'center_x': .5, 'top': .46 }) self.layout.add_widget(self.password_box) self.layout.add_widget( HoverButton(text="Enter", size_hint=(None, None), pos_hint={ 'center_x': .5, 'top': .39 }, size=(120, 40), on_press=lambda x: self.login(), button_up=BTN_LCHRC[0], button_down=BTN_LCHRC[1])) self.err_label = Label(text="Incorrect Username and Password", font_size=11, size_hint=(None, None), color=(1, 0, 0, 1), pos_hint={ 'center_x': .5, 'top': .36 }) self.popups = Popups() self.err_present = False self.username_box.bind(on_text_validate=lambda x: self.login()) self.password_box.bind(on_text_validate=lambda x: self.login()) self.add_widget(self.layout) ## # Class Method: login # ------------------- # This method verify_user to check entered credentials, and, upon succussful # authentication, updates information in manager and redraws the main menu # for the newly logged in user. # # @params # (LoginScreen) self This instance of LoginScreen ## def login(self): if self.verify_user(): manager.LOGGED_IN = self.username_box.text manager.ADMIN = database.is_admin( self.username_box.text) or self.username_box.text == "admin" manager.sm.current = "menu" manager.menu.draw_menu() self.username_box.text = "" self.password_box.text = "" if manager.admin_pw == 'admin' and manager.ADMIN: self.popups.change_admin_prompt(None) if self.err_present: self.layout.remove_widget(self.err_label) self.err_present = False else: if not self.err_present: self.err_present = True self.layout.add_widget(self.err_label) ## # Class Method: verify_user # ------------------------- # This method queries the FreeRADIUS database to verify that the entered credentials # authenticate a user in the database. # # @params # (LoginScreen) self This instance of LoginScreen # # (bool) return True if authentication successful, false if not # def verify_user(self): username = self.username_box.text password = self.password_box.text if (username == "admin" and password == manager.admin_pw): return True actual_password = database.get_user_password(username) if not actual_password: return False if actual_password[0] == "Cleartext-Password": if actual_password == password: return True else: return False else: return database.check_passwd(password, actual_password[2])
class ebotsScreen(Screen): '''this class is written without real time function for monitoring the ebots location due to the limitations of our knowledge on the ebots. hence, the information is superimposed with pictures instead. however, should self.intruder == True , this screen will be triggered to example display how guards will be alerted by the app after pressing the refresh button''' def __init__(self, **kwargs): Screen.__init__(self, **kwargs) self.tryout = StackLayout(orientation='lr-bt') self.floatt = FloatLayout() #variable for gettinginformation() self.counter = 0 # Title of the screen self.floatt.add_widget( Label( text= '[color=000000][size=40][font=yorkwhiteletter]EBOTS INFORMATION[/font][/size][/color]', size_hint=(0.5, 0.2), markup=True, pos_hint={ 'x': 0.05, 'y': 0.8 })) #information on ebots with 'good' status self.ebotgoodpic = Image( source='C:\Users\The Gt Zan\Pictures\ebotinfo.PNG') self.floatt.add_widget(self.ebotgoodpic) #buttons at the bottom self.switchtomenu = Button( text= '[size=50][font=yorkwhiteletter][color=000000]MENU[/font][/size][/color]', markup=True, size_hint=(0.2, 0.2), background_color=(1, 1, 1, 0), on_press=self.changeToMenu) self.switchtoebot = Button( text= '[size=50][font=yorkwhiteletter][color=000000]EBOTS[/font][/size][/color]', markup=True, size_hint=(0.2, 0.2), background_color=(1, 1, 1, 0), on_press=self.changeToebots) self.switchtopersonal = Button( text= '[size=50][font=yorkwhiteletter][color=000000]INDIVIDUAL[/font][/size][/color]', markup=True, size_hint=(0.2, 0.2), background_color=(1, 1, 1, 0), on_press=self.changeToPersonal) self.tryout.add_widget(self.switchtoebot) self.tryout.add_widget(self.switchtopersonal) self.tryout.add_widget(self.switchtomenu) #getting information self.refresh = Button( text= '[size=50][font=yorkwhiteletter][color=000000]REFRESH[/font][/size][/color]', markup=True, size_hint=(0.2, 0.2), background_color=(1, 1, 1, 0), on_press=self.gettinginformation) self.tryout.add_widget(self.refresh) #add layouts self.add_widget(self.tryout) self.add_widget(self.floatt) def gettinginformation(self, value): self.intruder = fire.get('/intruder/') #actual # self.intruder = True #variable for testing only if self.intruder == True: if self.counter == 0: self.refresh.text = '[size=50][font=yorkwhiteletter][color=000000]CLEAR[/font][/size][/color]' self.ebotgoodpic.pos_hint = { 'x': 0.0, 'y': 0.15 } #to move the image upwards self.ebotintruderfound = Image( source='C:\Users\The Gt Zan\Pictures\ebotinforbad.PNG', pos_hint={ 'x': 0.0, 'y': -0.1 }) self.floatt.add_widget(self.ebotintruderfound) else: #upon clearing, the ebot page will only show info of the robots in 'normal' status self.ebotgoodpic.pos_hint = {'x': 0.0, 'y': 0.0} self.floatt.remove_widget( self.ebotintruderfound ) #to clear intruder status ebot when the button in state 'clear' is pressed self.refresh.text = '[size=50][font=yorkwhiteletter][color=000000]REFRESH[/font][/size][/color]' else: #self.intruder == False , there isn't a need to display the warning 'intruder detected' ebot alert if self.counter == 0: self.refresh.text = '[size=50][font=yorkwhiteletter][color=000000]CLEAR[/font][/size][/color]' self.ebotgoodpic.pos_hint = {'x': 0.0, 'y': 0.0} else: self.refresh.text = '[size=50][font=yorkwhiteletter][color=000000]REFRESH[/font][/size][/color]' self.counter += 1 #is to increase self.counter = self.counter % 2 #mod two so that counter remains at 0 or 1 only # print self.intruder #for monitoring on command prompt only return self.refresh.text def changeToMenu(self, value): self.manager.transition.direction = 'right' self.manager.current = 'menu' def changeToebots(self, value): self.manager.transition.direction = 'right' self.manager.current = 'bots' def changeToPersonal(self, value): self.manager.transition.direction = 'right' self.manager.current = 'individual'
class PersonalScreen(Screen): def __init__(self, **kwargs): Screen.__init__(self, **kwargs) Window.clearcolor=(1,1,1,1) #change master bg colour, RGB in .% , last is a binary: 1 = On, 0 = Off . Currently the colour is white #Layouts self.tryout = StackLayout(orientation ='lr-bt') #buttons would be placed from left to right first then bottom to top => the buttons would be stacked at the bottom from left to right first self.floatt = FloatLayout() #free size #variable for def gettinginformation() self.counter = 0 #title of the screen to be seen self.floatt.add_widget(Label(text='[color=000000][size=40][font=yorkwhiteletter]Last Screened Individual[/size][/font][/color]',size_hint= (0.5,0.2), halign='center',markup=True,pos_hint={'x':0.05,'y':0.8})) #information , left column. FIXED TEXT '''x is moving left right, y is moving up and down 0.0 for y is in the middle. to move down, use -ve column of the table is fixed at x=0.2, or 0.2 left relative to floatlayout''' self.Lname=Label(text='[color=000000][size=40][font=Impact Label Reversed]Name\nBatch[/font][/size][/color]',markup = True,pos_hint={'x':-0.2,'y':0.1}) self.Lid=Label(text='[color=000000][size=40][font=Impact Label Reversed]Card ID[/font][/size][/color]',markup = True,pos_hint={'x':-0.2,'y':0.0}) self.Llocation = Label(text='[color=000000][size=40][font=Impact Label Reversed]Location[/font][/size][/color]',markup = True,pos_hint={'x':-0.2,'y':-0.1}) self.Ltime=Label(text='[color=000000][size=40][font=Impact Label Reversed]Time\nDate[/font][/size][/color]',markup = True,pos_hint={'x':-0.2,'y':-0.2}) self.floatt.add_widget(self.Lname) self.floatt.add_widget(self.Lid) self.floatt.add_widget(self.Ltime) self.floatt.add_widget(self.Llocation) #widgets to get information, depending on the card ID received, RHS column of information #currently made RHS columns contain a '-' to show no information is being displayed self.namee = Label(text='[color=000000][size=40][font=Impact Label Reversed]-[/size][/font][/color]',halign='center',markup=True,pos_hint={'x':0.2,'y':0.1}) self.Rid=Label(text='[color=000000][size=40][font=Impact Label Reversed]-[/size][/font][/color]',markup=True,pos_hint={'x':0.2,'y':0.0}) self.Rlocation = Label(text='[color=000000][size=40][font=Impact Label Reversed]-[/size][/font][/color]',markup=True,pos_hint={'x':0.2,'y':-0.1}) self.Rtime = Label(text='[color=000000][size=40][font=Impact Label Reversed]%s[/size][/font][/color]' %(time.strftime("%H:%M:%S\n%d/%m/%Y")),markup=True,pos_hint={'x':0.2,'y':-0.2}) self.floatt.add_widget(self.namee) self.floatt.add_widget(self.Rid) self.floatt.add_widget(self.Rtime) self.floatt.add_widget(self.Rlocation) #fixed buttons at the bottom of the screen to navigate self.switchtomenu = Button(text='[size=50][font=yorkwhiteletter][color=000000]MENU[/font][/size][/color]',markup=True, size_hint=(0.2,0.2),background_color=(1,1,1,0),on_press=self.changeToMenu) self.switchtoebot = Button(text='[size=50][font=yorkwhiteletter][color=000000]EBOTS[/font][/size][/color]', markup=True,size_hint=(0.2,0.2),background_color=(1,1,1,0),on_press=self.changeToebots) self.switchtopersonal = Button(text='[size=50][font=yorkwhiteletter][color=000000]INDIVIDUAL[/font][/size][/color]', markup=True,size_hint=(0.2,0.2),background_color=(1,1,1,0),on_press=self.changeToPersonal) self.tryout.add_widget(self.switchtoebot) self.tryout.add_widget(self.switchtopersonal) self.tryout.add_widget(self.switchtomenu) # button to trigger gettinginformation self.refresh=Button(text='[size=50][font=yorkwhiteletter][color=000000]REFRESH[/font][/size][/color]', markup = True, size_hint=(0.2,0.2),background_color=(1,1,1,0),on_press=self.gettinginformation) self.tryout.add_widget(self.refresh) #add layouts self.add_widget(self.tryout) self.add_widget(self.floatt) def gettinginformation(self,value): #example dictionary acting as a database that kivy would check against self.known = {'162,180,172,117,207':'Joshua Lim\nFreshmore','345,456,567':'Chua Ah Bheng\nSenior','154,168,144,85,247':'Hoo Jian Li\nFreshmore','225,19,229,43,60':'Donald Trump\nPOTUS Candidate'} #getting information from Firebase self.cardno = fire.get('/cardID/') #information is received in string self.intruder = fire.get('/intruder/') #actual ; received in boolean # self.intruder = False #<--- variable for testing # self.cardno = '345,456,67' #<--- variable for testing ''' from the raspberry pi , self.intruder is given a default state of False. so when the state remains false, kivy app will check against self.known to anlayse if the person is a registered user or not. if it is, self.intruder changes to True. False is sent over from raspberry pi when 1. Invalid card is scanned 2. Valid card is scanned occurs the only time that self.intruder is read as True from the raspberry pi would be when the intruder does not scan the card at all.''' if self.intruder == False: #if given that self.intruder is False for number in self.known: if self.cardno == number: self.intruder = False if self.cardno != number: self.intruder = True #guards will click the 'refresh' button to capture information if self.intruder== True: if self.counter ==0: self.refresh.text = '[size=50][font=yorkwhiteletter][color=000000]CLEAR[/font][/size][/color]' #to change the text of the button self.namee.text = '[color=ff0000][size=40][font=Impact Label Reversed]INTRUDER-\nNO CARD DETECTED[/color][/size][/font]' #no valid name thus "intruder" is displayed instead self.Rtime.text = '[color=000000][size=40][font=Impact Label Reversed]%s[/size][/font][/color]' %(time.strftime("%H:%M:%S\n%d/%m/%Y")) #to update time self.angryface = Image(source='C:\Users\The Gt Zan\Pictures\leangryface.PNG',pos_hint={'x':0.2,'y':0.3}) #an angry face self.floatt.add_widget(self.angryface) self.Rlocation.text = '[color=ff0000][size=40][font=Impact Label Reversed]FAB LAB[/color][/size][/font]' fire.put('/','veriFlag',2) #placing into firebase to signal to ebot to play evil toned music print 'Gave firebase a 2!' # to check whether successful or not in the command prompt/ terminal #if-else case: if no card info is received, then a '-' is seen. if card info is received then the card info is displayed if self.cardno == '': self.Rid.text = '[color=000000][size=40][font=Impact Label Reversed]-[/font][/size][/color]' else: self.Rid.text = '[color=000000][size=35][font=Impact Label Reversed]%s[/font][/size][/color]'%(self.cardno) else: #to revert back self.floatt.remove_widget(self.angryface) self.namee.text = '[color=000000][size=40]-[/size][/color]' self.Rid.text ='[color=000000][size=40][font=Impact Label Reversed]-[/size][/font][/color]' self.Rlocation.text = '[color=000000][size=40][font=Impact Label Reversed]-[/size][/font][/color]' self.Rtime.text = '[color=000000][size=40][font=Impact Label Reversed]%s[/size][/font][/color]' %(time.strftime("%H:%M:%S\n%d/%m/%Y")) #to update time self.refresh.text = '[size=50][font=yorkwhiteletter][color=000000]REFRESH[/font][/size][/color]' fire.put('/','intruder',False) #to switch back the boolean from self.intruder to the default False else: if self.counter ==0: fire.put('/','veriFlag',1) #placing into firebase to signal to ebot to play happy toned music print 'Gave firebase a 1!' # to check whether successful or not self.refresh.text = '[size=50][font=yorkwhiteletter][color=000000]CLEAR[/font][/size][/color]' d = self.known c = self.cardno name = d[c] #to retrieve information from database. the corresponding student info is retrieved self.happyface = Image(source='C:\Users\The Gt Zan\Pictures\lehappyface.PNG',pos_hint={'x':0.2,'y':0.3}) self.floatt.add_widget(self.happyface) self.Rtime.text = '[color=000000][size=40][font=Impact Label Reversed]%s[/size][/font][/color]' %(time.strftime("%H:%M:%S\n%d/%m/%Y")) #to update time self.namee.text = '[color=007700][size=40][font=Impact Label Reversed]%s[/font][/color]' %(name) self.Rid.text = '[color=000000][size=35][font=Impact Label Reversed]%s[/font][/color]' %(self.cardno) self.Rlocation.text = '[color=007700][size=40][font=Impact Label Reversed]CC02[/font][/color]' else: #revert back to the initial '-' symbols self.floatt.remove_widget(self.happyface) #remove the happy face image when cleared self.namee.text = '[color=000000][size=40]-[/size][/color]' self.Rlocation.text = '[color=000000][size=40][font=Impact Label Reversed]-[/font][/color]' self.Rid.text ='[color=000000][size=40][font=Impact Label Reversed]-[/size][/font][/color]' self.Rtime.text = '[color=000000][size=40][font=Impact Label Reversed]%s[/size][/font][/color]' %(time.strftime("%H:%M:%S\n%d/%m/%Y")) #to update time self.refresh.text = '[size=50][font=yorkwhiteletter][color=000000]REFRESH[/font][/size][/color]' self.counter +=1 #is to increase self.counter = self.counter % 2 #mod two so that counter remains at 0 or 1 only # print self.intruder #to check whether the correct information is received, seen in command prompt return self.refresh.text def changeToMenu(self,value): self.manager.transition.direction = 'right' self.manager.current= 'menu' def changeToebots(self,value): self.manager.transition.direction = 'right' self.manager.current= 'bots' def changeToPersonal(self,value): self.manager.transition.direction = 'right' self.manager.current= 'individual'
class DogfightGame(FloatLayout, ConnectionListener): def __init__(self, *kargs, **kwargs): FloatLayout.__init__(self, *kargs, **kwargs) # Bind the keyboard self._keyboard = Window.request_keyboard(self._keyboard_closed, self) self._keyboard.bind(on_key_down = self._on_keyboard_down) self._keyboard.bind(on_key_up = self._on_keyboard_up) # Set up the controls self.controls = { 'thrust': 0, 'turning': 0, 'attack': 0, } self.old_controls = dict(self.controls) self.hud = FloatLayout(size_hint=(1, 1)) self.add_widget(self.hud) health_label = Label( text='Health', pos_hint={ 'top': 1.4, 'center_x': 0.5, } ) self.hud.add_widget(health_label) self.health = ProgressBar( pos_hint={ 'top': 1, 'center_x': 0.5, }, size_hint=(0.5, 0.1) ) self.hud.add_widget(self.health) # Screen objects self.space = FloatLayout() self.add_widget(self.space) # Objects to display self.objects = {} self.player_id = None # Debug Object if DEBUG: data = { 'object_id': 0, 'type': 'player', 'pos_x': 100, 'pos_y': 100, 'angle': 50, 'vel_x': 10, 'vel_y': 10, 'vel_angle': 120, } self.add_object(data) # Network Logic def send_action(self, action): "Send data to the server" self.Send(action) def Network_update(self, data): "Server says these objects need updates" for u in data['updates']: self.update_object(u) def Network_player(self, data): "Response from server giving player data" if 'info' in data: if 'id' in data['info']: self.player_id = data['info']['id'] self.health.max = data['info']['max_health'] self.health.value = data['info']['health'] def Network_delete(self, data): "Server says an object was removed" self.remove_object(data['object_id']) def Network(self, data): "All network data comes through here." if DEBUG: print 'Game Window:', data # Game Logic def update(self, delta_time): "Update all the objects on the screen" # Send any new controls to the server. self.send_action({'action': 'player'}) self.update_controls() if game.connected: self.Pump() # Update each object objects = self.objects for i in objects: obj = objects[i] obj.update(delta_time) if self.player_id: x, y = self.objects[self.player_id].true_pos self.starfield.scroll(x, y, 0) def update_object(self, data): "Update an object based on the data given" if not data: return # If the object doesn't exist, create it. object_id = data['object_id'] if object_id not in self.objects: self.add_object(data) return # Update it with new data. self.objects[object_id].update_data(data) # If it is not the player, then tell the object who the player is. if self.player_id and self.player_id != object_id: player = self.objects[self.player_id] self.objects[object_id].new_player(player) def add_object(self, data): "Add new object to the screen." object_id = data['object_id'] # Image for each type of entity if data['type'] == 'player': image = 'images/playerS.png' elif data['type'] == 'bullet': image = 'images/weapon.png' elif data['type'] == 'planet': image = 'images/planet.png' else: # TODO: Create generic object image. image = 'images/player.png' # Create the new object and update it with the data. new_object = GenericObject(source=image) self.objects[object_id] = new_object self.update_object(data) # Add it to the display. self.space.add_widget(new_object) def remove_object(self, object_id): "Remove an object from the screen" if object_id in self.objects: obj = self.objects[object_id] self.space.remove_widget(obj) # Delete all references. Clean up. del self.objects[object_id] del obj # Game Controls def update_controls(self): "Check if there are updates to the controls. If so, send it to the server" if self.controls != self.old_controls: self.old_controls = dict(self.controls) action = { 'action': 'controls', 'controls': self.old_controls, } self.send_action(action) def _keyboard_closed(self): "If the keyboard is closed for some reason (tablets) unbind it" self._keyboard.unbind(on_key_down = self._on_keyboard_down) self._keyboard = None def _on_keyboard_down(self, keyboard, keycode, text, modifiers): "When a key is pressed, update the controls" key = keycode[1] if key == 'w': self.controls['thrust'] = 1 if key == 'a': self.controls['turning'] = 1 elif key == 'd': self.controls['turning'] = 2 if key == 'spacebar': self.controls['attack'] = 1 def _on_keyboard_up(self, keyboard, keycode): "When a key is lifted, update the controls" key = keycode[1] if DEBUG: print key if key == 'w': self.controls['thrust'] = 0 if key == 'a' or key == 'd': self.controls['turning'] = 0 if key == 'spacebar': self.controls['attack'] = 0
class MainApp(App): def build(self): ''''Initialisation de l'app (text et bouton)''' self.fenetre = FloatLayout() self.date = 'Aujourd\'hui' self.label_ville_depart = 'Ville de départ' #pour les test : 'Ville de départ !' en temp normal self.ville_depart = None #pour les test : None en temp normal self.arret_depart = None #pour les test : None en temp normal self.status_ville_depart = None #permet de gerer si c'est pour le bouton de depart ou d'arriver self.label_ville_arriver = 'Ville d\'arriver' #pour les test : 'Ville d\'arriver !' en temp normal self.ville_arriver = None #pour les test : None en temp normal self.arret_arriver = None #pour les test : None en temp normal self.init_list_adapter_alphabet() self.init_list_adapter_ville([]) self.init_list_adapter_arret([]) self.titre = Image(source='Images/le_sept.png', size_hint=(.6, .8), pos_hint={'x': 0.2, 'center_y': 0.80}) self.affichage_date = Label(text='[color=682279]'+self.date+'[/color]', markup= True, font_size= 35, pos_hint={'x': 0, 'center_y': 0.55}) self.bouton_changer_date = Button(text='[color=682279]Changer[/color]', font_size= 35, font_name= 'fonts/Soft Elegance.ttf', background_color=(1, 1, 1, 1), markup= True, size_hint=(.2, .07), pos_hint={'x': 0.25, 'center_y': 0.40}) self.bouton_valider_date = Button(text='[color=682279]Valider[/color]', font_size= 35, font_name= 'fonts/Soft Elegance.ttf', background_color=(1, 1, 1, 1), markup= True, size_hint=(.2, .07), pos_hint={'x': 0.55, 'center_y': 0.40}) self.bouton_changer_date.bind(on_press=self.pose_choix_ville_depart) self.bouton_valider_date.bind(on_press=self.pose_choix_ville_depart) self.fenetre.add_widget(self.titre) self.fenetre.add_widget(self.affichage_date) self.fenetre.add_widget(self.bouton_changer_date) self.fenetre.add_widget(self.bouton_valider_date) return self.fenetre def pose_choix_ville_depart(self, adapter): self.fenetre.clear_widgets() self.affichage_date = Label(text='[color=682279]'+self.date+'[/color]', markup= True, font_size= 35, pos_hint={'x': 0, 'center_y': 0.55}) self.init_bouton_label_ville_depart() self.init_bouton_retour(0.1, 0.1) self.bouton_retour.bind(on_press=self.retour_main) self.bouton_label_ville_depart.bind(on_press=self.afficher_alphabet) self.fenetre.add_widget(self.titre) self.fenetre.add_widget(self.bouton_retour) self.fenetre.add_widget(self.affichage_date) self.fenetre.add_widget(self.bouton_label_ville_depart) def pose_choix_ville_arriver(self): self.fenetre.clear_widgets() self.affichage_ville_depart = Label(text='[color=682279]'+self.label_ville_depart+'[/color]', markup= True, font_size= 35, pos_hint={'x': 0, 'center_y': 0.45}) self.init_bouton_label_ville_arriver() self.init_bouton_retour(0.1, 0.1) self.bouton_retour.bind(on_press=self.retour_main) self.bouton_label_ville_arriver.bind(on_press=self.afficher_alphabet) self.fenetre.add_widget(self.titre) self.fenetre.add_widget(self.bouton_retour) self.fenetre.add_widget(self.affichage_date) self.fenetre.add_widget(self.affichage_ville_depart) self.fenetre.add_widget(self.bouton_label_ville_arriver) def pose_recherche(self): self.fenetre.clear_widgets() self.affichage_ville_arriver = Label(text='[color=682279]'+self.label_ville_arriver+'[/color]', markup= True, font_size= 35, pos_hint={'x': 0, 'center_y': 0.35}) self.bouton_recherche = Button(text='[color=682279]Recherche[/color]', font_size=35, font_name= 'fonts/Soft Elegance.ttf', background_color=(1, 1, 1, 1), markup=True, size_hint=(.3, .07), pos_hint={'x': 0.35, 'center_y': 0.1}) self.init_bouton_retour(0.1, 0.1) self.bouton_retour.bind(on_press=self.retour_main) self.bouton_recherche.bind(on_press=self.recherche) self.fenetre.add_widget(self.titre) self.fenetre.add_widget(self.bouton_retour) self.fenetre.add_widget(self.affichage_date) self.fenetre.add_widget(self.bouton_recherche) self.fenetre.add_widget(self.affichage_ville_depart) self.fenetre.add_widget(self.affichage_ville_arriver) def init_list_adapter_alphabet(self): ''''Initialise les données de la liste de l'alphabet''' if self.status_ville_depart == None: self.list_adapter_alphabet = ListAdapter( data=gestion_bd.select_alphabet_ville_depart(), cls=ListItemButton, sorted_keys=[], selection_mode='multiple', ) else: self.list_adapter_alphabet = ListAdapter( data=gestion_bd.select_alphabet_ville_arriver(self.ville_depart), cls=ListItemButton, sorted_keys=[], selection_mode='multiple', ) def init_list_adapter_ville(self, donnee): '''Initialise les données de la liste des villes''' self.list_adapter_ville = ListAdapter( data=donnee, cls=ListItemButton, sorted_keys=[], selection_mode='multiple', ) def init_list_adapter_arret(self, donnee): '''Initialise les données de la liste des arrets''' self.list_adapter_arret = ListAdapter( data=donnee, cls=ListItemButton, sorted_keys=[], selection_mode='multiple', ) def init_bouton_label_ville_depart(self): '''Initialise le bouton ville de depart''' self.bouton_label_ville_depart = Button(text='[color=682279]'+self.label_ville_depart+'[/color]', font_size= 35, font_name= "fonts/Soft Elegance.ttf", background_color=(1, 1, 1, 1), markup= True, size_hint=(0.3,0.07), pos_hint={'x': 0.35, 'center_y': 0.4}) def init_bouton_label_ville_arriver(self): '''Initialise le bouton ville d'arriver''' self.bouton_label_ville_arriver = Button(text='[color=682279]'+self.label_ville_arriver+'[/color]', font_size=35, markup= True, font_name= "fonts/Soft Elegance.ttf", background_color=(1, 1, 1, 1), size_hint=(0.3,0.07), pos_hint={'x': 0.35, 'center_y': 0.25}) def afficher_alphabet(self, value): '''Affiche la liste de l'alphabet''' if self.status_ville_depart == None: self.list_adapter_alphabet.bind(on_selection_change=self.afficher_list_ville) self.list_view_alphabet = ListView(adapter=self.list_adapter_alphabet) self.fenetre.add_widget(self.list_view_alphabet) else: self.init_list_adapter_alphabet() self.list_adapter_alphabet.bind(on_selection_change=self.afficher_list_ville) self.list_view_alphabet = ListView(adapter=self.list_adapter_alphabet) self.fenetre.add_widget(self.list_view_alphabet) def afficher_list_ville(self, adapter): ''' Initialise la liste des villes, supprime la liste de l'alphabet et affiche la liste des villes ''' if self.status_ville_depart == None: for element in adapter.selection: index_element = element.index self.init_list_adapter_ville(gestion_bd.select_villes(str(adapter.data[index_element]))) self.fenetre.remove_widget(self.list_view_alphabet) self.list_adapter_ville.bind(on_selection_change=self.select_ville) self.list_view_ville = ListView(adapter=self.list_adapter_ville) self.fenetre.add_widget(self.list_view_ville) else: for element in adapter.selection: index_element = element.index self.init_list_adapter_ville(gestion_bd.select_seconde_villes(self.ville_depart, adapter.data[index_element])) self.fenetre.remove_widget(self.list_view_alphabet) self.list_adapter_ville.bind(on_selection_change=self.select_ville) self.list_view_ville = ListView(adapter=self.list_adapter_ville) self.fenetre.add_widget(self.list_view_ville) def select_ville(self, adapter): ''' Self.label_ville_depart devient le nom de la ville de départ Initialise la liste des arrets ''' if self.status_ville_depart == None: for element in adapter.selection: index_element = element.index self.label_ville_depart = adapter.data[index_element] self.ville_depart = adapter.data[index_element] self.status_ville_depart = 'ville' self.init_list_adapter_arret(gestion_bd.select_arrets(self.label_ville_depart)) self.select_arret() else: for element in adapter.selection: index_element = element.index self.label_ville_arriver = adapter.data[index_element] self.ville_arriver = adapter.data[index_element] self.init_list_adapter_arret(gestion_bd.select_arrets(self.label_ville_arriver)) self.select_arret() def select_arret(self): '''Supprime la listes des villes, affiche la liste des arrets''' if self.status_ville_depart == 'ville': self.fenetre.remove_widget(self.list_view_ville) self.list_adapter_arret.bind(on_selection_change=self.modif_bouton) self.list_view_arret = ListView(adapter=self.list_adapter_arret) self.fenetre.add_widget(self.list_view_arret) else: self.fenetre.remove_widget(self.list_view_ville) self.list_adapter_arret.bind(on_selection_change=self.modif_bouton) self.list_view_arret = ListView(adapter=self.list_adapter_arret) self.fenetre.add_widget(self.list_view_arret) def modif_bouton(self, adapter): '''Modifie les bouton depart ou arriver''' if self.status_ville_depart == 'ville': for element in adapter.selection: index_element = element.index self.label_ville_depart = "'"+self.label_ville_depart+", "+adapter.data[index_element]+"'" self.status_ville_depart = 'ville+arret' self.arret_depart = adapter.data[index_element] self.pose_choix_ville_arriver() else: for element in adapter.selection: index_element = element.index self.label_ville_arriver = "'"+self.label_ville_arriver+", "+adapter.data[index_element]+"'" self.arret_arriver = adapter.data[index_element] self.init_bouton_label_ville_arriver() self.pose_recherche() def retour_main(self, adapter): self.fenetre.clear_widgets() MainApp().run() def init_bouton_retour(self, pos_x, pos_y): '''Initialise le bouton de réinitialisation de l'app''' self.bouton_retour = Button(text='[color=682279]Retour[/color]', font_size= 35, font_name= "fonts/Soft Elegance.ttf", markup= True, size_hint=(0.2,0.07), pos_hint={'x': pos_x, 'center_y': pos_y}) def recherche(self, value): '''Le select général''' if self.label_ville_depart != 'Ville de départ !' and self.label_ville_arriver != 'Ville d\'arriver !': self.retour = gestion_bd.select_horaire(self.ville_depart, self.arret_depart, self.ville_arriver, self.arret_arriver) if self.retour[0] == False or self.retour == 'ERREUR': self.fenetre.clear_widgets() self.affichage_erreur = Label(text='[color=682279]Il n\'y a aucun bus ce jour ci.[/color]', markup= True, font_size= 35, pos_hint={'x': 0, 'center_y': 0.60}) self.init_bouton_retour(0.42, 0.4) self.bouton_retour.bind(on_press=self.retour_main) self.fenetre.add_widget(self.affichage_erreur) self.fenetre.add_widget(self.bouton_retour) else: self.afficher_resultat() def afficher_resultat(self): '''Vide la fenêtre et affiche les resultats''' self.fenetre.clear_widgets() self.affichage_ville_depart = Label(text='[color=682279]'+self.ville_depart+'[/color]', markup= True, font_size= 25, pos_hint={'x': -0.2, 'center_y': 0.90}) self.affichage_ville_arriver = Label(text='[color=682279]'+self.ville_arriver+'[/color]', markup= True, font_size= 25, pos_hint={'x': 0.2, 'center_y': 0.90}) self.affichage_arret_depart = Label(text='[color=682279]'+self.arret_depart+'[/color]', markup= True, font_size= 25, pos_hint={'x': -0.2, 'center_y': 0.83}) self.affichage_arret_arriver = Label(text='[color=682279]'+self.arret_arriver+'[/color]', markup= True, font_size= 25, pos_hint={'x': 0.2, 'center_y': 0.83}) self.affichage_date = Label(text='[color=682279]'+str(self.date)+'[/color]', markup= True, font_size= 25, pos_hint={'x': -0.38, 'center_y': 0.98}) '''Pour chaque horaire, l'affiche''' for ville in self.retour[1]: i = 1 for bus in self.retour[1][ville]: if ville == self.ville_depart: self.affichage_horaire_depart = Label(text='[color=682279]'+'Départ à '+self.retour[1][ville]['bus'+str(i)][1]+'[/color]', markup= True, font_size= 30, pos_hint={'x': -0.2, 'center_y': 0.70-i/16}) self.fenetre.add_widget(self.affichage_horaire_depart) i += 1 else: self.affichage_horaire_arriver = Label(text='[color=682279]'+'Arrivée à '+self.retour[1][ville]['bus'+str(i)][1]+'[/color]', markup= True, font_size= 30, pos_hint={'x': 0.2, 'center_y': 0.70-i/16}) self.fenetre.add_widget(self.affichage_horaire_arriver) i += 1 self.init_bouton_retour(0.42, 0.1) self.bouton_retour.bind(on_press=self.retour_main) self.fenetre.add_widget(self.bouton_retour) self.fenetre.add_widget(self.affichage_ville_depart) self.fenetre.add_widget(self.affichage_ville_arriver) self.fenetre.add_widget(self.affichage_arret_depart) self.fenetre.add_widget(self.affichage_arret_arriver) self.fenetre.add_widget(self.affichage_date)
class MainApp(App): def __init__(self, _GabrielClient, **kwargs): super().__init__(**kwargs) self.Client = _GabrielClient def build(self): self.GabrielPage = FloatLayout() self.EditPage = FloatLayout() self.SettingsPage = FloatLayout() self.MainMenu = TabbedPanel(background_color=(1, 1, 1, 1), default_tab_text='Габриэль', default_tab_content=self.GabrielPage) self.EditMenu = TabbedPanelItem(text='Edit') self.SettingsMenu = TabbedPanelItem(text='Settings') self.MainMenu.add_widget(self.EditMenu) self.MainMenu.add_widget(self.SettingsMenu) self.In_GabrielPage() self.In_EditPage() self.In_SettingsPage() return self.MainMenu def In_GabrielPage(self): self.GabrielPage.add_widget( Image(source='./Resurses/main.jpg', color=(1, 1, 1, 0.5))) self.GabrielPage.add_widget( Button(text="LOGIN IN", on_press=self.LoginGab, size_hint=(None, None), size=(100, 50), pos=(0, 0))) def In_EditPage(self): self.EditMenu.add_widget(self.EditPage) self.EditPage_InformationMenu = FloatLayout() self.EditPage.add_widget(self.EditPage_InformationMenu) self._SelectUser = Spinner(text='Не выбран', size_hint=(None, None), size=(100, 30), pos=(0, 1000), on_press=self.find_members, on_text=self.GetInfoUser) self.EditPage.add_widget(self._SelectUser) def In_SettingsPage(self): self.SettingsMenu.add_widget(self.SettingsPage) self.SettingsPage.add_widget(Label(text="Настройки типа тут будут ")) def LoginGab(self, button): self.GabrielPage.remove_widget(button) threading.Thread(target=self.Client.run, args=(token, )).start() def find_members(self, _Spinner): if _Spinner.text == "Не выбран": self.Users = [] for file in os.listdir("./Statictics/"): self.Users.append( GabrielUser.Open(int(file.split(".gabriel")[0]), Save=False)) _Spinner.values = tuple([str(a.Name) for a in self.Users]) self.GetInfoUser(_Spinner) else: self.GetInfoUser(_Spinner) def GetInfoUser(self, _Spinner): Layout = GridLayout(cols=5) try: User = [user for user in self.Users if user.Name == _Spinner.text][0] except: return for Varname in User.__dir__(): value = User.__getattribute__(Varname) if type(value) in [str, int, float, bool, list, tuple]: ti = TextInput(text=str(value), size_hint=(None, None), size=(300, 50), background_color=(.3, 1, .6, .7)) ti.add_widget(Label(text=str(Varname), color=(1, 0, 0, 1))) Layout.add_widget(ti) self.EditPage_InformationMenu.add_widget(Layout)
class CreateGroup(Popup): ## # Class Constructor: __init__ # --------------------------- # This method is called during creation of the CreateGroup class. # This function creates the layout for the popup as well as initializes all the # popup attributes. # # @params # (CreateGroup) self This instance of CreateGroup # (Various) **kwargs Arguments for constuction of internal Popup object ## def __init__(self, **kwargs): self.layout = FloatLayout(size=(Window.width, 200)) super(CreateGroup, self).__init__(title='Add Group', content=self.layout, size_hint=(None,None), size=(400,200), background=BKGD_DCHRC, pos_hint={"center_x":.5, 'top':.7}, auto_dismiss=False, **kwargs) ## # Class Method: draw_layout # ------------------------- # This method creates the entire layout for the create group popup by calling functions to create # the group name text box, create the users dropdown, and the add or cancel buttons # # @params # (CreateGroup) self This instance of CreateGroup ## def draw_layout(self): self.dropdown = DropDown(auto_width=False, width=180, max_height=180, on_dismiss=self.display_num_down) self.dropdown.main_button = HoverButton(text="Select Users", size=(180,30), size_hint=(None,None), pos_hint={"center_x":.5, 'top':.65}, button_down=DD_DCHRC[1], button_up=DD_DCHRC[0], on_release=self.display_label) self.group_name = TextInput(size_hint=(None, None), size=(250, 30), pos_hint={'center_x':.5, 'top':.91}, hint_text='Group Name', multiline=False) self.layout.add_widget(self.group_name) self.layout.add_widget(self.dropdown.main_button) self.add_group_dropdown() self.layout.add_widget(HoverButton(text="Add", button_down=BTN_DCHRC[1], button_up=BTN_DCHRC[0], font_size=14, size_hint=(None,None), size=(100,40), pos_hint={"center_x":.7, 'top':.35}, on_press=self.add_group)) self.layout.add_widget(HoverButton(text="Cancel", button_down=BTN_DCHRC[1], button_up=BTN_DCHRC[0], font_size=14, size_hint=(None,None), size=(100,40), pos_hint={"center_x":.3, 'top':.35}, on_press=self.dismiss)) ## # Class Method: open_popup # ------------------------ # This method is called to clear the widgets of the current popup layout and redraw the # layout according to the current situation. # # @params # (CreateGroup) self This instance of CreateGroup ## def open_popup(self): self.layout.clear_widgets() self.draw_layout() self.open() ## # Class Method: display_num_down # ------------------------------ # This method displays the number of users selected in the dropdown on the mainbutton # and creates all of the ToggleButtons for all of the users # # @params # (CreateGroup) self This instance of CreateGroup # (DropDown) instance This is the dropdown that calls this function on_dismiss ## def display_num_down(self, instance): num_down = 0 for user_panel in self.dropdown.container.children: for user in user_panel.children: if type(user) == ToggleButton: if user.state == 'down': num_down += 1 if num_down == 1: self.dropdown.main_button.text = str(num_down) + " User Selected" else: self.dropdown.main_button.text = str(num_down) + " Users Selected" for child in self.layout.children: if type(child) == Label and child.text == 'Priority': self.layout.remove_widget(child) ## # Class Method: display_label # --------------------------- # This method displays the label priority when the popup opens for clarification of the text boxes # in the ToggleButtons # # @params # (CreateGroup) self This instance of CreateGroup # (HoverButton) instance This is the main button for the dropdown ## def display_label(self, instance): self.dropdown.open(self.dropdown.main_button) self.layout.add_widget(Label(text="Priority", size_hint=(None,None), size = (40,20), font_size=9, pos_hint={'center_x':.7, 'top':.56})) ## # Class Method: add_group_dropdown # -------------------------------- # This method adds all of the ToggleButtons to the dropdown # # @params # (CreateGroup) self This instance of CreateGroup ## def add_group_dropdown(self): all_users = database.get_all_users() for user in all_users: user_tog = UserToggle(user) self.dropdown.add_widget(user_tog) ## # Class Method: add_group # ----------------------- # This method adds all of the selected users to a group with the name stored in the group name text input. # If no users are selected or no group name is provided, and error label appears to inform the end user # # @params # (CreateGroup) self This instance of CreateGroup # (HoverButton) instance The button pressed in order to call add_group ## def add_group(self, instance): if self.group_name.text == '': for child in self.layout.children: if type(child) == Label and child.text == "Please Insert a Group Name and Select Group Members": self.content.remove_widget(child) self.content.add_widget(Label(text="Please Insert a Group Name and Select Group Members", size_hint=(None,None), font_size=12, color=(1,0,0,1), pos_hint={'center_x':.5, 'top':1.8})) else: names_selected = False for user_panel in self.dropdown.container.children: for user in user_panel.children: if type(user) == ToggleButton and user.state == 'down': names_selected = True database.add_group_member(user.text, self.group_name.text, user_panel.priority_text.text) if not names_selected: for child in self.layout.children: if type(child) == Label and child.text == "Please Insert a Group Name and Select Group Members": self.content.remove_widget(child) self.content.add_widget(Label(text="Please Insert a Group Name and Select Group Members", size_hint=(None,None), font_size=12, color=(1,0,0,1), pos_hint={'center_x':.5, 'top':1.8})) else: self.dismiss() manager.menu.show_groups()
class Breakout(Widget): score = NumericProperty() game_start = False paddle_speed = 40 def __init__(self, **kw): super().__init__(**kw) #To lay bricks when game is start, also for changing levels #self.game_start = False #Keyboard magic self.keyboard = Window.request_keyboard(self.keyboard_closed, self) self.keyboard.bind(on_key_down=self.on_keyboard_down) #This is the container for all bricks #Remember to add_widget... self.layout = FloatLayout() self.add_widget(self.layout) #Figure out how the keyboard works def keyboard_closed(self): self.keyboard.unbind(on_key_down=self.on_keyboard_down) self.keyobard = None def on_keyboard_down(self, keyboard, keycode, text, modifiers): if keycode[1] == 'left': self.player.center_x -= self.paddle_speed elif keycode[1] == 'right': self.player.center_x += self.paddle_speed def update( self, dt ): # the game's clock added to update to be able to control the update from the game #Initialization for game, game_start is now a one use variable, banished from the realm if not self.game_start: self.begin() self.toggle_start() #Below is fixed through unsatisfying end game condition on game end #game_start variable system needs to be replaced so begin() or game_over() aren't called repeatedly #Checks for end of game if not self.layout.children or self.ball.top < 0: self.ball.center = self.ball.start_pos self.ball.velocity = (0, 0) self.game_over() #Core game loop #Changing direction when hitting walls needs to be implemented self.ball.move() for brick in self.layout.children: brick.collide_ball(self.ball, self) self.player.collide_ball(self.ball) def game_over(self): #Tests if there is any bricks left/if the player loses before starting game over #Condition transferred to update() #Learn to toggle UI elements on/off with .kv lang over_screen = Label(text='Your score is {}'.format(str(self.score)), font_size=72, pos=self.center, size=(0, 0)) self.add_widget(over_screen) #schedule_once calls a function after the 2nd argument amount of seconds #REGARDING THE LAMBDA PARTIAL, DON'T BUT LAMBDA IN THE FOR LOOP, ADD *args to all functions, and lambda individually todo_list = [ self.clear_bricks, lambda dt: partial(self.remove_widget, over_screen)(), self.begin ] for itm in todo_list: Clock.schedule_once(itm, 2) def begin(self, *args): self.lay_bricks(0) # Lvl 0 self.ball.init(self) self.score = 0 def toggle_start(self, *args): self.game_start = not self.game_start def lay_bricks(self, level): #List of Brick classes based on the given level ''' new_bricks = [] for i in BrickManager.levels[level]: new_bricks += [i] * 10 bricks = [Brick(itm) for itm in new_bricks] # 800 * 600, 800 / 80 width == 10 #Subwidget for holding all the bricks layout = Widget() #TO DO: Auto layout of bricks x = 0 for layer, brick in enumerate(bricks): y = self.height - 100 - (layer+1) * brick.height #Assigning pos this way does not seem to work, thus the function was rewritten brick.pos = (x, y) x += brick.width layout.add_widget(brick) self.layout = layout self.add_widget(self.layout) ''' #Diff between this and docstring is that the classes are instantiated much later bricks = BrickManager.levels[level] #For every layer, it creates 10 bricks with unique positions to add for order, itm in enumerate(bricks): x = 0 y = self.height - 100 - (order + 1) * Brick().height for _ in range(10): self.layout.add_widget(Brick(itm, (x, y))) x += Brick().width def clear_bricks(self, *args): for i in self.layout.children: self.layout.remove_widget(i)
class InteractionScreen( Screen ): #This is the main screen for drawing and user input. Next steps include nesting layouts and adding/binding buttons def __init__(self, **kwargs): super(InteractionScreen, self).__init__(**kwargs) self.INTERVAL = 2.6 #THIS INTERVAL IS USED FOR SYNCING IMAGE UPDATING W/ ALGORITHM ### CREATE LAYOUTS self.layout = FloatLayout( ) #creates a Float Layout called self.layout (self. allows reference for entire class?) self.layout.width = Window.width self.layout.height = Window.height self.layout.x = 0 self.layout.y = 0 self.rightlayout = FloatLayout( ) #creates Float Layout for object selector, speed and angle labels, go button self.rightlayout.width = self.layout.width * (1. / 6.) self.rightlayout.height = self.layout.height self.rightlayout.x = Window.width - self.rightlayout.width self.rightlayout.y = Window.height / 2 - self.rightlayout.height / 2 self.leftlayout = FloatLayout( ) # float layout for drawing area and background images self.leftlayout.width = self.layout.width * (5. / 6.) self.leftlayout.height = self.layout.height self.leftlayout.x = 0 #Window.width - self.centerlayout.width self.leftlayout.y = 0 #Window.width/2 - self.centerlayout.height/2 with self.rightlayout.canvas: #sets canvas instructions for the rightlayout and draws a blue rect. filling the entire layout Color(.125, .184, .31, 1) #BLUE Rectangle(pos=(self.rightlayout.x, self.rightlayout.y), size=(self.rightlayout.width, self.rightlayout.height)) ### LEFT LAYOUT CONTENT # DRAWING FUNCTIONALITY global drawUtility drawUtility = DrawingApp() drawUtility.size_hint = (5. / 6., 1) self.leftlayout.add_widget(drawUtility, 0) self.layout.add_widget(self.leftlayout, 2) self.layout.add_widget(self.rightlayout) self.add_widget(self.layout) # DEFAULT BACKGROUND IMAGE self.bg_image_default = Image(source=assetsdirectory + str('starfield.jpg')) self.bg_image_default.allow_stretch = True self.bg_image_default.keep_ratio = False self.bg_image_default.size_hint = ((5. / 6.), 1) self.bg_image_default.pos = (0, 0) self.bg_image_default.opacity = 1.0 self.leftlayout.add_widget(self.bg_image_default, 1) #ADDS DEFAULT BACKGROUND IMAGE #### BACKGROUND IMAGE UPDATE FUNCTION self.imageNumber = 1 #default image number, used in XOR function to alternate images in imageUpdate function self.event = Clock.schedule_interval( self.imageUpdate, self.INTERVAL ) #SCHEDULES THE IMAGE UPDATING TO OCCUR, INTERVAL DEFINED AT START OF CLASS ### RIGHT LAYOUT CONTENT # HOME BUTTON homeButton = Button(text='HOME', font_size='25sp') homeButton.pos_hint = {'x': 0, 'y': .8} homeButton.color = [.937, .804, .769, 1] homeButton.size_hint = ((1. / 6.), .2) homeButton.background_color = [.353, .396, .522, 1] homeButton.bind(on_press=self.changer) self.rightlayout.add_widget(homeButton, 0) # TOPOGRAPHY LABEL self.topoLabel = Label(text='TOPOGRAPHY', halign='center') self.topoLabel.pos_hint = {'x': 0, 'y': .65} self.topoLabel.color = [.937, .804, .769, 1] self.topoLabel.font_size = '17sp' self.topoLabel.size_hint = ((.1 / .6), .2) self.topoLabel.background_color = [.353, .396, .522, 1] self.rightlayout.add_widget(self.topoLabel) # TOPOGRAPHY TOGGLE SWITCH self.topoSwitch = Switch( active=True ) # switch to toggle between updating topography and static star field self.topoSwitch.pos_hint = {'x': 0, 'y': .6} self.topoSwitch.size_hint = ((1. / 6.), .15) self.topoSwitch.background_color = [.125, .184, .31, 1] self.rightlayout.add_widget(self.topoSwitch) self.topoSwitch.bind( active=self.topoChange) # bind switch to topoChange function # SPEED LABEL self.spdLabel = Label(text='SPEED:\n' + str(drawUtility.speed), halign='center') # label showing current speed self.spdLabel.pos_hint = {'x': 0, 'y': .4} self.spdLabel.font_size = '17sp' self.spdLabel.color = [.937, .804, .769, 1] self.spdLabel.size_hint = ((1. / 6.), .2) self.spdLabel.background_color = [.4, .4, .4, 1] self.rightlayout.add_widget(self.spdLabel) def update_speed( value, instance): # callback function to bind speed to vector self.spdLabel.text = 'SPEED:\n' + str(drawUtility.speed) drawUtility.bind(speed=update_speed) # bind speed to vector length # ANGLE LABEL self.angLabel = Label(text='ANGLE:\n' + str(drawUtility.angle), halign='center') # label showing current angle self.angLabel.pos_hint = {'x': 0, 'y': .2} self.angLabel.font_size = '17sp' self.angLabel.size_hint = ((1. / 6.), .2) self.angLabel.color = [.937, .804, .769, 1] self.angLabel.background_color = [.4, .4, .4, 1] self.rightlayout.add_widget(self.angLabel) def update_angle( value, instance): # callback function to bind angle to vector self.angLabel.text = 'ANGLE:\n' + str(drawUtility.angle) drawUtility.bind(angle=update_angle) # bind angle to vector # GO! BUTTON self.goButton = MyButton( text='GO!') # go button to send user input to algorithm self.goButton.pos_hint = {'x': 0, 'y': 0} self.goButton.font_size = '30sp' self.goButton.size_hint = ((1. / 6.), .2) self.goButton.color = [.937, .804, .769, 1] self.goButton.background_color = [.353, .396, .522, 1] self.goButton.bind( on_release=self.userInput ) # when the button is released the USERINPUT function is called self.rightlayout.add_widget(self.goButton) ### FUNCTIONS def userInput( self, *args ): # function to save user input and take output from algorithm name_of_file = 'algorithm_input' # USER INPUT FILENAME inputFileName = os.path.join(assetsdirectory, name_of_file + '.txt') #TOTAL PATH NAME with open( inputFileName, 'w' ) as f: # create file and write initial and final coordinate positions f.write('%f\t%f\t%f\t%f' % (drawUtility.x_initial, drawUtility.y_initial, drawUtility.x_final, drawUtility.y_final)) drawUtility.canvas.clear() particle = Particle( pos=(drawUtility.x_initial, drawUtility.y_initial), size=(10, 10)) # draw a particle at chosen initial position drawUtility.add_widget(particle) while os.path.isfile( 'algorithm_output.npy') == False: # search for output file sleep(1) print("Still no file") else: #x = np.load('mylistx.npy'); xs = np.split(x, len(x)/200, 0) # test data #y = np.load('mylisty.npy'); ys = np.split(y, len(y)/200, 0) print("File found!") x, y = np.load('algorithm_output.npy') # load in algorithm output xs = np.split(x, len(x) / 200, 0) ys = np.split( y, len(y) / 200, 0) # split x and y arrays into manageable chunks for animation #self.animate(xs, ys, 0, particle) # call animation function with output data ''' def animate(self, x_coords, y_coords, index, instance): # function to animate particle through orbit if index < len(x_coords): # check if reached last coordinate chunk animation = Animation(pos=(int(x_coords[index][0]), int(y_coords[index][0])), t='linear', duration=.02) # create animation instance beginning at first coordinate of chunk for i in np.arange(1, len(x_coords[index])): # add all points in chunk to animation instance in sequence animation += Animation(pos=(int(x_coords[index][i]), int(y_coords[index][i])), t='linear', duration=.02) animation.bind(on_complete=lambda x, y: (self.animate(x_coords, y_coords, index+1, instance))) # once one chunk is animated, animate next animation.start(instance) # begin animation ''' def changer(self, *args): # function to go back to home screen self.manager.current = 'screen1' self.manager.transition.direction = 'right' def topoChange( self, instance, value): # function for turning updating topography on and off if self.topoSwitch.active == True: # if topography active, call image update function once every .2 seconds self.event = Clock.schedule_interval(self.imageUpdate, self.INTERVAL) elif self.topoSwitch.active == False: # if topography not active, self.event.cancel() # cancel clock event self.leftlayout.remove_widget( self.bg_image) # remove the updating background image widget self.leftlayout.add_widget(self.bg_image_default, 1) # add default image widget def imageUpdate(self, dt): # function for live topography updating #TESTING MULTIPLE IMAGE UPDATE try: self.leftlayout.remove_widget( self.bg_image_default ) # try to remove both image widgets, ensures proper layering of widgets self.leftlayout.remove_widget(self.bg_image) except: pass self.imageNumber ^= 1 # XOR function for switching background images between color_field_0 and color_field_1 imageStr = assetsdirectory + str('color_field_') + str( self.imageNumber) + '.jpg' #color_field_ + 1 or 0 #print('imageNumber: %s' % self.imageNumber) self.bg_image = Image(source=imageStr) self.bg_image.allow_stretch = True self.bg_image.keep_ratio = False self.bg_image.size_hint = ((5. / 6.), 1) self.bg_image.pos = (0, 0) self.bg_image.opacity = 1.0 self.bg_image.nocache = True #self.bg_image.reload() self.leftlayout.add_widget(self.bg_image, 1) # add topography image widget
class MainApp(App): def build(self): """'Initialisation de l'app (text et bouton)""" self.fenetre = FloatLayout() self.date = self.init_date() self.label_ville_depart = "Ville de départ !" # pour les test : 'Ville de départ !' en temp normal self.ville_depart = None # pour les test : None en temp normal self.arret_depart = None # pour les test : None en temp normal self.status_ville_depart = None # permet de gerer si c'est pour le bouton de depart ou d'arriver self.label_ville_arriver = "Ville d'arriver !" # pour les test : 'Ville d\'arriver !' en temp normal self.ville_arriver = None # pour les test : None en temp normal self.arret_arriver = None # pour les test : None en temp normal self.init_list_adapter_alphabet() self.init_list_adapter_ville([]) self.init_list_adapter_arret([]) self.titre = Image(source="Images/le_sept.png", size_hint=(0.6, 0.8), pos_hint={"x": 0.2, "center_y": 0.80}) self.bouton_date = Button( text="[color=682279]" + self.date + "[/color]", font_size_hint=1, font_name="fonts/Soft Elegance.ttf", markup=True, size_hint=(0.3, 0.05), pos_hint={"x": 0.35, "center_y": 0.6}, ) self.init_bouton_label_ville_depart() self.init_bouton_label_ville_arriver() self.bouton_recherche = Button( text="[color=682279]Recherche[/color]", font_size_hint=1, font_name="fonts/Soft Elegance.ttf", markup=True, size_hint=(0.3, 0.05), pos_hint={"x": 0.35, "center_y": 0.2}, ) self.bouton_label_ville_depart.bind(on_press=self.afficher_alphabet) self.bouton_label_ville_arriver.bind(on_press=self.afficher_alphabet) self.bouton_recherche.bind(on_press=self.recherche) self.fenetre.add_widget(self.titre) self.fenetre.add_widget(self.bouton_date) self.fenetre.add_widget(self.bouton_label_ville_depart) self.fenetre.add_widget(self.bouton_label_ville_arriver) self.fenetre.add_widget(self.bouton_recherche) return self.fenetre def init_date(self): """Initialise la date""" objet_date = datetime.now() if len(str(objet_date.month)) == 1: mois = "0" + str(objet_date.month) else: mois = str(objet_date.month) date = str(objet_date.day) + "/" + mois + "/" + str(objet_date.year) return date def init_list_adapter_alphabet(self): """'Initialise les données de la liste de l'alphabet""" self.list_adapter_alphabet = ListAdapter( data=[ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", ], cls=ListItemButton, sorted_keys=[], selection_mode="multiple", ) def init_list_adapter_ville(self, donnee): """Initialise les données de la liste des villes""" self.list_adapter_ville = ListAdapter( data=donnee, cls=ListItemButton, sorted_keys=[], selection_mode="multiple" ) def init_list_adapter_arret(self, donnee): """Initialise les données de la liste des arrets""" self.list_adapter_arret = ListAdapter( data=donnee, cls=ListItemButton, sorted_keys=[], selection_mode="multiple" ) def init_bouton_label_ville_depart(self): """Initialise le bouton ville de depart""" self.bouton_label_ville_depart = Button( text="[color=682279]" + self.label_ville_depart + "[/color]", font_size_hint=0.5, markup=True, font_name="fonts/Soft Elegance.ttf", size_hint=(0.3, 0.05), pos_hint={"x": 0.35, "center_y": 0.5}, ) def init_bouton_label_ville_arriver(self): """Initialise le bouton ville d'arriver""" self.bouton_label_ville_arriver = Button( text="[color=682279]" + self.label_ville_arriver + "[/color]", font_size_hint=0.5, markup=True, font_name="fonts/Soft Elegance.ttf", size_hint=(0.3, 0.05), pos_hint={"x": 0.35, "center_y": 0.4}, ) def afficher_alphabet(self, value): """Affiche la liste de l'alphabet""" if self.status_ville_depart == None: self.list_adapter_alphabet.bind(on_selection_change=self.afficher_list_ville) self.list_view_alphabet = ListView(adapter=self.list_adapter_alphabet) self.fenetre.add_widget(self.list_view_alphabet) else: self.init_list_adapter_alphabet() self.list_adapter_alphabet.bind(on_selection_change=self.afficher_list_ville) self.list_view_alphabet = ListView(adapter=self.list_adapter_alphabet) self.fenetre.add_widget(self.list_view_alphabet) def afficher_list_ville(self, adapter): """ Initialise la liste des villes, supprime la liste de l'alphabet et affiche la liste des villes """ if self.status_ville_depart == None: for element in adapter.selection: index_element = element.index self.init_list_adapter_ville(gestion_bd.select_villes(str(adapter.data[index_element]))) self.fenetre.remove_widget(self.list_view_alphabet) self.list_adapter_ville.bind(on_selection_change=self.select_ville) self.list_view_ville = ListView(adapter=self.list_adapter_ville) self.fenetre.add_widget(self.list_view_ville) else: for element in adapter.selection: index_element = element.index self.init_list_adapter_ville( gestion_bd.select_seconde_villes(self.label_ville_depart, adapter.data[index_element]) ) self.fenetre.remove_widget(self.list_view_alphabet) self.list_adapter_ville.bind(on_selection_change=self.select_ville) self.list_view_ville = ListView(adapter=self.list_adapter_ville) self.fenetre.add_widget(self.list_view_ville) def select_ville(self, adapter): """ Self.label_ville_depart devient le nom de la ville de départ Initialise la liste des arrets """ if self.status_ville_depart == None: for element in adapter.selection: index_element = element.index self.label_ville_depart = adapter.data[index_element] self.ville_depart = adapter.data[index_element] self.status_ville_depart = "ville" self.init_list_adapter_arret(gestion_bd.select_arrets(self.label_ville_depart)) self.select_arret() else: for element in adapter.selection: index_element = element.index self.label_ville_arriver = adapter.data[index_element] self.ville_arriver = adapter.data[index_element] self.init_list_adapter_arret(gestion_bd.select_arrets(self.label_ville_arriver)) self.select_arret() def select_arret(self): """Supprime la listes des villes, affiche la liste des arrets""" if self.status_ville_depart == "ville": self.fenetre.remove_widget(self.list_view_ville) self.list_adapter_arret.bind(on_selection_change=self.modif_bouton) self.list_view_arret = ListView(adapter=self.list_adapter_arret) self.fenetre.add_widget(self.list_view_arret) else: self.fenetre.remove_widget(self.list_view_ville) self.list_adapter_arret.bind(on_selection_change=self.modif_bouton) self.list_view_arret = ListView(adapter=self.list_adapter_arret) self.fenetre.add_widget(self.list_view_arret) def modif_bouton(self, adapter): """Modifie les bouton depart ou arriver""" if self.status_ville_depart == "ville": for element in adapter.selection: index_element = element.index self.label_ville_depart = "'" + self.label_ville_depart + ", " + adapter.data[index_element] + "'" self.status_ville_depart = "ville+arret" self.arret_depart = adapter.data[index_element] self.fenetre.remove_widget(self.list_view_arret) self.fenetre.remove_widget(self.bouton_label_ville_depart) self.init_bouton_label_ville_depart() self.fenetre.add_widget(self.bouton_label_ville_depart) else: for element in adapter.selection: index_element = element.index self.label_ville_arriver = "'" + self.label_ville_arriver + ", " + adapter.data[index_element] + "'" self.arret_arriver = adapter.data[index_element] self.fenetre.remove_widget(self.list_view_arret) self.fenetre.remove_widget(self.bouton_label_ville_arriver) self.init_bouton_label_ville_arriver() self.fenetre.add_widget(self.bouton_label_ville_arriver) def recherche(self, value): """Le select général""" if self.label_ville_depart != "Ville de départ !" and self.label_ville_arriver != "Ville d'arriver !": self.retour = gestion_bd.select_horaire( self.ville_depart, self.arret_depart, self.ville_arriver, self.arret_arriver ) self.afficher_resultat() def afficher_resultat(self): """Vide la fenêtre et affiche les resultats""" self.fenetre.clear_widgets() self.affichage_ville_depart = Label( text="[color=682279]" + self.ville_depart + "[/color]", markup=True, font_size=25, pos_hint={"x": -0.2, "center_y": 0.90}, ) self.affichage_ville_arriver = Label( text="[color=682279]" + self.ville_arriver + "[/color]", markup=True, font_size=25, pos_hint={"x": 0.2, "center_y": 0.90}, ) self.affichage_arret_depart = Label( text="[color=682279]" + self.arret_depart + "[/color]", markup=True, font_size=25, pos_hint={"x": -0.2, "center_y": 0.83}, ) self.affichage_arret_arriver = Label( text="[color=682279]" + self.arret_arriver + "[/color]", markup=True, font_size=25, pos_hint={"x": 0.2, "center_y": 0.83}, ) self.affichage_date = Label( text="[color=682279]" + str(self.date) + "[/color]", markup=True, font_size=25, pos_hint={"x": -0.38, "center_y": 0.98}, ) """Pour chaque horaire, l'affiche""" for ville in self.retour: i = 1 for bus in self.retour[ville]: if ville == self.ville_depart: self.affichage_horaire_depart = Label( text="[color=682279]Départ à " + self.retour[ville]["bus" + str(i)][1] + "[/color]", markup=True, font_size=30, pos_hint={"x": -0.2, "center_y": 0.70 - (i / 16)}, ) self.fenetre.add_widget(self.affichage_horaire_depart) i += 1 else: self.affichage_horaire_arriver = Label( text="[color=682279]Arrivée à " + self.retour[ville]["bus" + str(i)][1] + "[/color]", markup=True, font_size=30, pos_hint={"x": 0.2, "center_y": 0.70 - (i / 16)}, ) self.fenetre.add_widget(self.affichage_horaire_arriver) i += 1 self.fenetre.add_widget(self.affichage_ville_depart) self.fenetre.add_widget(self.affichage_ville_arriver) self.fenetre.add_widget(self.affichage_arret_depart) self.fenetre.add_widget(self.affichage_arret_arriver) self.fenetre.add_widget(self.affichage_date)