Beispiel #1
0
    def initComponents(self):
        textFont = Fonts.getFont(Fonts.Courier, 30)
        window = self.window
        height, width = self.app.height, self.app.width
        title = Label(window, width/2, 0.5*height/3,
                            font=textFont, text="Load World")

        self.worldButtons = []
        y = [1.8, 2.5, 3.2]
        for i in range(3):
            button = Button(window, width/2, y[i]*height/4,
                            font=textFont, text="New World",
                            padding=10, fillColor=Colors.WHITE)
            button.setOnClickListener(self.loadWorld, i)
            self.worldButtons.append(button)

        self.deleteButtons = []
        for i in range(3):
            button = self.worldButtons[i]
            imgButton = ImageButton(window, width/2 + button.width, y[i]*height/4,
                                 Assets.assets["delete"], padding=10, borderWidth=0)
            imgButton.setOnClickListener(self.deleteWorld, i)
            self.deleteButtons.append(imgButton)

        self.addComponents(self.worldButtons)
        self.addComponents(self.deleteButtons)
        self.addComponent(title)
Beispiel #2
0
 def __init__(self):
     # -- Inicio modulos
     pygame.init()
     # -- Obtencion de info del hardware
     self._info = pygame.display.Info()
     # -- Se crea un display utilizando la info
     self._display = pygame.display.set_mode([self._info.current_w, self._info.current_h], pygame.FULLSCREEN | pygame.HWSURFACE)
     # -- Se definen los controles
     self._fuente_top_label = pygame.font.Font(None, 48)
     self._fuente_board = pygame.font.Font(None, 30)
     self._top_label = Label(self._fuente_top_label, "Butia Control Dashboard v1.0", (255, 255, 255), (0, 0, 0))
     self._boton = Button(Label(self._fuente_top_label, "Salir", (255, 255, 255), (0, 0, 0)), Label(self._fuente_top_label, "Salir", (0, 0, 0), (255, 255, 255)))
     self._boton_pausar = Button(Label(self._fuente_top_label, "Pausar", (255, 255, 255), (0, 0, 0)), Label(self._fuente_top_label, "Pausar", (0, 0, 0), (255, 255, 255)))
     self._boton.set_rect(self._info.current_w/2 - self._boton.get_rect().width / 2, self._info.current_h - (self._boton.get_rect().height + 10))
     self._boton_pausar.set_rect(self._info.current_w/2 - self._boton_pausar.get_rect().width / 2, self._info.current_h / 4 * 3 - (self._boton_pausar.get_rect().height / 2))
     self._label_estado = Label(self._fuente_board, "Estado:", (255, 255, 255), (0, 0, 0))
     self._label_estado_informacion = Label(self._fuente_board, "", (255, 255, 255), (0, 0, 0))
     self._label_tarea = Label(self._fuente_board, "Tarea:", (255, 255, 255), (0, 0, 0))
     self._label_tarea_informacion = Label(self._fuente_board, "", (255, 255, 255), (0, 0, 0))
     self._label_error_butia = Label(self._fuente_board, "Revise la conexion con el butia (!)", (255, 255, 255), (0, 0, 0))
     self._label_error_nxt = Label(self._fuente_board, "Revise la conexion con el nxt (!)", (255, 255, 255), (0, 0, 0))
     self._cursor = Cursor()
     # -- Se definen las variables
     self._butia_error = True
     self._nxt_error = True
     self._salir = False
     self._reloj = pygame.time.Clock()
     self._chronometer = Chronometer(1)
     self._timer = None
     self._ready = True
     self._times = 0
     self._pause = False
     # -- Se crean las instancias de butia y nxt
     self._butia = Butia()
     self._nxt = Nxt()
Beispiel #3
0
def window() -> Window:
    pygame.font.init()
    font = pygame.font.SysFont(None, 24)

    r = int(BOARD_WIDTH / 6)
    control = Control(BOARD_WIDTH, BOARD_HEIGHT, 6, r)

    start = Button("start-button",
                   FillMode.Fill(),
                   "green", "green",
                   padding=Padding.uniform(15),
                   child=Text('start-button-text', 'START', font,
                              FillMode.Fill(), 'black'),
                   on_click_action=lambda _: control.start())
    pause = Button("pause-button",
                   FillMode.Fill(),
                   "yellow", "yellow",
                   padding=Padding.uniform(15),
                   child=Text('pause-button-text', 'PAUSE', font,
                              FillMode.Fill(), 'black'),
                   on_click_action=lambda _: control.pause())
    clear = Button("clear-button",
                   FillMode.Fill(),
                   "red", "red",
                   padding=Padding.uniform(15),
                   child=Text('clear-button-text', 'CLEAR', font,
                              FillMode.Fill(), 'black'),
                   on_click_action=lambda _: control.clear())

    buttons = List("buttons", ListOrientation.HORIZONTAL,
                   FillMode.Fill(),
                   overflow=OverflowMode.Ignore(),
                   margins=Margins.uniform(0.01),
                   children=[(start, int(BOARD_WIDTH / 3)),
                             (pause, int(BOARD_WIDTH / 3)),
                             (clear, int(BOARD_WIDTH / 3))])

    floorboard = Floorboards('floorboards', control.state.cross_lines(),
                             control.state.cross, control.state.no_cross)

    left_panel = List("left", ListOrientation.VERTICAL,
                      FillMode.Fill(),
                      children=[(floorboard, BOARD_HEIGHT),
                                (buttons, HEIGHT - BOARD_HEIGHT)])

    info_panel = InfoPanel("info", control.state, font)

    wrapper = List("wrapper", ListOrientation.HORIZONTAL,
                   FillMode.Fill(),
                   overflow=OverflowMode.Restrict(),
                   children=[(left_panel, BOARD_WIDTH),
                             (info_panel, WIDTH - BOARD_WIDTH)])

    w = Window('Needle Simulation', Dimensions(WIDTH, HEIGHT),
               tick_speed=100000,
               child=wrapper,
               before_draw=lambda w: control.before_draw(w))
    return w
Beispiel #4
0
    def __init__(self, root: Panel):
        """Create a new MainMenuScene, creating the gui components to
        display.
        """
        size = root.get_rect().size
        title_rect = Rect(0, 0, 500, 70)
        title_rect.center = (size[0] / 2, size[1] / 2 - 200)

        # A panel for all the options
        options_panel = VerticalPanel(rect=Rect(size[0] / 4, size[1] / 2,
                                                size[0] / 2, size[1] / 4),
                                      expand_height=False,
                                      parent=root)

        # Title label
        Label(text="BATTLE SHIP!",
              rect=title_rect,
              style=Style(background_color=None,
                          border_width=0,
                          font=pygame.font.Font('freesansbold.ttf', 64),
                          primary_color=(255, 255, 255)),
              parent=root)

        # A style for all of the menu options
        button_style = Style(primary_color=(255, 255, 255),
                             background_color=(128, 0, 0),
                             border_width=1,
                             border_color=(0, 0, 0),
                             font=pygame.font.Font('freesansbold.ttf', 32))

        # Player vs Computer button
        Button(rect=Rect(0, 0, 400, 40),
               on_click=self._pvc_clicked,
               text="Player vs Computer",
               style=button_style,
               parent=options_panel)

        # Player vs Player button
        Button(rect=Rect(0, 0, 400, 40),
               on_click=self._pvp_clicked,
               text="Player vs Player",
               style=button_style,
               parent=options_panel)

        # Settings button
        Button(rect=Rect(0, 0, 400, 40),
               on_click=self._settings_clicked,
               text="Settings",
               style=button_style,
               parent=options_panel)

        # Quit button
        Button(rect=Rect(0, 0, 400, 40),
               on_click=self._quit_clicked,
               text="Quit",
               style=button_style,
               parent=options_panel)
    def __init__(self, navigator, client):
        self.table = Table((350, 100), navigator, client)
        self.chat = Chat((900, 120), navigator, client)
        self.navigator = navigator
        self.client = client

        self.button = Button((75, 50), 50, 'Sair', self.on_back)
        self.button_restart = Button((75, 150), 50, 'Reiniciar',
                                     self.on_restart_game)
    def set_parent(self, parent: Optional[Component]) -> None:
        """Set the component's parent. The default style is used if <parent>
        is None.
        """
        Panel.set_parent(self, parent)

        if (self._parent is None):
            return

        self.set_rect(self._parent.get_rect())
        size = self.get_rect().size

        title_rect = Rect(0, 0, 500, 70)
        title_rect.center = (size[0] / 2, size[1] / 2 - 200)

        self.clear_children()

        self.options_panel = VerticalPanel(rect=Rect(size[0] / 4, size[1] / 2,
                                                     size[0] / 2, size[1] / 4),
                                           expand_height=False,
                                           parent=self)

        self.title_label = Label(text="BATTLE SHIP!",
                                 rect=title_rect,
                                 style=Style(background_color=None,
                                             border_width=0,
                                             font=pygame.font.Font(
                                                 'freesansbold.ttf', 64),
                                             primary_color=(255, 255, 255)),
                                 parent=self)

        button_style = Style(primary_color=(255, 255, 255),
                             background_color=(128, 0, 0),
                             border_width=1,
                             border_color=(0, 0, 0),
                             font=pygame.font.Font('freesansbold.ttf', 32))

        self.cont_button = Button(rect=Rect(0, 0, 400, 40),
                                  on_click=self._cont_clicked,
                                  text="Continue",
                                  style=button_style,
                                  parent=self.options_panel)

        self.main_menu_button = Button(rect=Rect(0, 0, 400, 40),
                                       on_click=self._main_menu_clicked,
                                       text="Main menu",
                                       style=button_style,
                                       parent=self.options_panel)

        self.quit_button = Button(rect=Rect(0, 0, 400, 40),
                                  on_click=self._quit_clicked,
                                  text="Quit",
                                  style=button_style,
                                  parent=self.options_panel)
Beispiel #7
0
    def initComponents(self):
        textFont = Fonts.getFont(Fonts.Courier, 30)
        window = self.window
        height, width = self.app.height, self.app.width
        title = Label(window,
                      width / 2,
                      1 * height / 3,
                      font=textFont,
                      text="Craft112")

        startGame = Button(window,
                           width / 2,
                           1.5 * height / 3,
                           font=textFont,
                           text="Start Game",
                           padding=10)
        startGame.setOnClickListener(lambda: self.app.changeScene("load_game"))

        quitGame = Button(window,
                          width / 2,
                          2 * height / 3,
                          font=textFont,
                          text="Quit Game",
                          padding=10)
        quitGame.setOnClickListener(self.app.quit)

        self.addComponents([title, startGame, quitGame])
Beispiel #8
0
    def initOverlay(self):
        textFont = Fonts.getFont(Fonts.Courier, 30)
        window = self.window
        width, height = self.app.width, self.app.height

        unit = height / 4

        self.volumeButton = ImageButton(window,
                                        2 * width / 3,
                                        1.6 * unit,
                                        Assets.assets["volume_on"],
                                        fillColor=Colors.WHITE)
        self.volumeButton.setOnClickListener(self.toggleVolume)

        self.respawnButton = Button(window,
                                    width / 2,
                                    2 * unit,
                                    font=textFont,
                                    text="Respawn",
                                    fillColor=Colors.WHITE,
                                    padding=10)
        self.respawnButton.setOnClickListener(self.respawnPlayer)

        self.resumeButton = Button(window,
                                   width / 2,
                                   2 * unit,
                                   font=textFont,
                                   text="Resume Game",
                                   fillColor=Colors.WHITE,
                                   padding=10)
        self.resumeButton.setOnClickListener(self.togglePause)

        self.difficultyButton = Button(window,
                                       width / 2,
                                       2.5 * unit,
                                       font=textFont,
                                       text="Difficulty: Normal",
                                       fillColor=Colors.WHITE,
                                       padding=10)
        self.difficultyButton.setOnClickListener(self.cycleDifficulty)

        self.quitButton = Button(window,
                                 width / 2,
                                 3 * unit,
                                 font=textFont,
                                 text="Main Menu",
                                 fillColor=Colors.WHITE,
                                 padding=10)
        self.quitButton.setOnClickListener(self.quit)

        self.overlayComponents = [
            self.resumeButton, self.quitButton, self.respawnButton,
            self.volumeButton, self.difficultyButton
        ]

        for component in self.overlayComponents:
            component.setEnabled(False)

        self.addComponents(self.overlayComponents)
def run_game():
    # 初始化游戏并创建一个屏幕对象
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height)
    )
    pygame.display.set_caption("Alien Invasion")

    # 创建Play按钮
    play_button = Button(ai_settings, screen, "Play")

    # 创建统计信息实例
    stats = GameStats(ai_settings)
    sb = ScoreBoard(ai_settings, screen, stats)

    # 创建一艘飞船
    ship = Ship(ai_settings, screen)
    # 创建一个用于存储子弹的编组
    bullets = Group()
    # 创建一个外星人编组
    aliens = Group()

    # 创建外星人群
    gf.creat_fleet(ai_settings, screen, aliens, ship)

    # 开始游戏的主循环
    while True:
        gf.check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets)
        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_settings, screen, stats, sb, ship, bullets, aliens)
            gf.update_aliens(ai_settings, stats, screen, sb, ship, aliens, bullets)

        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets, play_button)
Beispiel #10
0
    def init_buttons(self):
        self.game = Button('menu', (
                (305 / 1024.0) * SCREEN_SIZE.W,
                (305 / 768.0) * SCREEN_SIZE.H),
            bg=pygame.image.load('menu/g.png'),
            fg=pygame.image.load('menu/gf.png'),
            on_left_click=lambda: load_game(1)
        )

        self.btn_1 = Button('menu', (
                (143 / 1024.0) * SCREEN_SIZE.W,
                (143 / 768.0) * SCREEN_SIZE.H),
            bg=pygame.image.load('menu/g1.png'),
            fg=pygame.image.load('menu/g1f.png'),
            text=Text('Game 1'),
            on_left_click=lambda: load_game(1)
        )

        self.btn_2 = Button('menu', (
                (143 / 1024.0) * SCREEN_SIZE.W,
                (143 / 768.0) * SCREEN_SIZE.H),
            bg=pygame.image.load('menu/g2.png'),
            fg=pygame.image.load('menu/g2f.png'),
            text=Text('Game 2'),
            on_left_click=lambda: load_game(2)
        )

        self.btn_3 = Button('menu', (
                (143 / 1024.0) * SCREEN_SIZE.W,
                (143 / 768.0) * SCREEN_SIZE.H),
            bg=pygame.image.load('menu/g3.png'),
            fg=pygame.image.load('menu/g3f.png'),
            text=Text('Game 3'),
            on_left_click=lambda: load_game(3)
        )

        self.btn_4 = Button('menu', (
                (143 / 1024.0) * SCREEN_SIZE.W,
                (143 / 768.0) * SCREEN_SIZE.H),
            bg=pygame.image.load('menu/g4.png'),
            fg=pygame.image.load('menu/g4f.png'),
            text=Text('Game 4')
        )

        self.btn_5 = Button('menu', (
                (143 / 1024.0) * SCREEN_SIZE.W,
                (143 / 768.0) * SCREEN_SIZE.H),
            bg=pygame.image.load('menu/g5.png'),
            fg=pygame.image.load('menu/g5f.png'),
            text=Text('Game 5')
        )

        self.profile = Button('menu', (
                (467 / 1024.0) * SCREEN_SIZE.W,
                (92 / 768.0) * SCREEN_SIZE.H),
            bg=pygame.image.load('menu/p.png'),
            fg=pygame.image.load('menu/pf.png'),
            text=Text('VIEW MY PROFILE')
        )
    def __init__(self, position, navigator, client):
        GameObject.__init__(self, position)
        self.position = position
        self.cells = []
        self.navigator = navigator
        self.client = client

        self.gif = Gif((self.position[0] - 140, self.position[1] - 20), 'tenor.gif')
        self.button = Button((self.position[0], self.position[1] + 350), 75, 'Continuar', self.on_confirm)
        self.text = Text((self.position[0], self.position[1] - 100), 100, 'Parabéns, você venceu!')
Beispiel #12
0
 def __init__(self,
              window,
              x,
              y,
              image,
              width=Constants.DEFAULT_WIDTH,
              height=Constants.DEFAULT_HEIGHT,
              fillColor=None,
              borderWidth=1,
              padding=0):
     Button.__init__(self,
                     window,
                     x,
                     y,
                     fillColor=fillColor,
                     borderWidth=borderWidth)
     self.type = "ImageButton"
     self.padding = padding
     self.image = image
     self.width, self.height = image.get_size()
Beispiel #13
0
 def __init__(self):
     pg.init()
     self.rows = 60
     self.columns = 40
     self.screen = pg.display.set_mode(
         (self.rows * 10, self.columns * 10 + 20))
     self.width, self.height = self.screen.get_size()
     self.screen_rect = self.screen.get_rect()
     self.done = False
     self.pause = True
     self.clock = pg.time.Clock()
     self.fps = 60
     self.color = pg.Color('white')
     self.title = pg.display.set_caption(
         'Conway\'s Game of Life (by void*)')
     self.start_button = Button((self.width - self.width, self.height - 20,
                                 self.width / 3 - 10, 20), 'gray', 'Start',
                                'black')
     self.pause_button = Button((self.width / 2 - self.width / 3 / 2 + 5,
                                 self.height - 20, self.width / 3 - 10, 20),
                                'gray', 'Pause', 'black')
     self.reset_button = Button((self.width - self.width / 3 + 10,
                                 self.height - 20, self.width / 3 - 10, 20),
                                'gray', 'Reset', 'black')
     self.cells = []
     self.last_updated_cell = None
     self.setupCells()
Beispiel #14
0
    def create_buttons(self, root: Component) -> None:
        """Create all buttons in the settings menu"""

        button_style = Style(background_color=(0, 255, 255),
                             primary_color=(0, 0, 0),
                             border_color=(0, 0, 0),
                             border_width=1)

        size = sm.SceneManager.instance.get_screen_size()
        self.back_button = Button(on_click=self._open_main_menu,
                                  rect=Rect(20, 20, 100, 100),
                                  style=Style(
                                      background_color=(255, 0, 0),
                                      background_image=pygame.image.load(
                                          "images/left-arrow-icon.png")),
                                  parent=root)

        self.fullscreen_button = Button(on_click=self._toggle_fullscreen,
                                        text=self._get_window_mode_text(),
                                        rect=Rect(450, 320, 150, 50),
                                        style=button_style,
                                        parent=self.window_mode_panel)
Beispiel #15
0
    def startup(self, persistent):
        pygame.mouse.set_visible(True)
        self.button_list = pygame.sprite.Group()

        start_button = Button((WIDTH / 2 - 50),
                              HEIGHT / 1.75,
                              100,
                              40,
                              self.end,
                              text="PLAY",
                              font=pygame.font.Font('freesansbold.ttf',
                                                    20)).add(self.button_list)

        super().startup(persistent)
Beispiel #16
0
class PauseScreen:
    def __init__(self):
        self.hidden = True
        self.width = 0
        self.max_witdh = 200

        self.init_buttons()

    def init_buttons(self):
        self.btn_back = Button('pause-screen', (self.max_witdh, 50),
                               bg=(80, 80, 80),
                               fg=(50, 50, 50),
                               text=Text('Back', color=COLOR_WHITE),
                               on_left_click=self.load_prev)

        self.btn_menu = Button('pause-screen', (self.max_witdh, 50),
                               bg=(80, 80, 80),
                               fg=(50, 50, 50),
                               text=Text('Main Menu', color=COLOR_WHITE),
                               on_left_click=self.load_menu)

        self.btn_quit = Button('pause-screen', (self.max_witdh, 50),
                               bg=(80, 80, 80),
                               fg=(50, 50, 50),
                               text=Text('Quit', color=COLOR_WHITE),
                               on_left_click=quit_game)

    def hide(self):
        self.width = 0
        self.hidden = True

    def load_menu(self):
        self.hide()
        ACTIVE.append('menu')

    def load_prev(self):
        self.hide()
        ACTIVE.pop()

    def render(self):
        if self.hidden:
            tint = pygame.Surface((SCREEN_SIZE.W, SCREEN_SIZE.H),
                                  pygame.SRCALPHA)
            tint.fill((0, 0, 0, 150))
            SCREEN.blit(tint, (0, 0))
            self.hidden = False

        SCREEN.fill((100, 100, 100),
                    (SCREEN_SIZE.W - self.width, 0, self.width, SCREEN_SIZE.H))

        self.btn_back.render((SCREEN_SIZE.W - self.width, 0))
        self.btn_menu.render((SCREEN_SIZE.W - self.width, 50))
        self.btn_quit.render((SCREEN_SIZE.W - self.width, 100))

        if self.width < self.max_witdh:
            self.width += 50
    def __init__(self, position, navigator, client):
        GameObject.__init__(self, position)
        self.position = position
        self.cells = []
        self.navigator = navigator
        self.client = client

        self.gif = Gif((self.position[0] - 280, self.position[1] - 200),
                       'address.gif')
        self.button = Button((self.position[0], self.position[1] + 320), 75,
                             'Connectar', self.on_connect)
        self.text = Text((self.position[0] - 200, self.position[1] + 212), 100,
                         'Endereço:')
        self.text_input = TextInput(
            (self.position[0] - 50, self.position[1] + 200), 100)
Beispiel #18
0
    def init_buttons(self):
        self.btn_back = Button(
            'pause-screen',
            (self.max_witdh, 50),
            bg=(80, 80, 80),
            fg=(50, 50, 50),
            text=Text('Back', color=COLOR_WHITE),
            on_left_click=self.load_prev)

        self.btn_menu = Button(
            'pause-screen',
            (self.max_witdh, 50),
            bg=(80, 80, 80),
            fg=(50, 50, 50),
            text=Text('Main Menu', color=COLOR_WHITE),
            on_left_click=self.load_menu)

        self.btn_quit = Button(
            'pause-screen',
            (self.max_witdh, 50),
            bg=(80, 80, 80),
            fg=(50, 50, 50),
            text=Text('Quit', color=COLOR_WHITE),
            on_left_click=quit_game)
    def __init__(self, position, ip, navigator, client):
        GameObject.__init__(self, position)
        self.position = position
        self.ip = ip
        self.cells = []
        self.navigator = navigator
        self.client = client

        self.gif = Gif((self.position[0] - 170, self.position[1] - 200),
                       'port.gif')
        self.button = Button((self.position[0], self.position[1] + 320), 75,
                             'Connectar', self.on_connect)
        self.text = Text((self.position[0] - 200, self.position[1] + 212), 100,
                         'Porta:')
        self.text_input = TextInput(
            (self.position[0] - 50, self.position[1] + 200), 100)
Beispiel #20
0
    def __init__(self, top):
        super().__init__()
        self.top = top
        self.setup_ui()
        self.scan_thread = None

        layout = Qt.QGridLayout()

        self.prop_layout = Qt.QVBoxLayout()
        # props
        self.scan()

        # button
        button_layout = Qt.QHBoxLayout()
        self.button_rescan = Button(self, '刷新', lambda e: self.scan())
        button_layout.addWidget(self.button_rescan)

        layout.addLayout(self.prop_layout, 0, 0)
        layout.addLayout(button_layout, 1, 0)
        self.setLayout(layout)
        self.show_at_center()
Beispiel #21
0
    def __init__(self, window, element=[], style={}, parent=None):

        self.window = window
        self.parent = parent

        #super().__init__(style)

        menu = View(self.window, style=style, parent=parent)
        layer = View(self.window,
                     style={
                         "width": "5%",
                         "background": (112, 109, 90),
                     },
                     parent=menu)
        overflow = View(self.window,
                        style={
                            "width": "20%",
                            "left": "60%",
                            "background": (141, 138, 119),
                        },
                        parent=layer)

        nbr = len(element)
        self.buttons = []
        size = int(parent.position[3] * 100 / nbr / parent.position[3] -
                   (nbr - 1))
        for i in range(nbr):
            self.buttons.append(
                Button(window,
                       element[i][0],
                       style={
                           "width": "90%",
                           "left": "10%",
                           "height": str(size) + "%",
                           "top": str(size * i + i * nbr) + "%",
                           "background": (137, 134, 115),
                           "after-color": (37, 37, 25)
                       },
                       parent=menu,
                       callback=element[i][1]))
Beispiel #22
0
    def init_buttons(self):
        self.btn_back = Button('pause-screen', (self.max_witdh, 50),
                               bg=(80, 80, 80),
                               fg=(50, 50, 50),
                               text=Text('Back', color=COLOR_WHITE),
                               on_left_click=self.load_prev)

        self.btn_menu = Button('pause-screen', (self.max_witdh, 50),
                               bg=(80, 80, 80),
                               fg=(50, 50, 50),
                               text=Text('Main Menu', color=COLOR_WHITE),
                               on_left_click=self.load_menu)

        self.btn_quit = Button('pause-screen', (self.max_witdh, 50),
                               bg=(80, 80, 80),
                               fg=(50, 50, 50),
                               text=Text('Quit', color=COLOR_WHITE),
                               on_left_click=quit_game)
from gc import mem_free

print("--- RAM free ---> " + str(mem_free()))

pinout = set_pinout()
built_in_led = Led(pinout.BUILT_IN_LED)

num_neo = 16  # 30 # number of Leds
np = Rgb(pinout.WS_LED_PIN, num_neo)

ws_r = 0
ws_g = 0
ws_b = 0

boot_pin = Pin(0, Pin.IN)
boot_button = Button(boot_pin, release_value=1)

servo = Servo(pinout.PWM1_PIN)
d7 = disp7_init()


def parse_rgba_msg(msg):
    """
    parse rgba message to dict from following formats:
    #ff00C3
    #ff00C3FF
    RGBA(255,0,200,255) or rgba(255,0,200,255)
    RGB(255,0,200,255) or rgb(255,0,200)
    [255,0,200,255]
    [255,0,200]
    """
Beispiel #24
0
def settings(mode='STANDARD'):
    pygame.init()

    json_file = open(os.getcwd() + r"\components\constants.json", "r")
    json_content = json.load(json_file)
    round_int = json_content["round_int"]
    json_file.close()

    BLACK = (0, 0, 0)
    WHITE = (255, 255, 255)
    GREY = (100, 100, 100)
    BROWN = (138, 79, 28)
    font = pygame.font.SysFont("DejaVu Sans", 30)
    # RED = (255, 0, 0), GREEN = (0, 255, 0), BLUE = (0, 0, 255)

    screen = pygame.display.set_mode((720, 480))
    screen.fill(BROWN)

    clock = pygame.time.Clock()

    pygame.display.update()

    title_label = font.render(mode, True, BLACK)

    Player1_label = font.render("Player 1:", True, BLACK)
    Player2_label = font.render("AI Difficuly:", True, BLACK)

    Player1 = InputBox(345, 200, 120, 32, WHITE, GREY)
    bot_diff = Slider(screen,
                      350,
                      260,
                      120,
                      15,
                      min=1,
                      max=20,
                      step=1,
                      initial=6)

    Accept_Button = Button(x=300,
                           y=300,
                           w=100,
                           h=50,
                           color_b=BLACK,
                           color_in=WHITE,
                           color_t=WHITE,
                           command=lambda: [
                               main(player1=Player1.export(),
                                    player2='Computer',
                                    mode=mode,
                                    bot_bool=True,
                                    bot_difficulty=bot_diff.getValue())
                           ],
                           text='Start Game')

    while True:
        clock.tick(60)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                quit()

            Player1.checkActivation(event)
            bot_diff.listen(event)

            Accept_Button.processEvent(event)

            screen.fill(BROWN)
            screen.blit(Player1_label, (150, 200))
            screen.blit(Player2_label, (150, 250))
            screen.blit(title_label, (pygame.display.get_window_size()[0] / 2 -
                                      title_label.get_rect().w / 2, 30))
            Player1.draw(screen)
            bot_diff.draw()

            Accept_Button.draw(screen)

            pygame.display.flip()
Beispiel #25
0
def main(player1="Player 1",
         player2="Player 2",
         mode="STANDARD",
         bot_bool=False,
         bot_difficulty=6):

    # resetting the variables in the .json file#
    json_file = open(r'components\constants.json', 'r')
    json_content = json.load(json_file)
    json_content["round_int"] = 0
    json_file.close()
    json_file = open(r'components\constants.json', 'w')
    json_file.writelines(json.dumps(json_content))
    json_file.close()

    Pieces.white_is_checked = False
    Pieces.black_is_checked = False
    Pieces.checking_piece = None

    #initiating pygame#
    pygame.init()

    player1 = "Spieler 1" if player1 == "" else player1
    player2 = "Spieler 2" if player2 == "" else player2

    #Constants#
    BLACK = (0, 0, 0)
    GREY = (50, 50, 50)
    WHITE = (255, 255, 255)
    BG_COLOR_1 = (0, 152, 163)
    BG_COLOR_2 = (2, 112, 120)

    #reading the constants from the json file#
    json_file = open(os.getcwd() + r"\components\constants.json", "r")
    json_content = json.load(json_file)
    round_int = json_content["round_int"]
    tile_size = json_content["tile_size"]
    anchor_point_s = (json_content["anchor_point_s_x"] * tile_size,
                      json_content["anchor_point_s_y"] * tile_size)
    anchor_point_h = (json_content["anchor_point_h_x"] * tile_size,
                      json_content["anchor_point_h_y"] * tile_size)
    anchor_point_hud = (json_content["anchor_point_hud_x"] * tile_size,
                        json_content["anchor_point_hud_y"] * tile_size)
    json_file.close()

    #setting up the variables for a new and fresh game#
    screen_size = (11 * tile_size, 11 * tile_size)
    font = pygame.font.SysFont("DejaVu Sans", int(tile_size * 0.2))
    font_titles = pygame.font.SysFont("DejaVu Sans", int(tile_size * 0.25))
    go = True
    timer = Clock(time=5)

    #creating the surfaces#
    screen = pygame.display.set_mode(screen_size, 0, 0)
    s = pygame.Surface((8 * tile_size, 8 * tile_size))
    hud = pygame.Surface((10.25 * tile_size, 2 * tile_size))
    p1 = pygame.Surface((3 * tile_size, 1.5 * tile_size))
    p2 = pygame.Surface((3 * tile_size, 1.5 * tile_size))
    h = Hud((2 * tile_size, 8 * tile_size))
    screen.fill(BG_COLOR_1)
    hud.fill(BG_COLOR_2)
    h.fill(BG_COLOR_2)
    h.print(pos=(0.6 * tile_size, 20), label='Spielhistorie', font=font)

    #window caption#
    pygame.display.set_caption("Chess")

    #creating a clock for the ingame ticks#
    clock = pygame.time.Clock()

    #creating the board on the subsurface#
    board = Board(master=s,
                  width=8,
                  height=8,
                  tile_size=tile_size,
                  color_a=(245, 216, 188),
                  color_b=(176, 142, 109),
                  color_t1=(240, 230, 221),
                  color_t2=(201, 181, 163),
                  anchor_point=anchor_point_s)

    #loading the images for the pieces#
    images = {
        "white_pawn_img": pygame.image.load(r'assets/white_pawn.png'),
        "white_rook_img": pygame.image.load(r'assets/white_rook.png'),
        "white_knight_img": pygame.image.load(r'assets/white_knight.png'),
        "white_bishop_img": pygame.image.load(r'assets/white_bishop.png'),
        "white_queen_img": pygame.image.load(r'assets/white_queen.png'),
        "white_king_img": pygame.image.load(r'assets/white_king.png'),
        "black_pawn_img": pygame.image.load(r'assets/black_pawn.png'),
        "black_rook_img": pygame.image.load(r'assets/black_rook.png'),
        "black_knight_img": pygame.image.load(r'assets/black_knight.png'),
        "black_bishop_img": pygame.image.load(r'assets/black_bishop.png'),
        "black_queen_img": pygame.image.load(r'assets/black_queen.png'),
        "black_king_img": pygame.image.load(r'assets/black_king.png')
    }
    #loading the icons for the buttons#
    quit_icon = pygame.image.load(r'assets/quit.png')
    takeback_icon = pygame.image.load(r'assets/takeback.png')
    resign_icon = pygame.image.load(r'assets/resign_flag.png')
    test_icon = pygame.image.load(r'assets/lightbulb.png')

    #creating the board
    build_board(mode, s, images)

    #creating the chessbot based on .json parameters
    bot = Stockfish(b'components\stockfish_20011801_x64.exe')
    bot.set_skill_level(bot_difficulty)

    quit_button = Button(x=8.5 * tile_size,
                         y=0.4 * tile_size,
                         w=int(0.6 * tile_size),
                         h=int(0.6 * tile_size),
                         color_b=BLACK,
                         color_in=GREY,
                         color_t=WHITE,
                         command=quit,
                         icon=quit_icon,
                         imaginary_x=anchor_point_hud[0],
                         imaginary_y=anchor_point_hud[1])

    resign_button = Button(x=9.2 * tile_size,
                           y=0.4 * tile_size,
                           w=int(0.6 * tile_size),
                           h=int(0.6 * tile_size),
                           color_b=BLACK,
                           color_in=GREY,
                           color_t=WHITE,
                           command=lambda: [decideWhoLost(round_int)],
                           icon=resign_icon,
                           imaginary_x=anchor_point_hud[0],
                           imaginary_y=anchor_point_hud[1])

    test_zone_button = Testmode_Button(
        x=9.2 * tile_size,
        y=0.4 * tile_size + 0.74 * tile_size,
        w=int(0.6 * tile_size),
        h=int(0.6 * tile_size),
        color_b=BLACK,
        color_in=GREY,
        color_t=WHITE,
        command1=lambda: [
            Board.change_testmode(),
            #Pieces.change_ignore_me_standard(),
            Pieces.crop_move_done(),
            Pieces.kill_board(),
            build_board(mode, s, images),
            Pieces.build_from_list(screen=s),
            Pieces.set_round(Pieces.round_safe)
        ],
        command2=lambda: [
            Board.change_testmode(),
            #Pieces.change_ignore_me_standard(),
            Pieces.safe_round()
        ],
        icon=test_icon,
        imaginary_x=anchor_point_hud[0],
        imaginary_y=anchor_point_hud[1],
        deaf=False)

    if bot_bool:
        command = lambda: [
            takeback(board, s, takeback_button),
            takeback(board, s, takeback_button)
        ]
    else:
        command = lambda: [takeback(board, s, takeback_button)]

    takeback_button = Button(x=8.5 * tile_size,
                             y=0.4 * tile_size + 0.74 * tile_size,
                             w=int(0.6 * tile_size),
                             h=int(0.6 * tile_size),
                             color_b=BLACK,
                             color_in=GREY,
                             color_t=WHITE,
                             command=command,
                             icon=takeback_icon,
                             imaginary_x=anchor_point_hud[0],
                             imaginary_y=anchor_point_hud[1])

    start_sound = mixer.Sound("assets/sounds/board-start.mp3")
    start_sound.play()

    #the mainloop#
    while go:
        #setting the framerate#
        clock.tick(60)

        #refreshing the round counter#
        json_file = open(os.getcwd() + r"\components\constants.json", "r")
        json_content = json.load(json_file)
        round_int = json_content["round_int"]
        json_file.close()

        #drawing the board#
        # if not Board.game_over:
        board.draw_board()

        #updating the bot with the new game state#
        bot.set_fen_position(Pieces.give_FEN())

        #detecting, if the game is over, or not
        if not Board.game_over:
            Pieces.detectingCheck()
            Board.game_over = Pieces.detectGameOver(round_int=round_int)

        #end the game if the game is over#
        if Board.game_over or Board.resign_w or Board.resign_b:
            if Pieces.white_is_checked or Board.resign_w:
                board.end_screen('BLACK', s)
            elif Pieces.black_is_checked or Board.resign_b:
                board.end_screen('WHITE', s)
            else:
                board.end_screen('STALEMATE', s)
            takeback_button.active = False
            resign_button.active = False
            test_zone_button.active = False

        #checking if a pawn is promotable#
        for pawn in Pieces.all_pieces_list:
            if 'Pawn-B' in pawn.name and pawn.y == 7 * tile_size or 'Pawn-W' in pawn.name and pawn.y == 0 * tile_size:
                pawn.promotion()

        Pieces.detectingCheck()
        #highlighting the checked king#
        if Pieces.white_is_checked:
            for king in Pieces.all_pieces_list:
                if isinstance(king, Kings) and king.farbe == WHITE:
                    board.check(king_pos=(king.x, king.y))

        #highlighting the checked king#
        elif Pieces.black_is_checked:
            for king in Pieces.all_pieces_list:
                if isinstance(king, Kings) and king.farbe == BLACK:
                    board.check(king_pos=(king.x, king.y))

        #drawing all the pieces#
        # if not Board.game_over:
        for pieces in Pieces.all_pieces_list:
            pieces.draw(screen)

        #updating the mainsurface#
        pygame.display.update()

        #clearing the Subsurfaces#
        p1.fill(BG_COLOR_1)
        p2.fill(BG_COLOR_1)
        hud.fill(BG_COLOR_2)

        #refresh the time of the timers#
        timer.refreshTime()

        #creating the labels to be printed on the subsurfaces#
        Player_1_label = font_titles.render(player1, 1, BLACK)
        Player_2_label = font_titles.render(player2, 1, BLACK)
        timer_label = font_titles.render(timer.getTime(), 1, BLACK)

        #printing the labes on the subsurfaces#
        p1.blit(Player_1_label,
                (p1.get_width() / 2 - Player_1_label.get_width() / 2, 0))
        p2.blit(Player_2_label,
                (p2.get_width() / 2 - Player_2_label.get_width() / 2, 0))

        #creating the history
        h.fill(BG_COLOR_2)
        h.print((0.31 * tile_size, 20), 'Spielhistorie', font)
        for i in range(len(Pieces.moves_done)):
            fac_50 = 5 / 7 * tile_size
            fac_20 = 2 / 7 * tile_size
            h.print(pos=((i % 2) * fac_50 + fac_20,
                         (i // 2) * fac_20 + 2 * fac_20),
                    label=Pieces.moves_done[i],
                    font=font)

        #showing the taken pieces#
        Pieces.taken_pieces.sort(key=lambda x: x.value, reverse=False)
        white_loss = [[], []]
        black_loss = [[], []]
        for piece in Pieces.taken_pieces:
            if piece.farbe == (0, 0, 0):
                if len(black_loss[0]) < 8:
                    black_loss[0].append(piece)
                else:
                    black_loss[1].append(piece)
            elif piece.farbe == WHITE:
                if len(white_loss[0]) < 8:
                    white_loss[0].append(piece)
                else:
                    white_loss[1].append(piece)

        for line in black_loss:
            for piece in line:
                p1.blit(
                    pygame.transform.scale(piece.image,
                                           (tile_size // 3, tile_size // 3)),
                    ((line.index(piece) * 11 / 32 + 6 / 40) * tile_size,
                     (black_loss.index(line) + 1) * 0.5 * tile_size))
        for line in white_loss:
            for piece in line:
                p2.blit(
                    pygame.transform.scale(piece.image,
                                           (tile_size // 3, tile_size // 3)),
                    ((line.index(piece) * 11 / 32 + 6 / 40) * tile_size,
                     (white_loss.index(line) + 1) * 0.5 * tile_size))

        value_white = 0
        value_black = 0

        for piece in Pieces.taken_pieces:
            if piece.farbe == (0, 0, 0):
                value_black += piece.value
            elif piece.farbe == WHITE:
                value_white += piece.value

        label = font.render('+' + str(abs(int(value_white - value_black))),
                            True, BLACK)
        if int(value_white - value_black) > 0:
            if len(white_loss[0]) < 8:
                p2.blit(label,
                        ((len(white_loss[0]) * 11 / 32 + 6 / 40) * tile_size,
                         0.55 * tile_size))
            else:
                p2.blit(label,
                        ((len(white_loss[1]) * 11 / 32 + 6 / 40) * tile_size,
                         1.05 * tile_size))
        elif int(value_white - value_black) < 0:
            if len(black_loss[0]) < 8:
                p1.blit(label,
                        ((len(black_loss[0]) * 11 / 32 + 6 / 40) * tile_size,
                         0.55 * tile_size))
            else:
                p1.blit(label,
                        ((len(black_loss[1]) * 11 / 32 + 6 / 40) * tile_size,
                         1.05 * tile_size))

        #updating the hud#
        if round_int % 2 == 0:
            pygame.draw.rect(hud, BLACK, [
                0.45 * tile_size, 0.2 * tile_size, 3.1 * tile_size,
                1.6 * tile_size
            ])
        elif round_int % 2 == 1:
            pygame.draw.rect(hud, BLACK, [
                4.45 * tile_size, 0.2 * tile_size, 3.1 * tile_size,
                1.6 * tile_size
            ])
        hud.blit(p1, (0.5 * tile_size, 0.25 * tile_size))
        hud.blit(p2, (4.5 * tile_size, 0.25 * tile_size))
        hud.blit(timer_label, (3.65 * tile_size, 0.75 * tile_size))

        #creating the buttons on the hud
        resign_button.draw(screen=hud)
        quit_button.draw(screen=hud)
        takeback_button.draw(screen=hud)
        test_zone_button.draw(screen=hud)

        items = [quit_button, resign_button, takeback_button, test_zone_button]

        #bliting the subsurfaces on the mainsurface
        screen.blit(s, anchor_point_s)
        screen.blit(h, anchor_point_h)
        screen.blit(hud, anchor_point_hud)

        #bot moves#
        if round_int % 2 == 1 and bot_bool and not Board.game_over and not Board.test_mode:
            opt_move = bot.get_best_move_time(random.randint(400, 1200))
            for piece in Pieces.all_pieces_list:
                if piece.farbe == BLACK:
                    move = piece.move_from_pos(
                        move=opt_move,
                        board=board,
                        screen=screen,
                        takeback_button=takeback_button,
                        ignore_me=Pieces.ignore_me_standard)
                    if move != None:
                        break

        #checking for events#
        else:
            for event in pygame.event.get():

                for item in items:
                    item.processEvent(event)

                #closing the screen by clicking the X#
                if event.type == pygame.QUIT:
                    go = False

                #Keyboard-Inputs#
                if event.type == pygame.KEYDOWN:

                    #kill window if ESC is pressed#
                    if event.key == pygame.K_ESCAPE:
                        Pieces.white_is_checked = False
                        Pieces.black_is_checked = False
                        Pieces.checking_piece = None

                        json_file = open(r'components\constants.json', 'r')
                        json_content = json.load(json_file)
                        json_content["round_int"] = 0
                        json_file.close()
                        json_file = open(r'components\constants.json', 'w')
                        json_file.writelines(json.dumps(json_content))
                        json_file.close()

                        quit()

                    #(TEMP) my information key (arrow down) to get certain information#
                    if event.key == pygame.K_DOWN:
                        print(Pieces.give_FEN())
                        #print([x.name for x in Pieces.all_pieces_list])
                        # for king in Pieces.all_pieces_list:
                        #     if "King-W" in king.name:
                        #         print(list(king.is_castle_legal()))

                #left mouse click#
                elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:

                    #getting the mouseposition and than correcting it by the relative position of the subsurface#
                    mouse_pos = pygame.mouse.get_pos()
                    mouse_pos = (mouse_pos[0] - anchor_point_s[0],
                                 mouse_pos[1] - anchor_point_s[1])

                    #checking if a Piece stands on the clicked tile#
                    if not Board.game_over:
                        for piece in Pieces.all_pieces_list:
                            if mouse_pos[0] >= piece.x and mouse_pos[
                                    1] >= piece.y:
                                if mouse_pos[
                                        0] < piece.x + tile_size and mouse_pos[
                                            1] < piece.y + tile_size:

                                    #if the clicked piece is one of the team that currently is to move...#

                                    with_bool = round_int % 2 == 0 and piece.farbe == (
                                        255, 255, 255)
                                    without_bool = round_int % 2 == 1 and piece.farbe == (
                                        0, 0, 0)

                                    if with_bool or without_bool:

                                        #...wait for the second mouse input#
                                        move_ = piece.move(
                                            board=board,
                                            screen=screen,
                                            takeback_button=takeback_button,
                                            ignore_me=Pieces.ignore_me_standard
                                        )

                                        move_ = move_[1][2:3] + move_[2] + str(
                                            move_[0][2:])

                                        #check if the white kiung is checked#
                                        Pieces.detectingCheck()

    #resetting class variables#
    Pieces.white_is_checked = False
    Pieces.black_is_checked = False
    Pieces.checking_piece = None

    #resetting the variables in the .json file#
    json_file = open(r'components\constants.json', 'r')
    json_content = json.load(json_file)
    json_content["round_int"] = 0
    json_file.close()
    json_file = open(r'components\constants.json', 'w')
    json_file.writelines(json.dumps(json_content))
    json_file.close()
Beispiel #26
0
# octopusLAB - simple example
## BLE controll for examples/ble/ble_led.py

from time import sleep
from machine import Pin
from components.button import Button
import blesync_client
import blesync_uart.client
import utils.ble.bluefruit as bf

built_in_led = Pin(2, Pin.OUT)
led_button = Button(0, release_value=1)

built_in_led.blink()
sleep(3)


@blesync_uart.client.UARTService.on_message
def on_message(service, message):
    print(message)


client = blesync_client.BLEClient(blesync_uart.client.UARTService)


def connect():
    while True:
        for device in blesync_client.scan():
            if device.adv_name == 'octopus-led-24de0':  # set yout UID
                services = client.connect(addr_type=device.addr_type,
                                          addr=device.addr)
Beispiel #27
0
class PauseScreen:
    def __init__(self):
        self.hidden = True
        self.width = 0
        self.max_witdh = 200

        self.init_buttons()

    def init_buttons(self):
        self.btn_back = Button(
            'pause-screen',
            (self.max_witdh, 50),
            bg=(80, 80, 80),
            fg=(50, 50, 50),
            text=Text('Back', color=COLOR_WHITE),
            on_left_click=self.load_prev)

        self.btn_menu = Button(
            'pause-screen',
            (self.max_witdh, 50),
            bg=(80, 80, 80),
            fg=(50, 50, 50),
            text=Text('Main Menu', color=COLOR_WHITE),
            on_left_click=self.load_menu)

        self.btn_quit = Button(
            'pause-screen',
            (self.max_witdh, 50),
            bg=(80, 80, 80),
            fg=(50, 50, 50),
            text=Text('Quit', color=COLOR_WHITE),
            on_left_click=quit_game)

    def hide(self):
        self.width = 0
        self.hidden = True

    def load_menu(self):
        self.hide()
        ACTIVE.append('menu')

    def load_prev(self):
        self.hide()
        ACTIVE.pop()

    def render(self):
        if self.hidden:
            tint = pygame.Surface(
                (SCREEN_SIZE.W, SCREEN_SIZE.H),
                pygame.SRCALPHA)
            tint.fill((0, 0, 0, 150))
            SCREEN.blit(tint, (0, 0))
            self.hidden = False

        SCREEN.fill(
            (100, 100, 100),
            (SCREEN_SIZE.W - self.width, 0, self.width, SCREEN_SIZE.H))

        self.btn_back.render((SCREEN_SIZE.W - self.width, 0))
        self.btn_menu.render((SCREEN_SIZE.W - self.width, 50))
        self.btn_quit.render((SCREEN_SIZE.W - self.width, 100))

        if self.width < self.max_witdh:
            self.width += 50
Beispiel #28
0
#  running TM from source programs_turing/program_xxx.txt

from time import sleep
from uturing import TuringMachine, run_src
from components.button import Button
from components.rgb import Rgb
import colors_rgb as rgb
import pubsub
# from utils.octopus import disp7_init

from machine import Pin
button0 = Button(Pin(0), release_value=1)

# d7 = disp7_init()  # 8 x 7segment display init
ws_num = 32
ws = Rgb(15, ws_num)
ws.simpleTest()

c1 = (32, 8, 0)
c0 = (0, 16, 0)

print()
print("Turing Machine Emulator (ESP32 - Micropython)")


def ws_clear_all(num=ws_num):
    for i in range(num):
        ws.color(rgb.BLACK, i)


def ws_show_tape(tape, ofset=5):
Beispiel #29
0
from utils.pinout import set_pinout
pinout = set_pinout()

from ST7735 import TFT, TFTColor
from assets.sysfont import sysfont
from machine import SPI, Pin
from time import sleep_ms, ticks_ms
from math import pi
from utils.octopus_lib import w

from components.button import Button
from utils.transform import Point2D

print("buttons init>")
pin_dwn = Pin(35, Pin.IN)
button_dwn = Button(pin_dwn, release_value=1)
pin_top = Pin(39, Pin.IN)
button_top = Button(pin_top, release_value=1)
pin_lef = Pin(36, Pin.IN)
button_lef = Button(pin_lef, release_value=1)
pin_rig = Pin(34, Pin.IN)
button_rig = Button(pin_rig, release_value=1)

SPI_SCLK = 18
SPI_MISO = 19
SPI_MOSI = 23

DC = 17  # PWM1
RST = 16  # PWM2
CS = 5  # SCE0
Beispiel #30
0
class Queries(Screen):
    def __init__(self, parent, app):
        super().__init__(parent, app)

    def _init_components(self):
        background_color = self.get_background()
        scrollbar_width = SCROLL_BAR_WIDTH
        height_buttons = BUTTON[1] + PADDING * 2
        width_buttons = BUTTON[1] + PADDING * 2

        self.button_back = ButtonBack(self,
                                      size=height_buttons,
                                      onClick=self.navigate_home)

        self.label_logo = Label(self)
        self.label_logo.config(
            text="weCoNet",
            font=LOGO,
            background=background_color,
            foreground=BLUE,
        )

        self.label_queries = Label(self)
        self.label_queries.config(text="QUERIES",
                                  font=BODY_BOLD,
                                  background=background_color,
                                  foreground=BLACK,
                                  anchor="nw")
        """
        ScrollView result     
        """
        self.canvas_queries = Canvas(
            self,
            highlightthickness=1,
        )
        self.frame_queries = Frame(
            self.canvas_queries,
            highlightthickness=1,
            #    borderwidth=1,
            #    relief="solid",
        )
        self.canvas_queries.config(
            background=WHITE,
            highlightthickness=0,
        )
        self.frame_queries.config(
            background=WHITE,
            highlightthickness=0,
        )

        self.scrollbar_queries = Scrollbar(self,
                                           orient="vertical",
                                           width=scrollbar_width,
                                           command=self.canvas_queries.yview)
        self.canvas_queries.config(yscrollcommand=self.scrollbar_queries.set, )

        self.canvas_queries.create_window(
            (0, 0),
            window=self.frame_queries,
            anchor="nw",
        )

        self.frame_queries.bind("<Configure>", self._onFrameConfigure)

        self.list_card_recommendation = None

        self.button_add = Button(self,
                                 self.app.width - PADDING * 2,
                                 height=height_buttons,
                                 text="See more ...",
                                 enable=True,
                                 onClick=self._on_click_see_more)

    def navigate_home(self):
        self.app.navigate(context="Home")

    def _on_click_see_more(self):
        controller.current += controller.delta
        self._update_list_card_queries()

    def _onFrameConfigure(self, event):
        '''Reset the scroll region to encompass the inner frame'''
        self.canvas_queries.config(
            scrollregion=self.canvas_queries.bbox("all"))

    def _callback_update_list_card_queries(self, **kw):
        authors = kw.get("authors", None)
        if (authors is not None):
            self.list_card_recommendation = [
                CardAuthor(self.frame_queries,
                           author,
                           clickable=True,
                           on_click=self._on_click_card) for author in authors
            ]
            return self._show_list_card_queries()
        return self._show_empty_list()

    def _on_click_card(self, *args, **kw):
        author = args[0]
        print("author", author)
        if (author is not None):
            self.app.navigate(context="Home", author_id=author._id)

    def _on_error_update_list_card_queries(self, err: ValueError):
        self._show_empty_list()

    def _update_list_card_queries(self, **kw):
        excute(
            task=controller.get_list_author,
            callback=self._callback_update_list_card_queries,
            on_error=self._on_error_update_list_card_queries,
        )

    def _show_empty_list(self):
        return

    def _show_list_card_queries(self):
        for (idx, card) in enumerate(self.list_card_recommendation):
            rowIdx = int(idx / max_by_row)
            colIdx = idx % max_by_row
            card.grid(row=rowIdx,
                      column=colIdx,
                      padx=(PADDING, PADDING),
                      pady=(PADDING, PADDING),
                      sticky="nw")
            card.show_components()

        # self.frame_result.config(
        #     background=self.get_background()
        # )

    def _screenWillShow(self, **kwargs):
        super()._screenWillShow(**kwargs)

        self._update_list_card_queries(**kwargs)

    def _show(self, **kw):

        rowIdx_button_filter = 0

        colIdx_button_filter = 0

        default_grid = {
            "row": rowIdx_button_filter,
            "sticky": "nw",
            "padx": (PADDING, PADDING)
        }

        self.button_back.pack(side="top", expand=False, anchor="nw")
        self.button_back.show_components()

        self.label_logo.pack(side="top", fill="both", expand=False)
        self.label_queries.pack(side="top",
                                fill="both",
                                expand=False,
                                padx=(PADDING, PADDING))
        self.button_add.pack(
            side="top",
            fill="x",
            expand=False,
            padx=(PADDING, PADDING),
            pady=(PADDING, PADDING),
        )
        self.button_add.show_components()

        self.canvas_queries.pack(side="left", fill="both", expand=True)
        self.scrollbar_queries.pack(side="right", fill="y")
Beispiel #31
0
class Menu:
    def __init__(self):
        self.bg = pygame.transform.scale(
            pygame.image.load('menu/menu.png'),
            (SCREEN_SIZE.W, SCREEN_SIZE.H))

        self.init_buttons()

    def init_buttons(self):
        self.game = Button('menu', (
                (305 / 1024.0) * SCREEN_SIZE.W,
                (305 / 768.0) * SCREEN_SIZE.H),
            bg=pygame.image.load('menu/g.png'),
            fg=pygame.image.load('menu/gf.png'),
            on_left_click=lambda: load_game(1)
        )

        self.btn_1 = Button('menu', (
                (143 / 1024.0) * SCREEN_SIZE.W,
                (143 / 768.0) * SCREEN_SIZE.H),
            bg=pygame.image.load('menu/g1.png'),
            fg=pygame.image.load('menu/g1f.png'),
            text=Text('Game 1'),
            on_left_click=lambda: load_game(1)
        )

        self.btn_2 = Button('menu', (
                (143 / 1024.0) * SCREEN_SIZE.W,
                (143 / 768.0) * SCREEN_SIZE.H),
            bg=pygame.image.load('menu/g2.png'),
            fg=pygame.image.load('menu/g2f.png'),
            text=Text('Game 2'),
            on_left_click=lambda: load_game(2)
        )

        self.btn_3 = Button('menu', (
                (143 / 1024.0) * SCREEN_SIZE.W,
                (143 / 768.0) * SCREEN_SIZE.H),
            bg=pygame.image.load('menu/g3.png'),
            fg=pygame.image.load('menu/g3f.png'),
            text=Text('Game 3'),
            on_left_click=lambda: load_game(3)
        )

        self.btn_4 = Button('menu', (
                (143 / 1024.0) * SCREEN_SIZE.W,
                (143 / 768.0) * SCREEN_SIZE.H),
            bg=pygame.image.load('menu/g4.png'),
            fg=pygame.image.load('menu/g4f.png'),
            text=Text('Game 4')
        )

        self.btn_5 = Button('menu', (
                (143 / 1024.0) * SCREEN_SIZE.W,
                (143 / 768.0) * SCREEN_SIZE.H),
            bg=pygame.image.load('menu/g5.png'),
            fg=pygame.image.load('menu/g5f.png'),
            text=Text('Game 5')
        )

        self.profile = Button('menu', (
                (467 / 1024.0) * SCREEN_SIZE.W,
                (92 / 768.0) * SCREEN_SIZE.H),
            bg=pygame.image.load('menu/p.png'),
            fg=pygame.image.load('menu/pf.png'),
            text=Text('VIEW MY PROFILE')
        )

    def render(self):
        SCREEN.blit(self.bg, (0, 0))

        self.game.render((
            (22 / 1024.0) * SCREEN_SIZE.W,
            (94 / 768.0) * SCREEN_SIZE.H))
        self.btn_1.render((
            (345 / 1024.0) * SCREEN_SIZE.W,
            (94 / 768.0) * SCREEN_SIZE.H))
        self.btn_2.render((
            (345 / 1024.0) * SCREEN_SIZE.W,
            (257 / 768.0) * SCREEN_SIZE.H))
        self.btn_3.render((
            (345 / 1024.0) * SCREEN_SIZE.W,
            (420 / 768.0) * SCREEN_SIZE.H))
        self.btn_4.render((
            (184 / 1024.0) * SCREEN_SIZE.W,
            (420 / 768.0) * SCREEN_SIZE.H))
        self.btn_5.render((
            (22 / 1024.0) * SCREEN_SIZE.W,
            (420 / 768.0) * SCREEN_SIZE.H))
        self.profile.render((
            (22 / 1024.0) * SCREEN_SIZE.W,
            (582 / 768.0) * SCREEN_SIZE.H))
Beispiel #32
0
def login(mode='STANDARD'):
    pygame.init()

    json_file = open(os.getcwd() + r"\components\constants.json", "r")
    json_content = json.load(json_file)
    round_int = json_content["round_int"]
    json_file.close()

    BLACK = (0, 0, 0)
    WHITE = (255, 255, 255)
    BROWN = (138, 79, 28)
    font = pygame.font.SysFont("DejaVu Sans", 30)
    # RED = (255, 0, 0), GREEN = (0, 255, 0), BLUE = (0, 0, 255)

    screen = pygame.display.set_mode((720, 480))
    screen.fill(BROWN)

    clock = pygame.time.Clock()

    pygame.display.update()

    title_label = font.render(mode, True, BLACK)

    Player1_label = font.render("Player 1:", True, BLACK)
    Player2_label = font.render("Player 2:", True, BLACK)

    Player1 = InputBox(300, 200, 100, 32, WHITE, (10, 10, 10))
    Player2 = InputBox(300, 250, 100, 32, WHITE, (10, 10, 10))

    Accept_Button = Button(x=300,
                           y=300,
                           w=100,
                           h=50,
                           color_b=BLACK,
                           color_in=WHITE,
                           color_t=WHITE,
                           command=lambda: [
                               main(player1=Player1.export(),
                                    player2=Player2.export(),
                                    mode=mode,
                                    bot_bool=False)
                           ],
                           text='Start Game')

    boxes_arr = [Player1, Player2]

    while True:
        clock.tick(60)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                quit()

            for box in boxes_arr:
                box.checkActivation(event)

            Accept_Button.processEvent(event)

            screen.fill(BROWN)
            screen.blit(Player1_label, (150, 200))
            screen.blit(Player2_label, (150, 250))
            screen.blit(title_label, (pygame.display.get_window_size()[0] / 2 -
                                      title_label.get_rect().w / 2, 30))
            for box in boxes_arr:
                box.draw(screen)

            Accept_Button.draw(screen)

            pygame.display.flip()
Beispiel #33
0
    def _init_components(self):
        background_color = self.get_background()
        scrollbar_width = SCROLL_BAR_WIDTH
        height_buttons = BUTTON[1] + PADDING * 2
        width_buttons = BUTTON[1] + PADDING * 2

        self.button_back = ButtonBack(self,
                                      size=height_buttons,
                                      onClick=self.navigate_home)

        self.label_logo = Label(self)
        self.label_logo.config(
            text="weCoNet",
            font=LOGO,
            background=background_color,
            foreground=BLUE,
        )

        self.label_queries = Label(self)
        self.label_queries.config(text="QUERIES",
                                  font=BODY_BOLD,
                                  background=background_color,
                                  foreground=BLACK,
                                  anchor="nw")
        """
        ScrollView result     
        """
        self.canvas_queries = Canvas(
            self,
            highlightthickness=1,
        )
        self.frame_queries = Frame(
            self.canvas_queries,
            highlightthickness=1,
            #    borderwidth=1,
            #    relief="solid",
        )
        self.canvas_queries.config(
            background=WHITE,
            highlightthickness=0,
        )
        self.frame_queries.config(
            background=WHITE,
            highlightthickness=0,
        )

        self.scrollbar_queries = Scrollbar(self,
                                           orient="vertical",
                                           width=scrollbar_width,
                                           command=self.canvas_queries.yview)
        self.canvas_queries.config(yscrollcommand=self.scrollbar_queries.set, )

        self.canvas_queries.create_window(
            (0, 0),
            window=self.frame_queries,
            anchor="nw",
        )

        self.frame_queries.bind("<Configure>", self._onFrameConfigure)

        self.list_card_recommendation = None

        self.button_add = Button(self,
                                 self.app.width - PADDING * 2,
                                 height=height_buttons,
                                 text="See more ...",
                                 enable=True,
                                 onClick=self._on_click_see_more)
Beispiel #34
0
def start():
    pygame.init()

    json_file = open(os.getcwd() + r"\components\constants.json", "r")
    json_content = json.load(json_file)
    round_int = json_content["round_int"]
    json_file.close()

    BLACK = (0, 0, 0)
    WHITE = (255, 255, 255)
    BROWN = (138, 79, 28)
    font_large = pygame.font.SysFont("DejaVu Sans", 30)
    font_small = pygame.font.SysFont("DejaVu Sans", 22)

    screen = pygame.display.set_mode((720, 480))
    screen.fill(BROWN)

    clock = pygame.time.Clock()

    choose_label = font_large.render("Choose a gamemode", 1, BLACK)
    screen.blit(choose_label, (200, 60))

    bot_box = TickBox(posx=320, posy=350, size=30)
    button_standard = Button(
        x=100,
        y=200,
        w=200,
        h=100,
        color_b=BLACK,
        color_in=WHITE,
        color_t=WHITE,
        command=lambda:
        [intermediary(bot=bot_box.getStatus(), mode="STANDARD")],
        text='STANDARD')

    button_960 = Button(
        x=400,
        y=200,
        w=200,
        h=100,
        color_b=BLACK,
        color_in=WHITE,
        color_t=WHITE,
        command=lambda:
        [intermediary(bot=bot_box.getStatus(), mode="CHESS 960")],
        text='CHESS 960')

    bot_label = font_small.render("Play against AI", 1, BLACK)
    screen.blit(bot_label, (120, 350))

    items = [button_standard, button_960, bot_box]
    for item in items:
        item.draw(screen=screen)
    pygame.display.update()

    while True:
        clock.tick(60)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                quit()

            for item in items:
                item.processEvent(event)

            bot_box.draw(screen)

        pygame.display.flip()
Beispiel #35
0
# from utils.pinout import set_pinout
# pinout = set_pinout()

# --- leds ---

from components.led import Led

led2 = Led(16)  # PWM2
led3 = Led(25)  # PWM3

# --- buttons ---
from machine import Pin
from components.button import Button

boot_pin = Pin(0, Pin.IN)
boot_button = Button(boot_pin, release_value=1)

pin34 = Pin(34, Pin.IN)
pin35 = Pin(35, Pin.IN)
# pin36 = Pin(36, Pin.IN)
# pin39 = Pin(39, Pin.IN)
right_button = Button(pin35, release_value=1)
left_button = Button(pin34, release_value=1)

# --- relay ---
relay = Led(17)  # PWM1

# --- oled ---
# I2C oled display
from utils.octopus import oled_init
from components.oled import threeDigits
Beispiel #36
0
class Main():
    def __init__(self):
        # -- Inicio modulos
        pygame.init()
        # -- Obtencion de info del hardware
        self._info = pygame.display.Info()
        # -- Se crea un display utilizando la info
        self._display = pygame.display.set_mode([self._info.current_w, self._info.current_h], pygame.FULLSCREEN | pygame.HWSURFACE)
        # -- Se definen los controles
        self._fuente_top_label = pygame.font.Font(None, 48)
        self._fuente_board = pygame.font.Font(None, 30)
        self._top_label = Label(self._fuente_top_label, "Butia Control Dashboard v1.0", (255, 255, 255), (0, 0, 0))
        self._boton = Button(Label(self._fuente_top_label, "Salir", (255, 255, 255), (0, 0, 0)), Label(self._fuente_top_label, "Salir", (0, 0, 0), (255, 255, 255)))
        self._boton_pausar = Button(Label(self._fuente_top_label, "Pausar", (255, 255, 255), (0, 0, 0)), Label(self._fuente_top_label, "Pausar", (0, 0, 0), (255, 255, 255)))
        self._boton.set_rect(self._info.current_w/2 - self._boton.get_rect().width / 2, self._info.current_h - (self._boton.get_rect().height + 10))
        self._boton_pausar.set_rect(self._info.current_w/2 - self._boton_pausar.get_rect().width / 2, self._info.current_h / 4 * 3 - (self._boton_pausar.get_rect().height / 2))
        self._label_estado = Label(self._fuente_board, "Estado:", (255, 255, 255), (0, 0, 0))
        self._label_estado_informacion = Label(self._fuente_board, "", (255, 255, 255), (0, 0, 0))
        self._label_tarea = Label(self._fuente_board, "Tarea:", (255, 255, 255), (0, 0, 0))
        self._label_tarea_informacion = Label(self._fuente_board, "", (255, 255, 255), (0, 0, 0))
        self._label_error_butia = Label(self._fuente_board, "Revise la conexion con el butia (!)", (255, 255, 255), (0, 0, 0))
        self._label_error_nxt = Label(self._fuente_board, "Revise la conexion con el nxt (!)", (255, 255, 255), (0, 0, 0))
        self._cursor = Cursor()
        # -- Se definen las variables
        self._butia_error = True
        self._nxt_error = True
        self._salir = False
        self._reloj = pygame.time.Clock()
        self._chronometer = Chronometer(1)
        self._timer = None
        self._ready = True
        self._times = 0
        self._pause = False
        # -- Se crean las instancias de butia y nxt
        self._butia = Butia()
        self._nxt = Nxt()
        # -- Se definen los sensores nxt

    # -- DEFINICION DEL GAMELOOP
    def update(self):
        # -- Se actualizan los parametros
        # -- Deteccion de eventos
        for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    self._salir = True
                if event.type == pygame.MOUSEBUTTONDOWN:
                    btn1, btn2, btn3 = pygame.mouse.get_pressed()
                    if btn1:
                        if self._boton.on_click(self._cursor):
                            self._salir = True
                        if self._boton_pausar.on_click(self._cursor):
                            if self._pause:
                                self._pause = False
                            elif not self._pause:
                                self._pause = True
        # -- Obtencion del info del entorno
        # -- Comprobacion de conexiones
        if self._butia.get_butia().getFirmwareVersion() == -1:
            self._butia_error = True
        else:
            self._butia_error = False
        if not self._nxt.get_nxt():
            self._nxt_error = True
        else:
            self._nxt_error = False
        # -- Se corre el seguidor solo si la conexion funciona
        if not self._pause:
            if not self._butia_error and not self._nxt_error:
                if self._butia.get_butia().getGray(5) < 14000 and self._butia.get_butia().getGray(2) < 40000:
                        self._butia.get_butia().set2MotorSpeed(1, 600, 1, 600)
                elif self._butia.get_butia().getGray(5) < 14000 and self._butia.get_butia().getGray(2) > 40000:
                        self._butia.get_butia().set2MotorSpeed(1, 600, 0, 600)
                elif self._butia.get_butia().getGray(5) > 14000 and self._butia.get_butia().getGray(2) < 40000:
                        self._butia.get_butia().set2MotorSpeed(0, 600, 1, 600)
                if self._nxt.get_nxt().get_port(1).getSample() < 20:
                    if self._ready:
                        self._label_tarea_informacion.set_text("Recogiendo muestras")
                        self._label_tarea_informacion.update(self._display, self._info.current_w/4 + self._label_estado.get_rect().width + 20, self._info.current_h/3 + 10 + self._label_estado_informacion.get_rect().height)
                        self.accionar_mecanismo()
                self._label_tarea_informacion.set_text("Recorriendo el mundo")
            self._label_tarea_informacion.set_text("Ninguna")
        else:
            self._label_tarea_informacion.set_text("Pausado")
            self._butia.get_butia().set2MotorSpeed(0, 0, 0, 0)

    def accionar_mecanismo(self):
        # -- Secuencia que realiza la pala
        # -- Ajustar valores de rotacion para alcanzar la medida exacta
        self._ready = False
        self._butia.get_butia().set2MotorSpeed(0, 0, 0, 0)
        self._nxt.get_nxt().get_port("a").turn(-20, 160)
        self._nxt.get_nxt().get_port("b").turn(20, 640)
        try:
            self._nxt.get_nxt().get_port("a").turn(20, 220)
        except Exception:
            self._nxt.get_nxt().get_port("b").turn(-20, 10)
            self._nxt.get_nxt().get_port("a").turn(20, 110)
        self._nxt.get_nxt().get_port("b").turn(-20, 320)
        self._nxt.get_nxt().get_port("a").turn(-20, 110)
        self._nxt.get_nxt().get_port("b").turn(-20, 320)
        #self.motorA.turn(-20, 110)
        self._nxt.get_nxt().get_port("a").turn(20, 90)
        self._times += 1
        if self._times < 3:
            self.motorC.turn(-20, 450)
        else:
            self._nxt.get_nxt("a").turn(-20, 50)
            self._nxt.get_nxt("c").turn(20, 450*2)
            self._nxt.get_nxt("a").turn(20, 50)
            self._times = 0
            self._timer = Timer(5)

    def render(self):
        # -- Se redibuja la pantalla con las actualizaciones pertinentes
        self._display.fill((0, 0, 0))
        self._boton.on_collide(self._display, self._cursor)
        self._boton_pausar.on_collide(self._display, self._cursor)
        self._cursor.update()
        self._top_label.update(self._display, self._info.current_w/2 - self._top_label.get_rect().width/2, 10)
        self._label_estado.update(self._display, self._info.current_w/4, self._info.current_h/3)
        self._label_estado_informacion.update(self._display, self._info.current_w/4 + self._label_estado.get_rect().width + 20, self._info.current_h/3)
        self._label_tarea.update(self._display, self._info.current_w/4, self._info.current_h/3  + 10 + self._label_estado.get_rect().height)
        self._label_tarea_informacion.update(self._display, self._info.current_w/4 + self._label_estado.get_rect().width + 20, self._info.current_h/3 + 10 + self._label_estado_informacion.get_rect().height)
        if not self._butia_error and not self._nxt_error:
            self._label_estado_informacion.set_text("Activo")
        if self._butia_error and self._chronometer.get_value():
            self._label_error_butia.update(self._display, self._info.current_w/5 * 3, self._info.current_h/3)
            self._label_estado_informacion.set_text("Error")
        if self._nxt_error and self._chronometer.get_value():
            self._label_error_nxt.update(self._display, self._info.current_w/5 * 3, self._info.current_h/3 + 10 + self._label_error_nxt.get_rect().height)
            self._label_estado_informacion.set_text("Error")
        pygame.display.flip()

    def sleep(self):
        # -- Se espera
        self._reloj.tick(100)

    def run(self):
        while not self._salir:
            self.update()
            self.render()
            self.sleep()

    def set_ready(self):
        self._ready = True