Ejemplo n.º 1
0
    def cache_datewidget(self):
        self.datewidget_cache = {}
        datefont_size = self.ui.calculate_font_size(4)

        datetime_text = (
            datetime.now().strftime(self.config.setting["dateformat"]) + "  " +
            datetime.now().strftime(
                self.config.setting["timeformat"])).upper()
        self.datetime_text = datetime_text

        date_text = datetime.now().strftime(
            self.config.setting["dateformat"]).upper()

        self.datewidget_cache["datetime_text"] = gui.Text(
            datetime_text, datefont_size, self.ui.boldfont_file)

        self.datewidget_cache["date_text"] = gui.Text(date_text, datefont_size,
                                                      self.ui.boldfont_file)

        self.datewidget_cache[
            "datetime_text"].Position = self.ui.calculate_position(
                (1, -3), self.datewidget_cache["datetime_text"].Surface, "top",
                "right")
        self.datewidget_cache[
            "date_text"].Position = self.ui.calculate_position(
                (1, -3), self.datewidget_cache["date_text"].Surface, "top",
                "right")
Ejemplo n.º 2
0
    def cache_musicscreen(self):
        self.musicscreen_cache = {}
        self.musicplayer.trackdata_changed = False

        if self.musicplayer.image != None:
            albumart_image_size = (self.ui.display_size[0] * .25,
                                   self.ui.display_size[1] * .5)
            self.musicscreen_cache["albumart_image"] = gui.Image(
                self.musicplayer.image, albumart_image_size)
        else:
            self.musicscreen_cache["albumart_image"] = gui.Image(
                pygame.Surface((1, 1), flags=pygame.SRCALPHA))

        self.musicscreen_cache[
            "albumart_image"].Position = self.ui.calculate_position(
                (0, 4), self.musicscreen_cache["albumart_image"].Surface,
                "center", "left")

        track = self.musicplayer.title
        trackfont_size = self.ui.calculate_font_size(4)

        self.musicscreen_cache["track_text"] = gui.Text(
            track, trackfont_size, font=self.ui.boldfont_file, wrapwidth=16)
        self.musicscreen_cache[
            "track_text"].Position = self.ui.calculate_position(
                (0, 0), self.musicscreen_cache["track_text"].Surface, "center",
                "left")

        self.musicscreen_cache["track_text"].Position = (
            self.musicscreen_cache["albumart_image"].Position[0] +
            self.musicscreen_cache["albumart_image"].Surface.get_size()[0] *
            1.05, self.musicscreen_cache["track_text"].Position[1])

        artistfont_size = self.ui.calculate_font_size(3)
        self.musicscreen_cache["artist_text"] = gui.Text(
            self.musicplayer.artist,
            artistfont_size,
            font=self.ui.basefont_file)

        artist_text_y = self.musicscreen_cache["track_text"].Position[1] - (
            self.ui.display_size[1] * 0.08)
        self.musicscreen_cache["artist_text"].Position = (
            self.musicscreen_cache["track_text"].Position[0], artist_text_y)

        self.musicscreen_cache["album_text"] = gui.Text(
            self.musicplayer.album,
            artistfont_size,
            font=self.ui.basefont_file)
        album_text_y = ((self.ui.display_size[1] * 0.03) +
                        self.musicscreen_cache["track_text"].Rect.bottom)
        self.musicscreen_cache["album_text"].Position = (
            self.musicscreen_cache["track_text"].Position[0], album_text_y)
Ejemplo n.º 3
0
    def cache_idlescreen(self):
        self.idlescreen_cache = {}
        time_string = datetime.now().strftime(
            self.config.setting["timeformat"])
        timefont_size = self.ui.calculate_font_size(30)
        fontcolor = pygame.color.Color(50, 50, 50, 255)
        self.idlescreen_cache["time_text"] = gui.Text(
            time_string,
            timefont_size,
            color=fontcolor,
            font=self.ui.basefont_file,
            shadowoffset=(0.5, 0.5))
        self.idlescreen_cache[
            "time_text"].Position = self.ui.calculate_position(
                (0, 0), self.idlescreen_cache["time_text"].Surface, "center",
                "center")

        empty_image = pygame.Surface(self.ui.display_size)

        def reset_idle():
            self.is_idle = False

        self.idlescreen_cache["button"] = gui.Button(empty_image,
                                                     self.ui.display_size,
                                                     reset_idle)
        self.idlescreen_cache["button"].Position = (0, 0)
Ejemplo n.º 4
0
    def cache_alarm_widget(self, updatetime=False):
        icon_size = (self.ui.display_size[0] * .05,
                     self.ui.display_size[1] * .05)

        if not updatetime:
            alarm_symbol_name = "alarm-symbolic.png" if self.alarm.enabled else "alarm-off-symbolic.png"
            self.alarm_widget_cache = {}
            self.alarm_widget_cache["alarm_image_button"] = gui.Button(
                self.ui.image_cache[alarm_symbol_name], icon_size,
                self.switch_to_alarmset_screen)
            self.alarm_widget_cache[
                "alarm_image_button"].Position = self.ui.calculate_position(
                    (1, 4),
                    self.alarm_widget_cache["alarm_image_button"].Surface,
                    "top", "left")

        self.alarm_widget_cache["time"] = str(
            self.alarm.alarmtime.strftime(
                self.config.setting["timeformat"])).upper()
        alarmfont_size = self.ui.calculate_font_size(4.5)
        alarm_text = gui.Text(self.alarm_widget_cache["time"], alarmfont_size,
                              self.ui.boldfont_file)
        self.alarm_widget_cache["alarm_text_button"] = gui.Button(
            alarm_text.Surface, alarm_text.Surface.get_size(),
            self.switch_to_alarmset_screen)
        self.alarm_widget_cache["alarm_text_button"].Position = (
            self.alarm_widget_cache["alarm_image_button"].Position[0] +
            (icon_size[1] * 1.1),
            self.alarm_widget_cache["alarm_image_button"].Position[1] * 1.2)
Ejemplo n.º 5
0
    def __init__(self,
                 label,
                 value="",
                 bgcolor=None,
                 min=1,
                 max=32,
                 acceptable_chars="0123456789abcdefghijklmnopqrstuvwxyz-_."):
        gui.EventHandler.__init__(self)
        self.keyboard = resource_loader.loadImage("keyboard.png")
        self.label = gui.Text(gui.res.font_messagebox)
        self.label.setText(label, TextInputBox.WIDTH)
        self.value = gui.EditText(gui.res.font_select_option, (96, 255, 96))
        self.value.setText(value, TextInputBox.WIDTH)
        self.value.showCaret(True)
        self.value.setAcceptableChars(acceptable_chars)
        gui.Window.__init__(
            self,
            (TextInputBox.WIDTH + 10, self.label.getHeight() +
             self.value.getHeight() + 10 + 10 + self.keyboard.get_height()))
        self.bgcolor = bgcolor if bgcolor != None else gui.res.color_dialog_positive
        self.min = min
        self.max = max
        #self.available_chars = available_chars

        self.addChild("label", self.label, (5, 5))
        self.addChild("value", self.value, (5, 5 + self.label.getHeight()))
 def notify(self, subject):
     """
     
     """
     ##        print "notify from: ", subject, " value: ", subject.get_current_value()
     if subject == self.spinners[0]:
         if len(self.spinners) - 1 > subject.get_current_value():
             spinner = self.spinners.pop()
             spinner.remove_observer(self)
             events.RootEventSource().remove_listener(spinner)
             self.texts.pop()
             config.players.pop()
             self.rand_lands()
         elif len(self.spinners) - 1 < subject.get_current_value():
             # add new spinner for player
             xpos, ypos = self.spinners[-1].position
             spinner = gui.Spinner(self.font, (xpos, ypos + 30))
             for item in self.items:
                 spinner.add(item)
             events.RootEventSource().add_listener(spinner)
             self.spinners.append(spinner)
             self.texts.append(gui.Text("Player "+str(len(self.spinners)-1)+\
                                 ": ", self.font, (xpos - 100, ypos + 30)))
             config.players.append(Player(len(self.spinners) - 1))
             self.rand_lands()
Ejemplo n.º 7
0
    def __init__(self, container, rect, frame_rate, windows_controller):

        gui.Window.__init__(self, container, rect, frame_rate,
                            windows_controller, "personal_window")

        self.active_personal_events = []  # tuple (event, animation)
        self.index_personal_event = 0

        self.personal_next = gui.ImageButton(
            self.rect, pygame.Rect(120, 95, 30, 30), 1,
            os.path.join(BASEPATH, "assets/events/go-next.png"),
            self._cb_button_click_personal_next)
        self.personal_back = gui.ImageButton(
            self.rect, pygame.Rect(5, 95, 30, 30), 1,
            os.path.join(BASEPATH, "assets/events/go-back.png"),
            self._cb_button_click_personal_back)

        self.add_button(self.personal_next)
        self.add_button(self.personal_back)

        self.personal_next.visible = False
        self.personal_back.visible = False

        self.count_personal_events = gui.Text(self.rect, 60, 100, 1, "", 22,
                                              TEXT_COLOR,
                                              gui.Text.ALIGN_CENTER, True,
                                              False)
        self.add_child(self.count_personal_events)

        self.current_animation = None  # Visible event at panel
Ejemplo n.º 8
0
    def __init__(self, container, rect, frame_rate, windows_controller,
                 character):
        gui.Window.__init__(self, container, rect, frame_rate,
                            windows_controller, "customization_window")
        self.set_bg_image(os.path.join(BASEPATH,
                                       "assets/windows/window_2.png"))

        kid_rect = pygame.Rect((20, 10), (1, 1))
        self.kid = CustomizatedKid(self.rect, kid_rect, 1, character)
        self.add_child(self.kid)

        title = gui.Text(self.rect,
                         590,
                         60,
                         1,
                         _(u"Creá tu personaje"),
                         32,
                         pygame.Color("#0f5e65"),
                         alignment=gui.Text.ALIGN_CENTER,
                         bold=True)
        self.add_child(title)

        btn_close = utilities.get_accept_button(
            self.rect, pygame.Rect((400, 500), (1, 1)), _("Continue"),
            self._cb_button_click_close)

        button_back = pygame.image.load(
            os.path.join(
                BASEPATH,
                "customization/customization_button.png")).convert_alpha()
        btn_hair = gui.TextButton2(self.rect, pygame.Rect((500, 100),
                                                          (70, 30)), 1,
                                   _("Hair"), 28, (255, 255, 255), button_back,
                                   self._cb_button_hair)
        btn_skin = gui.TextButton2(self.rect, pygame.Rect((500, 170),
                                                          (70, 30)), 1,
                                   _("Skin"), 28, (255, 255, 255), button_back,
                                   self._cb_button_skin)
        btn_sweater = gui.TextButton2(self.rect,
                                      pygame.Rect((500, 240), (70, 30)), 1,
                                      _("Sweater"), 28, (255, 255, 255),
                                      button_back, self._cb_button_sweater)
        btn_pants = gui.TextButton2(self.rect, pygame.Rect((500, 310),
                                                           (70, 30)), 1,
                                    _("Pants"), 28, (255, 255, 255),
                                    button_back, self._cb_button_pants)
        btn_shoes = gui.TextButton2(self.rect, pygame.Rect((500, 380),
                                                           (70, 30)), 1,
                                    _("Shoes"), 28, (255, 255, 255),
                                    button_back, self._cb_button_shoes)
        map(self.add_button,
            [btn_close, btn_hair, btn_skin, btn_sweater, btn_pants, btn_shoes])

        self.hair_color_index = 0
        self.skin_color_index = 0
        self.sweater_color_index = 0
        self.pants_color_index = 0
        self.shoes_color_index = 0
Ejemplo n.º 9
0
    def cache_alarmscreen(self):

        self.alarmscreen_cache = {}
        icon_size = (self.ui.display_size[0] * .3,
                     self.ui.display_size[1] * .3)

        epoch = int(time.time())
        if (epoch % 2) == 0:
            fgcolor = self.ui.bg_color
            bgcolor = self.ui.fg_color
            shadow = False
        else:
            fgcolor = self.ui.fg_color
            bgcolor = pygame.Color(0, 0, 0, 0)
            shadow = True

        self.alarmscreen_cache["background"] = gui.GuiObject()
        self.alarmscreen_cache["background"].Surface = pygame.Surface(
            self.ui.display_size, flags=pygame.SRCALPHA)
        self.alarmscreen_cache["background"].Position = (0, 0)
        self.alarmscreen_cache["background"].Surface.fill(bgcolor)

        current_time_text = str(datetime.now().strftime(
            self.config.setting["timeformat"]))

        self.alarmscreen_cache["alarm_button"] = gui.Button(
            self.ui.image_cache["alarm-symbolic.png"], icon_size,
            self.stop_alarm)
        self.alarmscreen_cache[
            "alarm_button"].Position = self.ui.calculate_position(
                (0, -55), self.alarmscreen_cache["alarm_button"].Surface,
                "center", "center")

        timefont_size = self.ui.calculate_font_size(25)

        time_text = gui.Text(current_time_text,
                             timefont_size,
                             font=self.ui.boldfont_file,
                             color=fgcolor,
                             shadow=shadow)

        self.alarmscreen_cache["time_text_button"] = gui.Button(
            time_text.Surface, time_text.Surface.get_size(), self.stop_alarm)
        self.alarmscreen_cache[
            "time_text_button"].Position = self.ui.calculate_position(
                (0, -30), self.alarmscreen_cache["alarm_button"].Surface,
                "center", "center")
        self.alarmscreen_cache["time_text_button"].Position = (
            self.alarmscreen_cache["alarm_button"].Position[0] +
            icon_size[1] * 1.2,
            self.alarmscreen_cache["alarm_button"].Position[1])
Ejemplo n.º 10
0
    def __init__(self, mod: WorldSubjectMod):
        super().__init__(self)

        self.bomb_color = (3, 16, 8)
        self._bg_color = (66, 66, 66)  # red, green, blue format
        ft = pygame.font.Font(None, 19)
        self.img = ft.render('Inside the game', True, (0, 0, 0))
        self.img_pos = (200, 60)
        self._mod = mod

        # load assets...
        def open_sprsheet(filename):
            with open(filename, 'r') as myimg:
                surff = pygame.image.load(myimg)
                return SpriteSheet(surff, (16, 16),
                                   pygame.color.Color('blue'),
                                   upscaling=4)

        # -- load ASSETS (tileset, avatars) --
        tileset = open_sprsheet(os.path.join('..', 'assets', 'tileset.png'))

        self.floor_spr = tileset[369]  # ou 553 pour du sol plus clair
        self.weakwall_spr = tileset[342]
        self.invblock_spr = tileset[370]

        self.avatar_sprsheets = {
            0: open_sprsheet(os.path.join('..', 'assets', 'avatar0.png')),
            1: open_sprsheet(os.path.join('..', 'assets', 'avatar1.png')),
            2: open_sprsheet(os.path.join('..', 'assets', 'avatar2.png')),
            3: open_sprsheet(os.path.join('..', 'assets', 'avatar3.png')),
        }
        self.__plcode_to_gfxid = dict()

        # -- end load assets

        self._player_infos = list()
        self._bomb_positions = list()
        self._weakwall_positions = list()
        self._invblock_positions = list()

        self._refresh_block_n_walls()

        # wait text
        ft = pygame.font.Font(None, 77)
        titlepos = [glvars.SCR_SIZE[0] // 2, glvars.SCR_SIZE[1] // 2]
        titlepos[1] -= glvars.SCR_SIZE[1] // 3
        self._plz_wait_label = gui.Text(
            'Waiting for other players... Please wait',
            ft,
            titlepos,
            anchortype=gui.Text.ANCHOR_CENTER)
Ejemplo n.º 11
0
    def __init__(self,
                 container,
                 rect,
                 frame_rate,
                 windows_controller,
                 challenges_creator,
                 register_id,
                 bg_color=(0, 0, 0)):
        gui.Window.__init__(self, container, rect, frame_rate,
                            windows_controller, register_id, bg_color)

        self.set_bg_image(os.path.join(BASEPATH,
                                       "assets/windows/window_1.png"))

        ###### Sounds ######
        self.s_correct = pygame.mixer.Sound(S_CORRECT_PATH)
        self.s_over = pygame.mixer.Sound(S_OVER_PATH)
        self.s_incorrect = pygame.mixer.Sound(S_INCORRECT_PATH)
        ####################

        self.topic = None  # The topic is the bar whose we are playing

        self.choices = []
        self.correct = None
        self.correct_index = 0

        self.tries = 0

        self.challenges_creator = challenges_creator

        # If a question is setted, we have to "erase" the old challenge
        self.question = None

        self.title = gui.Text(self.rect,
                              30,
                              35,
                              1,
                              u"Elije la opción correcta",
                              24, (255, 255, 255),
                              bold=True)
        self.add_child(self.title)

        # Close Button
        self.btn_close = gui.TextButton(self.rect,
                                        pygame.Rect((910, 0),
                                                    (30, 30)), 1, "X", 32,
                                        (0, 0, 0), self._cb_button_click_close)
        #self.add_button(self.btn_close)

        self.wait = 0
Ejemplo n.º 12
0
    def __init__(self):
        gui.Window.__init__(self, title='Functions', size=(500, 300))
        box = gui.Box(self, 'horizontal')

        #        split = gui.Splitter(box, 'horizontal', stretch=1)
        #        self.categories = gui.List(split)
        self.category = gui.List(box, model=RegModel(registry), stretch=1)
        self.category.connect('selection-changed', self.on_select_function)
        self.category.connect('item-activated', self.on_item_activated)

        rbox = gui.Box(box, 'vertical', stretch=2)

        toolbar = gui.Toolbar(rbox, stretch=0)
        toolbar.append(gui.Command('New', '', self.on_new, 'new.png'))
        toolbar.append(gui.Command('Delete', '', self.on_remove, 'remove.png'))
        toolbar.append(gui.Command('Save', '', self.on_save, 'save.png'))
        toolbar._widget.Realize()

        book = gui.Notebook(rbox)

        edit = gui.Box(book, 'vertical', page_label='edit')
        g = gui.Grid(edit, 2, 2, stretch=0, expand=True)
        g.layout.AddGrowableCol(1)
        gui.Label(g, 'Name', pos=(0, 0))
        gui.Label(g, 'Parameters', pos=(1, 0))
        self.name = gui.Text(g, pos=(0, 1), expand=True)
        self.params = gui.Text(g, pos=(1, 1), expand=True)

        #        self.text = gui.Text(edit, multiline=True, stretch=1)
        self.text = gui.PythonEditor(edit, stretch=1)

        extra = gui.Box(book, 'vertical', page_label='extra')
        #        self.extra = gui.Text(extra, multiline=True, stretch=1)
        self.extra = gui.PythonEditor(extra, stretch=1)

        self.functions = functions
        self.function = None
Ejemplo n.º 13
0
    def cache_clockscreen(self):
        self.clockscreen_cache = {}

        time_string = datetime.now().strftime(
            self.config.setting["timeformat"])
        timefont_size = self.ui.calculate_font_size(30)

        self.clockscreen_cache["time_text"] = gui.Text(
            time_string,
            timefont_size,
            font=self.ui.basefont_file,
            shadowoffset=(0.5, 0.5))
        self.clockscreen_cache[
            "time_text"].Position = self.ui.calculate_position(
                (0, 0), self.clockscreen_cache["time_text"].Surface, "center",
                "center")
Ejemplo n.º 14
0
 def __init__(self, windows_controller, container, name, root_bar, children_bar, size, position, icon_path):
     
     rect = pygame.Rect(position, size)
     gui.Window.__init__(self, container, rect, 1, windows_controller, "bar_section_window")
     
     # section attributes
     self.name = name
     self.root_bar = root_bar
     self.children_bar = children_bar
     
     font = utilities.get_font(16, True, True)
     
     #label_render = font.render(self.name, 1, pygame.Color(TEXT_COLOR))
     #label_rect = pygame.Rect((0,0), label_render.get_size())
     #label_rect.right = self.rect.right - 8
     pos = self.rect.right - 8, 0
     label_widget = gui.Text(self.rect, pos[0], pos[1], 1, self.name, 16, pygame.Color(TEXT_COLOR), "normal", gui.Text.ALIGN_RIGHT, True, True)
     
     # visuals
     self.root_bar_display = BarDisplay(BAR_HEIGHT, BAR_WIDTH, (BAR_OFFSET_X, SECTION_TOP_PADDING), self.root_bar, ROOT_BAR_PARTITIONS)
     self.root_bar_display.show_name = False
     
     self.displays_list = self.__get_displays()      # obtengo los displays para cada barra.
     
     self.fixed_widgets = [label_widget, self.root_bar_display]
     
     if icon_path:
         icon = pygame.image.load(icon_path).convert_alpha()
         self.icon = gui.Widget(self.rect, pygame.Rect((0, 0), icon.get_size()), 1, icon)
         self.icon.keep_dirty = True
         self.fixed_widgets.append(self.icon)
     else:
         self.icon = None
     
     # visuals constant
     self.init_top = self.rect[1]
     self.init_height = size[1]
     self.max_expand = len(children_bar) * BAR_HEIGHT
     
     self.expanded = False   # Este flag se activa cuando se están mostrando las sub-barras
     self.__calculate()      # calculo la posición de cada barra en la sección
Ejemplo n.º 15
0
    def __init__(self,
                 container,
                 rect,
                 frame_rate,
                 windows_controller,
                 challenges_creator,
                 text_intro,
                 text_result_good,
                 text_result_bad,
                 slide=None,
                 bg_color=(0, 0, 0)):
        gui.Window.__init__(self, container, rect, frame_rate,
                            windows_controller, "info_challenge_window",
                            bg_color)

        self.set_bg_image(os.path.join(BASEPATH,
                                       "assets/windows/window_2.png"))
        self.challenges_creator = challenges_creator

        self.rect = rect

        self.btn_continue = utilities.get_accept_button(
            self.rect, pygame.Rect((400, 500), (1, 1)), _("Continue"),
            self._cb_button_click_continue)
        self.add_button(self.btn_continue)

        # Texts
        self.title = gui.Text(rect, 40, 40, 1, "Verdadero o Falso", 45,
                              TITLE_COLOR)
        self.text = gui.TextBlock(rect, 40, 120, 1, "", 35, TEXT_COLOR,
                                  "normal", False)
        self.image = gui.Image(
            rect, pygame.Rect(640, 240, 80, 80), 1,
            os.path.join(BASEPATH, "assets/challenges/ninio_normal.png"))

        self.add_child(self.title)
        self.add_child(self.text)
        self.add_child(self.image)
Ejemplo n.º 16
0
    def __init__(self,
                 label,
                 value="",
                 min=1,
                 max=32,
                 acceptable_chars="0123456789abcdefghijklmnopqrstuvwxyz-_",
                 password_mode=False):

        self.label = gui.Text(gui.res.font_system.getFont(22), (0, 0, 0))
        self.label.setText(label, TextInputBox.CONTENTS_WIDTH)
        self.value = gui.EditText(gui.res.font_select_option, (0, 128, 0))
        self.value.setPasswordMode(password_mode)
        self.value.setText(value, TextInputBox.CONTENTS_WIDTH)
        self.value.showCaret(True)
        self.value.setCaretColor((0, 0, 0))
        if acceptable_chars != None:
            self.value.setAcceptableChars(acceptable_chars)
        self.dialog = dialogbox.DialogBase(
            (TextInputBox.CONTENTS_WIDTH,
             self.label.getHeight() + self.value.getHeight() + 8))
        (ox, oy) = self.dialog.getContentsOffset()
        self.dialog.addChild("label", self.label, (ox, oy))
        self.dialog.addChild("value", self.value,
                             (ox, oy + self.label.getHeight() + 8))
        self.keyboard = gui.Bitmap(gui.res.keyboard)

        gui.EventHandler.__init__(self)
        gui.Window.__init__(self,
                            (self.dialog.getWidth(), self.dialog.getHeight() +
                             self.keyboard.getHeight() - 10))
        self.addChild("dialog", self.dialog, (0, 0), 2)
        self.addChild("keyboard", self.keyboard,
                      ((self.getSize()[0] - self.keyboard.getWidth()) / 2,
                       self.dialog.getHeight() - 10), 1)

        self.min = min
        self.max = max
Ejemplo n.º 17
0
import math

# preperation
dir_name = os.path.dirname(__file__)
pygame.init()
pygame.freetype.init()
pygame.mixer.init()
clock = pygame.time.Clock()

screen = pygame.display.set_mode((width, height))  # + log_width
pygame.display.set_caption('Smart Sheep')

americano_active = False

buttons = [
    gui.Text("START"),
    gui.Text("Start manual"),
    gui.Text("Settings"),
    gui.Text("Stop music")
]

my_hot_mixtape = os.path.join(dir_name, 'sound/sheep-theme.mp3')
pygame.mixer.music.load(my_hot_mixtape)
pygame.mixer.music.play(-1)


def render_buttons():
    buttons[0].render(black, 10, 420, 22, screen)
    buttons[1].render(black, 210, 420, 22, screen)
    buttons[2].render(black, 410, 420, 22, screen)
    buttons[3].render(black, 610, 420, 22, screen)
Ejemplo n.º 18
0
def _(text):
    return gui.Text(interface, text, align="right")
Ejemplo n.º 19
0
def manual():
    global screen
    if not americano_active:
        screen = pygame.display.set_mode((width, height))
    sheep = gui.Object(['img/sheep1.png', 'img/sheep2.png'], 100, ground_y)
    wolf = gui.Object(['img/wolf1.png', 'img/wolf2.png'], width + 1, ground_y)
    food = gui.Object(['img/food1.png', 'img/food2.png', 'img/food3.png'],
                      width + 1, ground_y)
    ground = gui.Object(['img/background.png'], 0, ground_y + 10)
    hunger_text = gui.Text("0")
    score_text = gui.Text("0")
    step = 0
    while True:
        step += 1
        # collisions
        if sheep.collision(wolf):
            text = gui.Text("Game Over")
            text.render(black, 1 / 3 * width, 50, 22, screen)
            pygame.display.flip()
            pygame.time.delay(2000)
            # don't overuse it ;)
            manual()
            return -1
            buttons[1].string = "Start manual"
        if sheep.collision(food):
            if food.surface_counter == 0:
                sheep.hunger = 0
                food.animate()

        # increase the hunger
        sheep.hunger += 1

        # check for max hunger
        if sheep.hunger > 600:
            text = gui.Text("Game Over")
            text.render(black, 1 / 3 * width, 50, 22, screen)
            pygame.display.flip()
            pygame.time.delay(2000)
            # don't overuse it ;)
            manual()
            return -1
            buttons[1].string = "Start manual"

        # input
        event = events()
        if event == 11:
            buttons[1].string = "Start manual"
            return -1
        keys = pygame.key.get_pressed()
        if keys[pygame.K_SPACE]:
            if sheep.mask.bottom == ground_y:
                sheep.vy = -18
        if event == 13:
            if buttons[3].string == "Stop music":
                pygame.mixer.music.pause()
                buttons[3].string = "Start music"
            else:
                pygame.mixer.music.unpause()
                buttons[3].string = "Stop music"

        # movement
        if not wolf.x_bounds():
            if random.randint(1, wolf_spawn_chance) == 2:
                wolf.move_to_x(width - 1)
        if not food.x_bounds():
            if random.randint(1, food_spawn_chance) == 2:
                food.surface_counter = 0
                food.move_to_x(width - 1)

        if ground.mask.x < -800:
            ground.move_to(0, ground.mask.y)

        wolf.move_by(wolf_speed, 0)
        food.move_by(food_speed, 0)
        ground.move_by(food_speed, 0)

        sheep.move_by(0, sheep.vy)
        sheep.vy += g
        # if sheep is too low
        if sheep.mask.bottom > ground_y:
            sheep.vy = 0
            sheep.mask.y = ground_y - sheep.mask.height

        # rendering
        if food.mask.right < sheep.mask.x and food.surface_counter == 1:
            food.animate()

        if step % anime_speed == 0:
            wolf.animate()
            sheep.animate()

        score_text.string = "score: " + str(step)
        hunger_text.string = "hunger: " + str(sheep.hunger)
        screen.fill(background_color)
        score_text.render(black, 650, 5, 18, screen)
        if sheep.hunger > 500:
            hunger_text.render((255, 10, 10), 650, 30, 18, screen)
        else:
            hunger_text.render(black, 650, 30, 18, screen)
        wolf.render(screen)
        food.render(screen)
        sheep.render(screen)
        ground.render(screen)
        pygame.time.delay(17)
        render_buttons()
        pygame.display.flip()
Ejemplo n.º 20
0
UDivisions	= gui.IntNumber(interface, 'U: ', 16, 3, 1024)
VDivisions	= gui.IntNumber(interface, 'V: ', 16, 3, 1024)
Smooth		= gui.Toggle(interface, 'Smooth', True)

Create		= gui.Button(interface, 'Create', callback=create)

Hemisphere	= gui.Toggle(interface, 'Hemisphere', False)
Cap			= gui.Toggle(interface, 'Cap', True)
CapMethod	= gui.MultipleToggle(interface,  ['simple', 'symmetrical'], 0)
Percent		= gui.FloatSlider(interface, '', 50, 0, 100)

Origin		= gui.MultipleToggle(interface, [ ('World center',CENTER), ('3D cursor',CURSOR) ], 0, tooltip="Origin")
Orientation	= gui.RadioButtons(interface,  [('xz',XZ), ('xy',XY), ('yz',YZ)], XZ, tooltip="Orientation")

rows = gui.Rows(interface, 10, 10, 300, 20, padx=4)
rows.addrow( gui.Text(interface, 'Sphere radius') )
rows.addvspace("quarter")
rows.addrow( Radius )
rows.addvspace()

rows.addrow( gui.Text(interface, 'Divisions:') )
rows.addvspace("quarter")
rows.addrow( UDivisions )
rows.addvspace("quarter")
rows.addrow( VDivisions )

rows.addvspace()

rows.addrow( [Hemisphere, Cap, CapMethod] )
rows.addvspace("quarter")
rows.addrow( Percent )
Ejemplo n.º 21
0
    def cache_alarmset_screen(self):
        self.alarmset_screen_cache = {}

        def changeAlarmTime(m):
            delattr(self, 'alarmset_screen_cache')
            self.alarm.changeAlarm(m)

        alarmtime_text = self.alarm.time.strftime(
            self.config.setting["timeformat"])
        alarmtime_size = self.ui.calculate_font_size(22)
        self.alarmset_screen_cache["alarmtime"] = gui.Text(
            alarmtime_text,
            alarmtime_size,
            self.ui.boldfont_file,
            shadowoffset=(0.5, 0.5))
        self.alarmset_screen_cache[
            "alarmtime"].Position = self.ui.calculate_position(
                (0, -34), self.alarmset_screen_cache["alarmtime"].Surface,
                "center", "right")

        icon_size = (self.ui.display_size[0] * .25,
                     self.ui.display_size[1] * .25)

        big_icon_size = (self.ui.display_size[0] * .33,
                         self.ui.display_size[1] * .33)

        self.alarmset_screen_cache["addminute_button"] = gui.Button(
            self.ui.image_cache["add.png"], icon_size,
            lambda: changeAlarmTime(1), lambda: changeAlarmTime(5))
        self.alarmset_screen_cache[
            "addminute_button"].Position = self.ui.calculate_position(
                (-15, -40),
                self.alarmset_screen_cache["addminute_button"].Surface,
                "center", "right")

        self.alarmset_screen_cache["subminute_button"] = gui.Button(
            self.ui.image_cache["sub.png"], icon_size,
            lambda: changeAlarmTime(-1), lambda: changeAlarmTime(-5))
        self.alarmset_screen_cache[
            "subminute_button"].Position = self.ui.calculate_position(
                (15, -40),
                self.alarmset_screen_cache["subminute_button"].Surface,
                "center", "right")

        self.alarmset_screen_cache["addhour_button"] = gui.Button(
            self.ui.image_cache["add.png"], icon_size,
            lambda: changeAlarmTime(60))
        self.alarmset_screen_cache[
            "addhour_button"].Position = self.ui.calculate_position(
                (-15, -85),
                self.alarmset_screen_cache["addhour_button"].Surface, "center",
                "right")

        self.alarmset_screen_cache["subhour_button"] = gui.Button(
            self.ui.image_cache["sub.png"], icon_size,
            lambda: changeAlarmTime(-60))
        self.alarmset_screen_cache[
            "subhour_button"].Position = self.ui.calculate_position(
                (15, -85),
                self.alarmset_screen_cache["subhour_button"].Surface, "center",
                "right")

        self.alarmset_screen_cache["cancel_button"] = gui.Button(
            self.ui.image_cache["cancel.png"], big_icon_size, self.reset_alarm)
        self.alarmset_screen_cache[
            "cancel_button"].Position = self.ui.calculate_position(
                (-15, 8), self.alarmset_screen_cache["cancel_button"].Surface,
                "center", "left")

        self.alarmset_screen_cache["ok_button"] = gui.Button(
            self.ui.image_cache["ok.png"], big_icon_size, self.set_alarm)
        self.alarmset_screen_cache[
            "ok_button"].Position = self.ui.calculate_position(
                (15, 8), self.alarmset_screen_cache["ok_button"].Surface,
                "center", "left")

        self.alarmset_screen_cache["off_button"] = gui.Button(
            self.ui.image_cache["off.png"], icon_size, self.switch_alarm_off)
        self.alarmset_screen_cache[
            "off_button"].Position = self.ui.calculate_position(
                (15, -5), self.alarmset_screen_cache["off_button"].Surface,
                "center", "right")
Ejemplo n.º 22
0
def test(generation, generation_size, nets):
    text = [
        gui.Text("Generation " + str(generation)),
        gui.Text(
            str(generation_size) + " out of " + str(generation_size) + "alive")
    ]
    delay = 0
    screen.fill(white)
    welcome = gui.Text("Testing generation " + str(generation))
    welcome.render(black, 1 / 10 * width, 2 / 3 * height, 40, screen)
    pygame.display.flip()
    pygame.time.delay(500)
    screen.fill(background_color)
    # we are testing all the sheep in the same time
    sheep = [
        gui.Object(['img/sheep1.png', 'img/sheep2.png'], 100, ground_y)
        for i in range(generation_size)
    ]
    # number of sheeps alive
    sheep_alive = generation_size
    # there is only 1 wolf and 1 package of food on the screen at the same time, so we dont need to create new
    wolf = gui.Object(['img/wolf1.png', 'img/wolf2.png'], width + 1, ground_y)
    food = gui.Object(['img/food1.png', 'img/food2.png', 'img/food3.png'],
                      width + 1, ground_y)
    ground = gui.Object(['img/background.png'], 0, ground_y + 10)
    fitness = [1 for i in range(generation_size)]
    # game loop
    step = 0
    while True:
        step += 1
        # check for collisions
        for i in range(generation_size):
            if not sheep[i].alive:
                continue
            if sheep[i].collision(food) and food.surface_counter == 0:
                food.animate()
                fitness[i] += food_value
                sheep[i].hunger = 0
            if sheep[i].collision(wolf) and wolf.x_bounds():
                sheep_alive -= 1
                sheep[i].kill()
        if wolf.x_bounds() and wolf.mask.right < 100:
            for i in range(generation_size):
                if sheep[i].alive:
                    fitness[i] += wolf_value

        pygame.time.delay(delay)

        # check for jumping
        # using NN
        # one node in first layer contains the distance to the wolf ahead ( if any), the other one to the food package
        input_layer = np.ndarray(shape=(2, 1))
        if wolf.mask.x > 100 + sheep[0].mask.height and wolf.x_bounds():
            input_layer[0][0] += 1 / math.sqrt(wolf.mask.x - 100 -
                                               sheep[0].mask.height)
        else:
            input_layer[0][0] = 0

        if food.mask.x > 100 + sheep[0].mask.height and food.x_bounds():
            input_layer[1][0] += 1 / math.sqrt(food.mask.x - 100 -
                                               sheep[0].mask.height)
        else:
            input_layer[1][0] = 0

        for i in range(generation_size):
            if not sheep[i].alive:
                continue
                # increase fitness !!
            fitness[i] += step_value
            output = nets[i].feed_forward(input_layer)
            if output[0][0] > output[1][0] and sheep[i].vy == 0 and sheep[
                    i].mask.bottom == ground_y:
                sheep[i].vy = sheep_jump
        # move
        if not wolf.x_bounds():
            if random.randint(1, wolf_spawn_chance) == 2:
                wolf.move_to_x(width - 1)
        if not food.x_bounds():
            if random.randint(1, food_spawn_chance) == 2:
                food.surface_counter = 0
                food.move_to_x(width - 1)

        ground.move_by(food_speed, 0)
        if ground.mask.x < -800:
            ground.move_to(0, ground.mask.y)
        if food.x_bounds():
            food.move_by(food_speed, 0)
        if wolf.x_bounds():
            wolf.move_by(wolf_speed, 0)
        for i in sheep:
            if i.alive:
                i.move_by(0, i.vy)
                if i.mask.bottom < ground_y:
                    i.vy += g
            if i.mask.bottom > ground_y or (i.vy >= 0
                                            and i.mask.bottom == ground_y):
                i.mask.y = ground_y - i.mask.height
                i.vy = 0

        # hunger
        for i in sheep:
            i.hunger += hunger_value
            if i.hunger > max_hunger:
                i.kill()

        # events
        speed = events()
        if speed == -1:
            return fitness
        if speed == 1:
            delay = 0
        if speed == 2:
            delay = 30
        if speed == 3:
            delay = 500
        if speed == 4:
            delay -= 10
        if speed == 5:
            delay += 10

        if speed == 10:
            buttons[0].string = "START"
            fitness = []
            return fitness

        if speed == 13:
            if buttons[3].string == "Stop music":
                pygame.mixer.music.pause()
                buttons[3].string = "Start music"
            else:
                pygame.mixer.music.unpause()
                buttons[3].string = "Stop music"

        # animations
        if food.mask.right < 100 and food.surface_counter == 1:
            food.animate()
        if step % anime_speed == 0:
            wolf.animate()
            for i in sheep:
                i.animate()

        # rendering
        screen.fill(background_color)
        food.render(screen)
        for i in sheep:
            i.render(screen)
        wolf.render(screen)
        ground.render(screen)
        # text
        text[1].string = str(sheep_alive) + " out of " + str(
            generation_size) + " alive"
        text[0].render(black, 2 / 3 * width, 50, 20, screen)
        text[1].render(black, 2 / 3 * width, 100, 18, screen)
        render_buttons()
        pygame.display.flip()

        if sheep_alive <= 0:
            return fitness
    def cache_alarm_widget(self, updatetime=False):
        icon_size = (self.ui.display_size[0] * .05,
                     self.ui.display_size[1] * .05)
        icon_size_enable = (self.ui.display_size[0] * .1,
                            self.ui.display_size[1] * .1)
        if not updatetime:
            self.alarm_widget_cache = {}
            self.alarm_widget_cache["alarm_image_button"] = gui.Button(
                self.ui.image_cache["alarm-symbolic.png"], icon_size,
                self.switch_to_alarmset_screen)
            self.alarm_widget_cache[
                "alarm_image_button"].Position = self.ui.calculate_position(
                    (1, 4),
                    self.alarm_widget_cache["alarm_image_button"].Surface,
                    "top", "left")

            self.alarm_widget_cache[
                "alarm_image_disabled_button"] = gui.Button(
                    self.ui.image_cache["alarm-disabled-symbolic.png"],
                    icon_size, self.switch_to_alarmset_screen)
            self.alarm_widget_cache[
                "alarm_image_disabled_button"].Position = self.ui.calculate_position(
                    (1, 4), self.
                    alarm_widget_cache["alarm_image_disabled_button"].Surface,
                    "top", "left")

            self.alarm_widget_cache["alarm_snooze_button"] = gui.Button(
                self.ui.image_cache["alarm-snooze.png"], icon_size,
                self.alarm.turnOffSnooze)
            self.alarm_widget_cache[
                "alarm_snooze_button"].Position = self.ui.calculate_position(
                    (1, 4),
                    self.alarm_widget_cache["alarm_snooze_button"].Surface,
                    "top", "left")

        self.alarm_widget_cache["time"] = str(
            self.alarm.alarmtime.strftime(
                self.config.setting["timeformat"])).upper()
        alarmfont_size = self.ui.calculate_font_size(4.5)
        alarm_text = gui.Text(self.alarm_widget_cache["time"], alarmfont_size,
                              self.ui.boldfont_file)
        self.alarm_widget_cache["alarm_text_button"] = gui.Button(
            alarm_text.Surface, alarm_text.Surface.get_size(),
            self.switch_to_alarmset_screen)
        self.alarm_widget_cache["alarm_text_button"].Position = (
            self.alarm_widget_cache["alarm_image_button"].Position[0] +
            (icon_size[1] * 1.1) + 20,
            self.alarm_widget_cache["alarm_image_button"].Position[1] * 1.2)

        self.alarm_widget_cache["alarm_edit_enabled_button"] = gui.Button(
            self.ui.image_cache["alarm-edit-enabled.png"], icon_size_enable,
            self.disable_alarm)
        self.alarm_widget_cache[
            "alarm_edit_enabled_button"].Position = self.ui.calculate_position(
                (0, 0),
                self.alarm_widget_cache["alarm_edit_enabled_button"].Surface,
                "top", "center")

        self.alarm_widget_cache["alarm_edit_disabled_button"] = gui.Button(
            self.ui.image_cache["alarm-edit-disabled.png"], icon_size_enable,
            self.enable_alarm)
        self.alarm_widget_cache[
            "alarm_edit_disabled_button"].Position = self.ui.calculate_position(
                (0, 0),
                self.alarm_widget_cache["alarm_edit_disabled_button"].Surface,
                "top", "center")
Ejemplo n.º 24
0
    def __init__(self, container, rect, frame_rate, windows_controller):

        self.timing = 1  # la idea de timing es llevar una cuenta adentro, de los frames que fueron pasando
        gui.Window.__init__(self, container, rect, frame_rate,
                            windows_controller, "panel_window")

        self.set_bg_image(PANEL_BG_PATH, False)

        # Actions
        self.rect_action = pygame.Rect((560, 36), (310, 124))

        self.on_animation = False
        self.current_action = None
        self.current_animation = None

        self.action_progress_bar = None

        self.info_button_event = None
        self.image_info_blink = os.path.join(BASEPATH,
                                             "assets/layout/info.png")

        TEXT_COLOR = pygame.Color("#0f5e65")

        text = gui.Text(self.rect,
                        145,
                        22,
                        1,
                        _("Clima"),
                        18,
                        TEXT_COLOR,
                        type="normal",
                        alignment=gui.Text.ALIGN_CENTER,
                        bold=True,
                        italic=True)
        self.add_child(text)

        text = gui.Text(self.rect,
                        300,
                        22,
                        1,
                        _("Personal"),
                        18,
                        TEXT_COLOR,
                        type="normal",
                        alignment=gui.Text.ALIGN_CENTER,
                        bold=True,
                        italic=True)
        self.add_child(text)

        text = gui.Text(self.rect,
                        465,
                        22,
                        1,
                        _("Social"),
                        18,
                        TEXT_COLOR,
                        type="normal",
                        alignment=gui.Text.ALIGN_CENTER,
                        bold=True,
                        italic=True)
        self.add_child(text)

        text = gui.Text(self.rect,
                        705,
                        22,
                        1,
                        _(u"Acción"),
                        18,
                        TEXT_COLOR,
                        type="normal",
                        alignment=gui.Text.ALIGN_CENTER,
                        bold=True,
                        italic=True)
        self.add_child(text)

        ### Events ###
        # Personal
        self.personal_window = PersonalWindow(
            self.rect, pygame.Rect((224, 35), (142, 127)), 1,
            self.windows_controller)
        self.add_window(self.personal_window)

        # Social
        self.social_window = SocialWindow(self.rect,
                                          pygame.Rect((391, 35), (142, 127)),
                                          1, self.windows_controller)
        self.add_window(self.social_window)

        # Customization
        customization_button = gui.ImageButton(
            self.rect, pygame.Rect(953, 0, 1, 1), 1,
            os.path.join(BASEPATH, "assets/layout/customization.png"),
            self._cb_button_click_customization)
        customization_button.set_tooltip(_("Customization module"))
        self.add_button(customization_button)

        # Info
        self.info_button = gui.ImageButton(
            self.rect, pygame.Rect(885, 0, 1, 1), 1,
            os.path.join(BASEPATH, "assets/layout/info.png"),
            self._cb_button_click_info)
        self.add_button(self.info_button)
        self.info_button.visible = False
        self.info_button_blink_timeout = 0

        # Environment
        self.weather_widget = None
        self.set_weather()
Ejemplo n.º 25
0
                        0.0,
                        100.0,
                        callback=live_update)
Axis = gui.RadioButtons(interface, [('X', AXIS_X), ('Y', AXIS_Y),
                                    ('Z', AXIS_Z)],
                        AXIS_Y,
                        callback=live_update)
Angle = gui.FloatSlider(interface,
                        'Angle: ',
                        0.0,
                        0.0,
                        360.0 * 100,
                        callback=live_update)
LiveUpdate = gui.Toggle(interface, 'Live update', False)

Info = gui.Text(interface, 'No mesh selected', align='center')
GetMesh = gui.Button(interface, 'Get mesh', callback=get_selected)

Cancel = gui.Button(interface, 'Cancel', callback=cancel)
Apply = gui.Button(interface, 'Apply', callback=apply)
Update = gui.Button(interface, 'Update', callback=update)

rows = gui.Rows(interface, 10, 10, 250, 20)

rows.addrow(Info).addvspace('half')

rows.addrow(StartFrom)
rows.addrow(EndAt).addvspace('half')
rows.addrow(Axis)
rows.addrow(Angle).addvspace('half')
Ejemplo n.º 26
0
def _(text): return gui.Text(interface, text, align="right")

rows.addrow( [ (_("Inner radius: "), 0.4), InnerRadius ] ).addvspace("quarter")
    def __init__(self):
        """
        
        """
        events.EventEnabled.__init__(self)
        font = pygame.font.Font(None, 25)
        self.font = font
        # create gui elements
        self.buttons = []
        self.buttons.append(
            gui.Button(font, "randomize map", (50, 350), self.rand_map))
        self.buttons.append(
            gui.Button(font, "randomize regions", (200, 350), self.rand_lands))
        self.buttons.append(gui.Button(font, "exit", (500, 350), self.quit))
        self.buttons.append(
            gui.Button(font, "start", (600, 350), self.start_game))

        self.spinners = []
        self.texts = []
        # number of players
        xpos = 500
        ypos = 30
        self.texts.append(gui.Text("number of Players: ", font, (xpos, ypos)))
        spinner = gui.Spinner(font, (xpos + 180, ypos), False)
        for num in range(2, 9):
            spinner.add(gui.Item(str(num), num))
        spinner.register_observer(self)
        self.spinners.append(spinner)
        # player config
        self.items = []
        self.items.append(gui.Item("human", player.HUMAN))
        self.items.append(gui.Item("passive AI", player.AI_PASSIVE))
        self.items.append(gui.Item("expander AI", player.AI_DUMB))
        self.items.append(gui.Item("AI 1", player.AI_1))
        self.items.append(gui.Item("none", None))
        for num in range(2):
            ypos += 30
            spinner = gui.Spinner(font, (xpos + 100, ypos))
            if num == 2:
                self.items.insert(0, self.items.pop(-1))
            for item in self.items:
                spinner.add(item)
##            spinner.register_observer(self)
            self.spinners.append(spinner)
            self.texts.append(gui.text.Text("Player "+str(num+1)+": ", font, \
                                                                (xpos, ypos)))
        self.texts.append(gui.text.Text( \
            "Quick instructions", font, (10, 460)))
        self.texts.append(gui.text.Text( \
            "Right click to end turn, Left click to select regions", font, \
                                                                    (10, 500)))
        self.texts.append(gui.text.Text( \
            "You have to first select any of your regions with more than 1 dice on it, then you can attack an", font, (10, 530)))
        self.texts.append(gui.text.Text( \
             "adjacent region of different colour/player"        , font, (10, 560)))

        # data
        self._running = True
        self._preview = pygame.Surface((0, 0))
        self._preview.fill((255, 255, 255))

        # events
        self.reg_event_func(pygame.KEYDOWN, self.on_keydown)
        self.reg_event_func(pygame.QUIT, self.quit)
        for spinner in self.spinners:
            events.RootEventSource().add_listener(spinner)
        for button in self.buttons:
            events.RootEventSource().add_listener(button)
        self.setup_map()