def show_image(self, obj):
     instaloader = Instaloader()
     username = self.user.text
     instaloader.download_profile(username, profile_pic_only=True)
     filename = glob(str(username + "/*jpg"))
     img_data = str(filename[0])
     image = Image(source=img_data,
                   pos_hint={
                       "center_x": 0.5,
                       "center_y": 0.3
                   },
                   size_hint=(0.5, 1))
     image.remove_widget(image)
     self.screen.add_widget(image)
Ejemplo n.º 2
0
class CoatiraneAdventures(App):
    title = f'Coatirane Adventures - {GAME_VERSION}'

    def __init__(self, *args, **kwargs):
        Window.bind(on_resize=self.on_resize)
        Window.bind(on_request_close=self.close_window)
        Window.bind(on_memorywarning=self.on_memory_warning)

        self._keyboard = None
        self._keycode = None
        self._bind_keyboard()

        # Builder.load_file('Game.kv')

        self._size = Window.size
        self.ratios = None
        self._background = None
        self._loader = None
        self._screen_manager = None
        self._popup_manager = PopupManager()
        self.use_kivy_settings = False
        self.width, self.height = self._size
        self.x, self.y = 0, 0
        self._end_screen = 'town_main'

        self._content = GameContent(PROGRAM_TYPE)

        Refs.gc = self._content
        Refs.gp = self._popup_manager
        Refs.log = self.log
        Refs.app = self

        self.settings_cls = Settings
        self._keyboard_bindings = {'on_key_up': [], 'on_key_down': []}

        super().__init__(**kwargs)
        self.initialized = False

    def _bind_keyboard(self):
        self.log('The keyboard has been bound!')
        self._keyboard = Window.request_keyboard(self._keyboard_closed, self)
        self._keyboard.bind(on_key_down=self._on_keyboard_down)
        self._keyboard.bind(on_key_up=self._on_keyboard_up)

    def _keyboard_closed(self):
        self.log('The keyboard has been closed!')
        self._keyboard.unbind(on_key_down=self._on_keyboard_down)
        self._keyboard.unbind(on_key_up=self._on_keyboard_up)
        self._keyboard = None

    def map_key_name(self, code):
        if code == '':
            return
        key_name = None
        if code in ('w', 'up'):
            key_name = 'move_up'
        elif code in ('a', 'left'):
            key_name = 'move_left'
        elif code in ('s', 'down'):
            key_name = 'move_down'
        elif code in ('d', 'right'):
            key_name = 'move_right'
        elif code in ('m', ):
            key_name = 'map'
        elif code in ('o', ):
            key_name = 'options'
        elif code in ('i', ):
            key_name = 'inventory'
        elif code in ('esc', ):
            key_name = 'pause'
        elif code in ('q', ):
            key_name = 'secondary_action_1'
        elif code in ('e', ):
            key_name = 'secondary_action_2'
        elif code in ('f', ):
            key_name = 'primary_action'
        elif code in ('f12', ):
            key_name = 'screenshot'
        return key_name

    def take_screenshot(self):
        path = expanduser(
            '~/Saved Games/Coatirane Adventures/screenshots/').replace(
                '\\', '/')
        if not exists(path):
            mkdir(path)
        Window.screenshot(
            f'{path}Coatirane Adventures - {datetime.now().strftime("%d-%m-%Y %H-%M-%S")}.png'
        )

    def _on_keyboard_down(self, keyboard, keycode, text, modifiers):
        if self._keycode != keycode:
            self._keycode = keycode
            Refs.log(f'Key was pressed - {keycode}')
        key_name = self.map_key_name(keycode[1])
        if key_name is not None:
            if key_name == 'screenshot':
                self.take_screenshot()
            else:
                for callback in self._keyboard_bindings['on_key_down']:
                    callback(keyboard, key_name, text, modifiers)

    def _on_keyboard_up(self, keyboard, keycode):
        self._keycode = None
        key_name = self.map_key_name(keycode[1])
        if key_name == 'screenshot' or key_name is None:
            return
        for callback in self._keyboard_bindings['on_key_up']:
            callback(keyboard, key_name)

    def bind_keyboard(self, **kwargs):
        self.log(f'Add binding for master keyboard')
        for key, callback in kwargs.items():
            self._keyboard_bindings[key].append(callback)

    def unbind_keyboard(self, **kwargs):
        self.log(f'Remove binding for master keyboard')
        for key, callback in kwargs.items():
            self._keyboard_bindings[key].remove(callback)

    def log(self, message, level='info', tag='CoatiraneAdventures'):
        Logger.log({
            'info': 20,
            'warn': 30,
            'debug': 10,
            'error': 40
        }[level], f"{tag}: {message}")

    def to_window(self, x, y):
        return x, y

    def build(self):
        self.log('loading the starting game window')
        self._background = Image(source="game_bounds.png", allow_stretch=True)

        self.log('creating background loader')
        self._loader = CALoader(PROGRAM_TYPE)

        self._loader.load_base_values()
        self._loader.size = self._size

        self.ratios = self._loader.load_ratios()

        # self.background.add_widget(self.loader)
        self._screen_manager = Root(self)
        Refs.gs = self._screen_manager
        self._screen_manager.size = self._size
        self._background.add_widget(self._screen_manager)
        return self._background

    def start_loading(self, save_slot, finish_screen):
        self.log('Starting background loader')
        self._background.add_widget(self._loader)
        self._screen_manager.opacity = 0
        self._end_screen = finish_screen
        Refs.gc.set_save_slot(save_slot)
        Clock.schedule_once(lambda dt: self._loader.load_game(save_slot), 0)

    def finished_loading(self):
        self.log('Finished Loading')
        self._background.remove_widget(self._loader)
        self._screen_manager.display_screen(self._end_screen, True, False)
        self._screen_manager.opacity = 1

    def reset_loader(self):
        self._loader.reset()

    def get_manager(self):
        return self._screen_manager

    # def add_manager(self, manager):
    #     self._screen_manager = manager
    #     manager.size = self.width, self.height
    #
    # def set_manager(self):
    #     self._background.add_widget(self._screen_manager)

    def allow_sleep(self):
        Window.allow_screensaver = True

    def deny_sleep(self):
        Window.deny_screensaver = True

    def close_window(self, *args):
        self.log('Save Game')
        self.log('Closing the window')
        if platform == 'win':
            Window.close()

    def on_memory_warning(self):
        self.log('received memory warning')

    # The game may or may not return from a pause.
    def on_pause(self):
        self.log('game paused')
        if platform == 'win':
            return True
        else:
            return True

    def exit_game(self):
        self.stop()

    def on_resize(self, *args):
        Clock.unschedule(self.fix_size)
        Clock.schedule_once(self.fix_size, .25)

    def get_content(self):
        return self._content

    def make_windowed(self):
        Window.fullscreen = 0
        Window.borderless = 0
        w, h = int(Config.get('graphics',
                              'width')), int(Config.get('graphics', 'height'))
        sw, sh = int(Config.get('graphics', 'screen_width')), int(
            Config.get('graphics', 'screen_height'))
        if w == sw and h == sh:
            w, h = int(w * 2 / 3), int(h * 2 / 3)
            l, t = int(sw / 2 - w / 2), int(sh / 2 - h / 2)
            Window.left = l
            Window.top = t
            Config.set('graphics', 'width', int(w))
            Config.set('graphics', 'height', int(h))
            Config.set('graphics', 'left', l)
            Config.set('graphics', 'top', t)
            Config.write()
        Window.size = w, h
        self.log(f'Window size is {w}x{h}')
        self.width, self.height = w, h

    def make_fake_fullscreen(self):
        Window.fullscreen = 0
        Window.borderless = 1
        Window.pos = 0, 0
        Window.left = 0
        Window.top = 0
        width, height = int(Config.get('graphics', 'screen_width')), int(
            Config.get('graphics', 'screen_height'))
        Config.set('graphics', 'width', width)
        Config.set('graphics', 'height', height)
        Config.set('graphics', 'left', 0)
        Config.set('graphics', 'top', 0)
        Config.write()
        Window.size = width, height
        self.width, self.height = width, height

    def fix_size(self, *args):
        if self._size == Window.size:
            return
        self._size = Window.size
        self._background.size = Window.size

        offset = self._background.width / 2 - self._background.norm_image_size[
            0] / 2, self._background.height / 2 - self._background.norm_image_size[
                1] / 2
        if self._loader:
            self._loader.size = self._background.norm_image_size
            self._loader.pos = offset
            #if self.initialized:
            self._screen_manager.size = self._background.norm_image_size
            self._screen_manager.pos = offset

    def get_dkey(self, key, x=None, y=None, z=None, w=None, t=None, u=None):
        # This is to get a ratio. All ratios will be designed at res 1706 x 960
        # This function will get the ratios for 1x and scale them up or down if needed

        dict_key, v = key.split(' ')
        d = self.ratios
        for k in dict_key.split('.'):
            d = d.get(k)
        if v == 'p_h':
            # print(d['p_h'])
            values = d['p_h']
            for key in values.keys():
                if not isinstance(values[key], float) and not isinstance(
                        values[key], int):
                    values[key] = eval(values[key].format(x=x,
                                                          y=y,
                                                          z=z,
                                                          w=w,
                                                          t=t,
                                                          u=u))
            return values
        elif v == 's' or v == 'p':
            return eval(d[v + '_x'].format(x=x, y=y, z=z, w=w, t=t,
                                           u=u)), eval(d[v + '_y'].format(x=x,
                                                                          y=y,
                                                                          z=z,
                                                                          w=w,
                                                                          t=t,
                                                                          u=u))
        else:
            return eval(d[v].format(x=x, y=y, z=z, w=w, t=t, u=u))
Ejemplo n.º 3
0
class Juego(Screen):
    def __init__(self, **Kwargs):
        super(Juego, self).__init__(**Kwargs)
        self.orientation = "vertical"
        S = Image(source='imagenes/juego.jpeg', allow_stretch=True)
        self.add_widget(S)  #añade la imagen al widget
        self.option = ""
        self.botones = []

        self.my_box1 = FloatLayout(size=(300, 300))
        labelTitle = Label(text='[color=000000] CENTINELA [/color]',
                           markup=True,
                           font_size="70dp",
                           font_name="Times",
                           size_hint=(0.3, 0.3),
                           pos=(120, 450))
        labelChat = Label(text='[color=000000] CHAT [/color]',
                          markup=True,
                          font_size="50dp",
                          font_name="Times",
                          size_hint=(0.3, 0.3),
                          pos=(500, 450))

        SP1 = Image(source='imagenes/moneda.png',
                    size_hint=(0.2, 0.1),
                    pos=(30, 370))
        SP2 = Image(source='imagenes/moneda.png',
                    size_hint=(0.2, 0.1),
                    pos=(150, 370))
        SP3 = Image(source='imagenes/moneda.png',
                    size_hint=(0.2, 0.1),
                    pos=(270, 370))
        labelPunto1 = Label(text='[color=000000] ' + varg.getPuntos1() +
                            '[/color]',
                            markup=True,
                            font_size="30dp",
                            font_name="Times",
                            size_hint=(0.3, 0.3),
                            pos=(55, 350))
        labelPunto2 = Label(text='[color=000000] ' + varg.getPuntos2() +
                            '[/color]',
                            markup=True,
                            font_size="30dp",
                            font_name="Times",
                            size_hint=(0.3, 0.3),
                            pos=(175, 350))
        labelPunto3 = Label(text='[color=000000] ' + varg.getPuntos3() +
                            '[/color]',
                            markup=True,
                            font_size="30dp",
                            font_name="Times",
                            size_hint=(0.3, 0.3),
                            pos=(295, 350))

        #Acción de iniciar
        self.btnIniciar = Button(text="INICIAR",
                                 font_size=85,
                                 size_hint=(0.5, 0.5),
                                 background_color=[0, 166, 0, 38],
                                 pos=(100, 30))
        self.btnIniciar.bind(on_press=self.iniciar)
        #Acción de atacar
        self.btnAtacar = Button(text="Atacar",
                                font_size=24,
                                size_hint=(0.1, 0.1),
                                background_color=[0, 1, 0.6, 0.8],
                                pos=(100, 10))
        self.btnAtacar.bind(on_press=self.changerA)
        #Acción de sumar
        self.btnSumar = Button(text="Sumar",
                               font_size=24,
                               size_hint=(0.1, 0.1),
                               background_color=[0, 1, 0.6, 0.8],
                               pos=(200, 10))
        self.btnSumar.bind(on_press=self.changer)
        #Acción de Robar
        self.btnRobar = Button(text="Robar",
                               font_size=24,
                               size_hint=(0.1, 0.1),
                               background_color=[0, 1, 0.6, 0.8],
                               pos=(300, 10))
        self.btnRobar.bind(on_press=self.changerR)

        self.labelPunto = Label(text='[color=000000] ' + varg.getPuntos() +
                                '[/color]',
                                markup=True,
                                font_size="30dp",
                                font_name="Times",
                                size_hint=(0.3, 0.3),
                                pos=(375, -10))
        self.puntosImg = Image(source='imagenes/moneda.png',
                               size_hint=(0.2, 0.1),
                               pos=(350, 10))

        #Chat
        self.messageInput = TextInput(size_hint=(0.2, 0.1), pos=(550, 10))
        #Boton para enviar mensaje
        btn = Button(text="Enviar",
                     font_size=24,
                     size_hint=(0.1, 0.1),
                     background_color=[0, 1, 0.6, 0.8],
                     pos=(720, 10))
        btn.bind(on_press=self.sendMessage)

        self.my_box1.add_widget(labelTitle)
        self.my_box1.add_widget(labelChat)
        self.my_box1.add_widget(self.messageInput)
        self.my_box1.add_widget(SP1)
        self.my_box1.add_widget(SP2)
        self.my_box1.add_widget(SP3)
        self.puntosImg.add_widget(self.labelPunto)
        self.puntosImg.add_widget(labelPunto1)
        self.puntosImg.add_widget(labelPunto2)
        self.puntosImg.add_widget(labelPunto3)
        self.my_box1.add_widget(btn)
        self.my_box1.add_widget(self.btnAtacar)
        self.my_box1.add_widget(self.btnRobar)
        self.my_box1.add_widget(self.btnSumar)
        self.my_box1.add_widget(self.puntosImg)
        self.my_box1.add_widget(self.btnIniciar)
        self.add_widget(self.my_box1)

    def sendMessage(self, btn):
        requestmsg = varg.getplayer_name() + " chat " + self.messageInput.text
        print(requestmsg)
        self.my_box1.remove_widget(self.messageInput)
        self.my_box1.add_widget(self.messageInput)
        s.sendall(requestmsg.encode())

    def escucharTurno(self):
        while (varg.getturno() != varg.getplayer_name()):
            time.sleep(1)
            s.sendall(b'turno')
            data = s.recv(1024).decode()
            varg.setturno(data)
            print(data)
            print(varg.getturno())
            self.my_box1.remove_widget(self.labelTurno)
            self.labelTurno = Label(text='[color=165B03] Es turno de: ' +
                                    varg.getprimerTurno() + '[/color]',
                                    markup=True,
                                    font_size="20dp",
                                    font_name="Times",
                                    size_hint=(0.3, 0.3),
                                    pos=(120, 380))
            self.my_box1.add_widget(self.labelTurno)
        self.my_box1.remove_widget(self.labelTurno)
        self.labelTurno = Label(text='[color=165B03] Es turno de: ' +
                                varg.getprimerTurno() + '[/color]',
                                markup=True,
                                font_size="20dp",
                                font_name="Times",
                                size_hint=(0.3, 0.3),
                                pos=(120, 380))
        self.my_box1.add_widget(self.labelTurno)

    def jugada(self, btn):
        print("boton", btn.text)
        if (self.option == "S"):
            print(varg.getnameTurno())
            requestS = "S " + btn.text + " " + varg.getnameTurno()
            print(requestS)
            s.sendall(requestS.encode())
            data = s.recv(1024).decode()
            print(requestS)
            print("respuesta de suma:", data)
            varg.setPuntos(data)
            # TODO: ACTUALIZAR LABEL DE PUNTOS
            self.puntosImg.remove_widget(self.labelPunto)
            self.labelPunto = Label(text='[color=000000] ' + varg.getPuntos() +
                                    '[/color]',
                                    markup=True,
                                    font_size="30dp",
                                    font_name="Times",
                                    size_hint=(0.3, 0.3),
                                    pos=(375, -10))
            self.puntosImg.add_widget(self.labelPunto)
            print("antes de las cartas")
            misCartasAct = varg.getmisCartas()
            index = misCartasAct.index(btn.text)
            newarray = []
            for carta in misCartasAct:
                if (index != misCartasAct.index(carta)):
                    newarray.append(carta)
            varg.setmisCartas(newarray)
            print("mis cartas", varg.getmisCartas())

            #self.escucharTurno()

        elif (self.option == "A"):
            namePlayer = self.Jugador.text
            orden = varg.getorden()
            indeP = orden.index(namePlayer)
            if (indeP == 0):
                elPlayer = "p1"
            elif (indeP == 1):
                elPlayer = "p2"
            elif (indeP == 2):
                elPlayer = "p3"
            elif (indeP == 3):
                elPlayer = "p4"

            requestA = "S" + " -" + btn.text + " " + elPlayer
            print(requestA)
            s.sendall(requestA.encode())

            misCartas = varg.getmisCartas()
            index = misCartas.index(btn.text)
            newarray = []
            for carta in misCartas:
                if (index != misCartas.index(carta)):
                    newarray.append(carta)
            varg.setmisCartas(newarray)

        elif (self.option == "R"):
            requestS = "R"

        print("antes del for")
        for a in self.botones:
            self.my_box1.remove_widget(a)
        self.my_box1.add_widget(self.btnAtacar)
        self.my_box1.add_widget(self.btnRobar)
        self.my_box1.add_widget(self.btnSumar)

    def generarCartas(self, cartas):
        x = 30
        y = 100
        cont = 0

        for a in cartas:
            self.btnC = Button(text=a,
                               font_size=24,
                               size_hint=(0.05, 0.08),
                               background_color=[0, 1, 0.6, 0.8],
                               pos=(x, y))
            self.btnC.bind(on_press=self.jugada)
            self.my_box1.add_widget(self.btnC)
            self.botones.append(self.btnC)
            cont = cont + 1
            if (cont < 7):
                x = x + 50
            elif (cont == 7):
                y = 50
                x = 30
            else:
                x = x + 50

    def threaded_msg(self):
        while True:
            time.sleep(1)
            data = s.recv(1024).decode()
            print(data)

    def iniciar(self, btn):
        self.my_box1.remove_widget(self.btnIniciar)
        jugadores = varg.getjugadores()
        labelPin = Label(text='[color=165B03] Estas en la sala: ' +
                         varg.getnum() + '[/color]',
                         markup=True,
                         font_size="20dp",
                         font_name="Times",
                         size_hint=(0.3, 0.3),
                         pos=(120, 400))
        self.labelTurno = Label(text='[color=165B03] Es turno de: ' +
                                varg.getprimerTurno() + '[/color]',
                                markup=True,
                                font_size="20dp",
                                font_name="Times",
                                size_hint=(0.3, 0.3),
                                pos=(120, 380))
        labelP1 = Label(text='[color=165B03] ' + jugadores[0] + '[/color]',
                        markup=True,
                        font_size="20dp",
                        font_name="Times",
                        size_hint=(0.3, 0.3),
                        pos=(-20, 270))
        labelP2 = Label(text='[color=165B03] ' + jugadores[1] + '[/color]',
                        markup=True,
                        font_size="20dp",
                        font_name="Times",
                        size_hint=(0.3, 0.3),
                        pos=(110, 270))
        labelP3 = Label(text='[color=165B03] ' + jugadores[2] + '[/color]',
                        markup=True,
                        font_size="20dp",
                        font_name="Times",
                        size_hint=(0.3, 0.3),
                        pos=(220, 270))

        self.my_box1.add_widget(labelPin)
        self.my_box1.add_widget(self.labelTurno)
        self.my_box1.add_widget(labelP1)
        self.my_box1.add_widget(labelP2)
        self.my_box1.add_widget(labelP3)

        #start_new_thread(self.threaded_msg, ())

    def cartas(self):
        if (self.option == "A" or self.option == "R"):
            self.my_box1.remove_widget(self.btnCon)
            self.my_box1.remove_widget(self.Jugador)
            self.my_box1.remove_widget(self.labelJ)
            if (self.option == "A"):
                self.generarCartas(varg.getmisCartas())
            elif (self.option == "R"):
                self.generarCartas([
                    "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11",
                    "12", "13"
                ])

        elif (self.option == "S"):
            self.generarCartas(varg.getmisCartas())

    def changerAR(self):  #Cambiar de pantalla
        self.my_box1.remove_widget(self.btnAtacar)
        self.my_box1.remove_widget(self.btnRobar)
        self.my_box1.remove_widget(self.btnSumar)

        self.labelJ = Label(text='[color=165B03] Jugador: [/color]',
                            markup=True,
                            font_size="30dp",
                            font_name="Times",
                            size_hint=(0.3, 0.3),
                            pos=(10, 10))
        self.my_box1.add_widget(self.labelJ)
        self.Jugador = TextInput(size_hint=(0.2, 0.1), pos=(40, 10))
        self.btnCon = Button(text="continuar",
                             font_size=24,
                             size_hint=(0.17, 0.1),
                             background_color=[0, 1, 0.6, 0.8],
                             pos=(210, 15))
        self.btnCon.bind(on_press=self.change)
        self.my_box1.add_widget(self.btnCon)
        self.my_box1.add_widget(self.Jugador)

    def changerA(self, btn):
        self.option = "A"
        self.changerAR()

    def changerR(self, btn):
        self.option = "R"
        self.changerAR()

    def change(self, btn):
        self.cartas()

    def changer(self, btn):  #Cambiar de pantalla
        self.option = "S"
        self.my_box1.remove_widget(self.btnAtacar)
        self.my_box1.remove_widget(self.btnRobar)
        self.my_box1.remove_widget(self.btnSumar)
        self.cartas()