Exemplo n.º 1
0
class GUI:
    """
    Controls the GUI (HUD) of this application
    """

    def __init__(self, window, controls, bodies):
        self.window = window
        self.controls = controls
        self.bodies = bodies

        self.fps_counter = FPSCounter(window, self.fps_update)

        # Setup HUD elements
        self.label_fps = Label("", bold=True, font_name="Arial", font_size=12, color=(127, 127, 127, 127))
        self.label_time = Label("", bold=True, font_name="Arial", font_size=18, color=(127, 127, 127, 127))
        self.label_help = BetterLabel(load_string('help.txt'), bold=False, font_name="Arial", font_size=18, color=(170, 170, 170, 255), multiline=True, lblwidth=600)
        self.label_planet_info = BetterLabel("", bold=False, font_name="Arial", font_size=12, color=(170, 170, 170, 255), multiline=True, lblwidth=400, lblalign='right')
        self.managers = [
            Manager(self.label_fps, window=window, theme=empty_theme, is_movable=False, anchor=ANCHOR_TOP_LEFT),
            Manager(self.label_time, window=window, theme=empty_theme, is_movable=False, anchor=ANCHOR_BOTTOM_LEFT)
        ]
        self.label_help_manager = Manager(self.label_help, window=window, theme=empty_theme, is_movable=False, anchor=ANCHOR_TOP_LEFT, offset=(0, -17))
        self.label_planet_info_manager = Manager(self.label_planet_info, window=window, theme=empty_theme, is_movable=False, anchor=ANCHOR_BOTTOM_RIGHT, offset=(-180, 36))

        body_buttons = []
        for body in self.bodies:
            body_buttons.append(BodyButton(self, body).button)

        self.managers_when_not_locked = [
            Manager(VerticalContainer(body_buttons, align=HALIGN_RIGHT), window=window, theme=ThemeFromPath("theme/bodybutton"), is_movable=False, anchor=ANCHOR_TOP_RIGHT)
        ]

    def fps_update(self, fps):
        self.label_fps.set_text(str(fps) + "fps")

    def update_time(self, timestep, solarsystem_time):
        self.label_time.set_text("1 second = " + str(floor(timestep / 60 / 60)) + "hours. Current Date: " + str(J2000 + datetime.timedelta(seconds=solarsystem_time)))

    def draw(self):
        if self.controls.draw_help_label:
            self.label_help_manager.draw()

        if self.controls.selected_body:
            body = self.controls.selected_body
            text = ""
            text += "Name: " + body.name + "\n"
            text += "Position: " + str(round(body.xyz.x, 2)) + " " + str(round(body.xyz.y, 2)) + " " + str(round(body.xyz.z, 2)) + "\n"
            text += "Rotation Period: " + str(round(body.sidereal_rotation_period / 60 / 60 / 24, 2)) + "days\n"
            self.label_planet_info.set_text(text)
            self.label_planet_info_manager.draw()

        for manager in self.managers:
            manager.draw()

        if not self.controls.mouse_locked:
            for manager in self.managers_when_not_locked:
                manager.draw()
class StatsWindow(Manager):
    coinsText=None
    def __init__(self):
        self.coinsText = Label("Coins: 0")
        Manager.__init__(self,
            self.coinsText,
            window=g.gameEngine.window,
            batch=g.guiBatch,
            theme=g.theme,
            is_movable=False,
            anchor=ANCHOR_TOP,
            offset=(0,-25))
    def updateCoinText(self,coinAmount):
        self.coinsText.set_text("Coins: %s" % str(coinAmount))
Exemplo n.º 3
0
def LabelFactory(model ,path):
        binding = Binding(context=model, path=path)
        label = Label(path='label')
        binding.setter = lambda value: label.set_text(value)
        if label.is_loaded:
            binding.apply_binding()

        return label
Exemplo n.º 4
0
class MeneStats(Manager):
    def __init__(self, name, level, hp, maxhp):
        self.nameLabel = Label(name,
                               color=g.whiteColor,
                               font_size=g.theme["font_size"] + 2,
                               bold=True)
        self.levelLabel = Label('Lvl: ' + str(level),
                                color=g.whiteColor,
                                font_size=g.theme["font_size"] + 2,
                                bold=True)
        self.hpBar = HpBar()
        Manager.__init__(
            self,
            VerticalContainer(content=[
                HorizontalContainer(
                    content=[self.nameLabel, None, self.levelLabel]),
                self.hpBar
            ],
                              align=HALIGN_LEFT),
            window=g.screen,
            batch=g.guiBatch,
            is_movable=False,
            anchor=ANCHOR_BOTTOM_LEFT,
            offset=(0, 0),
            theme=g.theme)
        self.hpBar.setHP(hp, maxhp)

    def updateLevel(self, level):
        self.levelLabel.set_text("Lvl: " + str(level))

    def updateInfo(self, name, level, hp, maxhp):
        self.levelLabel.set_text("Lvl: " + str(level))
        self.nameLabel.set_text(name)
        self.hpBar.setHP(hp, maxhp=maxhp)

    def setPos(self, x, y):
        self.set_position(x, y)

    def delete(self):
        super(Manager, self).delete()
Exemplo n.º 5
0
class NpcTalkWindow(Manager):
    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)

    def updateMoney(self, money, es):
        if self.yourmoney is None or self.yourES is None:
            return
        moneyTmp = g.moneyAmount / 100.0
        self.yourmoney.set_text("%.2f" % moneyTmp)
        self.yourES.set_text("%s" % es)
        if Items["es"]["cost"] > money and not self.esButton.disabled:
            self.esButton.disabled = True
            self.esButton.reload()
            self.esButton.layout()
        elif Items["es"]["cost"] <= money and self.esButton.disabled:
            self.esButton.disabled = False
            self.esButton.reload()
            self.esButton.layout()

    def healButton(self, event):
        sendHealMenes()
        self.delete(None)

    def delete(self, event):
        super(Manager, self).delete()
        g.npcTalkWindowOpened = False
        if g.talkingToNpc is not None:
            if npcList[g.talkingToNpc].name == self.name:
                sendStopTalkToNpc(self.name)

    def setPos(self, x, y):
        self.set_position(x, y)
Exemplo n.º 6
0
class Updater:
    def loopFunction(self):

        self.screen.clear()
        self.currTick = int(
            (datetime.datetime.utcnow() -
             datetime.datetime(1970, 1, 1)).total_seconds() * 1000)
        if self.toConnect and self.currTick > self.nextConnect + 3000:
            self.initConnection()

        if self.screen.has_exit:
            reactor.stop()
        if self.mode == MODE_CONNECTING:
            if self.currTick - self.lastMoveTick > 500:
                self.updateConnectText()
                self.lastMoveTick = self.currTick

        self.screen.dispatch_events()
        self.guiBatch.draw()
        self.screen.flip()

    def updateConnectText(self):
        if self.animationStep == 0:
            self.statusText.set_text("Connecting :D")
            self.animationStep += 1
        elif self.animationStep == 1:
            self.statusText.set_text("Connecting :D :D")
            self.animationStep += 1
        elif self.animationStep == 2:
            self.statusText.set_text("Connecting :D :D :D")
            self.animationStep += 1
        else:
            self.statusText.set_text("Connecting")
            self.animationStep = 0

    def removeEmptyDicts(self, dic):
        def removeEmpties(dic2, keys):
            for k, v in dic2.iteritems():
                if isinstance(v, basestring):
                    pass
                elif isinstance(v, dict):
                    if len(v) == 0 or k is None:
                        asd = keys + [k]
                        del reduce(lambda a, b: a[b], asd[:-1], dic)[asd[-1]]
                    else:
                        removeEmpties(v, keys + [k])

        n = 0

        while n < 10:
            removeEmpties(copy.deepcopy(dic), [])
            n += 1

    def checkFiles(self, argument, dict, first=False):
        for f1 in os.listdir(argument):
            if f1 not in self.ignores:
                if os.path.isdir(argument + '/' + f1):
                    if not first:
                        dict[f1] = {}
                        self.checkFiles(argument + '/' + f1, dict[f1])
                    else:
                        dict[f1] = {}
                        self.checkFiles(f1, dict[f1])
                else:
                    dict[f1] = hashlib.md5(
                        open(argument + '/' + f1, 'rb').read()).hexdigest()
        return dict

    def myprint(self, t, d, keys):
        for k, v in t.iteritems():
            if isinstance(v, dict):
                if k in d:
                    self.myprint(v, d[k], keys + [k])
                else:
                    pass
                    #print "NO DIRECTORY NAMED", k,keys
            else:
                if k in d:
                    if v == d[k]:
                        asd = keys + [k]
                        del reduce(lambda a, b: a[b], asd[:-1],
                                   self.copiedList)[asd[-1]]
                    else:
                        filename = ''
                        a = 0
                        for i in keys + [k]:
                            if a == 0:
                                filename = i
                            else:
                                filename += '/' + i
                            a += 1
                        os.remove(filename)
                        #pass
                        #print "WRONG FILE", k, v, d[k]
                else:
                    pass
                    #print "NO FILE NAMED", k, v, keys
    def initManager(self):
        self.mode = MODE_CONNECTING
        self.guiBatch = pyglet.graphics.Batch()
        self.statusText = Label("Connecting", color=(255, 255, 255, 255))
        self.downloadText = Label("", color=(255, 255, 255, 255))
        self.manager = Manager(VerticalContainer(
            [self.statusText, self.downloadText]),
                               window=self.screen,
                               batch=self.guiBatch,
                               theme=theme)

    def init(self):
        self.mode = MODE_INIT
        self.lastMoveTick = 0
        self.animationStep = 0
        self.receivedHashes = {}
        self.copiedList = {}
        self.myHashes = {}
        self.downloadSize = 0
        self.downloaded = 0

        self.nextConnect = 0
        self.toConnect = False
        self.ignores = [
            'screenshots', 'temp', 'test.py', 'game.cfg', 'updater.py',
            'pyglet_gui'
        ]
        s_width = pyglet.window.get_platform().get_default_display(
        ).get_default_screen().width
        s_height = pyglet.window.get_platform().get_default_display(
        ).get_default_screen().height
        self.screen = pyglet.window.Window(
            fullscreen=False,
            width=550,
            height=400,
            style=pyglet.window.Window.WINDOW_STYLE_DIALOG)
        self.screen.set_location((s_width - 550) / 2, (s_height - 400) / 2)
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
        self.initManager()
        tick = LoopingCall(self.loopFunction)
        tick.start(1. / 300)
        self.initConnection()
        #connectionProtocol = startConnection()
        #self.tcpConn = TCPConnection(connectionProtocol)
        reactor.run()

    def initConnection(self):
        self.toConnect = False
        self.receivedHashes = {}
        self.maxRounds = 0
        self.currentRound = 0
        self.copiedList = {}
        self.myHashes = {}
        self.downloadSize = 0
        self.downloaded = 0
        self.animationStep = 0
        self.mode = MODE_CONNECTING
        connectionProtocol = startConnection()
        self.tcpConn = TCPConnection(connectionProtocol)

    def checkFiles(self, argument, dict, first=False):
        for f1 in os.listdir(argument):
            if f1 not in self.ignores:
                if os.path.isdir(argument + '/' + f1):
                    if not first:
                        dict[f1] = {}
                        self.checkFiles(argument + '/' + f1, dict[f1])
                    else:
                        dict[f1] = {}
                        self.checkFiles(f1, dict[f1])
                else:
                    dict[f1] = hashlib.md5(
                        open(argument + '/' + f1, 'rb').read()).hexdigest()
        return dict

    def constructPath(self, args):
        string = ""
        first = True
        for arg in args:
            string = string + arg + '/'

            #if first:
            #    string=arg
            #    first=False
            #else:
            #    string=string+"/"+arg
        return string

    def myprint1(self, d, args):
        for k, v in d.iteritems():
            if isinstance(v, dict):
                newArgs = args + [k]
                self.myprint1(v, newArgs)
            else:
                path = self.constructPath(args) + k
                isExisting = os.path.isfile(path)
                if isExisting:
                    md5hash = hashlib.md5(open(path,
                                               'rb').read()).hexdigest()[:4]
                    if md5hash != v:
                        pass
                        #print "vaara tiedosto!" + md5hash + " vs. " + v
                    else:
                        asd = args + [k]
                        del reduce(lambda a, b: a[b], asd[:-1],
                                   self.receivedHashes)[asd[-1]]
                        #print "{0} : {1} in {2}, {3}".format(k, v, path, md5hash)
                else:
                    pass
                    #print k +" ei loytynyt!"
    def checkTesti(self, arguments, dict, first=False):
        path = self.constructPath(arguments)
        for f1 in os.listdir(path):
            #if f1 not in self.ignores:
            newArgs = arguments.append(f1)
            newPath = self.constructPath(arguments)
            #if os.path.isdir(newPath):
            #        self.
            #print f1
        #print path
        return None, None
        #for f1 in os.listdir()
    def checkFilePaskas(self):
        #print self.copiedList
        self.currentFolder = []
        self.currentDepth = 0
        self.testi = {}
        self.args = []
        self.myprint1(self.copiedList, [])
        self.removeEmptyDicts(self.receivedHashes)
        #self.checkTesti(self.args, self.copiedList, True)
        '''
        for i in self.copiedList:
            self.currentDepth=0
            if type(self.copiedList[i]) is dict:
                for j in self.currentFolder[i]:
                    self.currentDepth=1
                    if type(self.copiedList[i]) is dict:
                        for k in self.currentFolder[i][j]:
                            self.currentDepth=2
                            if type(self.copiedList[i][j][k]) is dict:
                                for m in self.currentFolder[i][j][k]:
                                    self.currentDepth=3
            else:'''

    #def loopFiles():
    def dataHandler(self, data):
        jsonData = json.loads(data)
        packetType = jsonData[0]["p"]
        #print jsonData
        if packetType == ServerPackets["SendHashes"]:

            self.receivedHashes = jsonData[0]["d"]
            self.maxRounds = jsonData[0]["r"]
            self.currentRound = jsonData[0]["c"]
            validating = jsonData[0]["v"]
            self.copiedList = copy.deepcopy(self.receivedHashes)
            self.mode = MODE_CHECKINGINTEGRITY
            self.statusText.set_text("Checking for integrity...")
            self.checkFilePaskas()
            if len(self.receivedHashes) > 0:
                updater.mode = MODE_FOUND_UPDATED
                updater.statusText.set_text("Found an update!")
                packet = json.dumps([{
                    "p": ClientPackets["SendHashes"],
                    'd': self.receivedHashes
                }])
                self.tcpConn.sendData(packet)
            elif self.currentRound == self.maxRounds or validating:
                updater.mode = MODE_NOTFOUND
                updater.statusText.set_text(
                    "The game is up to date! Launching the game...")
                self.downloadText.set_text('')
                os.startfile('Spurdola.exe')
                reactor.stop()
            else:
                packet = json.dumps([{"p": ClientPackets["Received"]}])
                updater.tcpConn.sendData(packet)
                #print self.copiedList
            #self.myHashes=self.checkFiles(".",self.myHashes,True)
            '''
            self.myprint(self.receivedHashes,self.myHashes,[])
            self.removeEmptyDicts(self.copiedList)
            if len(self.copiedList)>0:
                updater.mode=MODE_FOUND_UPDATED
                updater.statusText.set_text("Found an update!")
                packet = json.dumps([{"p": ClientPackets["SendHashes"], 'd':self.copiedList}])
                self.tcpConn.sendData(packet)
            elif self.currentRound==self.maxRounds or validating:
                updater.mode=MODE_NOTFOUND
                updater.statusText.set_text("The game is up to date! Launching the game...")
                self.downloadText.set_text('')
                os.startfile('Golden ES.exe')
                reactor.stop()
            else:
                packet = json.dumps([{"p": ClientPackets["Received"]}])
                updater.tcpConn.sendData(packet)
                #print self.copiedList
            '''
        elif packetType == ServerPackets["SendFileInfo"]:
            self.file_data = [jsonData[0]["d"], jsonData[0]["h"]]
            self.mode = MODE_RAWMODE
        elif packetType == ServerPackets["DownloadFinished"]:
            self.mode = MODE_VALIDATING
            updater.statusText.set_text("Validating...")
            packet = json.dumps([{"p": ClientPackets["Validating"]}])
            self.tcpConn.sendData(packet)
            #self.mode=MODE_NOTFOUND
            #updater.statusText.set_text("The game is up to date! Launching the game...")
            #self.downloadText.set_text('')
            #os.startfile('goldenes.exe')
            #reactor.stop()
        elif packetType == ServerPackets["DownloadSize"]:
            self.downloadSize = jsonData[0]["d"]

    def updateDownloadText(self):
        downloaded = self.downloaded / 1000000.0
        downloadable = self.downloadSize / 1000000.0
        self.downloadText.set_text('{}/{} MB'.format("%.2f" % downloaded,
                                                     '%.2f' % downloadable))
Exemplo n.º 7
0
class GameSettingsWindow(Manager):
    def __init__(self):
        g.gameSettingsWindowOpened = True
        self.mouseoverPaint = g.selectPaint
        self.hoverPaint = g.hoverPaint
        self.musicEnabled = g.MUSIC
        self.musicVolume = g.MUSICVOLUME
        self.soundEnabled = g.SOUND
        self.soundVolume = g.SOUNDVOLUME
        titleText = Label("Game Settings",
                          color=g.loginFontColor,
                          font_size=g.theme["font_size"] + 2)
        mouseoverBtn = Checkbox("Paint tile select",
                                on_press=self.mouseoverSelect,
                                is_pressed=self.mouseoverPaint,
                                align=HALIGN_LEFT,
                                width=24,
                                height=24)
        hoverBtn = Checkbox("Paint hover players",
                            on_press=self.hoverSelect,
                            is_pressed=self.hoverPaint,
                            align=HALIGN_LEFT)
        audioEnabled = Checkbox("Enable music",
                                on_press=self.musicSelect,
                                is_pressed=self.musicEnabled,
                                align=HALIGN_LEFT)
        musicVolume = Label("Music volume")
        musicSlider = HorizontalSlider(on_set=self.musicVolumeChange,
                                       value=self.musicVolume)
        self.musicVolumeNumber = Label('%.2f' % self.musicVolume)
        soundEnabled = Checkbox("Enable sounds",
                                on_press=self.soundSelect,
                                is_pressed=self.soundEnabled,
                                align=HALIGN_LEFT)
        soundVolume = Label("Sound volume")
        soundSlider = HorizontalSlider(on_set=self.soundVolumeChange,
                                       value=self.soundVolume)
        self.soundVolumeNumber = Label('%.2f' % self.soundVolume)
        horz2 = HorizontalContainer(
            [musicVolume, musicSlider, self.musicVolumeNumber], padding=0)
        horz3 = HorizontalContainer(
            [soundVolume, soundSlider, self.soundVolumeNumber], padding=0)
        discardBtn = HighlightedButton(label="Discard",
                                       on_release=self.delete,
                                       width=120,
                                       height=30)
        saveBtn = HighlightedButton(label="Save",
                                    on_release=self.onSave,
                                    width=120,
                                    height=30)
        horzBtn = HorizontalContainer([discardBtn, saveBtn])
        Manager.__init__(self,
                         Frame(
                             VerticalContainer([
                                 titleText, mouseoverBtn, hoverBtn,
                                 audioEnabled, horz2, soundEnabled, horz3,
                                 horzBtn
                             ])),
                         window=g.screen,
                         batch=g.guiBatch,
                         theme=g.theme,
                         is_movable=False)

    def soundSelect(self, event):
        self.soundEnabled = event

    def soundVolumeChange(self, volume):
        g.SOUNDVOLUME = volume
        #self.musicVolume=volume
        self.soundVolumeNumber.set_text('%.2f' % volume)

    def musicVolumeChange(self, volume):
        g.gameEngine.musicManager.volume = volume
        self.musicVolume = volume
        self.musicVolumeNumber.set_text('%.2f' % volume)

    def musicSelect(self, event):
        self.musicEnabled = event
        if not event and g.gameEngine.musicManager.playing:
            g.gameEngine.musicManager.pause()
        elif event and not g.gameEngine.musicManager.playing:
            g.gameEngine.musicManager.play()

    def hoverSelect(self, event):
        self.hoverPaint = event

    def mouseoverSelect(self, event):
        self.mouseoverPaint = event

    def delete(self, event):
        if g.gameEngine.musicManager.playing and not g.MUSIC:
            g.gameEngine.musicManager.pause()
        elif not g.gameEngine.musicManager.playing and g.MUSIC:
            g.gameEngine.musicManager.play()
        g.gameEngine.musicManager.volume = g.MUSICVOLUME
        g.SOUNDVOLUME = self.soundVolume
        g.settingsWindowOpened = False
        super(Manager, self).delete()

    def onSave(self, event):
        if self.mouseoverPaint != g.selectPaint:
            g.selectPaint = self.mouseoverPaint
            cfg_parser.saveCfg("selectpaint", g.selectPaint)
        if self.hoverPaint != g.hoverPaint:
            g.hoverPaint = self.hoverPaint
            cfg_parser.saveCfg("hoverpaint", g.hoverPaint)
        if self.musicEnabled != g.MUSIC:
            g.MUSIC = self.musicEnabled
            cfg_parser.saveCfg("MUSIC", g.MUSIC)
        if self.musicVolume != g.MUSICVOLUME:
            g.MUSICVOLUME = self.musicVolume
            cfg_parser.saveCfg("MUSICVOLUME", g.MUSICVOLUME)
        if self.soundVolume != g.SOUNDVOLUME:
            self.soundVolume = g.SOUNDVOLUME
            cfg_parser.saveCfg("SOUNDVOLUME", g.SOUNDVOLUME)
        if self.soundEnabled != g.SOUND:
            g.SOUND = self.soundEnabled
            cfg_parser.saveCfg("SOUND", g.SOUND)
        self.delete(None)
        g.gameSettingsWindowOpened = False
Exemplo n.º 8
0
class MeneWindow(Manager):
    def __init__(self):
        t1=time.time()*1000
        g.meneWindowOpened = True
        label1=Label("My Menes",bold=True,color=g.loginFontColor)
        closeBtn =HighlightedButton("",on_release=self.delete,width=19,height=19,path='delete')
        self.meneCont= []
        self.menes=[]
        self.established=False
        for c in meneList:
            self.menes.append({"name":c.name,
                               "hp":c.hp,
                               "maxhp":c.maxhp,
                               "xp":c.xp,
                               "level":c.level,
                               "power":c.power,
                               "id":c.ID,
                               "defense":c.defense,
                               "speed":c.speed,
                               "attack1":c.attack1,
                               "attack2":c.attack2,
                               "attack3":c.attack3,
                               "attack4":c.attack4,
                               "sprite":c.spriteName,
                               "defaultmene":c.defaultMene})
        #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=getDefaultMeneID()
        
        for i in range(6):
            if i < len(self.menes):
                if self.menes[i]["id"]==self.selectedMene:
                    menebutton = Button("",on_press=self.updateWindow,width=64,height=64, argument=self.menes[i]["id"],texture=g.gameEngine.resManager.meneSprites[self.menes[i]["sprite"]]["portrait"],is_pressed=True,outline='menewindowbutton')
                else:
                    menebutton = Button("",on_press=self.updateWindow,width=64,height=64, argument=self.menes[i]["id"],texture=g.gameEngine.resManager.meneSprites[self.menes[i]["sprite"]]["portrait"],is_pressed=False,outline='menewindowbutton')
                nameLabel = Label(self.menes[i]["name"],bold=True,color=g.npcColor)
                levelLabel = Label("Lvl " + str(self.menes[i]["level"]),color=g.whiteColor,font_size=g.theme["font_size_small"])
                defaultMeneLabel=None
                if self.menes[i]["defaultmene"]==1:
                    defaultMeneLabel= Label('Default Mene',color=g.whiteColor,font_size=g.theme["font_size_small"])
                    #self.meneCont.append(HorizontalContainer(content=[menebutton,VerticalContainer(content=[nameLabel,levelLabel,defaultMeneLabel],align=HALIGN_LEFT)],align=HALIGN_CENTER))
                #else:
                self.meneCont.append(HorizontalContainer(content=[menebutton,VerticalContainer(content=[nameLabel,levelLabel,defaultMeneLabel],align=HALIGN_LEFT)],align=HALIGN_CENTER))
            else:
                
                menebutton = Button("",width=64,height=64,is_pressed=False,path='menewindowbutton',disabled=True)
                self.meneCont.append(menebutton)
       
        self.menelisting = VerticalContainer(content=[label1,VerticalContainer(content=self.meneCont,align=HALIGN_LEFT)])
        
        properties=Label("Mene Properties",bold=True,color=g.loginFontColor)
        #horzCont = HorizontalContainer(content=[properties,closeBtn])
        nameinfoLabel = Label("Name:",color=g.whiteColor)
        self.selectedNAME = Label("Uusi mene",bold=True,color=g.npcColor)
        
        levelinfoLabel = Label("Level:",color=g.whiteColor)
        self.selectedLevel = Label("0",bold=True,color=g.npcColor)
        
        hpinfoLabel = Label("HP:",color=g.whiteColor)
        self.selectedHp = Label("0",bold=True,color=g.npcColor)
        
        xpinfoLabel = Label("XP:",color=g.whiteColor)
        #self.selectedXp = Label("0",bold=True,color=g.npcColor)
        
        attackinfoLabel = Label("Power:",color=g.whiteColor)
        self.selectedAttack = Label("0",bold=True,color=g.npcColor)
        
        self.hpBar = HpBar()
        
        self.defaultButton = HighlightedButton("Set Default Mene :D",argument=None,on_release=makeDefaultMene)
        
        self.xpBar = HpBar(type="xp",height=20,width=100)
        
        defenseinfoLabel = Label("Defense:",color=g.whiteColor)
        self.selectedDefense = Label("0",bold=True,color=g.npcColor)
        
        speedinfoLabel = Label("Speed:",color=g.whiteColor)
        self.selectedSpeed = Label("0",bold=True,color=g.npcColor)
        
        #selectTheme = Theme({'uusimene': {
        #                "image": {
        #                    "source": 'uusimene_front.png'
        #                },
        #                "gui_color": [255,255,255,255]
        #            }
        #        },resources_path=g.dataPath+'/menes/'
        #    )
            
        self.picture = Graphic(texture=g.gameEngine.resManager.meneSprites['uusimene']['front'])
        abilities = ['burger', 'burger']
        #abilityTheme = self.constructAbilityTheme(abilities)
        abilityButtons=[]
        for i in xrange(4):
            #if i<len(abilities):
            #    self.abilityButtons.append(HoverGraphic(width=50,height=50,path=abilities[i],alternative=abilityTheme,outline='abilityoutline',hover=onHover,hoveringType=HOVERING_ABILITY,arguments={'name':'Burger Attack','type':'Attack','info':'Throws a burger at the enemy. Deals X damage.'}))
            #else:
            abilityButtons.append(Graphic(width=50,height=50,path='abilityoutline'))

        
        infoCont1 = VerticalContainer([nameinfoLabel,levelinfoLabel,xpinfoLabel],align=HALIGN_LEFT)
        infoCont2 = VerticalContainer([attackinfoLabel,defenseinfoLabel,speedinfoLabel],align=HALIGN_LEFT)
        statsCont1 = VerticalContainer([self.selectedNAME,self.selectedLevel,self.xpBar],align=HALIGN_LEFT)
        statsCont2 = VerticalContainer([self.selectedAttack,self.selectedDefense,self.selectedSpeed],align=HALIGN_LEFT)
        
        infoAndStatsCont = HorizontalContainer([infoCont1,statsCont1,infoCont2,statsCont2])
        
        self.abilityCont = HorizontalContainer(abilityButtons,padding=10)
        rightFrame = VerticalContainer(content=[properties,self.picture,self.hpBar,infoAndStatsCont,self.abilityCont,self.defaultButton])
        total = HorizontalContainer(content=[self.menelisting,Spacer(30,0),rightFrame,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)
        self.changeInfos(self.selectedMene)
    
    def updateWindow(self,argument):
        for c in self.meneCont:
            try:
                if c.content[0].arg!=argument and c.content[0]._is_pressed:
                    c.content[0].changeStateWithoutFnc()
            except:
                break
        for c in self.meneCont:
            try:
                if c.content[0].arg==argument and not c.content[0]._is_pressed:
                    c.content[0].changeStateWithoutFnc()
            except:
                break
        
        self.changeInfos(argument)
    def constructAbilityButtons(self,a1,a2,a3,a4):
        if a1 is not None:
            self.abilityCont.add(HoverGraphic(width=50,height=50,outline='abilityoutline',hover=onHover,texture=g.gameEngine.resManager.abilities[a1.spriteName],hoveringType=HOVERING_ABILITY,arguments={'name':a1.name,'type':getAbilityTypeName(a1.abilityType),'info':a1.infotext,"args":(a1.power, a1.length)}))
        else:
            self.abilityCont.add(Graphic(width=50,height=50,path='abilityoutline'))
        if a2 is not None:
            self.abilityCont.add(HoverGraphic(width=50,height=50,outline='abilityoutline',texture=g.gameEngine.resManager.abilities[a2.spriteName],hover=onHover,hoveringType=HOVERING_ABILITY,arguments={'name':a2.name,'type':getAbilityTypeName(a2.abilityType),'info':a2.infotext,"args":(a2.power, a2.length)}))
        else:
            self.abilityCont.add(Graphic(width=50,height=50,path='abilityoutline'))
        if a3 is not None:
            self.abilityCont.add(HoverGraphic(width=50,height=50,outline='abilityoutline',texture=g.gameEngine.resManager.abilities[a3.spriteName],hover=onHover,hoveringType=HOVERING_ABILITY,arguments={'name':a3.name,'type':getAbilityTypeName(a3.abilityType),'info':a3.infotext,"args":(a3.power, a3.length)}))
        else:
            self.abilityCont.add(Graphic(width=50,height=50,path='abilityoutline'))
        if a4 is not None:
            self.abilityCont.add(HoverGraphic(width=50,height=50,outline='abilityoutline',texture=g.gameEngine.resManager.abilities[a4.spriteName],hover=onHover,hoveringType=HOVERING_ABILITY,arguments={'name':a4.name,'type':getAbilityTypeName(a4.abilityType),'info':a4.infotext,"args":(a4.power, a4.length)}))
        else:
            self.abilityCont.add(Graphic(width=50,height=50,path='abilityoutline'))
        
    def changeInfos(self,ID):
        selectedMene = None
        for c in self.menes:
            if c["id"]==ID:
                
                selectedMene=c
        #print selectedMene, self.selectedMene
        if selectedMene != None and (ID!=self.selectedMene or (ID==self.selectedMene and not self.established)):
            self.selectedMene=ID
            for i in reversed(range(len(self.abilityCont.content))):
                self.abilityCont.remove(self.abilityCont.content[0])
            #self.abilityCont.unload_content()
            #for c in self.abilityCont.content:
            #    self.abilityCont.remove()
            #for abilityButton in self.abilityButtons:
            #    abilityButton.unload()
            #print self.abilityCont.__dict__
            #for abilityButton in self.abilityButtons:
            #    print abilityButton.__dict__
            #    self.abilityCont.remove(abilityButton)
            self.constructAbilityButtons(selectedMene["attack1"],selectedMene["attack2"],selectedMene["attack3"],selectedMene["attack4"])
            #self.abilityCont.load_content()
            #self.abilityCont.remove(self.abilityButtons[0])
            #self.abilityCont.add(Graphic(width=50,height=50,path='abilityoutline'),0)
            self.selectedNAME.set_text(selectedMene["name"])
            self.selectedLevel.set_text(str(selectedMene["level"]))
            #self.selectedHp.set_text(str(selectedMene["hp"])+' / '+str(selectedMene["maxhp"]))
            self.hpBar.setHP(selectedMene["hp"],selectedMene["maxhp"])
            self.xpBar.setHP(selectedMene["xp"]-selectedMene["level"]**3,(selectedMene["level"]+1)**3-selectedMene["level"]**3)
            #self.selectedXp.set_text(str(selectedMene["xp"]))
            self.selectedAttack.set_text(str(selectedMene["power"]))
            self.selectedDefense.set_text(str(selectedMene["defense"]))
            self.selectedSpeed.set_text(str(selectedMene["speed"]))
            if selectedMene["defaultmene"]==1:
                self.defaultButton._label._set_text("Dis is default mene")
            else:
                self.defaultButton._label._set_text("Set Default Mene :D")
            self.defaultButton.layout()
            self.defaultButton.arg=ID
            
            #selectTheme = Theme({selectedMene["sprite"]: {
            #            "image": {
            #                "source": selectedMene["sprite"]+'_front.png'
            #            },
            #            "gui_color": [255,255,255,255]
            #        }
            #    },resources_path=g.dataPath+'/menes/'
            #)
            #self.picture._path=selectedMene["sprite"]
            #self.picture._alt=selectTheme
            self.picture.textureTmp = g.gameEngine.resManager.meneSprites[selectedMene["sprite"]]['front']
            #self.picture.unload_graphics(False)
            self.picture.reload()
            self.picture.layout()
            self.established=True
    def delete(self,event):
        super(Manager,self).delete()
        g.meneWindowOpened = False
        if g.hoveringType==HOVERING_ABILITY:
            g.gameEngine.graphics.hoverWindow.delete(None)
        
    #def on_mouse_motion(self,x,y,dx,dy):
    #    print self._hover