Domanda Risolto Mi servirebbe una mano in python

Stato
Discussione chiusa ad ulteriori risposte.

N3v5

Utente Silver
24 Ottobre 2020
169
19
40
80
Ultima modifica:
Ciao ragazzi. Sto provando a fare un menu in pygame con pygame_menu. Ho questo codice ma alcune righe non le capisco. In particolare vorrei sapere a cosa servono le righe: 27,32-33, 45-46-47 e cosa significa la -> None di riga 60.

Python:
"""
pygame-menu
https://github.com/ppizarror/pygame-menu
EXAMPLE - IMAGE BACKGROUND
Menu using background image + BaseImage object.
License:
-------------------------------------------------------------------------------
The MIT License (MIT)
Copyright 2017-2021 Pablo Pizarro R. @ppizarror
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-------------------------------------------------------------------------------
"""

__all__ = ['main']    #QUESTA

import sys
from typing import Optional

sys.path.insert(0, '../../')  #QUESTE DUE
sys.path.insert(0, '../../../')

import pygame
import pygame_menu
from pygame_menu.examples import create_example_window

# -----------------------------------------------------------------------------
# Constants and global variables
# -----------------------------------------------------------------------------
FPS = 60
WINDOW_SIZE = (640, 480)

# QUESTE TRE
sound: Optional['pygame_menu.sound.Sound'] = None
surface: Optional['pygame.Surface'] = None
main_menu: Optional['pygame_menu.Menu'] = None

# -----------------------------------------------------------------------------
# Load image
# -----------------------------------------------------------------------------
background_image = pygame_menu.baseimage.BaseImage(
    image_path=pygame_menu.baseimage.IMAGE_EXAMPLE_WALLPAPER
)


# -----------------------------------------------------------------------------
# Methods
# -----------------------------------------------------------------------------

#QUESTA
def main_background() -> None:
    """
    Background color of the main menu, on this function user can plot
    images, play sounds, etc.
    :return: None
    """
    background_image.draw(surface)


def main(test: bool = False) -> None:
    """
    Main program.
    :param test: Indicate function is being tested
    :return: None
    """

    # -------------------------------------------------------------------------
    # Globals
    # -------------------------------------------------------------------------
    global main_menu
    global sound
    global surface

    # -------------------------------------------------------------------------
    # Create window
    # -------------------------------------------------------------------------
    surface = create_example_window('Example - Image Background', WINDOW_SIZE)
    clock = pygame.time.Clock()

    # -------------------------------------------------------------------------
    # Create menus: Main menu
    # -------------------------------------------------------------------------
    main_menu_theme = pygame_menu.themes.THEME_ORANGE.copy()
    main_menu_theme.set_background_color_opacity(0.5)  # 50% opacity

    main_menu = pygame_menu.Menu(
        height=WINDOW_SIZE[1] * 0.7,
        onclose=pygame_menu.events.EXIT,  # User press ESC button
        theme=main_menu_theme,
        title='Epic Menu',
        width=WINDOW_SIZE[0] * 0.8
    )

    widget_colors_theme = pygame_menu.themes.THEME_ORANGE.copy()
    widget_colors_theme.widget_font_size = 20
    widget_colors_theme.set_background_color_opacity(0.5)  # 50% opacity

    widget_colors = pygame_menu.Menu(
        height=WINDOW_SIZE[1] * 0.7,
        theme=widget_colors_theme,
        title='Widget backgrounds',
        width=WINDOW_SIZE[0] * 0.8
    )

    button_image = pygame_menu.baseimage.BaseImage(pygame_menu.baseimage.IMAGE_EXAMPLE_CARBON_FIBER)

    widget_colors.add_button('Opaque color button', None,
                             background_color=(100, 100, 100))
    widget_colors.add_button('Transparent color button', None,
                             background_color=(50, 50, 50, 200), font_size=40)
    widget_colors.add_button('Transparent background inflate to selection effect', None,
                             background_color=(50, 50, 50, 200), margin=(0, 15)
                             ).background_inflate_to_selection_effect()
    widget_colors.add_button('Background inflate + font background color', None,
                             background_color=(50, 50, 50, 200), font_background_color=(200, 200, 200)
                             ).background_inflate_to_selection_effect()
    widget_colors.add_button('This inflates background to match selection effect', None,
                             background_color=button_image, font_color=(255, 255, 255), font_size=15
                             ).selection_expand_background = True
    widget_colors.add_button('This is already inflated to match selection effect', None,
                             background_color=button_image, font_color=(255, 255, 255), font_size=15
                             ).background_inflate_to_selection_effect()

    main_menu.add_button('Test different widget colors', widget_colors)
    main_menu.add_button('Another fancy button', lambda: print('This button has been pressed'))
    main_menu.add_button('Quit', pygame_menu.events.EXIT)

    # -------------------------------------------------------------------------
    # Main loop
    # -------------------------------------------------------------------------
    while True:

        # Tick
        clock.tick(FPS)

        # Main menu
        main_menu.mainloop(surface, main_background, disable_loop=test, fps_limit=FPS)

        # Flip surface
        pygame.display.flip()

        # At first loop returns
        if test:
            break


if __name__ == '__main__':
    main()
 
Le righe 27,32-33, 45-46-47 sono righe di commento.
Boh, in realtà il codice me le mette dove devono essere. Comunque ho modificato il messaggio e ci ho scritto "QUESTE" nelle righe interessate. Metodo un po' rudimentale ma no avevo altre idee
 
Premetto che di Python ne mastico poco ma cerco di dare una mano, se c'e' qualche imprecisione rispondete.

Python:
__all__ = ['main']    #QUESTA
Esporta come pubblica solo la funzione main

Python:
sys.path.insert(0, '../../')  #QUESTE DUE
sys.path.insert(0, '../../../')
Inserisce in PATH quei due percorsi, facendo un esempio lo script viene eseguito in /gioco/v1/lib/bin/ mettera' in PATH /gioco/v1 e /gioco, magari ci sono file a cui deve accedere con facilita'.

Python:
# QUESTE TRE
sound: Optional['pygame_menu.sound.Sound'] = None
surface: Optional['pygame.Surface'] = None
main_menu: Optional['pygame_menu.Menu'] = None
Dichiara quelle tre variabili come Optional, il che significa che possono essere o del tipo specificato in quadre oppure None, e le inizializza a None.

Python:
#QUESTA
def main_background() -> None:
    """
    Background color of the main menu, on this function user can plot
images, play sounds, etc.
:return: None
    """
    background_image.draw(surface)

Difficile a dirlo senza conoscere il codice di pygame e pygame_menu che vengono importati, se devo dare retta all'apparenza e' una funzione che non ritorna niente e che disegna sullo sfondo l'immagine contenuta in surface (la quale e' di tipo pygame.Surface).
 
Premetto che di Python ne mastico poco ma cerco di dare una mano, se c'e' qualche imprecisione rispondete.

Python:
__all__ = ['main']    #QUESTA
Esporta come pubblica solo la funzione main

Python:
sys.path.insert(0, '../../')  #QUESTE DUE
sys.path.insert(0, '../../../')
Inserisce in PATH quei due percorsi, facendo un esempio lo script viene eseguito in /gioco/v1/lib/bin/ mettera' in PATH /gioco/v1 e /gioco, magari ci sono file a cui deve accedere con facilita'.

Python:
# QUESTE TRE
sound: Optional['pygame_menu.sound.Sound'] = None
surface: Optional['pygame.Surface'] = None
main_menu: Optional['pygame_menu.Menu'] = None
Dichiara quelle tre variabili come Optional, il che significa che possono essere o del tipo specificato in quadre oppure None, e le inizializza a None.

Python:
#QUESTA
def main_background() -> None:
    """
    Background color of the main menu, on this function user can plot
images, play sounds, etc.
:return: None
    """
    background_image.draw(surface)

Difficile a dirlo senza conoscere il codice di pygame e pygame_menu che vengono importati, se devo dare retta all'apparenza e' una funzione che non ritorna niente e che disegna sullo sfondo l'immagine contenuta in surface (la quale e' di tipo pygame.Surface).
Grazie mille, sei sempre il migliore :) ma cosa significa che esporta come pubblica solo la funzione main?
 
  • Mi piace
Reazioni: Q1P0
Grazie mille, sei sempre il migliore :) ma cosa significa che esporta come pubblica solo la funzione main?

Significa che, ipotizzando che il tuo script si chiami gioco.py, se lo importi da un altro script con from gioco import * potrai chiamare solo la funzione main, se per esempio provassi a chiamare main_background ti darebbe errore perche' non e' esportata pubblicamente.
 
  • Mi piace
Reazioni: N3v5
Significa che, ipotizzando che il tuo script si chiami gioco.py, se lo importi da un altro script con from gioco import * potrai chiamare solo la funzione main, se per esempio provassi a chiamare main_background ti darebbe errore perche' non e' esportata pubblicamente.
E qual è il vantaggio di questa cosa?
 
E' un po' come quando nella OOP dichiari membri come privati, potresti anche metterli pubblici funzionerebbe uguale, il vantaggio e' che se e' una funzionalita' ad uso interno hai la garanzia che qualcuno non la chiami da fuori causando problemi imprevedibili.

Immagina di avere una funzione interna che salva su file lo stato del gioco, ma che questa sia progettata per essere eseguita in un certo modo da un altro thread e si aspetta dei valori gia' inizializzati in delle variabili, arriva un altro programmatore e vedendo la funzione chiamabile dall'esterno decide di farlo, causando ogni sorta di problema dalle race condition all'utilizzare variabili non inizializzate ecc. Per togliere il rischio non viene esportata, costringendo l'altro programmatore a studiare il modo corretto per farlo.
 
E' un po' come quando nella OOP dichiari membri come privati, potresti anche metterli pubblici funzionerebbe uguale, il vantaggio e' che se e' una funzionalita' ad uso interno hai la garanzia che qualcuno non la chiami da fuori causando problemi imprevedibili.

Immagina di avere una funzione interna che salva su file lo stato del gioco, ma che questa sia progettata per essere eseguita in un certo modo da un altro thread e si aspetta dei valori gia' inizializzati in delle variabili, arriva un altro programmatore e vedendo la funzione chiamabile dall'esterno decide di farlo, causando ogni sorta di problema dalle race condition all'utilizzare variabili non inizializzate ecc. Per togliere il rischio non viene esportata, costringendo l'altro programmatore a studiare il modo corretto per farlo.
Perfetto, chiarissimo come sempre
 
Stato
Discussione chiusa ad ulteriori risposte.