class GameOverDlg(Popup): def __init__(self, **kw): super(GameOverDlg, self).__init__(**kw) self.content = GridLayout(rows=4) self.title = 'Rainballz' self.content.add_widget(Label( text='GAME OVER', font_name='font/Mouser 3D.ttf', font_size=60)) self.content.add_widget(Label( text='SCORE: ' + str(kw['score']), font_name='font/Mouser 3D.ttf', font_size=60)) self.content.add_widget(Label( text='CONTINUE?', font_name='font/Mouser 3D.ttf', font_size=60)) self.bl_btns = GridLayout(cols=2) self.img_yes = Image(source='img/yes_gray.png', size_hint=(.5, .5)) self.img_no = Image(source='img/no_gray.png', size_hint=(.5, .5)) self.bl_btns.add_widget(self.img_yes) self.bl_btns.add_widget(self.img_no) self.content.add_widget(self.bl_btns) self.timeout = False Clock.schedule_once(self.set_timeout, 2) def set_timeout(self, *args): self.timeout = True self.img_yes.source='img/yes.png' self.img_no.source='img/no.png' def on_touch_down(self, touch): if self.timeout: app = App.get_running_app() if self.img_no.collide_point(*touch.pos): app.stop() elif self.img_yes.collide_point(*touch.pos): wnd = app.root_window for child in wnd.children: wnd.remove_widget(child) del child from rootwidget import RootWidget wnd.add_widget(RootWidget())
class GameOverDlg(Popup): def __init__(self, **kw): super(GameOverDlg, self).__init__(**kw) self.content = GridLayout(rows=4) self.title = 'Rainballz' self.content.add_widget( Label(text='GAME OVER', font_name='font/Mouser 3D.ttf', font_size=60)) self.content.add_widget( Label(text='SCORE: ' + str(kw['score']), font_name='font/Mouser 3D.ttf', font_size=60)) self.content.add_widget( Label(text='CONTINUE?', font_name='font/Mouser 3D.ttf', font_size=60)) self.bl_btns = GridLayout(cols=2) self.img_yes = Image(source='img/yes_gray.png', size_hint=(.5, .5)) self.img_no = Image(source='img/no_gray.png', size_hint=(.5, .5)) self.bl_btns.add_widget(self.img_yes) self.bl_btns.add_widget(self.img_no) self.content.add_widget(self.bl_btns) self.timeout = False Clock.schedule_once(self.set_timeout, 2) def set_timeout(self, *args): self.timeout = True self.img_yes.source = 'img/yes.png' self.img_no.source = 'img/no.png' def on_touch_down(self, touch): if self.timeout: app = App.get_running_app() if self.img_no.collide_point(*touch.pos): app.stop() elif self.img_yes.collide_point(*touch.pos): wnd = app.root_window for child in wnd.children: wnd.remove_widget(child) del child from rootwidget import RootWidget wnd.add_widget(RootWidget())
class MyImage(Scatter): def __init__(self, no, **kwargs): super(MyImage, self).__init__(**kwargs) self.no = no self.image = Image(source="bluerose.png") self.add_widget(self.image) self.size_hint = None, None self.width = 140 self.height = 140 self.pos = 400-70+random.randint(-200,200), 300-70+random.randint(-150,150) def on_touch_down(self, touch): if self.image.collide_point( *touch.pos): print self.no else: print "failed", self.no return super(MyImage, self).on_touch_down(touch)
class Game(Widget): def __init__(self): super(Game, self).__init__() self.map = tmx.TileMapWidget('images/platformer.tmx', Window.size, params.scale) self.add_widget(self.map) spawn = self.map.map.layers['objects'].find('spawn')[0] self.player = Player((spawn.px, spawn.py), self.map.map) self.map.add_widget(self.player) # add to map so it's scrolled Clock.schedule_interval(self.update, 1.0 / 60.0) if True: #platform() == 'android': self.left_button = Image(allow_stretch=True, source='images/left-arrow-button.png', size=(sp(60), sp(60)), pos=(sp(10), sp(10))) self.add_widget(self.left_button) self.right_button = Image(allow_stretch=True, source='images/right-arrow-button.png', size=(sp(60), sp(60)), pos=(sp(80), sp(10))) self.add_widget(self.right_button) self.jump_button = Image(allow_stretch=True, source='images/up-arrow-button.png', size=(sp(60), sp(60)), pos=(Window.width - sp(70), sp(10))) self.add_widget(self.jump_button) def update(self, *ignore): self.player.update() self.map.set_focus(*self.player.pos) def on_touch_down(self, touch): if self.left_button.collide_point(touch.x, touch.y): keys[Keyboard.keycodes['left']] = True elif self.right_button.collide_point(touch.x, touch.y): keys[Keyboard.keycodes['right']] = True elif self.jump_button.collide_point(touch.x, touch.y): keys[Keyboard.keycodes['spacebar']] = True def on_touch_up(self, touch): if self.left_button.collide_point(touch.ox, touch.oy): keys[Keyboard.keycodes['left']] = False elif self.right_button.collide_point(touch.ox, touch.oy): keys[Keyboard.keycodes['right']] = False elif self.jump_button.collide_point(touch.ox, touch.oy): keys[Keyboard.keycodes['spacebar']] = False
class Game(Widget): def __init__(self): super(Game, self).__init__() self.map = tmx.TileMapWidget('images/platformer.tmx', Window.size, params.scale) self.add_widget(self.map) spawn = self.map.map.layers['objects'].find('spawn')[0] self.player = Player((spawn.px, spawn.py), self.map.map) self.map.add_widget(self.player) # add to map so it's scrolled Clock.schedule_interval(self.update, 1.0/60.0) if True: #platform() == 'android': self.left_button = Image(allow_stretch=True, source='images/left-arrow-button.png', size=(sp(60), sp(60)), pos=(sp(10), sp(10))) self.add_widget(self.left_button) self.right_button = Image(allow_stretch=True, source='images/right-arrow-button.png', size=(sp(60), sp(60)), pos=(sp(80), sp(10))) self.add_widget(self.right_button) self.jump_button = Image(allow_stretch=True, source='images/up-arrow-button.png', size=(sp(60), sp(60)), pos=(Window.width - sp(70), sp(10))) self.add_widget(self.jump_button) def update(self, *ignore): self.player.update() self.map.set_focus(*self.player.pos) def on_touch_down(self, touch): if self.left_button.collide_point(touch.x, touch.y): keys[Keyboard.keycodes['left']] = True elif self.right_button.collide_point(touch.x, touch.y): keys[Keyboard.keycodes['right']] = True elif self.jump_button.collide_point(touch.x, touch.y): keys[Keyboard.keycodes['spacebar']] = True def on_touch_up(self, touch): if self.left_button.collide_point(touch.ox, touch.oy): keys[Keyboard.keycodes['left']] = False elif self.right_button.collide_point(touch.ox, touch.oy): keys[Keyboard.keycodes['right']] = False elif self.jump_button.collide_point(touch.ox, touch.oy): keys[Keyboard.keycodes['spacebar']] = False
class CoreTask(Task): """Widget for all tasks that are currently on a core.""" def __init__(self, name, tid, core, status, **kwargs): Logger.debug("CoreTask: Inited coretask %s" % tid) self.tid = tid self._core = core self._status = status self.info_built = False self.info_showing = False self.info_button = None self.label = None self.info = None self.stop_button = None self.pause_button = None self.move_button = None self.kill_button = None self.button_strings = dict() self.scroll = None self._outfile = None self._out = [] self._cpu = 0.0 self._mem = 0.0 super(CoreTask, self).__init__(name, core.manyman, **kwargs) self._build() def _build(self): """Render this task.""" self.info_button = Image( source=self.manyman.settings['task_info_image'], color=(.8, .8, .8, 1), size_hint=(None, None), size=(40, 40) ) self.layout.add_widget(self.info_button) self.label = Label( text="..........", halign='center' ) self.layout.add_widget(self.label) # Initialize the detailed task info popup self.info = InfoPopup( title="%s (%s) - %s on core %d" % \ (self.name, self.tid, self.status, self.core.index), size_hint=(None, None), size=(600, 450) ) self.info.bind(on_show=self.info_show, on_dismiss=self.info_dismiss) # Initialize the performance graphs located in the popup self.cpu_graph = PerfGraph("CPU", container=self) self.mem_graph = PerfGraph("MEM", container=self) self.bind(pos=self.update_graphics_pos, size=self.update_graphics_size) self.update_graphics_pos(self, self.pos) self.update_graphics_size(self, self.size) self.label.text = '%s\nStatus: %s' % (self.name, self.status) def build_info(self): """Render the detailed task info popup.""" layout = BoxLayout(spacing=10) # Render the performance graphs graphs = BoxLayout( orientation='vertical', spacing=10, padding=5 ) graphs.add_widget(self.cpu_graph) graphs.add_widget(self.mem_graph) layout.add_widget(graphs) sidebar = BoxLayout( orientation='vertical', spacing=10, padding=5, size_hint_x=None, width=400 ) # Render the task control buttons controls = BoxLayout( spacing=10, padding=5, size_hint_y=None, height=60 ) self.stop_button = ImageButton( self.manyman.settings['task_stop_image'] ) self.bind_button(self.stop_button, self.stop) controls.add_widget(self.stop_button) self.pause_button = ImageButton( self.manyman.settings['task_pause_image'] ) self.bind_button(self.pause_button, self.pause) controls.add_widget(self.pause_button) self.move_button = ImageButton( self.manyman.settings['task_move_image'] ) self.bind_button(self.move_button, self.move) controls.add_widget(self.move_button) self.kill_button = ImageButton( self.manyman.settings['task_kill_image'] ) self.bind_button(self.kill_button, self.kill) controls.add_widget(self.kill_button) sidebar.add_widget(controls) # Render the output field self.scroll = ScrollView(do_scroll_x=False) self.output = Label( text=NO_OUTPUT_TEXT, text_size=(390, None), size_hint=(None, None), valign='top' ) if len(self._out) > 0: self.set_output(self._out) self.output.bind(texture_size=self.output.setter('size')) self.scroll.add_widget(self.output) sidebar.add_widget(self.scroll) layout.add_widget(sidebar) self.info.content = layout self.info_built = True def update_graphics_pos(self, instance, value): """ Handler when the task object moves. Updates its contents' positions. """ super(CoreTask, self).update_graphics_pos(instance, value) def update_graphics_size(self, instance, value): """ Handler when the task object resizes. Updates its contents' sizes. """ super(CoreTask, self).update_graphics_size(instance, value) def bind_button(self, button, string): """Bind an action (string) to the given button.""" self.button_strings[button] = string button.bind(on_release=string) def unbind_button(self, button): """Unbind all actions (strings) from a button.""" if not button in self.button_strings: return button.unbind(on_release=self.button_strings[button]) def unbind_all_buttons(self): """Unbind all actions (strings) from all buttons.""" for button, string in self.button_strings.items(): button.unbind(on_release=string) self._status = "unbound" def show_info(self): """Show the detailed task info popup.""" Logger.debug("CoreTask: Showing info") self.info.show() def info_show(self, *largs): """Handler when the detailed task info popup is opened.""" if not self.info_built: # Render the popup if not done yet self.build_info() self.info_showing = True # Request the task output every second Clock.schedule_interval(self.request_output, 1.0) def info_dismiss(self, *largs): """Handler when the detailed task info popup is closed.""" Logger.debug("CoreTask: Hiding info") self.info_showing = False # Stop requesting for output Clock.unschedule(self.request_output) def request_output(self, *largs): """Request the output of the task.""" self.manyman.comm.request_output(self.tid, len(self._out)) def kill(self, *largs): """Kill the task.""" Logger.debug("CoreTask: Killing task %s" % self.tid) self.info.dismiss() self.manyman.comm.stop_task(self.tid) self.unbind_all_buttons() def stop(self, *largs): """Stop the task.""" Logger.debug("CoreTask: Stopping task %s" % self.tid) self.manyman.comm.move_task(self, -1) self.unbind_all_buttons() def pause(self, *largs): """Pause the task.""" Logger.debug("CoreTask: Pausing task %s" % self.tid) self.manyman.comm.pause_task(self.tid) self.unbind_all_buttons() def resume(self, *largs): """Resume the task.""" Logger.debug("CoreTask: Resuming task %s" % self.tid) self.manyman.comm.resume_task(self.tid) self.unbind_all_buttons() def move(self, *largs): """Smart-move the task""" Logger.debug("CoreTask: Smart-moving task %s" % self.tid) self.manyman.comm.move_task(self) self.unbind_all_buttons() def set_output(self, output): """Append the new output to the previous output.""" self._out += output if self.manyman.settings['output_to_file']: # Write output to a file if not isdir(self.manyman.settings['output_folder']): mkdir(self.manyman.settings['output_folder']) f = open(self.outfile, "a") f.write("".join(output)) f.close() if not self.info_showing: # Do not render output when the info popup is hidden return # Determine if the output window should scroll down or not scroll_down = self.scroll.scroll_y == 0 or \ self.output.text == NO_OUTPUT_TEXT # Show the last lines of the output self.output.text = "".join( self._out[-self.manyman.settings['output_buffer_size']:] ) if scroll_down: self.scroll.scroll_y = 0 def on_touch_down(self, touch): """Handler when a task is touched. Checks for button presses first.""" x, y = touch.x, touch.y if self.info_button.collide_point(x, y): self.info_button.color = (.9, .6, 0, 1) self.show_info() return False if not self.status == "Running": return False if not super(CoreTask, self).on_touch_down(touch): return False return True def on_touch_move(self, touch): """Handler when a task is moved.""" if not self.status == "Running": return False if not super(CoreTask, self).on_touch_move(touch): return False self.info_button.color = (.8, .8, .8, 1) return True def on_touch_up(self, touch): """ Handler when a task is released. Moves the task if released on a core, stops it otherwise. """ x, y = touch.x, touch.y self.info_button.color = (.8, .8, .8, 1) if self.info_button.collide_point(x, y): return False if not super(CoreTask, self).on_touch_up(touch): return False if not self.status == "Running": return False if self.coll_core and self.coll_core.core_type != "Epiphany": self.manyman.comm.move_task(self, self.coll_core.index) self.coll_core = None else: self.manyman.comm.move_task(self, -1) return True def update_title(self): """Update the title of the detailed popup.""" if self.core and not self.status in ["Finished", "Failed"]: self.info.title = "%s (%s) - %s on core %d" % \ (self.name, self.tid, self.status, self.core.index) else: self.info.title = "%s (%s) - %s" % \ (self.name, self.tid, self.status) def get_core(self): """Retrieve the core the task is running on.""" return self._core def set_core(self, value): """Set the core the task is running on.""" self._core = value self.update_title() if not self.core: self.info.dismiss() def get_status(self): """Getter for the task's status.""" return self._status def set_status(self, value): """Setter for the task's status. Binds and unbinds buttons.""" if self._status == value: return Logger.debug("CoreTask: Set status to %s" % value) self._status = value self.label.text = '%s\nStatus: %s' % (self.name, value) self.update_title() if not self.info_built: return if self.status == "Running": self.unbind_button(self.pause_button) self.pause_button.image = self.manyman.settings['task_pause_image'] self.bind_button(self.stop_button, self.stop) self.bind_button(self.pause_button, self.pause) self.bind_button(self.move_button, self.move) self.bind_button(self.kill_button, self.kill) elif self.status == "Stopped": self.unbind_button(self.pause_button) self.pause_button.image = \ self.manyman.settings['task_resume_image'] self.bind_button(self.pause_button, self.resume) elif self.status == "Finished" or self.status == "Killed": Clock.unschedule(self.request_output) def get_cpu(self): """Getter for the current CPU usage.""" return self._cpu def set_cpu(self, value): """Setter for the current CPU usage. Updates the performance graphs.""" self._cpu = value * .01 self.core.cpu_graph.update_line(self.tid, value) self.cpu_graph.update(value) def get_mem(self): """Getter for the current memory usage.""" return self._mem def set_mem(self, value): """Setter for the current mem usage. Updates the performance graphs.""" self._mem = value * .01 self.core.mem_graph.update_line(self.tid, value) self.mem_graph.update(value) def get_outfile(self): """Getter for the output file. Generates one when not present.""" if not self._outfile: self._outfile = self.manyman.settings['output_folder'] + "/" + \ strftime("%Y%m%d-%H%M%S-") + "%s-%s.txt" % \ (self.name, self.tid) return self._outfile # Define getters and setters core = property(get_core, set_core) status = property(get_status, set_status) load_cpu = property(get_cpu, set_cpu) load_mem = property(get_mem, set_mem) outfile = property(get_outfile)
class PendingTask(Task): """Widget for tasks in the pending tasks list.""" def __init__(self, name, tid, manyman, **kwargs): Logger.debug("PendingTask: Inited pendingtask %s" % name) self.tid = tid self.command = kwargs.get('command', '') self.dup_button = None self.start_button = None super(PendingTask, self).__init__(name, manyman, **kwargs) self._build() def _build(self): """Render the PendingTask.""" self.dup_button = Image( source=self.manyman.settings['task_dup_image'], color=(.8, .8, .8, 1), size_hint=(None, None), size=(40, 40) ) self.layout.add_widget(self.dup_button) self.label = Label( text="AAAAAAAAAAAAAA", halign='center' ) self.layout.add_widget(self.label) self.start_button = Image( source=self.manyman.settings['task_start_image'], color=(.8, .8, .8, 1), size_hint=(None, None), size=(40, 40) ) self.layout.add_widget(self.start_button) self.bind( pos=self.update_graphics_pos, size=self.update_graphics_size ) self.update_graphics_pos(self, self.pos) self.update_graphics_size(self, self.size) # Force Kivy to render the labels self.label.text = "AAADSldjbdejhvdsaf" if self.is_new(): self.label.text = "%s\nNew" % self.name else: self.label.text = "%s\nStopped" % self.name def is_new(self): """Determine whether a task is new or stopped.""" return self.tid[0] == 'P' def on_touch_down(self, touch): """Handler when a task is touched. Checks for button touches first.""" x, y = touch.x, touch.y if self.dup_button.collide_point(x, y): # Duplicate the task self.dup_button.color = (.9, .6, 0, 1) Logger.debug("PendingTask: Duplicating task %s" % self.tid) if self.is_new(): self.manyman.new_task(self.command, self.name) else: self.manyman.comm.duplicate_task(self.tid) return False if self.start_button.collide_point(x, y): # Smart-start the task self.start_button.color = (.9, .6, 0, 1) if self.is_new(): self.manyman.comm.start_task(self.name, self.command) else: self.manyman.comm.move_task(self) self.parent.remove_widget(self) return False if not super(PendingTask, self).on_touch_down(touch): return False return True def on_touch_move(self, touch): """Handler when a task is dragged. Reset the button colors.""" if not super(PendingTask, self).on_touch_move(touch): return False self.dup_button.color = (.8, .8, .8, 1) self.start_button.color = (.8, .8, .8, 1) return True def on_touch_up(self, touch): """ Handler when a task is released. Starts the task on the core it was released on (if any). """ x, y = touch.x, touch.y self.dup_button.color = (.8, .8, .8, 1) self.start_button.color = (.8, .8, .8, 1) if self.dup_button.collide_point(x, y): return False if self.start_button.collide_point(x, y): return False if not super(PendingTask, self).on_touch_up(touch): return False if self.coll_core and self.coll_core.core_type != "Epiphany": if self.is_new(): self.manyman.comm.start_task( self.name, self.command, self.coll_core.index ) else: self.manyman.comm.move_task(self, self.coll_core.index) self.center = self.from_pos self.coll_core = None self.parent.remove_widget(self) return True
class AppLauncherIconWidget(GridLayout): """ Displays icon and name of a single application Also handles input on the app icon """ __imageParent = None # type: AnchorLayout __imageWidget = None # type: ImageWidget __nameWidget = None # type: Label __starter = None # type: AppStarter __paddingTmp = -1 # type: int __touched = False # type: int def __init__(self, image: Image, name: str, starter: AppStarter, height: int, **kwargs): super(AppLauncherIconWidget, self).__init__(**kwargs) self.__starter = starter self.cols = 1 self.rows = 2 self.rows_minimum[0] = height * 0.8 self.rows_minimum[1] = height - self.rows_minimum[0] self.row_force_default = True self.__imageParent = AnchorLayout() self.__imageParent.anchor_x = 'center' self.__imageParent.anchor_y = 'center' self.__imageWidget = ImageWidget() self.__imageWidget.allow_stretch = True self.__imageWidget.keep_ratio = True self.__imageWidget.texture = image.texture self.__nameWidget = Label() self.__nameWidget.text = name self.__nameWidget.color = [0, 0, 0, 1] self.__imageParent.add_widget(self.__imageWidget) self.add_widget(self.__imageParent) self.add_widget(self.__nameWidget) def set_image_size(self, size: int, percentage: float): if self.__paddingTmp is -1: self.__imageParent.padding = [(size - (size * percentage)) / 2, (size - (size * percentage)) / 2, (size - (size * percentage)) / 2, (size - (size * percentage)) / 2] else: self.__paddingTmp = (size - (size * percentage)) / 2 def on_touch_down(self, touch): if self.__imageWidget.collide_point(*touch.pos): self.__touched = True self.__paddingTmp = self.__imageParent.padding[0] self.__imageParent.padding = [self.__paddingTmp * 1 / 0.8, self.__paddingTmp * 1 / 0.8, self.__paddingTmp * 1 / 0.8, self.__paddingTmp * 1 / 0.8] else: self.__touched = False def on_touch_up(self, touch): if self.__imageParent.collide_point(*touch.pos): self.__starter.start_app() self.__imageParent.padding = [self.__paddingTmp, self.__paddingTmp, self.__paddingTmp, self.__paddingTmp] self.__paddingTmp = -1 self.__touched = False
class SettingPos(SettingString): '''Implementation of a string setting on top of a :class:`SettingItem`. It is visualized with a :class:`~kivy.uix.label.Label` widget that, when clicked, will open a :class:`~kivy.uix.popup.Popup` with a :class:`~kivy.uix.textinput.Textinput` so the user can enter a custom value. ''' popup = ObjectProperty(None, allownone=True) '''(internal) Used to store the current popup when it's shown. :attr:`popup` is an :class:`~kivy.properties.ObjectProperty` and defaults to None. ''' # position = ObjectProperty(None) '''(internal) Used to store the current textinput from the popup and to listen for changes. :attr:`textinput` is an :class:`~kivy.properties.ObjectProperty` and defaults to None. ''' pic = StringProperty() position = StringProperty('50*50') def __init__(self, **kwargs): super(SettingPos, self).__init__(**kwargs) self.img = Image(source=self.pic) def on_panel(self, instance, value): if value is None: return self.bind(on_release=self._create_popup) def _dismiss(self, *largs): if self.popup: self.popup.dismiss() self.popup = None def _register(self, instance, touch): if self.img.collide_point(*touch.pos): # self.position = '*'.join([str(p) for p in touch.pos]) # print(touch) # print(self.img.pos) # print(self.img.size) # print(Window.size) x, y = self.img.to_widget(touch.pos[0], touch.pos[1], True) x = x - self.img.pos[0] - 20.0 y = y + 68.0 # print('%s * %s' % (x, y)) self.position = str(x) + '*' + str(y) def _validate(self, instance): value = self.position self.value = value # print(self.value) self._dismiss() def _create_popup(self, instance): # create popup layout content = BoxLayout(orientation='vertical', spacing='5dp') # popup_width = min(0.95 * Window.width, dp(500)) self.popup = popup = Popup( title=self.title, content=content) pos = [float(c) for c in self.value.split('*')] scat = ScatterCross(size=(20, 20), size_hint=(None, None), pos=pos) scat.bind(on_touch_up=self._register) self.img.add_widget(scat) content.add_widget(self.img) content.add_widget(SettingSpacer()) # 2 buttons are created for accept or cancel the current value btnlayout = BoxLayout(size_hint_y=None, height='50dp', spacing='5dp') btn = Button(text='Ok') btn.bind(on_release=self._validate) btnlayout.add_widget(btn) btn = Button(text='Cancel') btn.bind(on_release=self._dismiss) btnlayout.add_widget(btn) content.add_widget(btnlayout) # all done, open the popup ! popup.open()