예제 #1
0
    def on_status(self, instance, new_value):
        status = new_value

        sums = [
            sum(status[0:3]),
            sum(status[3:6]),
            sum(status[6:9]),
            sum(status[0::3]),
            sum(status[1::3]),
            sum(status[2::3]),
            sum(status[::4]),
            sum(status[2:-2:2])
        ]

        winner = None
        if 3 in sums:
            winner = "Os win!"
        elif -3 in sums:
            winner = "Xs win!"
        elif 0 not in self.status:
            winner = "Draw!"

        if winner:
            popup = ModalView(size_hint=(0.75, 0.5))
            victory_label = Label(text=winner, font_size=50)
            popup.add_widget(victory_label)
            popup.bind(on_dismiss=self.reset)
            popup.open()
예제 #2
0
    def on_status(self, instance, new_value):
        status = new_value

        # Sum each row, column and diagonal.
        # Could be shorter, but let's be extra
        # clear what’s going on

        sums = [sum(status[0:3]), # rows
               sum(status[3:6]), sum(status[6:9]), sum(status[0::3]), # columns
               sum(status[1::3]), sum(status[2::3]), sum(status[::4]), # diagonals
               sum(status[2:-2:2])]

        # Sums can only be +-3 if one player
        # filled the whole line
        winner = None

        if -3 in sums:
            winner = 'Крестик Выиграл!'
        elif 3 in sums:
            winner = 'Нолик Выиграл!'
        elif 0 not in self.status:
            winner = 'Ничья....!'

        if winner:
            popup = ModalView(size_hint=(0.75, 0.5))
            victory_label = Label(text=winner, font_size=50)
            popup.add_widget(victory_label)
            popup.bind(on_dismiss=self.reset)
            popup.open()
예제 #3
0
파일: main.py 프로젝트: Juanvulcano/GCI
 def button_pressed(self, button):
     colours = {-1: (1, 0, 0, 1), 1: (0, 1, 0, 1)} # (r, g, b, a)
     row, column = button.coords 
     if button.pressed == 1:
         button.text = {-1: Finish.surrounded(row, column), 1: 'X'}[self.status[row][column]]
         button.background_color = colours[self.status[row][column]]
         print ('{} button clicked!'.format(button.coords))
         button.pressed = 0
         if Finish.board[row][column] == 1:
             self.treasuresfound = self.treasuresfound + 1
             if self.treasuresfound == 9:
                 popup = ModalView(size_hint=(0.75, 0.5))
                 endlabel = Button(text="You won !", font_size=50)
                 endlabel.background_color = (0, 1, 0, 1)
                 popup.add_widget(endlabel)
                 popup.bind(on_dismiss=self.reset)
                 popup.open()
         else:
            self.attempts = self.attempts - 1
            if self.attempts == 0:
               popup = ModalView(size_hint=(0.75, 0.5))
               endlabel = Button(text="Try again", font_size=50)
               popup.add_widget(endlabel)
               popup.bind(on_dismiss=self.reset)
               popup.open()
예제 #4
0
    def button_pressed(self, button):
        player = {1: 'X', -1: 'O'}
        colours = {1: (0, 1, 0, 1), -1: (1, 0, 0, 1)}

        x, y, z, w = button.coords
        already_played = self.board[x, y, z, w] != 0

        if not already_played:
            self.board[x, y, z, w] = self.current_player
            button.text = player[self.current_player]
            button.background_color = colours[self.current_player]
            winner = None
            if check_win(move = button.coords, player = self.current_player, \
                        moves = self.move_list[self.current_player], \
                        board = self.board):
                winner = '{0} wins!'.format(player[self.current_player])
            elif 0 not in self.board:
                winner = 'Draw... nobody wins!'
            if winner:
                popup = ModalView(size_hint=(0.75, 0.5))
                victory_label = Label(text=winner, font_size=50)
                popup.add_widget(victory_label)
                popup.bind(on_dismiss=self.reset)
                popup.open()
            else:
                self.current_player *= -1
예제 #5
0
	def on_status(self, instance, new_value):
		status = new_value

		# Sum each row, col and diag
		# Could be shorter, but let's be extra
		# clear what's going on

		sums = [#rows
				sum(status[0:3]),
				#columns
				sum(status[3:6]),
				sum(status[6:9]),
				sum(status[0::3]),
				#diagonals
				sum(status[1::3]), 
				sum(status[2::3]),
				sum(status[::4]),
				sum(status[2:-2:2])]
		# Sums can only be +-3 if one player
		# filled the whole line

		winner = ''
		if 3 in sums:
			winner = '{} win!'.format('Nitya')
		elif -3 in sums:
			winner = '{} win!'.format('Pranav')
		elif 0 not in self.status: #Grid full
			winner = 'Draw...Nobody wins!'

		if winner:
			popup = ModalView(size_hint = (0.75 , 0.5 ))
			victory_label = Label(text = winner, font_size = 50)
			popup.add_widget(victory_label)
			popup.bind(on_dismiss = self.reset)
			popup.open()
예제 #6
0
    def reset(self, *args):
        self.status = [0 for _ in range(9)]

        for child in self.children:
            child.text = ''
            child.background_color = (1, 1, 1, 1)

        self.current_player = 1

        winner = None

        if -3 in sums:
            winner = 'Выиграли крестики'
        elif 3 in sums:
            winner = 'Выиграли нолики'
        elif 0 not in self.status:
            winner = 'Ничья'

        if winner:
            popup = ModalView(size_hint=(0.75, 0.5))
            victory_label = Label(text=winner, font_size=50)
            popup.add_widget(victory_label)
            popup.bind(on_dismiss=self.reset)
            popup.open()

        for row in range(3):
            for column in range(3):
                grid_entry = GridEntry(coords=(row, column))
                grid_entry.bind(on_release=self.button_pressed)
                self.add_widget(grid_entry)
예제 #7
0
class StudentGridLayout(GridLayout):
    records = ''
    show = False

    def __init__(self, **kwargs):
        super().__init__()
        self.cols = 2
        self.app = AssessmentApp()

    def load_student_data(self, dt, records):
        num = 0
        for record in records:
            for data in record:
                self.add_widget(Label(text=str(dt[num])))
                self.add_widget(Button(text=str(data), size_hint=(.2, .2)))
                num += 1
                print(num)
        self.add_widget(TextInput())
        self.add_widget(Button(text='edit'))
        self._popup = ModalView(size_hint=(.5, .5))
        self._popup.add_widget(
            self)  #Popup(content=self,title='Student data',size_hint=(.7,.7))
        self._popup.open()
        self._popup.bind(
            on_dismiss=lambda *x: self._popup.remove_widget(self)
        )  #self._popup.bind(on_dismiss=self._popup.remove_widget(self.children)
예제 #8
0
    def on_status(self, instance, new_value):
        status = new_value  # updates the status property with new value

        # Sum each row, column and diagonal.
        # Could be shorter, but let’s be extra
        # clear what’s going on
        sums = [
            sum(status[0:3]),
            sum(status[3:6]),
            sum(status[6:9]),  # rows
            sum(status[0::3]),
            sum(status[1::3]),
            sum(status[2::3]),  # columns
            sum(status[0::4]),
            sum(status[2:7:2])  # diagonals
        ]

        winner = None

        if 3 in sums:
            winner = 'Kolečka vítězí!'
        elif -3 in sums:
            winner = 'Křížky vítězí!'
        elif 0 not in status:
            winner = 'Remíza ... nikdo nezvítězil!'

        if winner:
            popup = ModalView(size_hint=(0.75, 0.5))
            victory_label = Label(text=winner, font_size=50)
            popup.add_widget(victory_label)
            popup.bind(on_dismiss=self.reset)
            popup.open()
예제 #9
0
	def on_status(self, instance, new_value):
		status = new_value

		# Sum each row, col and diag
		# Could be shorter, but let's be extra
		# clear what's going on

		sums = [#rows
				sum(status[0:3]),
				#columns
				sum(status[3:6]),
				sum(status[6:9]),
				sum(status[0::3]),
				#diagonals
				sum(status[1::3]), 
				sum(status[2::3]),
				sum(status[::4]),
				sum(status[2:-2:2])]
		# Sums can only be +-3 if one player
		# filled the whole line

		winner = ''
		if 3 in sums:
			winner = '{} win!'.format('O')
		elif -3 in sums:
			winner = '{} win!'.format('X')
		elif 0 not in self.status: #Grid full
			winner = 'Draw...Nobody wins!'

		if winner:
			popup = ModalView(size_hint = (0.75 , 0.5 ))
			victory_label = Label(text = winner, font_size = 50)
			popup.add_widget(victory_label)
			popup.bind(on_dismiss = self.reset)
			popup.open()
예제 #10
0
파일: exitus.py 프로젝트: 00joshi/Exitus
 def GameOverNote(self,survivaltime):
     popup = ModalView(size_hint=(0.75, 0.5))
     victory_label = Label(text="Game Over\n" + "%0.2f"%survivaltime + " sec", font_size=50)
     popup.add_widget(victory_label)
     popup.bind(on_dismiss=game.reset)
     popup.bind(on_press=popup.dismiss)
     popup.open()
예제 #11
0
    def on_status(self, instance, new_value):
        status = new_value
        sums = [
            sum(status[0:3]),
            sum(status[3:6]),
            sum(status[6:9]),
            sum(status[0::3]),
            sum(status[1::3]),
            sum(status[2::3]),
            sum(status[::4]),
            sum(status[2:-2:2])
        ]

        resultado = None
        if -3 in sums:
            resultado = 'O Joogador 02 (X) ganhou!'
        elif 3 in sums:
            resultado = 'O Jogador 01 (O) ganhou!'
        elif 0 not in self.status:
            resultado = "Velhou!"

        if resultado:
            popup = ModalView(size_hint=(0.75, 0.5))
            labelResultado = Label(text=resultado, font_size=50)
            popup.add_widget(labelResultado)
            popup.bind(on_dismiss=self.reset)
            popup.open()
예제 #12
0
    def on_preferences(self, *args):
        settings_view = SettingsWithNoMenu()
        base_dir = self._settings.base_dir
        settings_view.add_json_panel('Dashboard Preferences', self._settings.userPrefs.config, os.path.join(base_dir, 'resource', 'settings', 'dashboard_settings.json'))

        popup = ModalView(size_hint=DashboardView._POPUP_SIZE_HINT)
        popup.add_widget(settings_view)
        popup.bind(on_dismiss=self._popup_dismissed)
        popup.open()
        self._popup = popup
예제 #13
0
    def action(self, button):

        item = []

        if type(button.parent.parent.parent).__name__ == 'History':
            for data in self.left_check_list:

                if data.state == 'down':
                    item.append(data.parent.parent)
        else:
            item.append(button.parent.parent.parent)
            item_data = str(item[0].text + ' ' + item[0].secondary_text)

        if button.icon == 'content-copy':
            Clipboard.copy(item_data)

        elif button.icon == 'history':
            self.main.pages.pages_list[
                current_page[0]].entry.text = item_data.split()[0]
            self.parent.dismiss()
        elif button.icon == 'qrcode':

            image = Image(source="")
            imgIO = io.BytesIO()

            qrcode.make(item_data).save(imgIO, ext='png')

            imgIO.seek(0)
            imgData = io.BytesIO(imgIO.read())
            image.texture = CoreImage(imgData, ext='png').texture
            image.reload()

            dialog = ModalView(size_hint=(None, None), size=image.texture.size)
            dialog.add_widget(image)
            dialog.open()

        elif button.icon in ['delete', 'delete-sweep']:
            dialog_yes = MDFlatButton(text="yes")
            dialog_no = MDRaisedButton(text="no")
            dialog = MDDialog(text="Delete {} item{}?".format(
                len(item), '' if len(item) == 1 else 's'),
                              buttons=[dialog_no, dialog_yes])

            with open('history.json', 'r') as file:
                data = json.load(file)
                for item_ in item:
                    data.pop(item_.time)
                dialog_no.bind(on_release=dialog.dismiss)
                dialog_yes.bind(on_release=dialog.dismiss)
                dialog_yes.bind(on_release=lambda button: json.dump(
                    data, open('history.json', 'w'), indent=4))
                dialog_yes.bind(on_release=self.item_check)
            dialog.bind(on_dismiss=self.refresh)
            dialog.open()
예제 #14
0
    def on_preferences(self, *args):
        settings_view = SettingsWithNoMenu()
        base_dir = self._settings.base_dir
        settings_view.add_json_panel(
            'Dashboard Preferences', self._settings.userPrefs.config,
            os.path.join(base_dir, 'resource', 'settings',
                         'dashboard_settings.json'))

        popup = ModalView(size_hint=self._POPUP_SIZE_HINT)
        popup.add_widget(settings_view)
        popup.bind(on_dismiss=self._popup_dismissed)
        popup.open()
        self._popup = popup
예제 #15
0
    def call_modal_item(self, btn):
        text1 = btn.data_datch
        text2 = btn.text
        popup = ModalView(size_hint=(0.5, 0.5))
        layout = BoxLayout(orientation='vertical')

        tem_label = MyLabel(text=text1, font_size=40, color=[1, 1, 0, 1], size_hint=(1, None))
        hum_label = MyLabel(text=text2, font_size=70, color=[0.5, 0.5, 1, 1])

        layout.add_widget(tem_label)
        layout.add_widget(hum_label)
        popup.add_widget(layout)
        popup.bind()
        popup.open()
예제 #16
0
파일: main.py 프로젝트: snaiffer/TreeNote
class ButtonTreeItem(Button):
  def __init__(self, num, outward, **kwargs):
    super(ButtonTreeItem, self).__init__(**kwargs)
    self.size = (20, window_height/btnHeightRate) # 20 isn't change anything
    self.size_hint_y = None
    self.num = num
    self.context = False
    self.outward = outward

  def on_touch_down(self, touch):
    if self.collide_point(*touch.pos):
      self.create_clock()
    return super(ButtonTreeItem, self).on_touch_down(touch) 
  def on_touch_up(self, touch):
    if self.collide_point(*touch.pos):
      self.delete_clock()
      if self.context :
        self.context = False
        return True 
    return super(ButtonTreeItem, self).on_touch_up(touch) 

  def create_clock(self, *args):
    Clock.schedule_once(self.openContextMenu, timeOut_forContextMenu)
  def delete_clock(self, *args):
    Clock.unschedule(self.openContextMenu)

  def openContextMenu(self, *args):
    self.context = True
    self.contextMenu = ModalView(size_hint=(0.5, 0.5))
    self.contextMenu.bind(on_dismiss=self.outward.showTree())
    contextLayout = BoxLayout(
        padding = 10,
        spacing = 10,
        pos_hint = {'center_x': 0.5, 'center_y': 0.5}, 
        size_hint = (0.7, 0.8), 
        orientation = 'vertical')
    contextLayout.add_widget(Label(text=self.text))
    btnDelete = Button(text='delete')
    btnDelete.bind(on_press=self.delete)
    contextLayout.add_widget(btnDelete)
    close = Button(text='close')
    close.bind(on_release=self.contextMenu.dismiss)
    contextLayout.add_widget(close)
    self.contextMenu.add_widget(contextLayout)
    self.contextMenu.open()
  def delete(self, *args):
    tree.curItem().remove(self.num)
    self.contextMenu.dismiss()
    self.outward.showTree()
예제 #17
0
    def decision(self, message_decision, method):
        grid = ViewGridDecision(message_decision)
        view = ModalView(auto_dismiss=False)
        view.add_widget(grid)
        grid.yes_btn.bind(on_release=view.dismiss)
        grid.no_btn.bind(on_release=view.dismiss)
        view.open()
        spielplangrid = self

        def do(self):
            if grid.feedback:
                message = method()
                spielplangrid.message_(message)

        view.bind(on_dismiss=do)
예제 #18
0
    def on_heatmap_options(self):
        def popup_dismissed(response):
            self._update_heatmap_preferences()

        settings_view = SettingsWithNoMenu()
        base_dir = self._settings.base_dir
        settings_view.add_json_panel(
            'Heatmap Settings', self._settings.userPrefs.config,
            os.path.join(base_dir, 'autosportlabs', 'racecapture', 'views',
                         'dashboard', 'heatmap_settings.json'))

        popup = ModalView(size_hint=HeatmapView._POPUP_SIZE_HINT)
        popup.add_widget(settings_view)
        popup.bind(on_dismiss=popup_dismissed)
        popup.open()
예제 #19
0
    def generate_gameover_screen(self):
        # Check how is the winner and prepare game end message accordingly
        winner = self.check_winner(self.status)
        if winner == 3:
            winningText = "You win!"
        elif winner == 2:
            winningText = "The AI win!"
        else:
            winningText = "Draw!"

        # Create a pop up to display the winner and reset the game when dismissed
        popup = ModalView(size_hint=(0.75, 0.5))
        victory_label = Label(text=winningText, font_size=50)
        popup.add_widget(victory_label)
        popup.bind(on_dismiss=self.reset)
        popup.open()
예제 #20
0
    def on_preferences(self, *args):
        """
        Display the dashboard preferences view 
        """
        settings_view = DashboardPreferences(self._settings, self._dashboard_factory)

        def popup_dismissed(*args):
            self._notify_preference_listeners()
            screens = settings_view.get_selected_screens()
            screens = self._filter_dashboard_screens(screens)
            self._settings.userPrefs.set_dashboard_screens(screens)
            self._update_screens(screens)

        popup = ModalView(size_hint=DashboardView._POPUP_SIZE_HINT)
        popup.add_widget(settings_view)
        popup.bind(on_dismiss=popup_dismissed)
        popup.open()
예제 #21
0
    def on_status(self, instance, new_value):

        status = new_value

        # Sum each row, column and diagonal.
        # Could be shorter, but let's be extra
        # clear what’s going on

        sums = [
            sum(status[0:3]),  # rows
            sum(status[3:6]),
            sum(status[6:9]),
            sum(status[0::3]),  # columns
            sum(status[1::3]),
            sum(status[2::3]),
            sum(status[::4]),  # diagonals
            sum(status[2:-2:2])
        ]

        # Sums can only be +-3 if one player
        # filled the whole line
        winner = None

        if -3 in sums:

            winner = 'Xs win!'

        elif 3 in sums:

            winner = 'Os win!'

        elif 0 not in self.status:

            winner = 'Nobody wins!'

        if winner:

            modwin = ModalView(size_hint=(0.75, 0.5))

            victory_label = Label(text=winner, font_size=50)

            modwin.add_widget(victory_label)

            modwin.bind(on_dismiss=self.reset)

            modwin.open()
예제 #22
0
    def on_preferences(self, *args):
        """
        Display the dashboard preferences view 
        """
        settings_view = DashboardPreferences(self._settings,
                                             self._dashboard_factory)

        def popup_dismissed(*args):
            self._notify_preference_listeners()
            screens = settings_view.get_selected_screens()
            screens = self._filter_dashboard_screens(screens)
            self._settings.userPrefs.set_dashboard_screens(screens)
            self._update_screens(screens)

        popup = ModalView(size_hint=DashboardView._POPUP_SIZE_HINT)
        popup.add_widget(settings_view)
        popup.bind(on_dismiss=popup_dismissed)
        popup.open()
예제 #23
0
def on_win (self, winner):
    _size_hint = {"size_hint" : [0.75, 0.5]}
    popup = ModalView(**_size_hint)
    _victory_label = {"font_size" : 50, "text" : winner}
    victoryLabel = Label(**_victory_label)
    (popup.add_widget(victoryLabel) if callable(popup.add_widget) else popup.add_widget)
    _on_dismiss = {"on_dismiss" : self.reset}
    (popup.bind(**_on_dismiss) if callable(popup.bind) else popup.bind)
    return (popup.open() if callable(popup.open) else popup.open)
예제 #24
0
    def call_moadal(self):

        plt.plot([1, 2, 3, 4])
        plt.ylabel('some numbers')
        plt.show()
        text1 = "TEMP: {0} °C".format(self.data['temp_sr'])
        text2 = "HUMI: {0} %".format(self.data['hum_sr'])
        popup = ModalView(size_hint=(0.75, 0.6))
        layout = BoxLayout(orientation='vertical')

        tem_label = MyLabel(text=text1, font_size=70, color=[1, 1, 0, 1])
        hum_label = MyLabel(text=text2, font_size=70, color=[0.5, 0.5, 1, 1])


        layout.add_widget(tem_label)
        layout.add_widget(hum_label)
        popup.add_widget(layout)
        popup.bind()
        popup.open()
예제 #25
0
class Menu(Screen):
    que = None
    leave = None

    def connect_to_server(self):
        BigBoard.are_we_playing = True
        App.get_running_app().set_state("in_queue")
        self.que = ModalView(size_hint=(.75, .5))
        time_text = Label(text="00 : 00", font_size=50, id="time_text")
        App.get_running_app().clock_timer = Clock.schedule_interval(
            self.timer_for_que, 1.000)
        self.que.bind(on_dismiss=self.leave_queue_on_dismiss)
        self.que.add_widget(time_text)
        self.que.open()
        TicTacToeApp.que_for_game(App.get_running_app())

    @staticmethod
    def cancel_timer_and_set_menu():
        App.get_running_app().clock_timer.cancel()
        App.get_running_app().set_state("in_menu")

    def leave_queue_on_dismiss(self, dt):
        if App.get_running_app().state == "in_queue":
            self.cancel_timer_and_set_menu()
            App.get_running_app().s.stop()

    def leave_queue_on_join(self):
        self.cancel_timer_and_set_menu()
        self.que.dismiss()

    def timer_for_que(self, dt):
        self.que.children[0].text = plus_sec(self.que.children[0].text)

    def back_to_menu(self):
        self.leave = ModalView(size_hint=(.75, .5))
        text = Label(text="Your opponent leave", font_size=50)
        self.leave.bind(on_dismiss=lambda x: go_to_screen(1))
        self.leave.add_widget(text)
        self.leave.open()
        App.get_running_app().man.if_online = 0
        App.get_running_app().man.who_am_I = 0
        App.get_running_app().state = "in_menu"
        App.get_running_app().man.ids.screen_game_online.ids.pasek.reset()
예제 #26
0
    def on_heatmap_options(self):
        def popup_dismissed(response):
            self._update_heatmap_preferences()

        settings_view = SettingsWithNoMenu()
        base_dir = self._settings.base_dir
        settings_view.add_json_panel('Heatmap Settings',
                                     self._settings.userPrefs.config,
                                     os.path.join(base_dir,
                                                  'autosportlabs',
                                                  'racecapture',
                                                  'views',
                                                  'dashboard',
                                                  'heatmap_settings.json'))

        popup = ModalView(size_hint=HeatmapView._POPUP_SIZE_HINT)
        popup.add_widget(settings_view)
        popup.bind(on_dismiss=popup_dismissed)
        popup.open()
예제 #27
0
파일: MainScreen.py 프로젝트: hutsi/myhoney
    def choose(self, button):
        from HoneyApp import HoneyApp

        def get_date_diff_string():
            timestamp_diff = (datetime.datetime.fromtimestamp(self.current_images[self.IMAGE_TYPE_LEFT]['timestamp']) -
                              datetime.datetime.fromtimestamp(self.current_images[self.IMAGE_TYPE_RIGHT]['timestamp']))
            return str(abs(timestamp_diff.days)) + ' дней'

        if button.type == self.IMAGE_TYPE_LEFT:
            image_chosen_timestamp = self.current_images[self.IMAGE_TYPE_LEFT]['timestamp']
            image_another_timestamp = self.current_images[self.IMAGE_TYPE_RIGHT]['timestamp']
        else:
            image_chosen_timestamp = self.current_images[self.IMAGE_TYPE_RIGHT]['timestamp']
            image_another_timestamp = self.current_images[self.IMAGE_TYPE_LEFT]['timestamp']

        if image_chosen_timestamp < image_another_timestamp:
            status = True
        else:
            status = False

        modal = ModalView(size_hint=(None, None), size=(400, 200))
        if status:
            modal.bind(on_dismiss=self.renew_images)
            modal_data = random.choice(HoneyApp.success)
        else:
            modal_data = random.choice(HoneyApp.error)

        layout = GridLayout(cols=1, rows=2, on_touch_down=modal.dismiss)
        text = '[size=18][b]{text}[/b][/size]\n' \
               '[size=11]Эта фотография была сделана: [b]{image_date_chosen}[/b]\n' \
               'Дата второй фотографии: [b]{image_date_another}[/b]\n' \
               'Разница - [b]{date_diff}[/b][/size]'.\
            format(text=modal_data['text'],
                   image_date_chosen=datetime.datetime.fromtimestamp(image_chosen_timestamp).strftime('%d.%m.%Y %H:%M'),
                   image_date_another=datetime.datetime.fromtimestamp(image_another_timestamp).strftime('%d.%m.%Y %H:%M'),
                   date_diff=get_date_diff_string())

        layout.add_widget(Label(text=text, markup=True))
        layout.add_widget(Image(source=modal_data['filename']))
        modal.add_widget(layout)
        modal.open()
	def on_status(self, instance,status):
		status=self.status

		#sum each row, column and diagonal
		sums=[sum(status[0:3]),sum(status[3:6]),sum(status[6:9]), #rows
		      sum(status[0::3]),sum(status[1::3]),sum(status[2::3]), #cols
		      sum(status[0::4]),sum(status[2:-2:2])] # diagonals

		winner=None

		if 3 in sums:
			print(self.status)
			winner='Player 1 (O) wins!\n Would you like to play again?'
		elif -3 in sums:
			print(self.status)
			winner='Player 2 (X) wins!\n Would you like to play again?'
		elif 0 not in self.status: #grid full
			print(self.status)
			winner='Draw! \n Would you like to play again?'

		if winner:


			# create a button
			float=FloatLayout(size_hint=(0.5,0.5))
			y_button=Button(text="Y",font_size=20,pos_hint={'x':0.4, 'center_y': 0.5},size_hint=(None,None))
			n_button=Button(text="N",font_size=20,pos_hint={'x':0.6, 'center_y': 0.5},size_hint=(None,None))
			float.add_widget(y_button)
			float.add_widget(n_button)

			popup=ModalView(size_hint=(0.5,0.5))
			victory_label=Label(text=winner,pos_hint={'x': 0.3, 'center_y':0.7},size_hint=(None,None))
			float.add_widget(victory_label)

			popup.add_widget(float)

			if y_button:
				self.reset

			popup.bind(on_dismiss=self.reset)
			popup.open()
예제 #29
0
    def on_status(self, instance, new_value):
        status = new_value

        sums = [sum(status[0:3]), sum(status[3:6]), sum(status[6:9]),
                sum(status[0::3]), sum(status[1::3]), sum(status[2::3]),
                sum(status[::4]), sum(status[2:-2:2])]

        winner = None
        if 3 in sums:
            winner = "Os win!"
        elif -3 in sums:
            winner = "Xs win!"
        elif 0 not in self.status:
            winner = "Draw!"

        if winner:
            popup = ModalView(size_hint=(0.75, 0.5))
            victory_label = Label(text=winner, font_size = 50)
            popup.add_widget(victory_label)
            popup.bind(on_dismiss = self.reset)
            popup.open()
예제 #30
0
    def on_status(self, instance, newVal):
        status = newVal

        sums = [sum(status[0:3]), # rows
                sum(status[3:6]), sum(status[6:9]), sum(status[0::3]), # columns
                sum(status[1::3]), sum(status[2::3]), sum(status[::4]), # diagonals
                sum(status[2:-2:2])]

        winner = ""
        if 3 in sums:
            winner = 'Xs win!'
        elif -3 in sums:
            winner = 'Os win!'
        elif 0 not in self.status:
            winner = 'Draw!'

        if winner:
            popup = ModalView(**{'size_hint': [.75, .5]}) #
            victoryLabel = Label(**{'text': winner, 'font_size': 50}) #
            popup.add_widget(victoryLabel)
            popup.bind(**{'on_dismiss': self.reset}) #
            popup.open()
예제 #31
0
 def on_status(self, instance, new_value):
     status = new_value
     a = sum(status[0:3])
     b = sum(status[3:6])
     c = sum(status[6:9])
     d = sum(status[0::3])
     e = sum(status[1::3])
     f = sum(status[2::3])
     g = sum(status[::4])
     h = sum(status[2:-2:2])
     sums = [a, b, c, d, e, f, g, h]
     if 3 in sums:
         winner = 'O WIN'
     elif -3 in sums:
         winner = 'X'
     elif 0 not in self.status:
         winner = 'draw'
     if winner:
         popup = ModalView(size_hint=(0.75, 0.5))
         victory_label = Label(text=winner, font_size=50)
         popup.add_widget(victory_label)
         popup.bind(on_dismiss=self.reset)
         popup.open()
         popup.dismiss()
예제 #32
0
	def verifierGagnant(self):
			
		# si tous les pions rouges sont arrivés
		if self.plateau_jeu[206] == 1 and self.plateau_jeu[207] == 1 and self.plateau_jeu[221] == 1 and self.plateau_jeu[222] == 1 and self.plateau_jeu[223] == 1 and self.plateau_jeu[236] == 1 and self.plateau_jeu[237] == 1 and self.plateau_jeu[238] == 1 and self.plateau_jeu[239] == 1 and self.plateau_jeu[252] == 1 and self.plateau_jeu[253] == 1 and self.plateau_jeu[254] == 1 and self.plateau_jeu[255] == 1:
			popup = ModalView(size_hint=(0.6, 0.2))		
			victory_label = Label(text='Le joueur rouge a gagné !',font_size=30)		
			Window.clearcolor = (1, 1, 0, 1)
			popup.add_widget(victory_label)
			popup.bind(on_dismiss=self.reset) # lorsque le pop-up est fermée, on reset le plateau
			popup.open() # on ouvre la pop-up de victoire
		
		# si tous les pions verts sont arrivés
		if self.plateau_jeu[192] == 2 and self.plateau_jeu[193] == 2 and self.plateau_jeu[208] == 2 and self.plateau_jeu[209] == 2 and self.plateau_jeu[210] == 2 and self.plateau_jeu[224] == 2 and self.plateau_jeu[225] == 2 and self.plateau_jeu[226] == 2 and self.plateau_jeu[227] == 2 and self.plateau_jeu[240] == 2 and self.plateau_jeu[241] == 2 and self.plateau_jeu[242] == 2 and self.plateau_jeu[243] == 2:
			popup = ModalView(size_hint=(0.6, 0.2))		
			victory_label = Label(text='Le joueur vert a gagné !',font_size=30)		
			Window.clearcolor = (1, 1, 0, 1)
			popup.add_widget(victory_label)
			popup.bind(on_dismiss=self.reset) # lorsque le pop-up est fermée, on reset le plateau
			popup.open() # on ouvre la pop-up de victoire
		
		# si tous les pions jaunes sont arrivés		
		if self.plateau_jeu[0] == 3 and self.plateau_jeu[1] == 3 and self.plateau_jeu[2] == 3 and self.plateau_jeu[3] == 3 and self.plateau_jeu[16] == 3 and self.plateau_jeu[17] == 3 and self.plateau_jeu[18] == 3 and self.plateau_jeu[19] == 3 and self.plateau_jeu[32] == 3 and self.plateau_jeu[33] == 3 and self.plateau_jeu[34] == 3 and self.plateau_jeu[48] == 3 and self.plateau_jeu[49] == 3:
			popup = ModalView(size_hint=(0.6, 0.2))		
			victory_label = Label(text='Le joueur jaune a gagné !',font_size=30)		
			Window.clearcolor = (1, 1, 0, 1)
			popup.add_widget(victory_label)
			popup.bind(on_dismiss=self.reset) # lorsque le pop-up est fermée, on reset le plateau
			popup.open() # on ouvre la pop-up de victoire	
			
		# si tous les pions bleus sont arrivés
		if self.plateau_jeu[62] == 4 and self.plateau_jeu[63] == 4 and self.plateau_jeu[45] == 4 and self.plateau_jeu[46] == 4 and self.plateau_jeu[47] == 4 and self.plateau_jeu[28] == 4 and self.plateau_jeu[29] == 4 and self.plateau_jeu[30] == 4 and self.plateau_jeu[31] == 4 and self.plateau_jeu[12] == 4 and self.plateau_jeu[13] == 4 and self.plateau_jeu[14] == 4 and self.plateau_jeu[15] == 4:
			popup = ModalView(size_hint=(0.6, 0.2))		
			victory_label = Label(text='Le joueur bleu a gagné !',font_size=30)		
			Window.clearcolor = (1, 1, 0, 1)
			popup.add_widget(victory_label)
			popup.bind(on_dismiss=self.reset) # lorsque le pop-up est fermée, on reset le plateau
			popup.open()
예제 #33
0
class Text(TextInput):
    foreground_color = ListProperty(
        color(f"images/{theme_image[config_data['theme']][0]}.png"))
    background_active = StringProperty(
        f"images/{theme_image[config_data['theme']][2]}.png")
    cursor_color = ListProperty(
        color(f"images/{theme_image[config_data['theme']][0]}.png"))
    cursor_width = dp(5)
    from_unit = StringProperty()
    minimum_width = NumericProperty(1)
    to_unit = StringProperty()
    write_tab = False
    quantity = StringProperty()
    solved = False
    last_press = StringProperty()

    def on_focus(self, instance, value):
        def real(dt):
            if self.text == "":
                self.insert_text("0")

        Clock.schedule_once(real, 3)

    def on_cursor(self, instance, newPos):
        self.width = max(self.minimum_width, self.parent.width)

        if not (isinstance(self.parent, ScrollView) and self.multiline):
            return super(Text, self).on_cursor(instance, newPos)
        if newPos[0] == 0:
            self.parent.scroll_x = 0
        else:
            over_width = self.width - self.parent.width
            if over_width <= 0.0:
                return super(Text, self).on_cursor(instance, newPos)
            view_start = over_width * self.parent.scroll_x
            view_end = view_start + self.parent.width
            offset = self.cursor_offset()
            desired_view_start = offset - 5
            desired_view_end = (offset + self.padding[0] + self.padding[2] +
                                self.cursor_width + 5)
            if desired_view_start < view_start:
                self.parent.scroll_x = max(0, desired_view_start / over_width)
            elif desired_view_end > view_end:
                self.parent.scroll_x = min(
                    1, (desired_view_end - self.parent.width) / over_width)
        return super(Text, self).on_cursor(instance, newPos)

    def replace(self, exp):
        exp = exp.replace("sqrt", "math.sqrt")
        exp = exp.replace("^", "**")
        exp = exp.replace("x", "*")
        exp = exp.replace("÷", "/")
        exp = exp.replace("ceil", "math.ceil")
        exp = exp.replace("floor", "math.floor")
        exp = exp.replace("\u03c0", "math.pi")
        exp = exp.replace("e", "math.e")
        return exp

    def fac_solve(self, exp):
        for x in ("+", "-", "/", "*", "**"):
            exp = exp.replace(x, f" {x} ")
        exp = exp.split()

        for x_index, x in enumerate(exp):
            if "!" in x:
                if x[-1] == "!":
                    exp[x_index] = "math.factorial({})".format(
                        x.replace("!", ""))
                else:
                    return "symbol error"

        if "factorial()" in exp:
            return "Can't calculate factorial of nothing!"
        else:
            return str("".join(exp))

    def insert_text(self, substring, from_undo=False):
        self.page = self.parent.parent.parent

        if substring == "AC":
            self.text = ""
            return
        if substring == "Del":
            if self.last_press in "\r\n=":
                self.insert_text("AC")
            else:
                self.do_backspace()
            return

        if substring == "*":
            substring = "x"

        if substring == "**":
            substring = "^"

        if substring == "/":
            substring = "÷"

        if substring == "a\u00b2":
            substring = "^2"

        if substring == "ceil":
            if self.selection_text:
                self.text = self.text.replace(self.selection_text,
                                              f"ceil({self.selection_text})")
            else:
                self.text = f"ceil({self.text})"
            return
        if substring == "|a|":
            if self.selection_text:
                self.text = self.text.replace(self.selection_text,
                                              f"abs({self.selection_text})")
            else:
                self.text = f"abs({self.text})"
            return
        if substring == "floor":
            if self.selection_text:
                self.text = self.text.replace(self.selection_text,
                                              f"floor({self.selection_text})")
            else:
                self.text = f"floor({self.text})"
            return
        if substring == "\u221aa":
            if self.selection_text:
                self.text = self.text.replace(self.selection_text,
                                              f"sqrt({self.selection_text})")
            else:
                self.text = f"sqrt({self.text})"
            return

        if substring == "a!":
            substring = "!"

        if substring == str(config_data['base']) + '\u00aa':
            substring = str(config_data['base']) + '^'

        if self.last_press in "+-÷x^%\u00b1":
            if self.last_press == substring:
                return
            else:
                if self.text and substring in "+-÷x^%":
                    self.do_backspace()

        if substring in "÷x^" and (self.text == "0" or not self.text):
            return

        if ((current_page[0] == "standard"
             and substring not in string.digits + "%()+-x÷^.!=\r\n" + string.ascii_letters
             and not substring.isdecimal()
             and substring != "^2") or
            (current_page[0] == "scientific"
             and substring not in string.digits + "%()e+-x÷^.!sincotae=\r\n"
             and substring != "^2" and substring
             not in ['sin', 'cos', 'tan', 'cosec', 'cot', 'sec', 'log']
             and substring not in [
                 'sin\u00af\u00b9', 'cos\u00af\u00b9', 'tan\u00af\u00b9',
                 'cosec\u00af\u00b9', 'cot\u00af\u00b9', 'sec\u00af\u00b9'
            ] and substring != str(config_data['base'] + '^')
            and substring != '\u03c0')
                or (current_page[0] == "convert"
                    and substring not in string.digits + ".=\r\n")
                or (current_page[0] == "days"
                    and substring not in string.digits + "=\r\n")):

            return

        self.last_press = substring
        if substring in ["\r", "\n", "="]:
            if self.text == 'pass':
                self.text = ''
                self.page.parent.parent.parent.parent.options_open(
                    self.page.layout.buttons[-1][-1])
                self.modal_pass = ModalView(size_hint=(0.8, 0.8))
                self.modal_pass.add_widget(Pass())
                self.modal_pass.open()
                self.modal_pass.bind(
                    on_dismiss=lambda *args: self.page.parent.parent.parent.parent.options_close())
                return
            if self.text[-1] in "+-÷x^(%":
                self.page.preview.text = "Complete the equation first!"
                return
            self.last_press = substring
            for opr in "+-÷x^()!%":
                if self.text.count(opr):
                    break
            else:
                if current_page[0] not in ["scientific", "convert", "days"]:
                    link = False
                    if re.findall("[0-9]", self.text):
                        return
                    if self.text.count('.') == 0 and self.text.isalpha:
                        self.text = "www."+self.text+".com"
                        link = True
                    elif self.text.count('.') == 1:
                        if 'www' in self.text:
                            self.text += ".com"
                        else:
                            self.text = "www."+self.text
                        link = True

                    if self.text.count('.') == 2 or link:
                        webbrowser.get().open_new_tab(self.text)
                        self.page.preview.text = "Opened in web browser!"
                        Clock.schedule_once(lambda dt: setattr(
                            self.page.preview, 'text', ''), 1)
                        self.text = ''
                    return
            self.page.old_text = self.text
            self.page.preview.text = "[ref=self.old_text]" + \
                self.text + "[/ref]"

            if current_page[0] == "standard":
                substring = self.text
                substring = self.replace(substring)
                if "!" in self.text:
                    substring = self.fac_solve(self.text)
                try:
                    substring = Basic(exp=substring).solution
                except:
                    self.page.preview.text = (
                        "There's some error!")
                    return
            elif current_page[0] == "scientific":
                substring = self.text
                substring = self.replace(substring)
                if "!" in substring:
                    substring = self.fac_solve(substring)

                rad = 1 if self.page.layout.buttons[0][2].text == "RAD" else 0
                for r in ["sin", "tan", "cos", "cot", "cosec", "sec"]:
                    substring = substring.replace(r, f"Basic(rad={rad}).{r}")
                for r in [
                        "sin\u00af\u00b9", "tan\u00af\u00b9",
                        "cos\u00af\u00b9", "cot\u00af\u00b9",
                        "cosec\u00af\u00b9", "sec\u00af\u00b9"
                ]:
                    r1 = r.replace("\u00af\u00b9", "")
                    substring = substring.replace(r, f"a{r1}")
                substring = substring.replace(
                    "log", f"Basic(base={config_data['base']}).log")
                from math import factorial

                try:
                    substring = Basic(exp=substring).solution
                except:
                    self.page.preview.text = "Something went wrong!"
                    return
            elif current_page[0] == "convert":
                if not self.quantity:
                    self.quantity = self.page.layout.buttons[0][1].text
                if not self.from_unit:
                    self.from_unit = self.page.layout.buttons[1][1].text
                if not self.to_unit:
                    self.to_unit = self.page.layout.buttons[1][3].text
                try:
                    substring = (str(
                        eval("Convert." + self.quantity)
                        (self.text.split()[0], self.from_unit, self.to_unit)) +
                        " " + self.to_unit)
                    self.page.preview.text = ("[ref=self.old_text]" +
                                              self.text + " " +
                                              self.from_unit + "[/ref]")
                except:
                    self.page.preview.text = "There's some error!"
                    return
            elif current_page[0] == "days":
                try:
                    substring = days_number(
                        self.page.layout.buttons[1][0].text,
                        self.page.layout.buttons[1][2].text,
                    )
                    if self.page.layout.buttons[2][-1].state == "down":
                        substring += 1
                    if self.page.layout.buttons[3][-1].state == "down":
                        substring -= 1
                    substring = str(substring)
                    self.page.preview.text = f"{self.page.layout.buttons[1][0].text} to {self.page.layout.buttons[1][2].text}"
                except:
                    self.page.preview.text = "Oops! Couldn't find that!"
                    return
            self.solved = True
            write_history(
                self.page.preview.text if current_page[0] == "days" else
                MarkupLabel(self.page.preview.text).markup[1],
                substring,
                current_page[0],
            )
            self.text = ""

        if self.text == "0" and substring != ".":
            self.do_backspace()
        for sub_ in substring:
            return super(Text, self).insert_text(substring,
                                                 from_undo=from_undo)

    def on_text(self, instance, newText):

        width_calc = 0
        for line_label in self._lines_labels:
            width_calc = max(width_calc, line_label.width + 90)
        self.minimum_width = width_calc

    def keyboard_on_key_up(self, window, keycode):

        if keycode[1] == "right" or keycode[1] == "left":
            self.calc_scroll(keycode[1], True)

        key, key_str = keycode
        k = self.interesting_keys.get(key)
        if k:
            key = (None, None, k, 1)
            self._key_up(key)

    def calc_scroll(self, direction, key=None):

        if not key:
            self.do_cursor_movement("cursor_" + direction)

        if direction == "left":
            limit = ">0"
            sensitivity = "-"
        else:
            limit = "<1"
            sensitivity = "+"

        if eval("self.parent.scroll_x" + limit):
            self.parent.scroll_x += eval(sensitivity + "0.07")
        else:
            self.parent.scroll_x = limit[1:]

        if self.cursor_col == len(self.text):
            self.parent.scroll_x = 1

    def __init__(self, **kwargs):
        super(Text, self).__init__(**kwargs)

        self.background_disabled_normal = self.background_active
        self.background_normal = self.background_active
예제 #34
0
    def my_callback(self, dt):
        self.current += dt
        if self.current > 2:
            global CURRENT_PLAYER, LIST_OF_TARGETS1, LIST_OF_TARGETS, CURRENT, SOME_LIST, AMOUNT1, finish
            grid = self.manager.get_screen('board1').ids.grid
            rand = random.randint(0, len(LIST_OF_TARGETS) - 1)
            TARGETS = LIST_OF_TARGETS
            if len(LIST_OF_TARGETS1):
                rand = random.randint(0, len(LIST_OF_TARGETS1) - 1)
                TARGETS = LIST_OF_TARGETS1

            for child in grid.children:
                if child.coords == TARGETS[rand]:
                    if child.background_color == [1, 1, 1, 1]:
                        child.text = 'X'
                        child.background_color = [1, 0, 0, 1]
                        self.popup1.dismiss()
                        Clock.unschedule(self.my_callback)
                        CURRENT_PLAYER *= -1
                        self.sound.stop()
                        self.sound = SoundLoader.load('files/Not_ship.wav')
                        self.sound.play()
                        Clock.schedule_once(self.callback1, 0.7)
                        TARGETS.remove(child.coords)
                    else:
                        x, y = child.coords
                        CURRENT += 1
                        AMOUNT1 += 1
                        SOME_LIST.append((x, y))

                        if (x + 1, y + 1) in TARGETS:
                            TARGETS.remove((x + 1, y + 1))
                        if (x - 1, y - 1) in TARGETS:
                            TARGETS.remove((x - 1, y - 1))
                        if (x + 1, y - 1) in TARGETS:
                            TARGETS.remove((x + 1, y - 1))
                        if (x - 1, y + 1) in TARGETS:
                            TARGETS.remove((x - 1, y + 1))

                        if (x + 1, y + 1) in LIST_OF_TARGETS:
                            LIST_OF_TARGETS.remove((x + 1, y + 1))
                        if (x - 1, y - 1) in LIST_OF_TARGETS:
                            LIST_OF_TARGETS.remove((x - 1, y - 1))
                        if (x + 1, y - 1) in LIST_OF_TARGETS:
                            LIST_OF_TARGETS.remove((x + 1, y - 1))
                        if (x - 1, y + 1) in LIST_OF_TARGETS:
                            LIST_OF_TARGETS.remove((x - 1, y + 1))

                        if (x + 1, y) not in LIST_OF_TARGETS1 and (x + 1, y) in LIST_OF_TARGETS:
                            LIST_OF_TARGETS1.append((x + 1, y))
                            LIST_OF_TARGETS.remove((x + 1, y))
                        if (x - 1, y) not in LIST_OF_TARGETS1 and (x - 1, y) in LIST_OF_TARGETS:
                            LIST_OF_TARGETS1.append((x - 1, y))
                            LIST_OF_TARGETS.remove((x - 1, y))
                        if (x, y - 1) not in LIST_OF_TARGETS1 and (x, y - 1) in LIST_OF_TARGETS:
                            LIST_OF_TARGETS1.append((x, y - 1))
                            LIST_OF_TARGETS.remove((x, y - 1))
                        if (x, y + 1) not in LIST_OF_TARGETS1 and (x, y + 1) in LIST_OF_TARGETS:
                            LIST_OF_TARGETS1.append((x, y + 1))
                            LIST_OF_TARGETS.remove((x, y + 1))

                        child.background_color = [0, 1, 0, 1]
                        AMOUNT1 = 4 + 3 * 2 + 2 * 3 + 4
                        if AMOUNT1 == 4 + 3 * 2 + 2 * 3 + 4:
                            self.popup1.dismiss()
                            Clock.unschedule(self.my_callback)
                            finish = SoundLoader.load('files/proval.mp3')
                            finish.play()
                            winner = ModalView(size_hint=(0.75, 0.5))
                            winner.background = 'files/You_Lost.png'
                            # victory_label = Label(text='You Lost!!!!!', font_size=50)
                            # winner.add_widget(victory_label)
                            winner.bind(on_dismiss=self.somefunc)
                            winner.open()
                            return

                        TARGETS.remove((x, y))
                        if CURRENT == int(child.name):
                            LIST_OF_TARGETS1[:] = []
                            if self.sound != '':
                                self.sound.stop()
                            self.sound = SoundLoader.load('files/boom.mp3')
                            self.sound.play()

                            for ship in SOME_LIST:
                                x, y = ship
                                s = [1, 0, -1]
                                t = [1, 0, -1]
                                for xx in s:
                                    for yy in t:
                                        for child in grid.children:
                                            if child.coords == (x + xx, y + yy) and (x + xx, y + yy) not in SOME_LIST:
                                                child.text = 'X'
                                                child.background_color = [1, 0, 0, 1]
                            SOME_LIST = []
                            CURRENT = 0
                        else:
                            if self.sound != '':
                                self.sound.stop()
                            self.sound = SoundLoader.load('files/bomb2.wav')
                            self.sound.play()
                        self.current = 0
                    return

        child = self.popup1.children[0]
        if child.text[-1:-4:-1] == '...':
            child.text = child.text[:-3]
        else:
            child.text += '.'
예제 #35
0
    def button_pressed(self, button):
        if button.text == 'YES':
            self.manager.current = 'main'
            self.popup.dismiss()
        else:
            global CURRENT_PLAYER, AMOUNT, CURRENT1, SOME_LIST1, finish
            row, column = button.coords
            status_index = row * 10 + column
            already_played = self.status[status_index]
            if not already_played and CURRENT_PLAYER == 1:
                self.status[status_index] = CURRENT_PLAYER

                for ship in SHIPS_OF_COMP:
                    if ship[0] == (row, column):
                        CURRENT1 += 1
                        SOME_LIST1.append((row, column))
                        button.background_color = ship[1]
                        # button.text = str(ship[2])
                        if CURRENT1 == ship[2]:
                            if self.sound != '':
                                self.sound.stop()
                            self.sound = SoundLoader.load('files/boom.mp3')
                            self.sound.play()

                            for ship in SOME_LIST1:
                                x, y = ship
                                s = [1, 0, -1]
                                t = [1, 0, -1]
                                for xx in s:
                                    for yy in t:
                                        for child in self.ids.grid.children:
                                            if child.coords == (x + xx, y + yy) and (x + xx, y + yy) not in SOME_LIST1:
                                                child.text = 'X'
                                                child.background_color = [1, 0, 0, 1]
                            SOME_LIST1 = []
                            CURRENT1 = 0
                        else:
                            if self.sound != '':
                                self.sound.stop()
                            self.sound = SoundLoader.load('files/bomb2.wav')
                            self.sound.play()

                        AMOUNT += 1
                        AMOUNT = 4 + 3 * 2 + 2 * 3 + 4
                        if AMOUNT == 4 + 3 * 2 + 2 * 3 + 4:
                            finish = SoundLoader.load('files/winner.mp3')
                            finish.play()
                            winner = ModalView(size_hint=(0.75, 0.5))
                            winner.background = 'files/youWin.png'
                            # victory_label = Label(text='You WIN!!!!!', font_size=50)
                            # winner.add_widget(victory_label)
                            winner.bind(on_dismiss=self.somefunc)
                            winner.open()
                        break

                if button.background_color == [1, 1, 1, 1]:
                    button.text = 'X'
                    if self.sound != '':
                        self.sound.stop()
                    self.sound = SoundLoader.load('files/Not_ship.wav')
                    self.sound.play()

                    button.background_color = [1, 0, 0, 1]
                    Clock.schedule_once(self.callback, 1)
                    CURRENT_PLAYER *= -1
예제 #36
0
    def on_status(self, instance, status):
        status = self.status

        #sum each row, column and diagonal
        sums = [
            sum(status[0:3]),
            sum(status[3:6]),
            sum(status[6:9]),  #rows
            sum(status[0::3]),
            sum(status[1::3]),
            sum(status[2::3]),  #cols
            sum(status[0::4]),
            sum(status[2:-2:2])
        ]  # diagonals

        winner = None

        if 3 in sums:
            print(self.status)
            winner = 'Player 1 (O) wins!\n Would you like to play again?'
        elif -3 in sums:
            print(self.status)
            winner = 'Player 2 (X) wins!\n Would you like to play again?'
        elif 0 not in self.status:  #grid full
            print(self.status)
            winner = 'Draw! \n Would you like to play again?'

        if winner:

            # create a button
            float = FloatLayout(size_hint=(0.5, 0.5))
            y_button = Button(text="Y",
                              font_size=20,
                              pos_hint={
                                  'x': 0.4,
                                  'center_y': 0.5
                              },
                              size_hint=(None, None))
            n_button = Button(text="N",
                              font_size=20,
                              pos_hint={
                                  'x': 0.6,
                                  'center_y': 0.5
                              },
                              size_hint=(None, None))
            float.add_widget(y_button)
            float.add_widget(n_button)

            popup = ModalView(size_hint=(0.5, 0.5))
            victory_label = Label(text=winner,
                                  pos_hint={
                                      'x': 0.3,
                                      'center_y': 0.7
                                  },
                                  size_hint=(None, None))
            float.add_widget(victory_label)

            popup.add_widget(float)

            if y_button:
                self.reset

            popup.bind(on_dismiss=self.reset)
            popup.open()
예제 #37
0
    def verifierGagnant(self):

        # si tous les pions rouges sont arrivés
        if self.plateau_jeu[206] == 1 and self.plateau_jeu[
                207] == 1 and self.plateau_jeu[221] == 1 and self.plateau_jeu[
                    222] == 1 and self.plateau_jeu[223] == 1 and self.plateau_jeu[
                        236] == 1 and self.plateau_jeu[
                            237] == 1 and self.plateau_jeu[
                                238] == 1 and self.plateau_jeu[
                                    239] == 1 and self.plateau_jeu[
                                        252] == 1 and self.plateau_jeu[
                                            253] == 1 and self.plateau_jeu[
                                                254] == 1 and self.plateau_jeu[
                                                    255] == 1:
            popup = ModalView(size_hint=(0.6, 0.2))
            victory_label = Label(text='Le joueur rouge a gagné !',
                                  font_size=30)
            Window.clearcolor = (1, 1, 0, 1)
            popup.add_widget(victory_label)
            popup.bind(on_dismiss=self.reset
                       )  # lorsque le pop-up est fermée, on reset le plateau
            popup.open()  # on ouvre la pop-up de victoire

        # si tous les pions verts sont arrivés
        if self.plateau_jeu[192] == 2 and self.plateau_jeu[
                193] == 2 and self.plateau_jeu[208] == 2 and self.plateau_jeu[
                    209] == 2 and self.plateau_jeu[210] == 2 and self.plateau_jeu[
                        224] == 2 and self.plateau_jeu[
                            225] == 2 and self.plateau_jeu[
                                226] == 2 and self.plateau_jeu[
                                    227] == 2 and self.plateau_jeu[
                                        240] == 2 and self.plateau_jeu[
                                            241] == 2 and self.plateau_jeu[
                                                242] == 2 and self.plateau_jeu[
                                                    243] == 2:
            popup = ModalView(size_hint=(0.6, 0.2))
            victory_label = Label(text='Le joueur vert a gagné !',
                                  font_size=30)
            Window.clearcolor = (1, 1, 0, 1)
            popup.add_widget(victory_label)
            popup.bind(on_dismiss=self.reset
                       )  # lorsque le pop-up est fermée, on reset le plateau
            popup.open()  # on ouvre la pop-up de victoire

        # si tous les pions jaunes sont arrivés
        if self.plateau_jeu[0] == 3 and self.plateau_jeu[
                1] == 3 and self.plateau_jeu[2] == 3 and self.plateau_jeu[
                    3] == 3 and self.plateau_jeu[16] == 3 and self.plateau_jeu[
                        17] == 3 and self.plateau_jeu[
                            18] == 3 and self.plateau_jeu[
                                19] == 3 and self.plateau_jeu[
                                    32] == 3 and self.plateau_jeu[
                                        33] == 3 and self.plateau_jeu[
                                            34] == 3 and self.plateau_jeu[
                                                48] == 3 and self.plateau_jeu[
                                                    49] == 3:
            popup = ModalView(size_hint=(0.6, 0.2))
            victory_label = Label(text='Le joueur jaune a gagné !',
                                  font_size=30)
            Window.clearcolor = (1, 1, 0, 1)
            popup.add_widget(victory_label)
            popup.bind(on_dismiss=self.reset
                       )  # lorsque le pop-up est fermée, on reset le plateau
            popup.open()  # on ouvre la pop-up de victoire

        # si tous les pions bleus sont arrivés
        if self.plateau_jeu[62] == 4 and self.plateau_jeu[
                63] == 4 and self.plateau_jeu[45] == 4 and self.plateau_jeu[
                    46] == 4 and self.plateau_jeu[47] == 4 and self.plateau_jeu[
                        28] == 4 and self.plateau_jeu[
                            29] == 4 and self.plateau_jeu[
                                30] == 4 and self.plateau_jeu[
                                    31] == 4 and self.plateau_jeu[
                                        12] == 4 and self.plateau_jeu[
                                            13] == 4 and self.plateau_jeu[
                                                14] == 4 and self.plateau_jeu[
                                                    15] == 4:
            popup = ModalView(size_hint=(0.6, 0.2))
            victory_label = Label(text='Le joueur bleu a gagné !',
                                  font_size=30)
            Window.clearcolor = (1, 1, 0, 1)
            popup.add_widget(victory_label)
            popup.bind(on_dismiss=self.reset
                       )  # lorsque le pop-up est fermée, on reset le plateau
            popup.open()
class FileChooser():
    def __init__(self, path, title='', on_success=None, on_canceled=None,
                 select_dir=True, filetypes=[("all files", "*")]):
        self.path = path
        self.on_success = on_success
        self.on_canceled = on_canceled
        self.title = title
        self.select_dir = select_dir
        self.filetypes = filetypes

        self.open()

    def _tk_open(self, _):
        root = Tkinter.Tk()
        root.withdraw()  # use to hide tkinter window

        while True:

            if self.select_dir:
                tempnode = tkFileDialog.askdirectory(
                    parent=root,
                    initialdir=self.path,
                    title=self.title)
            else:
                tempnode = tkFileDialog.askopenfilename(
                    parent=root,
                    initialdir=self.path,
                    title=self.title,
                    filetypes=self.filetypes)

            if not tempnode:
                Logger.info('FileChooser: User canceled the prompt')
                if self.on_canceled:
                    self.on_canceled()

                self.p.dismiss()
                return

            if os.sep != '/':  # askdirectory uses '/' as separator
                tempnode = tempnode.replace('/', os.sep)

            Logger.info('FileChooser: User selected {}'.format(tempnode))

            if not self.on_success:
                break

            # Call callback. If the callback returns something other than False
            # Show the message and get show the dir selection prompt again.
            message = self.on_success(tempnode)
            if message:
                Logger.error('FileChooser: {}'.format(message))
                tkMessageBox.showinfo('Error', message)

            else:
                break


        self.p.dismiss()

    def open(self):
        self.p = ModalView(size=(0, 0), size_hint=(None, None),
                           auto_dismiss=False, border=[0, 0, 0, 0])
        self.p.bind(on_open=self._tk_open)
        self.p.open()
예제 #39
0
                        foreground_color=(1, 1, 1, 1))


def setFocus(*args, **kwargs):
    oText_input.focus = True


open_file_layout.add_widget(oText_input)

open_file_popup = ModalView(  #content=open_file_layout,
    size_hint=(None, None),
    size=(800, 40),
    auto_dismiss=False)
open_file_popup.add_widget(open_file_layout)

open_file_popup.bind(on_open=setFocus)


class TestBarApp(App):
    def __init__(self):
        super().__init__()
        self.current_img = FRONT_PAGE_IMG
        self.file_chooser_active = False
        self.img_index = 0
        self.amount = 0
        self.img_basename = ""
        self.selected_file = ""
        self.export_open = False
        self.select_file_open = False
        Window.bind(on_key_down=self._on_keyboard_down)
예제 #40
0
파일: main.py 프로젝트: psykzz/lol-connect
def show_winner(board):
    popup = ModalView(size_hint=(0.75, 0.5))
    victory_label = Label(text="You won!", font_size=50)
    popup.add_widget(victory_label)
    popup.bind(on_dismiss=board.on_win)
    popup.open()
예제 #41
0
class ButtonStack(MyBoxLayout):
    rows = NumericProperty(1)
    cols = NumericProperty(1)
    buttons = ListProperty()
    font_size = NumericProperty()
    text_list = ListProperty()

    def drop_close(self, button):
        self.parent.parent.parent.parent.parent.options_close(button)
        if button == self.quantity_drop:
            self.buttons[0][1].text = self.parent.entry.quantity = button.value
            self.from_drop.values = self.to_drop.values = eval(
                "convert_unit_" + button.value)
            self.from_drop.refresh()
            self.to_drop.refresh()
            self.buttons[1][1].text = self.from_drop.values[0]
            self.buttons[1][3].text = self.to_drop.values[1]
        elif button == self.from_drop:
            self.buttons[1][
                1].text = self.parent.entry.from_unit = button.value
        elif button == self.to_drop:
            self.buttons[1][3].text = self.parent.entry.to_unit = button.value

    def size_change(self, row, column, new):
        self.buttons[row][column].parent.size_hint_x *= new

    def options_select(self, button, *args, **kwargs):
        global current_page
        self.options.dismiss()
        current_page[0] = button.text
        self.parent.parent.parent.page_change(button)

    def inverse_change(self, button):

        if button.state == 'down':
            text = config_data['page_list'][1]['inv_text']
        else:
            text = config_data['page_list'][1]['text']

        c = 1
        for index, row in enumerate(self.buttons):
            for index_, cell in enumerate(row):
                if (index == 0 and index_ == 0) or index > 3:
                    c += 1
                    continue
                elif cell.text == 'log' and text == config_data['page_list'][
                        1]['inv_text']:
                    cell.text = str(config_data['base']) + '\u00aa'
                    c += 1
                    continue
                cell.text = text[c] if text[c] not in ['rm', ' '] else text[c +
                                                                            1]
                c += 1

    def __init__(self, **kwargs):
        super(ButtonStack, self).__init__(**kwargs)
        self.stack = StackLayout()
        text_var = 0

        for row in range(self.rows):
            row_list = []
            for cell in range(self.cols):

                padding = [self.spacing * 0.5] * 4
                if row == 0:
                    padding[1] = 0
                if row == self.rows - 1:
                    padding[3] = 0
                if cell == 0:
                    padding[0] = 0
                if cell == self.cols - 1:
                    padding[2] = 0

                button_box = BoxLayout(
                    size_hint_x=1 / self.cols,
                    size_hint_y=1 / self.rows,
                    padding=padding,
                )
                button = MButton(font_size=self.font_size,
                                 text=self.text_list[text_var])
                text_var += 1
                if button.text == "rm":
                    continue
                button_box.add_widget(button)
                self.stack.add_widget(button_box)
                row_list.append(button)

            self.buttons.append(row_list)

        for index_, button_ in enumerate(self.buttons):
            for index, button in enumerate(button_):
                if button.text == "db":
                    button.disabled = True
                    button.text = ""
                elif button.text in ["and", "between"]:
                    button.hover = False
                    button.ripple = False
                elif "include" in button.text:
                    button.toggle_state = True
                elif button.text in ["INV", "RAD"]:
                    button.toggle_state = True
                    if (config_data["inverse"] and button.text == "INV") or (
                            config_data["radian"] and button.text == "RAD"):
                        button.state = "down"
                        button.color = button.hover_color
                    if button.text == 'RAD':

                        button.bind(on_release=lambda button: setattr(
                            button, 'text', 'RAD'
                            if button.text == 'DEG' else 'DEG'))
                    if button.text == 'INV':
                        button.bind(on_release=self.inverse_change)
                else:
                    if button.text not in [" ", "..."]:
                        button.bind(on_release=lambda button=button: self.
                                    parent.entry.insert_text(button.text))

        self.options = ModalView(size_hint=(0.4, 0.6))
        self.options_layout = MyBoxLayout(orientation="vertical")
        for options_button_text in config_data["page_list"]:
            if options_button_text["mode"] != current_page:
                options_button = MButton(text=options_button_text["mode"],
                                         modal_button=True)
                self.options_layout.add_widget(options_button)
                options_button.bind(
                    on_release=lambda options_button=options_button: self.
                    options_select(options_button))
        self.options.add_widget(self.options_layout)
        self.options.bind(on_dismiss=lambda button: self.parent.parent.parent.
                          parent.parent.options_close(button))

        self.buttons[0][0].bind(on_release=self.options.open)
        self.buttons[0][0].bind(on_release=lambda button: self.parent.parent.
                                parent.parent.parent.options_open(button))

        self.buttons[-1][0].bind(
            on_release=lambda button: self.parent.parent.parent.parent.parent.
            effect_layout.settings.open())
        self.buttons[-1][0].bind(on_release=lambda button: self.parent.parent.
                                 parent.parent.parent.options_open(button))
        self.spacing = 0

        self.quantity_drop = Drop(title="quantity",
                                  values=convert_quantities,
                                  size_hint=(0.6, 0.6))
        self.from_drop = Drop(
            title="from",
            values=eval("convert_unit_" + convert_quantities[0]),
            size_hint=(0.6, 0.6),
        )

        self.to_drop = Drop(
            title="to",
            values=eval("convert_unit_" + convert_quantities[0]),
            default=eval("convert_unit_" + convert_quantities[0])[1],
            size_hint=(0.6, 0.6))

        self.quantity_drop.bind(
            on_dismiss=lambda button: self.drop_close(button))

        self.from_drop.bind(on_dismiss=lambda button: self.drop_close(button))
        self.to_drop.bind(on_dismiss=lambda button: self.drop_close(button))
        self.add_widget(self.stack)