Example #1
0
    def __init__(self, window, batch, space, level, height, width):
        self.space = space
        self.level = level
        status_text = pyglet.text.decode_attributed('''
Time: 0 sec \n
Points: 0 points \n
FPS: 00.00 FPS
''')
        self.status_doc = Document(status_text, height=height, width=width)
        status_frame = Frame(self.status_doc)
        inv_text = pyglet.text.decode_html("<h4>Inventory</h4>")
        inventory_header = Document(inv_text, width=width)
        self.inventory_container = VerticalContainer([])

        container = VerticalContainer(
            [inventory_header, self.inventory_container])
        self.inventory_frame = Frame(container)
        container = VerticalContainer([status_frame, self.inventory_frame])
        self.manager = Manager(container,
                               window=window,
                               batch=batch,
                               group=RenderingOrder.hud,
                               anchor=ANCHOR_TOP_RIGHT,
                               theme=theme,
                               is_movable=False)
        self.window = window
        self.window.push_handlers(on_draw=self.on_draw)
        self.tick = 0
Example #2
0
 def __init__(self, window, batch, space, level, height, width):
     self.space = space
     self.level = level
     self.height = height
     self.width = width
     progress_text = "Progress: ..."
     self.progress_doc = Document(progress_text, width=width / 2)
     objective_doc = Document(level.objective, width=width / 2)
     left_frame = Frame(VerticalContainer(
         [objective_doc, None, self.progress_doc]),
                        is_expandable=True)
     self.left_container = VerticalContainer([left_frame])
     victory_formula = level.victory_condition[0]
     info_frame = self.create_info_frame(victory_formula)
     self.info_container = VerticalContainer([info_frame])
     container = HorizontalContainer(
         [self.left_container, self.info_container])
     self.manager = Manager(container,
                            window=window,
                            batch=batch,
                            group=RenderingOrder.hud,
                            anchor=ANCHOR_BOTTOM_LEFT,
                            theme=theme,
                            is_movable=False)
     self.window = window
     self.window.push_handlers(on_draw=self.on_draw)
     self.tick = 0
     self.init_effects(space, level)
class EventLogController(pygsty.controllers.BaseController):
    def __init__(self):
        super().__init__()
        self.hud_batch = pyglet.graphics.Batch()
        self.doc = Document(self.last_message, width=800, height=100, is_fixed_size=True)
        self.frame = Frame(self.doc)
        self.manager = Manager(self.frame, window=pygsty.engine(), batch=self.hud_batch, theme=config.ui_theme)
        self.manager.set_position(0, 0)
        self._latest_event = None
        self._log = self.last_message

    def draw_hud(self):
        self.hud_batch.draw()

    @property
    def last_message(self):
        last_event = models.event_log.last_event()
        if last_event:
            return last_event.formatted_message()
        else:
            return ""

    def update(self, dt):
        if not models.event_log.last_event() is self._latest_event:
            self._log = self.last_message + self._log
            self.doc.set_text(self._log)
            self._latest_event = models.event_log.last_event()
Example #4
0
def create_folding_description(window, batch, heading, description, chapters=list()):
    """
        window - window
        batch - batch
        heading - heading of the widget
        description - description for the widget
        chapters - list of tuples (heading,text)
    """
    description_doc = pyglet.text.decode_attributed(description)

    layout = list()
    layout.append(SectionHeader(heading))
    layout.append(Document(description_doc, width=300))

    for chapter in chapters:
        heading, text = chapter
        text_doc = pyglet.text.decode_attributed(text)
        layout.append(FoldingSection(heading,
                      Document(text_doc, width=300),
                      is_open=False))

    content = Frame(Scrollable(VerticalContainer(layout, align=HALIGN_LEFT),height=400))

    Manager(content, window=window, batch=batch, group=RenderingOrder.gui,
           anchor=ANCHOR_BOTTOM_RIGHT, theme=theme, is_movable=False)
Example #5
0
class VerticalHUD():
    def __init__(self, window, batch, space, level, height, width):
        self.space = space
        self.level = level
        status_text = pyglet.text.decode_attributed('''
Time: 0 sec \n
Points: 0 points \n
FPS: 00.00 FPS
''')
        self.status_doc = Document(status_text, height=height, width=width)
        status_frame = Frame(self.status_doc)
        inv_text = pyglet.text.decode_html("<h4>Inventory</h4>")
        inventory_header = Document(inv_text, width=width)
        self.inventory_container = VerticalContainer([])

        container = VerticalContainer([inventory_header, self.inventory_container])
        self.inventory_frame = Frame(container)
        container = VerticalContainer([status_frame, self.inventory_frame])
        self.manager = Manager(container, window=window, batch=batch,
                group=RenderingOrder.hud, anchor=ANCHOR_TOP_RIGHT, theme=theme,
                is_movable=False)
        self.window = window
        self.window.push_handlers(on_draw=self.on_draw)
        self.tick = 0
        # Currently disabled
        #self.init_effects(space, level)

    def init_effects(self, space, level):
        pos = (self.inventory_frame.x,
               self.inventory_frame.y + self.inventory_frame.height / 2 - 50)
        self.inventory_effect = Effects.Inventory(space, pos, "Inventory",
                self.inventory_frame.width, self.inventory_frame.height + 100,
                ["H2O(l)", "CH4(g)", "NaCl(s)"], gui_container = self.inventory_container)

    def get_effects(self):
        return []
        #currently disabled
        #return [self.inventory_effect]

    def on_draw(self):
        self.tick += 1
        if self.tick > 30:
            return
        self.tick = 0
        self.update_status()

    def update_status(self):
        level_time = self.window.level.get_time()
        points = self.window.level.get_points()
        status_text = '''
Time: %d sec
Points: %d points
FPS: %.2f FPS
''' % (level_time, points, pyglet.clock.get_fps())
        self.status_doc.set_text(status_text)

    def delete(self):
        self.window.remove_handlers(on_draw = self.on_draw)
        self.manager.delete()
Example #6
0
 def __init__(self):
     g.postWindowOpened = True
     label1 = Label("Notifications", bold=True, color=g.loginFontColor)
     closeBtn = HighlightedButton("",
                                  on_release=self.delete,
                                  width=19,
                                  height=19,
                                  path='delete')
     self.postCont = []
     #self.menes = [{"name":"Hitler","hp":100,"level":1,"power":50,"defense":40,"speed":60,"sprite":'americanbear'},{"name":"Stalin","hp":100,"level":1,"power":50,"defense":40,"speed":60,"sprite":'lorslara'},{"name":"Ebin","hp":100,"level":1,"power":50,"defense":40,"speed":60,"sprite":'squadlider'},{"name":"Mao","hp":100,"level":1,"power":50,"defense":40,"speed":60,"sprite":'mongolbear'},{"name":"Uusi mene","hp":100,"level":1,"power":50,"defense":40,"speed":60,"sprite":'mongol'},{"name":"Hintti","hp":50,"level":15,"power":60,"defense":50,"speed":70,'sprite':'uusimene'}]
     #self.selectedMene=self.menes[0]["name"]
     for c in g.mails:
         label = Label(c["s"],
                       bold=True,
                       color=g.guiNameColor,
                       font_size=g.theme["font_size"] + 2)
         label1 = Label(c["t"][:16] + '...', color=g.whiteColor)
         deleteBtn = HighlightedButton("",
                                       on_release=self.deletemail,
                                       width=14,
                                       height=14,
                                       path='delete_alt',
                                       argument=c["id"])
         openBtn = HighlightedButton("",
                                     on_release=self.openmail,
                                     width=20,
                                     height=21,
                                     path='mailopen',
                                     argument=c["id"])
         self.postCont.append(
             VerticalContainer(content=[
                 HorizontalContainer(content=[openBtn, label, deleteBtn]),
                 label1
             ],
                               align=HALIGN_LEFT))
     self.vertCont = VerticalContainer(self.postCont, align=VALIGN_TOP)
     self.report = Document("",
                            is_fixed_size=True,
                            height=g.SCREEN_HEIGHT / 2,
                            width=g.SCREEN_WIDTH / 5)
     self.scrollable = Scrollable(content=self.vertCont,
                                  height=g.SCREEN_HEIGHT / 2,
                                  width=g.SCREEN_WIDTH / 5)
     total = HorizontalContainer(
         content=[self.scrollable, self.report, closeBtn], align=VALIGN_TOP)
     Manager.__init__(
         self,
         Frame(total),
         window=g.screen,
         batch=g.guiBatch,
         is_movable=False,
         anchor=ANCHOR_LEFT,
         offset=(40, int(g.SCREEN_HEIGHT * g.WINDOW_POSY_RELATIVE)),
         theme=g.theme)
     if len(self.postCont) > 0:
         self.openmail(self.postCont[0]._content[0]._content[0].arg)
Example #7
0
class ReportAnswerWindow(Manager):
    def __init__(self):
        g.reportAnswerWindowOpened = True
        self._reportid=-1
        getReport(True)
        label1=Label("Answer to Ticket",bold=True,color=g.loginFontColor)
        closeBtn =HighlightedButton("",on_release=self.delete,width=19,height=19,path='delete')
        horzCont = HorizontalContainer(content=[label1,None,closeBtn])
        #self.infoLabel = Label("No reports founds")
        self.report = Document("",is_fixed_size=True,width=g.SCREEN_WIDTH/3,height=g.SCREEN_HEIGHT/4)
        self.reportInput = TextInput(text="",padding=0,length=16,max_length=500,width=g.SCREEN_WIDTH/3,height=g.SCREEN_HEIGHT/4,multiline=True)
        deleteBtn = HighlightedButton("Delete",on_release=self.remove,width=120,height=30)
        sendBtn = HighlightedButton("Send",on_release=self.send,width=120,height=30)
        buttons = HorizontalContainer(content=[deleteBtn,Spacer(0,0),sendBtn])
        frame = Frame(VerticalContainer(content=[horzCont,self.report,self.reportInput,buttons]))
        
        Manager.__init__(self,
            frame,
            window=g.screen,
            batch=g.guiBatch,
            is_movable=False,
            theme=g.theme)
        frame.expand(g.SCREEN_WIDTH/2,height=g.SCREEN_HEIGHT/4*3)    
    def send(self,event):
        if self._reportid!=None and self._reportid!=-1:
            solveReport(self._reportid,self.reportInput.get_text())
            infoText("Ticket has been marked as solved.")
            self.clear(None)
            getReport(True)
        #print self.reportInput.get_text()
        #sendReport(self.reportInput.get_text())
        #print self.reportInput.get_text()
        #self.delete(None)
        
    def remove(self,event):
        solveReport(self._reportid,"",True)
        infoText("Ticket has been marked as solved.")
        self.clear(None)
        getReport(True)
        
    def clear(self,event):
        self._reportid=-1
        self.report.set_text("")
        self.reportInput.set_text("")
    def delete(self,event):
        g.chatFocus=False
        self.reportInput.focused = False
        super(Manager,self).delete()
        g.reportAnswerWindowOpened = False
 def __init__(self):
     super().__init__()
     self.hud_batch = pyglet.graphics.Batch()
     self.doc = Document(self.last_message, width=800, height=100, is_fixed_size=True)
     self.frame = Frame(self.doc)
     self.manager = Manager(self.frame, window=pygsty.engine(), batch=self.hud_batch, theme=config.ui_theme)
     self.manager.set_position(0, 0)
     self._latest_event = None
     self._log = self.last_message
Example #9
0
 def create_info_frame(self, formula):
     cml = CachedCml.getMolecule(formula)
     info_text = pyglet.text.decode_html(
         "<b>%s</b><br> %s" %
         (cml.property.get("Name", "Undefined"),
          cml.property.get("Description", "No Description Available")))
     info_doc = Document(info_text,
                         height=self.height,
                         width=self.width / 2,
                         is_fixed_size=True)
     info_frame = Frame(info_doc)
     return info_frame
Example #10
0
 def __init__(self):
     g.reportAnswerWindowOpened = True
     self._reportid=-1
     getReport(True)
     label1=Label("Answer to Ticket",bold=True,color=g.loginFontColor)
     closeBtn =HighlightedButton("",on_release=self.delete,width=19,height=19,path='delete')
     horzCont = HorizontalContainer(content=[label1,None,closeBtn])
     #self.infoLabel = Label("No reports founds")
     self.report = Document("",is_fixed_size=True,width=g.SCREEN_WIDTH/3,height=g.SCREEN_HEIGHT/4)
     self.reportInput = TextInput(text="",padding=0,length=16,max_length=500,width=g.SCREEN_WIDTH/3,height=g.SCREEN_HEIGHT/4,multiline=True)
     deleteBtn = HighlightedButton("Delete",on_release=self.remove,width=120,height=30)
     sendBtn = HighlightedButton("Send",on_release=self.send,width=120,height=30)
     buttons = HorizontalContainer(content=[deleteBtn,Spacer(0,0),sendBtn])
     frame = Frame(VerticalContainer(content=[horzCont,self.report,self.reportInput,buttons]))
     
     Manager.__init__(self,
         frame,
         window=g.screen,
         batch=g.guiBatch,
         is_movable=False,
         theme=g.theme)
     frame.expand(g.SCREEN_WIDTH/2,height=g.SCREEN_HEIGHT/4*3)    
Example #11
0
	def build_status_gui(self):
		self.status_box = Document(
			pyglet.text.document.UnformattedDocument(),
			width=self.window.width*0.9,
			height=self.window.height/4,
			is_fixed_size=True,
			)
		status_frame = Frame(self.status_box)
		self.status_gui_batch = pyglet.graphics.Batch()
		self.status_gui_manager = Manager(
			status_frame,
			window=self.window,
			theme=self.theme,
			batch=self.status_gui_batch,
			)
		self.status_gui_manager.set_position(
			(self.window.width - status_frame.width)/2,
			10,
			)
		self.status_gui_manager.is_movable = False
Example #12
0
    def __init__(self, client, name, title, dialog):

        self.client = client
        self.name = name
        title = Label(title, font_size=12)
        dialog = pyglet.text.decode_text(dialog)
        document = Document(dialog, width=300, height=100)

        accept_button = OneTimeButton(label="Ok, I'll do it!",
                                      on_release=self.accept)
        reject_button = OneTimeButton(label="No, Thanks.",
                                      on_release=self.reject)

        text_container = VerticalContainer([title, document])
        button_container = HorizontalContainer([accept_button, reject_button])
        quest_container = VerticalContainer([text_container, button_container])

        Manager.__init__(self,
                         Frame(quest_container, is_expandable=True),
                         window=self.client.window,
                         theme=UI_THEME,
                         is_movable=True)
Example #13
0
 def __init__(self, window, batch, space, level, height, width):
     self.space = space
     self.level = level
     self.height = height
     self.width = width
     progress_text = "Progress: ..."
     self.progress_doc = Document(progress_text, width = width/2)
     objective_doc = Document(level.objective, width = width/2)
     left_frame = Frame(VerticalContainer([objective_doc, None,
         self.progress_doc]), is_expandable = True)
     self.left_container = VerticalContainer([left_frame])
     victory_formula = level.victory_condition[0]
     info_frame = self.create_info_frame(victory_formula)
     self.info_container = VerticalContainer([info_frame])
     container = HorizontalContainer([self.left_container, self.info_container])
     self.manager = Manager(container, window=window, batch=batch,
             group=RenderingOrder.hud, anchor=ANCHOR_BOTTOM_LEFT,
             theme=theme, is_movable=False)
     self.window = window
     self.window.push_handlers(on_draw=self.on_draw)
     self.tick = 0
     self.init_effects(space, level)
Example #14
0
    def __init__(self, window, batch, space, level, height, width):
        self.space = space
        self.level = level
        status_text = pyglet.text.decode_attributed('''
Time: 0 sec \n
Points: 0 points \n
FPS: 00.00 FPS
''')
        self.status_doc = Document(status_text, height=height, width=width)
        status_frame = Frame(self.status_doc)
        inv_text = pyglet.text.decode_html("<h4>Inventory</h4>")
        inventory_header = Document(inv_text, width=width)
        self.inventory_container = VerticalContainer([])

        container = VerticalContainer([inventory_header, self.inventory_container])
        self.inventory_frame = Frame(container)
        container = VerticalContainer([status_frame, self.inventory_frame])
        self.manager = Manager(container, window=window, batch=batch,
                group=RenderingOrder.hud, anchor=ANCHOR_TOP_RIGHT, theme=theme,
                is_movable=False)
        self.window = window
        self.window.push_handlers(on_draw=self.on_draw)
        self.tick = 0
Example #15
0
class HorizontalHUD:
    def __init__(self, window, batch, space, level, height, width):
        self.space = space
        self.level = level
        self.height = height
        self.width = width
        progress_text = "Progress: ..."
        self.progress_doc = Document(progress_text, width = width/2)
        objective_doc = Document(level.objective, width = width/2)
        left_frame = Frame(VerticalContainer([objective_doc, None,
            self.progress_doc]), is_expandable = True)
        self.left_container = VerticalContainer([left_frame])
        victory_formula = level.victory_condition[0]
        info_frame = self.create_info_frame(victory_formula)
        self.info_container = VerticalContainer([info_frame])
        container = HorizontalContainer([self.left_container, self.info_container])
        self.manager = Manager(container, window=window, batch=batch,
                group=RenderingOrder.hud, anchor=ANCHOR_BOTTOM_LEFT,
                theme=theme, is_movable=False)
        self.window = window
        self.window.push_handlers(on_draw=self.on_draw)
        self.tick = 0
        self.init_effects(space, level)

    def init_effects(self, space, level):
        pos = (self.left_container.x + self.left_container.width / 2,
               self.left_container.y + self.left_container.height / 2 - 50)
        self.victory = Effects.VictoryInventory(space, pos, "Victory Inventory",
                self.left_container.width, self.left_container.height + 100,
                level.victory_condition)

    def get_effects(self):
        return [self.victory]

    def update_info_text(self, formula):
        info_frame = self.create_info_frame(formula)
        for content in self.info_container.content:
            self.info_container.remove(content)
        self.info_container.add(info_frame)

    def create_info_frame(self, formula):
        cml = CachedCml.getMolecule(formula)
        info_text = pyglet.text.decode_html("<b>%s</b><br> %s" %
                ( cml.property.get("Name", "Undefined"),
                  cml.property.get("Description", "No Description Available")
                ))
        info_doc = Document(info_text, height=self.height, width=self.width/2,
                is_fixed_size = True)
        info_frame = Frame(info_doc)
        return info_frame


    def on_draw(self):
        self.tick += 1
        if self.tick > 30:
            return
        self.tick = 0
        self.update_progress()

    def update_progress(self):
        progress_text = self.victory.progress_text()
        self.progress_doc.set_text("Progress: " + progress_text)

    def delete(self):
        self.window.remove_handlers(on_draw = self.on_draw)
        self.manager.delete()
Example #16
0
                },
                "padding": [0, 0, 0, 0]
            }
        }
    },
    resources_path='../theme')

document = pyglet.text.decode_attributed('''
In {bold True}Pyglet-gui{bold False} you can use
{underline (255, 255, 255, 255)}pyglet{underline None}'s documents in a
scrollable window.

You can also {font_name "Courier New"}change fonts{font_name Lucia Grande},
{italic True}italicize your text{italic False} and use all features of Pyglet's document.
''')
so = Document(document, width=300, height=50)


def f(y):
    document = "Hola mundo"
    so.set_text(document + so.get_text())


# Set up a Manager
Manager(so, window=window, batch=batch, theme=theme)
Manager(VerticalContainer([Button(label="Persistent button", on_press=f)]),
        window=window,
        batch=batch,
        theme=theme)

pyglet.app.run()
Example #17
0
    def __init__(self, name, text, actionType=0):
        g.npcTalkWindowOpened = True
        g.cursorRound = -1
        self.name = name
        sendTalkToNpc(name)
        if actionType == NPC_ACTIONTYPE_SHOP:
            namecolor = g.npcColor
            postcolor = g.whiteColor
            path = 'frame_npc_talk_shop'
        else:
            namecolor = g.npcColorLighter
            postcolor = g.postColor
            path = 'frame_npc_talk'
        label1 = Label(name, color=namecolor, bold=True)
        closeBtn = HighlightedButton("",
                                     on_release=self.delete,
                                     width=19,
                                     height=19,
                                     path='delete')
        horzCont = HorizontalContainer(content=[label1, None, closeBtn])
        self.yourmoney = None
        w1 = int(300 * (g.SCREEN_WIDTH / 1920.)) + 50
        h1 = int(500 * (g.SCREEN_HEIGHT / 1080.))
        textArr = text.split('\n\n')
        realText = ""

        for c in textArr:
            if c[0] == '>':
                realText += '{color ' + str(
                    g.greentextColor) + '}' + c + '\n\n'
            else:
                realText += '{color ' + str(postcolor) + '}' + c + '\n\n'
        realText = realText[:-2]
        document = pyglet.text.decode_attributed(realText)
        self.textArea = Document(document,
                                 width=w1,
                                 height=h1,
                                 background=False,
                                 font_size=g.chatTheme["font_size"],
                                 font_name=g.chatTheme["font"])
        if actionType == NPC_ACTIONTYPE_HEAL:
            healButton = HighlightedButton("Heal my menes",
                                           on_release=self.healButton)
            okButton = HighlightedButton("Goodbye", on_release=self.delete)
            cont = VerticalContainer(content=[
                horzCont, self.textArea,
                HorizontalContainer([healButton, okButton])
            ])
        elif actionType == NPC_ACTIONTYPE_SHOP:
            #TODO: When more items, do a loop that adds then dynamically instead of statically like this
            disabled = False
            if Items["es"]["cost"] > g.moneyAmount:
                #    print "TAPAHTU"
                disabled = True
            self.esButton = AbilityButton(
                width=50,
                height=50,
                argument=Items["es"]["id"],
                disabled=disabled,
                on_press=buyItem,
                texture=g.gameEngine.resManager.items[Items["es"]["sprite"]],
                outline='abilityoutline',
                hover=onHover,
                hoveringType=HOVERING_ITEM,
                arguments={
                    'name': Items["es"]["name"],
                    'info': Items["es"]["info"],
                    "args": ()
                })
            nameLabel = Label(Items["es"]["name"], color=g.npcColor)
            esCost = Items["es"]["cost"] / 100.0
            costLabel = Label("%.2f" % esCost)
            euroPicture = Graphic("euro")
            costCont = HorizontalContainer(content=[costLabel, euroPicture])
            infoCont = VerticalContainer(
                content=[Spacer(), nameLabel, costCont], align=HALIGN_LEFT)
            itemCont = HorizontalContainer(content=[self.esButton, infoCont])
            moneyTmp = g.moneyAmount / 100.0
            self.yourmoney = Label('%.2f' % moneyTmp)
            yourmoneyCont = HorizontalContainer(
                content=[self.yourmoney, Graphic("euro")])
            self.yourES = Label('%s' % g.esAmount)
            yourESCont = HorizontalContainer(
                content=[self.yourES, Graphic("es_icon")])
            okButton = HighlightedButton("Goodbye", on_release=self.delete)
            cont = VerticalContainer(content=[
                horzCont, self.textArea, itemCont,
                Spacer(0, 20),
                HorizontalContainer(content=[
                    Spacer(),
                    VerticalContainer(content=[yourmoneyCont, yourESCont],
                                      align=HALIGN_RIGHT)
                ]), okButton
            ])
        else:
            okButton = HighlightedButton("Goodbye", on_release=self.delete)
            cont = VerticalContainer(
                content=[horzCont, self.textArea, okButton])
        frame = Frame(cont, path=path)
        Manager.__init__(
            self,
            frame,
            window=g.screen,
            batch=g.guiBatch,
            is_movable=False,
            anchor=ANCHOR_LEFT,
            offset=(40, int(g.SCREEN_HEIGHT * g.WINDOW_POSY_RELATIVE)),
            theme=g.theme)
            }
        },
        "frame": {
            "image": {
                "source": "panel.png",
                "frame": [8, 8, 16, 16],
                "padding": [16, 16, 8, 8]
            }
        }
    },
    resources_path='../theme/')

content = Frame(
    Scrollable(VerticalContainer([
        SectionHeader("Folding"),
        Document("Click on the section headers below to open them.",
                 width=300),
        FoldingSection("Folding 1",
                       Document("This is the first folding.", width=300)),
        FoldingSection("Folding 2",
                       Document("This is the second folding.", width=300),
                       is_open=False),
        FoldingSection("Folding 3",
                       Document("This is the third folding.", width=300),
                       is_open=False),
    ],
                                 align=HALIGN_LEFT),
               height=400))

Manager(content, window=window, batch=batch, anchor=ANCHOR_CENTER, theme=theme)

pyglet.app.run()
class ChessGUI(pyglet.window.Window):
    chessboard = pyglet.resource.image('resources/chessboard.png')
    chessboardInv = pyglet.resource.image('resources/chessboardflipped.png')
    validImg = pyglet.resource.image('resources/validmove.png')
    promoImg = pyglet.resource.image('resources/promotion.png')
    hoverImg = pyglet.resource.image('resources/hoversquare.png')
    spriteimage = pyglet.resource.image('resources/spritesheet.png')
    dangerImg = pyglet.resource.image('resources/danger.png')

    backgroundImg = pyglet.resource.image('resources/Background.png')

    spritesheet = pyglet.image.ImageGrid(spriteimage, 2, 6)
    BLACK_KING, BLACK_QUEEN, BLACK_BISHOP, BLACK_KNIGHT, BLACK_ROOK, BLACK_PAWN, WHITE_KING, WHITE_QUEEN, WHITE_BISHOP, \
    WHITE_KNIGHT, WHITE_ROOK, WHITE_PAWN = range(12)

    dictPieces = {
        "NR": spritesheet[BLACK_KING],
        "ND": spritesheet[BLACK_QUEEN],
        "NA": spritesheet[BLACK_BISHOP],
        "NC": spritesheet[BLACK_KNIGHT],
        "NT": spritesheet[BLACK_ROOK],
        "NP": spritesheet[BLACK_PAWN],
        "BR": spritesheet[WHITE_KING],
        "BD": spritesheet[WHITE_QUEEN],
        "BA": spritesheet[WHITE_BISHOP],
        "BC": spritesheet[WHITE_KNIGHT],
        "BT": spritesheet[WHITE_ROOK],
        "BP": spritesheet[WHITE_PAWN]
    }

    # ["BTf1", "NTe7", "BAd5", "BRd6", "NRd8"]
    colPositions = {
        "a": 0,
        "b": 1,
        "c": 2,
        "d": 3,
        "e": 4,
        "f": 5,
        "g": 6,
        "h": 7
    }
    colPositionsInv = {
        "a": 0,
        "b": 1,
        "c": 2,
        "d": 3,
        "e": 4,
        "f": 5,
        "g": 6,
        "h": 7
    }
    stdChesBoard = [
        "NTa8",
        "NCb8",
        "NAc8",
        "NDd8",
        "NRe8",
        "NAf8",
        "NCg8",
        "NTh8",
        "NPa7",
        "NPb7",
        "NPc7",
        "NPd7",
        "NPe7",
        "NPf7",
        "NPg7",
        "NPh7",
        "BPa2",
        "BPb2",
        "BPc2",
        "BPd2",
        "BPe2",
        "BPf2",
        "BPg2",
        "BPh2",
        "BTa1",
        "BCb1",
        "BAc1",
        "BDd1",
        "BRe1",
        "BAf1",
        "BCg1",
        "BTh1",
    ]

    spanishToEnglish = {
        "A": "B",
        "T": "R",
        "D": "Q",
        "R": "K",
        "P": "P",
        "C": "N"
    }
    englishToSpanish = {
        "B": "A",
        "R": "T",
        "Q": "D",
        "K": "R",
        "P": "P",
        "N": "C"
    }
    ia_mode = True
    blackKing = None
    whiteKing = None
    promotion = False
    promotionMov = []
    promotedPiece = ""
    movement = [0, 0]
    animation = True

    def __init__(self, textPositions, castlingRigths, starts, CPUPlaysWhite,
                 pwindow, batch):
        super(ChessGUI,
              self).__init__(900,
                             600,
                             resizable=False,
                             caption='Chess',
                             config=pyglet.gl.Config(double_buffer=True),
                             vsync=False)
        pyglet.clock.schedule_interval(self.updatePosition, 1 / 60)
        self.board_imgs = [[None for _ in range(8)] for _ in range(8)]
        self.board = []
        self.window = pwindow
        self.batch = batch

        self.CPUPlaysWhite = CPUPlaysWhite
        self.castlingRigths = castlingRigths
        self.starts = starts

        if (starts == "b"):
            self.turn = "N"
        else:
            self.turn = "B"
        if CPUPlaysWhite:
            self.playerTurn = "N"
        else:
            self.playerTurn = "B"

        self.selectedPiece = []
        self.board_normal = pyglet.sprite.Sprite(self.chessboard)
        self.board_flipped = pyglet.sprite.Sprite(self.chessboardInv)
        self.hoverSprite = pyglet.sprite.Sprite(self.hoverImg)
        self.danger = pyglet.sprite.Sprite(self.dangerImg)
        self.piece_held = None
        self.textPositions = textPositions

        self.createBoard(textPositions)
        self.inFunction = False
        self.draws = 0

        self.game = Game(
            self.stdNotationToChess(self.board) + " " + starts + " " +
            castlingRigths + " - 0 1")
        self.wQueen = pyglet.sprite.Sprite(self.spritesheet[7], 131.25, 225)
        self.wRook = pyglet.sprite.Sprite(self.spritesheet[10], 218.75, 225)
        self.wBishop = pyglet.sprite.Sprite(self.spritesheet[8], 306.25, 225)
        self.wKnight = pyglet.sprite.Sprite(self.spritesheet[9], 393.75, 225)
        self.bQueen = pyglet.sprite.Sprite(self.spritesheet[1], 131.25, 225)
        self.bRook = pyglet.sprite.Sprite(self.spritesheet[4], 218.75, 225)
        self.bBishop = pyglet.sprite.Sprite(self.spritesheet[2], 306.25, 225)
        self.bKnight = pyglet.sprite.Sprite(self.spritesheet[3], 393.75, 225)
        self.background = pyglet.sprite.Sprite(self.backgroundImg)
        self.document = Document(pyglet.text.decode_attributed("\n" * 23),
                                 width=250,
                                 height=400)
        self.manager()
        self.numero = 0
        self.announcedFinal = False
        self.instanteInicial = None
        self.instanteFinal = None
        self.lineCont = 1
        self.annotations = ""

    def manager(self):
        Manager(Label(""), window=self, batch=self.batch, theme=getTheme())
        Manager(Frame(self.document),
                window=self,
                batch=self.batch,
                theme=getTheme(),
                anchor=ANCHOR_TOP_RIGHT,
                offset=(-10, -75),
                is_movable=False)
        Manager(HorizontalContainer([
            OneTimeButton(label="Guardar", on_release=self.saveGame),
            OneTimeButton(label="Volver", on_release=self.onclose)
        ]),
                window=self,
                batch=self.batch,
                theme=getTheme(),
                anchor=ANCHOR_BOTTOM_RIGHT,
                offset=(-50, 15),
                is_movable=False)
        self.document.set_text("")

    def updateDocument(self, y):
        self.numero += 1
        self.document.set_text(self.document.get_text() + "Hola Mundos " +
                               str(self.numero) + "\n")
        self.popupMessage("Partida guardada correctamente")

    def popupMessage(self, text):
        PopupMessage(text=text,
                     window=self,
                     batch=self.batch,
                     theme=getPopUpMenssageTheme())

    def saveGame(self, y):
        result = "{\n\tPosicionInicial: " + str(self.textPositions) + ",\n"
        result += "\tDesarrolloDeLaPartida: \"" + self.annotations + "\",\n"
        date = datetime.now().strftime("%d/%m/%Y")
        fileDate = datetime.now().strftime("%d-%m-%Y")
        result += "\tfecha: \"" + date + "\",\n"
        strTiempo = "null"
        if not (self.instanteInicial == None or self.instanteFinal == None):
            tiempo = (self.instanteFinal - self.instanteInicial)
            strTiempo = str(tiempo)
        result += "\ttiempo: \"" + strTiempo + "\" \n}"
        fileroute = easygui.filesavebox(default="BotFinalesDeAjedrez " +
                                        fileDate + ".txt",
                                        msg="hola",
                                        title="Seleccione el destino",
                                        filetypes="txt")
        if (fileroute != None):
            f = open(fileroute, "w")
            f.write(result)
            f.close()

    def stdNotationToChess(self, boardGUI):
        count = 0
        result = ""
        row = ""
        for x in range(8):
            if (result != ""):
                result += "/"
            for y in range(8):
                if boardGUI[x][y] == "":
                    count += 1
                else:
                    charName = self.spanishToEnglish[boardGUI[x][y][1]]
                    if (boardGUI[x][y][0] == "N"):
                        charName = charName.lower()
                    if count != 0:
                        row += str(count) + charName
                        count = 0
                    else:
                        row += charName
            if count != 0:
                row += str(count)
                count = 0
            result += row[::-1]
            row = ""
        if (not self.CPUPlaysWhite):
            result = result[::-1]
        return result

    def endOfTurn(self):
        if (self.turn == "B"):
            self.turn = "N"
        else:
            self.turn = "B"

    def moveOfAI(self):
        var = str(self.game.suggestedMove(self.starts))
        xi = self.colPositions[var[0]]
        yi = int(var[1]) - 1
        xf = self.colPositions[var[2]]
        yf = int(var[3]) - 1
        piece = ""
        if (len(var) == 5):
            piece = self.englishToSpanish[var[4].upper()]

        xi, yi, xf, yf = self.cordinatesComplement(xi, yi, xf, yf)
        self.pieceMove(xi, yi, xf, yf, piece)

    def ifIsFlipped(self, x):
        if (self.CPUPlaysWhite):
            return (7 - x)
        return x

    def promote(self):
        self.promoImg.blit(100, 200)
        if self.turn == "N":
            self.bQueen.draw()
            self.bRook.draw()
            self.bBishop.draw()
            self.bKnight.draw()
        else:
            self.wQueen.draw()
            self.wRook.draw()
            self.wBishop.draw()
            self.wKnight.draw()

    def createBoard(self, textPositions) -> list:

        self.board = [["" for i in range(8)] for i in range(8)]
        if textPositions:
            for i in textPositions:
                y = ord(i[2]) - 97
                x = int(i[3]) - 1
                p = i[0] + i[1]

                self.board[self.ifIsFlipped(x)][self.ifIsFlipped(y)] = p

                self.board_imgs[self.ifIsFlipped(x)][self.ifIsFlipped(
                    y)] = pyglet.sprite.Sprite(self.dictPieces[p])
                if (p == "BR"):
                    self.whiteKing = self.board_imgs[self.ifIsFlipped(x)][
                        self.ifIsFlipped(y)]
                elif (p == "NR"):
                    self.blackKing = self.board_imgs[self.ifIsFlipped(x)][
                        self.ifIsFlipped(y)]

    def onclose(self, y):
        self.window.set_visible(True)
        self.window.deleteManagers()
        self.window.manager()
        self.close()

    def on_draw(self):
        self.clear()
        self.background.draw()
        if (self.CPUPlaysWhite):
            self.board_flipped.draw()
        else:
            self.board_normal.draw()
        if (self.game.isCheck()):
            if (self.turn == "B"):
                self.danger.x = self.whiteKing.x
                self.danger.y = self.whiteKing.y
            else:
                self.danger.x = self.blackKing.x
                self.danger.y = self.blackKing.y
            self.danger.draw()

        if self.selectedPiece != []:
            self.hoverSprite.x = (self.selectedPiece[1] // 75) * 75
            self.hoverSprite.y = (self.selectedPiece[2] // 75) * 75
            self.hoverSprite.draw()

        for x, y in itertools.product(range(8), repeat=2):
            if self.board[y][x] != "":
                piece = self.board_imgs[y][x]

                if piece != self.piece_held:
                    piece.x = x * 75
                    piece.y = y * 75
                    piece.draw()
        if (self.piece_held != None):
            self.piece_held.draw()

        self.announceFinal()

        if (self.promotion):
            self.promote()

        if (self.draws < 60):
            self.draws += 1
        self.batch.draw()

    def announceFinal(self):
        if (self.instanteInicial == None):
            self.instanteInicial = datetime.now()
        if (self.game.isCheckMate() and not self.announcedFinal
                and self.draws == 60):
            self.announcedFinal = True
            self.instanteFinal = datetime.now()
            if (self.turn == "B"):
                self.popupMessage("Jaque mate de las piezas negras")
            if (self.turn == "N"):
                self.popupMessage("Jaque mate de las piezas blancas")
        if (self.game.isStalemate() and not self.announcedFinal
                and self.draws == 60):
            self.announcedFinal = True
            self.instanteFinal = datetime.now()
            self.popupMessage("Empate")

    def setPiece(self, xi, yi, piece):
        self.board[yi][xi] = self.board[yi][xi][0] + piece
        ximg = self.board_imgs[yi][xi].x
        yimg = self.board_imgs[yi][xi].y
        self.board_imgs[yi][xi] = pyglet.sprite.Sprite(
            self.dictPieces[self.board[yi][xi]])
        self.board_imgs[yi][xi].x = ximg
        self.board_imgs[yi][xi].y = yimg

    def cordinatesComplement(self, xi, yi, xf, yf):
        xi = self.ifIsFlipped(xi)
        yi = self.ifIsFlipped(yi)
        xf = self.ifIsFlipped(xf)
        yf = self.ifIsFlipped(yf)
        return xi, yi, xf, yf

    def pieceMove(self, xi, yi, xf, yf, piece=""):
        pieceEng = ""
        if (piece != ""):
            self.setPiece(xi, yi, piece)
            pieceEng = self.spanishToEnglish[piece].lower()
        xi, yi, xf, yf = self.cordinatesComplement(xi, yi, xf, yf)
        fromSquare = chr(xi + 97) + str(1 + yi)
        toSquare = chr(xf + 97) + str(1 + yf)
        result = self.game.doAMove(fromSquare + toSquare + pieceEng)
        xi, yi, xf, yf = self.cordinatesComplement(xi, yi, xf, yf)
        if (result[0] != ""):
            self.changePosition(xi, yi, xf, yf)
            if (result[0] == "PassantMove"):
                self.doPassant(xi, yi, xf, yf)

            elif (result[0] == "kingside" or result[0] == "queenside"):
                self.doCastling(result[0], yi, yf)
            self.anotateMove(result[1])
            self.endOfTurn()

    def anotateMove(self, move):
        result = ""
        if (self.turn == "N"):
            if (self.lineCont == 1 and self.annotations == ""):
                result += "1...  " + move + " "
            else:
                result += "  " + move + " "
            self.lineCont += 1

        elif (self.turn == "B"):
            result += str(self.lineCont) + ". " + move
        self.annotations += result

        newLine = "\n"
        if (self.turn == "N"):
            newLine = ""
        self.document.set_text(self.document.get_text() + newLine + result)

    def changePosition(self, xi, yi, xf, yf):
        self.board_imgs[yf][xf] = self.board_imgs[yi][xi]
        self.board_imgs[yi][xi] = None
        self.board[yf][xf] = self.board[yi][xi]
        self.board[yi][xi] = ""
        if self.animation:
            self.piece_held = self.board_imgs[yf][xf]
            xmovement = xf * 75 - xi * 75
            ymovement = yf * 75 - yi * 75
            self.movement = [xmovement, ymovement]

    def updatePosition(self, dt):
        if (len(self.movement) == 2 and self.piece_held != None):
            stepSize = 10
            if (self.movement[1] > 0):
                if (self.movement[1] <= stepSize):
                    self.piece_held.y += self.movement[1]
                    self.movement[1] = 0
                else:
                    self.piece_held.y += stepSize
                    self.movement[1] -= stepSize
            if (self.movement[1] < 0):
                if (self.movement[1] >= -stepSize):
                    self.piece_held.y += self.movement[1]
                    self.movement[1] = 0
                else:
                    self.piece_held.y -= stepSize
                    self.movement[1] += stepSize
            if (self.movement[0] > 0):
                if (self.movement[0] <= stepSize):
                    self.piece_held.x += self.movement[0]
                    self.movement[0] = 0
                else:
                    self.piece_held.x += stepSize
                    self.movement[0] -= stepSize
            if (self.movement[0] < 0):
                if (self.movement[0] >= -stepSize):
                    self.piece_held.x += self.movement[0]
                    self.movement[0] = 0
                else:
                    self.piece_held.x -= stepSize
                    self.movement[0] += stepSize

            if (self.movement[0] == 0 and self.movement[1] == 0):
                self.piece_held = None
                self.movement = []
                self.draws = 45
        if (self.turn != self.playerTurn and self.ia_mode
                and not self.game.isCheckMate()
                and not self.game.isStalemate() and self.piece_held == None
                and not self.inFunction and self.draws == 60):
            self.inFunction = True
            self.moveOfAI()
            self.turn = self.playerTurn
            self.inFunction = False

    def doCastling(self, side, yi, yf):
        if (side == "kingside"):
            self.changePosition(7, yi, 5, yf)
        if (side == "queenside"):
            self.changePosition(0, yi, 3, yf)

    def doPassant(self, xi, yi, xf, yf):
        if (self.turn == "B"):
            self.board_imgs[yf - 1][xf] = None
            self.board[yf - 1][xf] = ""
        if (self.turn == "N"):
            self.board_imgs[yf + 1][xf] = None
            self.board[yf + 1][xf] = ""

    def isPromote(self, yf):
        result = False
        if (((self.selectedPiece[0] == "BP" and not self.CPUPlaysWhite) or
             (self.selectedPiece[0] == "NP" and self.CPUPlaysWhite))
                and self.selectedPiece[2] // 75 == 6 and yf == 7):
            result = True
        elif (((self.selectedPiece[0] == "NP" and not self.CPUPlaysWhite) or
               (self.selectedPiece[0] == "BP" and self.CPUPlaysWhite))
              and self.selectedPiece[2] // 75 == 1 and yf == 0):
            result = True
        return result

    def on_mouse_press(self, x, y, button, modifiers):
        if (self.playerTurn == self.turn or not self.ia_mode
            ) and not self.game.isCheckMate() and x <= 600 and y <= 600:
            if (not self.promotion):
                if self.selectedPiece != []:
                    if (((self.board[y // 75][x // 75] == ""))
                            or (self.board[y // 75][x // 75] != "") and
                        (self.board[y // 75][x // 75][0] != self.turn)):
                        xi = self.selectedPiece[1] // 75
                        yi = self.selectedPiece[2] // 75
                        xf = x // 75
                        yf = y // 75
                        if (self.isPromote(yf)):
                            self.promotion = True
                            self.promotionMov = [xi, yi, xf, yf]
                        else:
                            self.pieceMove(xi, yi, xf, yf)

                        self.selectedPiece = []

                if (self.board[y // 75][x // 75] !=
                        "") and (self.board[y // 75][x // 75][0] == self.turn):
                    self.selectedPiece = [self.board[y // 75][x // 75]
                                          ] + [x, y]
            else:
                if 225 < y < 300:
                    xi = self.promotionMov[0]
                    yi = self.promotionMov[1]
                    xf = self.promotionMov[2]
                    yf = self.promotionMov[3]
                    piece = ""
                    if 131.25 < x < 206.25:  # queen
                        piece = "D"
                    elif 218.75 < x < 293.75:  # rook
                        piece = "T"
                    elif 306.25 < x < 381.25:  # bishop
                        piece = "A"
                    elif 393.75 < x < 468.75:  # knight
                        piece = "C"
                    self.pieceMove(xi, yi, xf, yf, piece)
                    self.promotion = False
                    self.promotionFinalPos = []
    def __init__(self, textPositions, castlingRigths, starts, CPUPlaysWhite,
                 pwindow, batch):
        super(ChessGUI,
              self).__init__(900,
                             600,
                             resizable=False,
                             caption='Chess',
                             config=pyglet.gl.Config(double_buffer=True),
                             vsync=False)
        pyglet.clock.schedule_interval(self.updatePosition, 1 / 60)
        self.board_imgs = [[None for _ in range(8)] for _ in range(8)]
        self.board = []
        self.window = pwindow
        self.batch = batch

        self.CPUPlaysWhite = CPUPlaysWhite
        self.castlingRigths = castlingRigths
        self.starts = starts

        if (starts == "b"):
            self.turn = "N"
        else:
            self.turn = "B"
        if CPUPlaysWhite:
            self.playerTurn = "N"
        else:
            self.playerTurn = "B"

        self.selectedPiece = []
        self.board_normal = pyglet.sprite.Sprite(self.chessboard)
        self.board_flipped = pyglet.sprite.Sprite(self.chessboardInv)
        self.hoverSprite = pyglet.sprite.Sprite(self.hoverImg)
        self.danger = pyglet.sprite.Sprite(self.dangerImg)
        self.piece_held = None
        self.textPositions = textPositions

        self.createBoard(textPositions)
        self.inFunction = False
        self.draws = 0

        self.game = Game(
            self.stdNotationToChess(self.board) + " " + starts + " " +
            castlingRigths + " - 0 1")
        self.wQueen = pyglet.sprite.Sprite(self.spritesheet[7], 131.25, 225)
        self.wRook = pyglet.sprite.Sprite(self.spritesheet[10], 218.75, 225)
        self.wBishop = pyglet.sprite.Sprite(self.spritesheet[8], 306.25, 225)
        self.wKnight = pyglet.sprite.Sprite(self.spritesheet[9], 393.75, 225)
        self.bQueen = pyglet.sprite.Sprite(self.spritesheet[1], 131.25, 225)
        self.bRook = pyglet.sprite.Sprite(self.spritesheet[4], 218.75, 225)
        self.bBishop = pyglet.sprite.Sprite(self.spritesheet[2], 306.25, 225)
        self.bKnight = pyglet.sprite.Sprite(self.spritesheet[3], 393.75, 225)
        self.background = pyglet.sprite.Sprite(self.backgroundImg)
        self.document = Document(pyglet.text.decode_attributed("\n" * 23),
                                 width=250,
                                 height=400)
        self.manager()
        self.numero = 0
        self.announcedFinal = False
        self.instanteInicial = None
        self.instanteFinal = None
        self.lineCont = 1
        self.annotations = ""
Example #21
0
                },
                "offset": [0, 0]
            },
            "bar": {
                "image": {
                    "source": "vscrollbar.png",
                    "region": [0, 64, 16, 16]
                },
                "padding": [0, 0, 0, 0]
            }
        }
    },
    resources_path='../theme')

document = pyglet.text.decode_attributed('''
In {bold True}Pyglet-gui{bold False} you can use
{underline (255, 255, 255, 255)}pyglet{underline None}'s documents in a
scrollable window.

You can also {font_name "Courier New"}change fonts{font_name Lucia Grande},
{italic True}italicize your text{italic False} and use all features of Pyglet's document.
''')

# Set up a Manager
Manager(Document(document, width=300, height=50),
        window=window,
        batch=batch,
        theme=theme)

pyglet.app.run()
Example #22
0
    def __init__(self):
        w1 = int(350 * (g.SCREEN_WIDTH / 1920.))
        h1 = int(300 * (g.SCREEN_HEIGHT / 1080.))
        if w1 > 300:
            g.chatTheme["font_size"] = 11
            g.theme["font_size"] = 11
            g.theme["button"]["font_size"] = 11
        elif w1 > 250:
            g.chatTheme["font_size"] = 12
            g.theme["font_size"] = 12
            g.theme["button"]["font_size"] = 12
            w1 = int(w1 * 1.1)
        elif w1 > 200:
            g.chatTheme["font_size"] = 11
            g.theme["font_size"] = 11
            g.theme["button"]["font_size"] = 11
            w1 = int(w1 * 1.2)
        elif w1 > 175:
            g.chatTheme["font_size"] = 10
            g.theme["font_size"] = 10
            g.theme["button"]["font_size"] = 10
            w1 = int(w1 * 1.3)
        else:
            g.chatTheme["font_size"] = 9
            g.theme["font_size"] = 9
            g.theme["button"]["font_size"] = 9
            w1 = int(w1 * 1.3)
        self.chatInput = TextInput(text="",
                                   padding=0,
                                   length=16,
                                   max_length=MAX_CHAT_INPUT,
                                   width=w1 - 5 - 50)
        sendButton = HighlightedButton(label="Send",
                                       on_release=self.sendMessage,
                                       width=50,
                                       height=35)
        realtext = '{font_size ' + str(
            g.chatTheme["font_size"]) + '}{background_color ' + str(
                g.postBgColor
            ) + '}{font_name "' + g.chatTheme["font"] + '"}{wrap "char"} '
        document = pyglet.text.decode_attributed(realtext)
        self.textArea = Document(document,
                                 width=w1,
                                 height=h1,
                                 background=True,
                                 font_size=g.chatTheme["font_size"],
                                 font_name=g.chatTheme["font"],
                                 chat=True)

        vertCont = VerticalContainer(content=[
            self.textArea,
            HorizontalContainer(content=[self.chatInput, sendButton])
        ],
                                     align=HALIGN_LEFT)
        Manager.__init__(self,
                         vertCont,
                         window=g.screen,
                         batch=g.guiBatch,
                         theme=g.chatTheme,
                         anchor=ANCHOR_BOTTOM_LEFT,
                         offset=(g.SCREEN_WIDTH * 0.05, g.SCREEN_HEIGHT * 0.1),
                         is_movable=False)
Example #23
0
class VerticalHUD():
    def __init__(self, window, batch, space, level, height, width):
        self.space = space
        self.level = level
        status_text = pyglet.text.decode_attributed('''
Time: 0 sec \n
Points: 0 points \n
FPS: 00.00 FPS
''')
        self.status_doc = Document(status_text, height=height, width=width)
        status_frame = Frame(self.status_doc)
        inv_text = pyglet.text.decode_html("<h4>Inventory</h4>")
        inventory_header = Document(inv_text, width=width)
        self.inventory_container = VerticalContainer([])

        container = VerticalContainer(
            [inventory_header, self.inventory_container])
        self.inventory_frame = Frame(container)
        container = VerticalContainer([status_frame, self.inventory_frame])
        self.manager = Manager(container,
                               window=window,
                               batch=batch,
                               group=RenderingOrder.hud,
                               anchor=ANCHOR_TOP_RIGHT,
                               theme=theme,
                               is_movable=False)
        self.window = window
        self.window.push_handlers(on_draw=self.on_draw)
        self.tick = 0
        # Currently disabled
        #self.init_effects(space, level)

    def init_effects(self, space, level):
        pos = (self.inventory_frame.x,
               self.inventory_frame.y + self.inventory_frame.height / 2 - 50)
        self.inventory_effect = Effects.Inventory(
            space,
            pos,
            "Inventory",
            self.inventory_frame.width,
            self.inventory_frame.height + 100, ["H2O(l)", "CH4(g)", "NaCl(s)"],
            gui_container=self.inventory_container)

    def get_effects(self):
        return []
        #currently disabled
        #return [self.inventory_effect]

    def on_draw(self):
        self.tick += 1
        if self.tick > 30:
            return
        self.tick = 0
        self.update_status()

    def update_status(self):
        level_time = self.window.level.get_time()
        points = self.window.level.get_points()
        status_text = '''
Time: %d sec
Points: %d points
FPS: %.2f FPS
''' % (level_time, points, pyglet.clock.get_fps())
        self.status_doc.set_text(status_text)

    def delete(self):
        self.window.remove_handlers(on_draw=self.on_draw)
        self.manager.delete()
Example #24
0
class HUD:

	def __init__(self, window):
		with open('etc/gui/theme.json') as theme_file:
			theme_dict = json.loads(theme_file.read())
		self.theme = Theme(
			theme_dict,
			resources_path=os.path.join(os.getcwd(), 'etc/gui/images')
			)
		self.window = window
		self.clear_action_gui()
		self.clear_status_gui()

	def handle_click(self, button_state, action):
		print(action)
		if button_state is not False:
			self.selected_action = action
		return True

	def handle_building_click(self, button_state, button, selected_object, action):
		if button_state is not False:
			self.selected_action = action
			selected_object.add_action(action) #this should probably get moved to the event_handler
		return True

	def clear_action_gui(self):
		self.selected_action = None
		self.action_gui_batch = None
		self.action_gui_manager = None

	def clear_status_gui(self):
		self.status_box = None
		self.status_gui_batch = None
		self.status_gui_manager = None

	def build_building_gui(self, selected_building):
		building = selected_building
		produce_content = [Label(text='Produce')]
		for resource in building.producable_resources:
			produce_button = GroupButton(
				group_id='action-gui-buttons',
				label=resource.name,
				on_press=lambda x: self.handle_building_click(x, produce_button, building, Produce(building, resource, selected_building.container.remaining_capacity(resource))),
				)
			produce_content.append(produce_button)
		produce_container = HorizontalContainer(produce_content)

		action_container = VerticalContainer([
			produce_container,
			])
		self.action_gui_batch = pyglet.graphics.Batch()
		self.action_gui_manager = Manager(
			action_container,
			window=self.window,
			theme=self.theme,
			batch=self.action_gui_batch,
			)
		self.action_gui_manager.set_position(
			#it's on the right as a hack to fix the Manager bug
			self.window.width - action_container.width - 30,
			self.window.height - action_container.height - 10,
			)
		self.action_gui_manager.is_movable = False

	def build_unit_gui(self, selected_object):
		harvest_content = [Label(text='Harvest')]
		#for resource in selected_object.harvestable_resources:
		#	harvest_button = GroupButton(
		#		group_id='action-gui-buttons',
		#		label=resource.name,
		#		on_press=lambda x: self.handle_click(x, Harvest(resource, selected_object.container.remaining_capacity(resource))),
		#		)
		#	harvest_content.append(harvest_button)
		harvest_wood_button = GroupButton(
			group_id='action-gui-buttons',
			label=Wood.name,
			on_press=lambda x: self.handle_click(x, Harvest(Wood, selected_object.container.remaining_capacity(Wood))),
			)
		harvest_content.append(harvest_wood_button)
		harvest_container = HorizontalContainer(harvest_content)

		building_content = [Label(text='Construct')]
		#for building_factory in selected_object.building_factories.values():
		#	building_button = GroupButton(
		#		group_id='action-gui-buttons',
		#		label=building_factory.product.name,
		#		on_press=lambda x:
		#			self.handle_click(x, Construct(building_factory.product)),
		#		)
		#	building_content.append(building_button)
		building_cabbage_farm_button = GroupButton(
			group_id='action-gui-buttons',
			label=CabbageFarm.name,
			on_press=lambda x:
				self.handle_click(x, Construct(CabbageFarm)),
			)
		building_content.append(building_cabbage_farm_button)
		building_iron_mine_button = GroupButton(
			group_id='action-gui-buttons',
			label=IronMine.name,
			on_press=lambda x:
				self.handle_click(x, Construct(IronMine)),
			)
		building_content.append(building_iron_mine_button)
		#building_farm_button = GroupButton(
		#	group_id='action-gui-buttons',
		#	label=building_factory.Farm.name,
		#	on_press=lambda x:
		#		self.handle_click(x, Construct(building_factory.Farm)),
		#	)
		#building_content.append(building_farm_button)
		construct_container = HorizontalContainer(building_content)

		deliver_content = [Label(text='Deliver')]
		#for resource in selected_object.carryable_resources:
		#	deliver_button = GroupButton(
		#		group_id='action-gui-buttons',
		#		label=resource.name,
		#		on_press=lambda x: self.handle_click(x, Deliver(resource, selected_object.container.current_load(resource))),
		#		)
		#	deliver_content.append(deliver_button)
		#
		#For some reason adding the buttons in a loop causes them to get the same action (same resource)
		#TODO change the interface so that only relevant resource buttons appear
		deliver_wood_button = GroupButton(
			group_id='action-gui-buttons',
			label=Wood.name,
			on_press=lambda x: self.handle_click(x, Deliver(Wood, selected_object.container.current_load(Wood))),
			)
		deliver_content.append(deliver_wood_button)
		deliver_lumber_button = GroupButton(
			group_id='action-gui-buttons',
			label=Lumber.name,
			on_press=lambda x: self.handle_click(x, Deliver(Lumber, selected_object.container.current_load(Lumber))),
			)
		deliver_content.append(deliver_lumber_button)
		deliver_container = HorizontalContainer(deliver_content)

		deliver_all_content = [Label(text='DeliverAll')]
		deliver_all_button = GroupButton(
			group_id='action-gui-buttons',
			label='all',
			on_press=lambda x: self.handle_click(x, DeliverAll(selected_object)
			))
		deliver_all_content.append(deliver_all_button)
		deliver_all_container = HorizontalContainer(deliver_all_content)

		pickup_content = [Label(text='Pick up')]
		#for resource in selected_object.carryable_resources:
		#	pickup_button = GroupButton(
		#		group_id='action-gui-buttons',
		#		label=resource.name,
		#		on_press=lambda x: self.handle_click(x, Pickup(resource, selected_object.container.remaining_capacity(resource))),
		#		)
		#	pickup_content.append(pickup_button)
		#pickup_container = HorizontalContainer(pickup_content)
		#
		#For some reason adding the buttons in a loop causes them to get the same action (same resource)
		#TODO change the interface so that only relevant resource buttons appear
		pickup_wood_button = GroupButton(
			group_id='action-gui-buttons',
			label=Wood.name,
			on_press=lambda x: self.handle_click(x, Pickup(Wood, selected_object.container.remaining_capacity(Wood))),
			)
		pickup_content.append(pickup_wood_button)
		pickup_lumber_button = GroupButton(
			group_id='action-gui-buttons',
			label=Lumber.name,
			on_press=lambda x: self.handle_click(x, Pickup(Lumber, selected_object.container.remaining_capacity(Lumber))),
			)
		pickup_content.append(pickup_lumber_button)
		pickup_container = HorizontalContainer(pickup_content)

		pickup_all_content = [Label(text='PickupAll')]
		pickup_all_button = GroupButton(
			group_id='action-gui-buttons',
			label='all',
			on_press=lambda x: self.handle_click(x, PickupAll(selected_object)
			))
		pickup_all_content.append(pickup_all_button)
		pickup_all_container = HorizontalContainer(pickup_all_content)

		action_container = VerticalContainer([
			harvest_container,
			construct_container,
			deliver_container,
			deliver_all_container,
			pickup_container,
			pickup_all_container
			])
		self.action_gui_batch = pyglet.graphics.Batch()
		self.action_gui_manager = Manager(
			action_container,
			window=self.window,
			theme=self.theme,
			batch=self.action_gui_batch,
			)
		self.action_gui_manager.set_position(
			10,
			self.window.height - action_container.height - 10,
			)
		self.action_gui_manager.is_movable = False

	def build_action_gui(self, selected_object):
		if selected_object is None:
			raise HUDException("Can't build action gui with a unit of None")

		if isinstance(selected_object, Building):
			self.build_building_gui(selected_object)

		if isinstance(selected_object, Unit):
			self.build_unit_gui(selected_object)

	def build_status_gui(self):
		self.status_box = Document(
			pyglet.text.document.UnformattedDocument(),
			width=self.window.width*0.9,
			height=self.window.height/4,
			is_fixed_size=True,
			)
		status_frame = Frame(self.status_box)
		self.status_gui_batch = pyglet.graphics.Batch()
		self.status_gui_manager = Manager(
			status_frame,
			window=self.window,
			theme=self.theme,
			batch=self.status_gui_batch,
			)
		self.status_gui_manager.set_position(
			(self.window.width - status_frame.width)/2,
			10,
			)
		self.status_gui_manager.is_movable = False

	def draw(self, selected_unit):
		glLoadIdentity()
		gluOrtho2D(0, self.window.width, 0, self.window.height)
		if selected_unit is not None:
			if self.action_gui_batch is None:
				self.build_action_gui(selected_unit)
			if self.action_gui_batch is not None:
				self.action_gui_batch.draw()
			if self.status_gui_batch is None:
				self.build_status_gui()
			self.status_box.set_text(selected_unit.status)
			self.status_gui_batch.draw()
Example #25
0
class PostWindow(Manager):
    def __init__(self):
        g.postWindowOpened = True
        label1 = Label("Notifications", bold=True, color=g.loginFontColor)
        closeBtn = HighlightedButton("",
                                     on_release=self.delete,
                                     width=19,
                                     height=19,
                                     path='delete')
        self.postCont = []
        #self.menes = [{"name":"Hitler","hp":100,"level":1,"power":50,"defense":40,"speed":60,"sprite":'americanbear'},{"name":"Stalin","hp":100,"level":1,"power":50,"defense":40,"speed":60,"sprite":'lorslara'},{"name":"Ebin","hp":100,"level":1,"power":50,"defense":40,"speed":60,"sprite":'squadlider'},{"name":"Mao","hp":100,"level":1,"power":50,"defense":40,"speed":60,"sprite":'mongolbear'},{"name":"Uusi mene","hp":100,"level":1,"power":50,"defense":40,"speed":60,"sprite":'mongol'},{"name":"Hintti","hp":50,"level":15,"power":60,"defense":50,"speed":70,'sprite':'uusimene'}]
        #self.selectedMene=self.menes[0]["name"]
        for c in g.mails:
            label = Label(c["s"],
                          bold=True,
                          color=g.guiNameColor,
                          font_size=g.theme["font_size"] + 2)
            label1 = Label(c["t"][:16] + '...', color=g.whiteColor)
            deleteBtn = HighlightedButton("",
                                          on_release=self.deletemail,
                                          width=14,
                                          height=14,
                                          path='delete_alt',
                                          argument=c["id"])
            openBtn = HighlightedButton("",
                                        on_release=self.openmail,
                                        width=20,
                                        height=21,
                                        path='mailopen',
                                        argument=c["id"])
            self.postCont.append(
                VerticalContainer(content=[
                    HorizontalContainer(content=[openBtn, label, deleteBtn]),
                    label1
                ],
                                  align=HALIGN_LEFT))
        self.vertCont = VerticalContainer(self.postCont, align=VALIGN_TOP)
        self.report = Document("",
                               is_fixed_size=True,
                               height=g.SCREEN_HEIGHT / 2,
                               width=g.SCREEN_WIDTH / 5)
        self.scrollable = Scrollable(content=self.vertCont,
                                     height=g.SCREEN_HEIGHT / 2,
                                     width=g.SCREEN_WIDTH / 5)
        total = HorizontalContainer(
            content=[self.scrollable, self.report, closeBtn], align=VALIGN_TOP)
        Manager.__init__(
            self,
            Frame(total),
            window=g.screen,
            batch=g.guiBatch,
            is_movable=False,
            anchor=ANCHOR_LEFT,
            offset=(40, int(g.SCREEN_HEIGHT * g.WINDOW_POSY_RELATIVE)),
            theme=g.theme)
        if len(self.postCont) > 0:
            self.openmail(self.postCont[0]._content[0]._content[0].arg)
        #self.changeInfos(self.selectedMene)
        #print str(int(time.time()*1000-t1)),"TIMEEE"

    def delete(self, event):
        super(Manager, self).delete()
        g.postWindowOpened = False

    def deletemail(self, event):
        deleteMail(event)
        for c in self.postCont:
            if c._content[0]._content[0].arg == event:
                self.vertCont.remove(c)
                self.postCont.remove(c)
                for d in g.mails:
                    if d["id"] == event:
                        g.mails.remove(d)
        if len(self.postCont) > 0:
            self.openmail(self.postCont[0]._content[0]._content[0].arg)
            self.scrollable.reset_size()
        else:
            self.delete(None)
            g.gameEngine.graphics.normalUI.removeMail()

    def openmail(self, event):
        text = ''
        for c in g.mails:
            if c["id"] == event:
                text = c["t"] + '\n\nt. ' + c["s"]
        self.report.set_text(text)
Example #26
0
class HorizontalHUD:
    def __init__(self, window, batch, space, level, height, width):
        self.space = space
        self.level = level
        self.height = height
        self.width = width
        progress_text = "Progress: ..."
        self.progress_doc = Document(progress_text, width=width / 2)
        objective_doc = Document(level.objective, width=width / 2)
        left_frame = Frame(VerticalContainer(
            [objective_doc, None, self.progress_doc]),
                           is_expandable=True)
        self.left_container = VerticalContainer([left_frame])
        victory_formula = level.victory_condition[0]
        info_frame = self.create_info_frame(victory_formula)
        self.info_container = VerticalContainer([info_frame])
        container = HorizontalContainer(
            [self.left_container, self.info_container])
        self.manager = Manager(container,
                               window=window,
                               batch=batch,
                               group=RenderingOrder.hud,
                               anchor=ANCHOR_BOTTOM_LEFT,
                               theme=theme,
                               is_movable=False)
        self.window = window
        self.window.push_handlers(on_draw=self.on_draw)
        self.tick = 0
        self.init_effects(space, level)

    def init_effects(self, space, level):
        pos = (self.left_container.x + self.left_container.width / 2,
               self.left_container.y + self.left_container.height / 2 - 50)
        self.victory = Effects.VictoryInventory(
            space, pos, "Victory Inventory", self.left_container.width,
            self.left_container.height + 100, level.victory_condition)

    def get_effects(self):
        return [self.victory]

    def update_info_text(self, formula):
        info_frame = self.create_info_frame(formula)
        for content in self.info_container.content:
            self.info_container.remove(content)
        self.info_container.add(info_frame)

    def create_info_frame(self, formula):
        cml = CachedCml.getMolecule(formula)
        info_text = pyglet.text.decode_html(
            "<b>%s</b><br> %s" %
            (cml.property.get("Name", "Undefined"),
             cml.property.get("Description", "No Description Available")))
        info_doc = Document(info_text,
                            height=self.height,
                            width=self.width / 2,
                            is_fixed_size=True)
        info_frame = Frame(info_doc)
        return info_frame

    def on_draw(self):
        self.tick += 1
        if self.tick > 30:
            return
        self.tick = 0
        self.update_progress()

    def update_progress(self):
        progress_text = self.victory.progress_text()
        self.progress_doc.set_text("Progress: " + progress_text)

    def delete(self):
        self.window.remove_handlers(on_draw=self.on_draw)
        self.manager.delete()