コード例 #1
0
    def __init__(self, app):
        size = Canvas(512, 384)
        DialogBox.__init__(self, app, size, 'Please authenticate')
        self._deferred = None
        self._host = None

        font = app.screenManager.fonts.defaultTextBoxFont
        btnColour = app.theme.colours.dialogButtonColour
        highlightColour = app.theme.colours.black
        errorTextColour = app.theme.colours.errorColour

        self.tabContainer = TabContainer(app,
                Region(topleft=self.Relative(0, 0),
                size=self.Relative(1, 0.75)), font,
                app.theme.colours.tabContainerColour)
        self.tabContainer.addTab(LoginTab(app))
        self.tabContainer.addTab(CreateAccountTab(app))

        self.errorText = TextElement(app, '', font,
            Location(self.Relative(0.5, 0.8), 'center'), errorTextColour)

        font = app.screenManager.fonts.bigMenuFont
        self.elements = [
            self.tabContainer,
            self.errorText,
            TextButton(app,
                Location(self.Relative(0.3, 0.9), 'center'),
                'Ok', font, btnColour, highlightColour,
                onClick=self.okClicked),
            TextButton(app,
                Location(self.Relative(0.7, 0.9), 'center'),
                'Cancel', font, btnColour, highlightColour,
                onClick=self.cancelClicked),
        ]
        self.cancelled = False
コード例 #2
0
    def __init__(self, app):
        size = Canvas(384, 150)
        DialogBox.__init__(self, app, size, 'Host game?')
        self._deferred = None

        font = app.screenManager.fonts.defaultTextBoxFont
        btnColour = app.theme.colours.dialogButtonColour
        highlightColour = app.theme.colours.black
        labelColour = app.theme.colours.dialogBoxTextColour
        btnFont = app.screenManager.fonts.bigMenuFont

        self.elements = [
            TextElement(app, 'No games found. Host a game?', font,
                        Location(self.Relative(0.5, 0.4), 'center'),
                        labelColour),
            TextButton(app,
                       Location(self.Relative(0.3, 0.85), 'center'),
                       'Yes',
                       btnFont,
                       btnColour,
                       highlightColour,
                       onClick=self.yesClicked),
            TextButton(app,
                       Location(self.Relative(0.7, 0.85), 'center'),
                       'No',
                       btnFont,
                       btnColour,
                       highlightColour,
                       onClick=self.noClicked),
        ]
コード例 #3
0
ファイル: table.py プロジェクト: iliescufm/pygame
class TextButtonCell(Cell):
    def __init__(self, app, row, column):
        super(TextButtonCell, self).__init__(app, row, column)
        textAlign = self.styleGet('textAlign')
        pos = Location(CellAttachedPoint((0, 0), self, textAlign), textAlign)
        self.textButton = TextButton(
            self.app, pos, '', self.styleGet('font'),
            self.styleGet('foreColour'), self.styleGet('hoverColour'))
        self.elements = [self.textButton]
        self._oldText = ''

    def setOnClick(self, onClick):
        self.textButton.onClick.addListener(onClick)
        self._boxClicked(None)

    def setText(self, text):
        if text != self._oldText:
            self.textButton.setText(text)
            self._styleChanged = True
            self._oldText = text

    def _update(self):
        self.textButton.setFont(self.styleGet('font'))
        self.textButton.setColour(self.styleGet('foreColour'))
        self.textButton.setHoverColour(self.styleGet('hoverColour'))
        self.textButton.setBackColour(self.styleGet('backColour'))
        textAlign = self.styleGet('textAlign')
        self.textButton.pos.anchor = textAlign
        self.textButton.pos.point.attachedAt = textAlign
コード例 #4
0
ファイル: table.py プロジェクト: iliescufm/pygame
 def __init__(self, app, row, column):
     super(TextButtonCell, self).__init__(app, row, column)
     textAlign = self.styleGet('textAlign')
     pos = Location(CellAttachedPoint((0, 0), self, textAlign), textAlign)
     self.textButton = TextButton(
         self.app, pos, '', self.styleGet('font'),
         self.styleGet('foreColour'), self.styleGet('hoverColour'))
     self.elements = [self.textButton]
     self._oldText = ''
コード例 #5
0
    def __init__(self, app, nick, head):
        title = 'Player settings'
        DialogBox.__init__(self, app, Canvas(400, 290), title)

        labelFont = app.screenManager.fonts.bigMenuFont
        labelColour = app.theme.colours.dialogBoxTextColour
        btnFont = app.screenManager.fonts.bigMenuFont
        btnColour = app.theme.colours.dialogButtonColour
        highlightColour = app.theme.colours.black
        inputFont = app.screenManager.fonts.defaultTextBoxFont
        inputColour = app.theme.colours.grey

        self.inputBox = InputBox(
            app,
            Region(topleft=self.Relative(0.1, 0.25),
                   bottomright=self.Relative(0.9, 0.45)),
            nick,
            font=inputFont,
            colour=inputColour,
            onClick=self.setFocus,
            onEnter=self.ok_clicked,
            onEsc=self.cancel_clicked,
        )

        self.heads = HeadSelector(
            app,
            Region(topleft=self.Relative(0.1, 0.5),
                   bottomright=self.Relative(0.9, 0.8)))
        self.heads.selected(head)

        self.elements = [
            TextElement(app, 'Nickname:', labelFont,
                        Location(self.Relative(0.1, 0.15), 'midleft'),
                        labelColour),
            self.inputBox,
            self.heads,
            TextButton(app,
                       Location(self.Relative(0.3, 0.9), 'center'),
                       'Ok',
                       btnFont,
                       btnColour,
                       highlightColour,
                       onClick=self.ok_clicked),
            TextButton(app,
                       Location(self.Relative(0.7, 0.9), 'center'),
                       'Cancel',
                       btnFont,
                       btnColour,
                       highlightColour,
                       onClick=self.cancel_clicked),
        ]

        self.setFocus(self.inputBox)
コード例 #6
0
 def setColour(self, colour):
     self.colour = colour
     self.dirty = True
     pos = Location(AttachedPoint((0,0), self._getRect, 'topright'),
             'topleft')
     if 'buttons' in self.fonts:
         font = self.fonts['buttons']
     else:
         font = self.app.fonts.scrollingButtonsFont
     self.upBtn = TextButton(self.app, pos, ' up', font, colour,
             (255,255,255))
     self.dnBtn = TextButton(self.app, pos, ' down', font, colour,
             (255,255,255))
コード例 #7
0
    def __init__(self, app, onClose=None, onStart=None):
        super(PractiseScreen, self).__init__(app)

        self.onClose = Event()
        if onClose is not None:
            self.onClose.addListener(onClose)
        self.onStart = Event()
        if onStart is not None:
            self.onStart.addListener(onStart)

        if app.displaySettings.alphaOverlays:
            alpha = 192
        else:
            alpha = None
        bg = SolidRect(app, app.theme.colours.playMenu, alpha,
                       Region(centre=Canvas(512, 384), size=Canvas(924, 500)))

        #colour = app.theme.colours.mainMenuColour
        #font = app.screenManager.fonts.consoleFont

        font = app.screenManager.fonts.bigMenuFont
        cancel = TextButton(app,
                            Location(Canvas(512, 624), 'midbottom'),
                            'Cancel',
                            font,
                            app.theme.colours.secondMenuColour,
                            app.theme.colours.white,
                            onClick=self.cancel)
        self.elements = [bg, cancel]
コード例 #8
0
    def __init__(self, app, onSucceed=None, onFail=None):
        super(PlayAuthScreen, self).__init__(app)
        self.onSucceed = Event(listener=onSucceed)
        self.onFail = Event(listener=onFail)
        self.lobby = None
        self.badServers = set()

        if app.displaySettings.alphaOverlays:
            alpha = 192
        else:
            alpha = None
        bg = SolidRect(app, app.theme.colours.playMenu, alpha,
                       Region(centre=Canvas(512, 384), size=Canvas(924, 500)))

        colour = app.theme.colours.mainMenuColour
        font = app.screenManager.fonts.consoleFont
        self.logBox = LogBox(
            app, Region(size=Canvas(900, 425), midtop=Canvas(512, 146)),
            colour, font)

        font = app.screenManager.fonts.bigMenuFont
        cancel = TextButton(app,
                            Location(Canvas(512, 624), 'midbottom'),
                            'Cancel',
                            font,
                            app.theme.colours.secondMenuColour,
                            app.theme.colours.white,
                            onClick=self.cancel)
        self.cancelled = False
        self.elements = [bg, self.logBox, cancel]
        self._passwordGetter = None
        self._gameSelectionBox = None
コード例 #9
0
    def __init__(self, app):
        size = Canvas(512, 384)
        DialogBox.__init__(self, app, size, 'Select arena')
        self._deferred = None
        self._games = None

        font = app.screenManager.fonts.defaultTextBoxFont
        btnColour = app.theme.colours.dialogButtonColour
        highlightColour = app.theme.colours.black
        labelColour = app.theme.colours.dialogBoxTextColour
        btnFont = app.screenManager.fonts.bigMenuFont
        listboxFont = app.screenManager.fonts.serverListFont
        listboxColour = app.theme.colours.mainMenuColour
        listboxHighlight = app.theme.colours.mainMenuHighlight

        self.gameList = ListBox(
            self.app,
            Region(topleft=self.Relative(0.05, 0.15),
                   size=self.Relative(0.9, 0.65)),
            [],
            listboxFont,
            listboxColour,
            listboxHighlight,
        )

        self.elements = [
            TextElement(app, 'Please select:', font,
                        Location(self.Relative(0.05, 0.05), 'topleft'),
                        labelColour),
            self.gameList,
            TextButton(app,
                       Location(self.Relative(0.3, 0.9), 'center'),
                       'Ok',
                       btnFont,
                       btnColour,
                       highlightColour,
                       onClick=self.okClicked),
            TextButton(app,
                       Location(self.Relative(0.7, 0.9), 'center'),
                       'Cancel',
                       btnFont,
                       btnColour,
                       highlightColour,
                       onClick=self.cancelClicked),
        ]
コード例 #10
0
    def __init__(self, app, title, label, validator=None):
        DialogBox.__init__(self, app, Canvas(400, 230), title)

        labelFont = app.screenManager.fonts.bigMenuFont
        labelColour = app.theme.colours.dialogBoxTextColour
        btnFont = app.screenManager.fonts.bigMenuFont
        btnColour = app.theme.colours.dialogButtonColour
        highlightColour = app.theme.colours.black
        inputFont = app.screenManager.fonts.defaultTextBoxFont
        inputColour = app.theme.colours.grey

        self.inputBox = InputBox(app,
                                 Region(topleft=self.Relative(0.1, 0.4),
                                        bottomright=self.Relative(0.9, 0.6)),
                                 font=inputFont,
                                 colour=inputColour,
                                 onClick=self.setFocus,
                                 onEnter=self.okClicked,
                                 onEsc=self.cancelClicked,
                                 validator=validator)

        self.elements = [
            TextElement(app, label, labelFont,
                        Location(self.Relative(0.1, 0.2), 'midleft'),
                        labelColour),
            self.inputBox,
            TextButton(app,
                       Location(self.Relative(0.3, 0.9), 'center'),
                       'Ok',
                       btnFont,
                       btnColour,
                       highlightColour,
                       onClick=self.okClicked),
            TextButton(app,
                       Location(self.Relative(0.7, 0.9), 'center'),
                       'Cancel',
                       btnFont,
                       btnColour,
                       highlightColour,
                       onClick=self.cancelClicked),
        ]

        self.setFocus(self.inputBox)
コード例 #11
0
    def __init__(self, app, area, text, colour, fonts, bgColour=None,
            textAlign='left', loop=False, startOff=False, antiAlias=False):
        super(ScrollingText,self).__init__(app)

        self.area = area
        self.border = False
        self.shadowColour = None
        self.loop = loop
        self.startOff = startOff
        self.bgColour = bgColour
        self.speed = 50

        self.offset = 0
        self.colour = colour
        self.fonts = fonts
        self.text = text
        self.textAlign = textAlign
        self.antiAlias = antiAlias
        self.dirty = False

        # A test to see whether the size has changed
        self.lastSize = app.screenManager.size

        self._setImage()

        self.autoScroll = False


        # Create up and down buttons for if there's autoscroll.
        if 'buttons' in fonts:
            font = fonts['buttons']
        else:
            font = app.fonts.scrollingButtonsFont
        pos = Location(AttachedPoint((0, 0), self._getRect, 'topright'),
                'topleft')
        self.upBtn = TextButton(app, pos, ' up', font, colour, (255,255,255))
        pos = Location(AttachedPoint((0,0), self._getRect, 'bottomright'),
                'bottomleft')
        self.dnBtn = TextButton(app, pos, ' down', font, colour, (255,255,255))

        self.onFinishedScrolling = Event()
コード例 #12
0
def mainButton(app, text, onClick, pos, anchor='topleft', hugeFont=False,
        smallFont=False):
    pos = Location(ScaledScreenAttachedPoint(ScaledSize(pos[0], pos[1]),
            'topleft'), anchor)
    if hugeFont:
        font = app.screenManager.fonts.hugeMenuFont
    elif smallFont:
        font = app.screenManager.fonts.menuFont
    else:
        font = app.screenManager.fonts.mainMenuFont
    result = TextButton(app, pos, text, font, app.theme.colours.mainMenuColour,
            app.theme.colours.mainMenuHighlight)
    result.onClick.addListener(lambda sender: onClick())
    return result
コード例 #13
0
def button(app, text, onClick, pos, anchor='topleft', hugeFont=False,
        smallFont=False, firstColour=None, secondColour=None):
    if firstColour is None:
        firstColour = app.theme.colours.secondMenuColour
    if secondColour is None:
        secondColour = app.theme.colours.mainMenuHighlight
    pos = Location(ScaledScreenAttachedPoint(ScaledSize(pos[0], pos[1]),
            anchor), anchor)
    if hugeFont:
        font = app.screenManager.fonts.hugeMenuFont
    elif smallFont:
        font = app.screenManager.fonts.menuFont
    else:
        font = app.screenManager.fonts.mainMenuFont
    result = TextButton(app, pos, text, font, firstColour, secondColour)
    result.onClick.addListener(lambda sender: onClick())
    return result
コード例 #14
0
    def __init__(self,
                 app,
                 message,
                 font,
                 area,
                 buttonPos,
                 textPos,
                 url=None,
                 textColour=(0, 0, 0),
                 closeColour=(0, 0, 0),
                 hoverColour=(255, 255, 255),
                 backColour=(255, 150, 150),
                 textAnchor='center'):
        super(NotificationBar, self).__init__(app)
        self.area = area
        self.url = url
        self.backColour = backColour

        self.rect = pygame.Rect(0, 0, 0, 0)
        self.background = pygame.Surface(self.rect.size)
        self.visible = False

        self.onClick = Event()
        self.onClose = Event()

        self.elements = [
            # A blank rectangle.
            SizedPicture(app, self.background, area, area.size),

            # The text.
            TextElement(app,
                        message,
                        font,
                        textPos,
                        textColour,
                        anchor=textAnchor),

            # A button to dismiss it.
            TextButton(app,
                       pos=buttonPos,
                       text='[close]',
                       font=font,
                       stdColour=closeColour,
                       hvrColour=hoverColour,
                       onClick=self._doHide)
        ]
コード例 #15
0
    def __init__(self, gvm, pos, items):
        self.gvm = gvm
        self.selected = 0

        Menu.__init__(self, '', items, self.selectItem)

        app = gvm.app
        stdColour = (255, 255, 0)
        hvrColour = (0, 255, 255)
        backColour = (0, 64, 192)
        self.button = TextButton(app,
                                 Location(Abs(pos, 0)),
                                 '',
                                 app.screenManager.fonts.ingameMenuFont,
                                 stdColour,
                                 hvrColour,
                                 backColour=backColour,
                                 onClick=self._toggleSubMenu)
コード例 #16
0
    def __init__(self, app, reason):
        width = app.screenManager.scaleFactor * absoluteWidth

        font = app.fonts.connectionFailedFont
        boundary = app.screenManager.scaleFactor * 20
        lines = wrapWords(app, reason, font, width - 2 * boundary)

        x = boundary
        elements = []
        colours = app.theme.colours
        for text in lines:
            elements.append(
                TextElement(app,
                            text,
                            font,
                            Location(
                                DialogBoxAttachedPoint(self, (0, x), 'midtop'),
                                'midtop'),
                            colour=colours.errorColour))
            x += font.getHeight(app)

        # Boundary * 3 for top, bottom, and middle
        height = boundary * 3 + font.getHeight(app) * (len(lines) + 1)
        size = ScaledSize(absoluteWidth, height)
        super(ConnectionFailedDialog, self).__init__(app, size,
                                                     'Connection Failed')

        self.elements = elements
        self.elements.append(
            TextButton(app,
                       Location(
                           DialogBoxAttachedPoint(self, (0, -boundary),
                                                  'midbottom'), 'midbottom'),
                       'OK',
                       font,
                       colours.dialogButtonColour,
                       colours.radioMouseover,
                       onClick=lambda sender: self.close()))
        self.onEnter = Event()
        self.onEnter.addListener(self.close)
コード例 #17
0
    def __init__(self, app, serverName='server', onCancel=None):
        super(ConnectingScreen, self).__init__(app)
        colours = app.theme.colours

        self.text = TextElement(self.app,
                                'Connecting to %s...' % serverName,
                                self.app.screenManager.fonts.bigMenuFont,
                                ScaledLocation(512, 384, 'center'),
                                colour=colours.connectingColour)

        button = TextButton(
            self.app,
            Location(ScaledScreenAttachedPoint(ScaledSize(0, 300), 'center'),
                     'center'),
            'cancel',
            self.app.screenManager.fonts.bigMenuFont,
            colours.mainMenuColour,
            colours.white,
            onClick=onCancel)
        self.onCancel = button.onClick

        self.elements = [button, self.text]
コード例 #18
0
    def setupButtons(self):
        lanButtonPos = Location(
            ScaledScreenAttachedPoint(ScaledPoint(100, 550), 'topleft'))
        self.lanButton = CheckBox(
            self.app,
            lanButtonPos,
            'LAN Discovery',
            self.app.screenManager.fonts.serverSelectionCheckboxesFont,
            self.app.theme.colours.mainMenuColour,
            initValue=self.app.connectionSettings.lanGames,
            style='circle',
            fillColour=self.app.theme.colours.mainMenuColour)
        self.lanButton.onValueChanged.addListener(lambda sender: self.save())

        lanSearchButtonPos = Location(
            ScaledScreenAttachedPoint(ScaledPoint(380, 550), 'topleft'))
        self.lanSearchButton = TextButton(
            self.app,
            lanSearchButtonPos,
            'Search LAN for Game',
            self.app.screenManager.fonts.serverSelectionCheckboxesFont,
            self.app.theme.colours.mainMenuHighlight,
            self.app.theme.colours.white,
            onClick=lambda sender: self.joinLan())

        createButtonPos = Location(
            ScaledScreenAttachedPoint(ScaledPoint(100, 600), 'topleft'))
        self.createButton = CheckBox(
            self.app,
            createButtonPos,
            'Create games on remote servers',
            self.app.screenManager.fonts.serverSelectionCheckboxesFont,
            self.app.theme.colours.mainMenuColour,
            initValue=self.app.connectionSettings.createGames,
            style='circle',
            fillColour=self.app.theme.colours.mainMenuColour)
        self.createButton.onValueChanged.addListener(
            lambda sender: self.save())

        otherButtonPos = Location(
            ScaledScreenAttachedPoint(ScaledPoint(100, 650), 'topleft'))
        self.otherButton = CheckBox(
            self.app,
            otherButtonPos,
            'Ask servers about other games',
            self.app.screenManager.fonts.serverSelectionCheckboxesFont,
            self.app.theme.colours.mainMenuColour,
            initValue=self.app.connectionSettings.otherGames,
            style='circle',
            fillColour=self.app.theme.colours.mainMenuColour)
        self.otherButton.onValueChanged.addListener(lambda sender: self.save())

        newButtonPos = Location(
            ScaledScreenAttachedPoint(ScaledPoint(850, 285), 'topleft'))
        self.newButton = TextButton(
            self.app,
            newButtonPos,
            '+ Server',
            self.app.screenManager.fonts.serverSelectionCheckboxesFont,
            self.app.theme.colours.serverSelectionNewItem,
            self.app.theme.colours.white,
            onClick=lambda sender: self.newServer())

        self.closeButton = elements.TextButton(
            self.app,
            Location(
                ScaledScreenAttachedPoint(ScaledSize(-70, 650), 'topright'),
                'topright'),
            'done',
            self.app.screenManager.fonts.bigMenuFont,
            self.app.theme.colours.mainMenuHighlight,
            self.app.theme.colours.white,
            onClick=lambda sender: self.onClose(),
        )
コード例 #19
0
ファイル: savedGameMenu.py プロジェクト: iliescufm/pygame
class SavedGameTab(Tab):
    def __init__(self, app, tabContainer, onCancel=None, onReplay=None):
        super(SavedGameTab, self).__init__(app, 'Saved Games')
        self.app = app
        self.tabContainer = tabContainer
        self.onCancel = Event(listener=onCancel)
        self.onReplay = Event(listener=onReplay)

        font = self.app.screenManager.fonts.ampleMenuFont
        smallFont = self.app.screenManager.fonts.menuFont
        colours = app.theme.colours

        # Static text
        self.staticText = [
            TextElement(self.app, 'server details:', font,
                        ScaledLocation(960, 200, 'topright'),
                        colours.headingColour),
            TextElement(self.app, 'date and time:', font,
                        ScaledLocation(960, 370, 'topright'),
                        colours.headingColour),
            TextElement(self.app, 'replay:', font,
                        ScaledLocation(620, 550, 'topleft'),
                        colours.headingColour),
            TextElement(self.app, 'stats:', font,
                        ScaledLocation(620, 605, 'topleft'),
                        colours.headingColour)
        ]

        # Dynamic text
        self.listHeaderText = TextElement(self.app, 'available game files:',
                                          font, ScaledLocation(65, 200),
                                          colours.headingColour)
        self.noFiles1Text = TextElement(self.app, '', font,
                                        ScaledLocation(65, 260),
                                        colours.noGamesColour)
        self.noFiles2Text = TextElement(self.app, '', font,
                                        ScaledLocation(65, 310),
                                        colours.noGamesColour)
        self.serverNameText = TextElement(self.app, '', smallFont,
                                          ScaledLocation(960, 255, 'topright'),
                                          colours.startButton)
        self.serverDetailsText = TextElement(
            self.app, '', smallFont, ScaledLocation(960, 295, 'topright'),
            colours.startButton)
        self.dateText = TextElement(self.app, '', smallFont,
                                    ScaledLocation(960, 425, 'topright'),
                                    colours.startButton)
        self.lengthText = TextElement(self.app, '', smallFont,
                                      ScaledLocation(960, 465, 'topright'),
                                      colours.startButton)
        self.noReplayText = TextElement(self.app, '', smallFont,
                                        ScaledLocation(960, 550, 'topright'),
                                        colours.noGamesColour)
        self.noStatsText = TextElement(self.app, '', smallFont,
                                       ScaledLocation(960, 605, 'topright'),
                                       colours.noGamesColour)

        self.dynamicText = [
            self.listHeaderText, self.noFiles1Text, self.noFiles2Text,
            self.serverNameText, self.serverDetailsText, self.dateText,
            self.lengthText, self.noReplayText, self.noStatsText
        ]

        # Text buttons
        self.watchButton = TextButton(self.app,
                                      ScaledLocation(960, 550,
                                                     'topright'), '', font,
                                      colours.secondMenuColour, colours.white)
        self.watchButton.onClick.addListener(self.watchReplay)

        self.statsButton = TextButton(self.app,
                                      ScaledLocation(960, 605,
                                                     'topright'), '', font,
                                      colours.secondMenuColour, colours.white)
        self.statsButton.onClick.addListener(self.viewStats)

        self.refreshButton = TextButton(self.app,
                                        ScaledLocation(620, 665,
                                                       'topleft'), 'refresh',
                                        font, colours.secondMenuColour,
                                        colours.white)
        self.refreshButton.onClick.addListener(self.populateList)

        self.cancelButton = TextButton(self.app,
                                       ScaledLocation(960, 665, 'topright'),
                                       'cancel', font,
                                       colours.secondMenuColour, colours.white)
        self.cancelButton.onClick.addListener(self._cancel)

        self.loadFileButton = TextButton(
            self.app, ScaledLocation(960, 190, 'bottomright'), 'load file...',
            font, colours.mainMenuColour, colours.mainMenuHighlight)
        self.loadFileButton.onClick.addListener(self.showOpenDialog)

        self.buttons = [
            self.watchButton, self.statsButton, self.refreshButton,
            self.cancelButton, self.loadFileButton
        ]

        # Replay list
        self.gameList = ListBox(self.app, ScaledArea(65, 255, 500, 450), [],
                                smallFont, colours.listboxButtons)
        self.gameList.onValueChanged.addListener(self.updateSidebar)

        # Combine the elements
        self.elementsFiles = (self.staticText + self.dynamicText +
                              self.buttons + [self.gameList])
        self.elementsNoFiles = self.dynamicText + self.buttons

        # Populate the list of replays
        self.populateList()

    def _cancel(self, sender):
        self.onCancel.execute()

    def showOpenDialog(self, sender):
        root = Tk()
        root.withdraw()
        tksupport.install(root)
        filename = askopenfilename(
            defaultextension='.trosrepl',
            filetypes=[
                ('Trosnoth replay', '*.trosrepl'),
            ],
            initialdir=getPath(user, replayDir),
            title='Select replay',
        )
        if filename:
            self.onReplay.execute(filename)

    def populateList(self, sender=None):

        # Clear out the sidebar
        for item in self.dynamicText:
            item.setText('')
        self.listHeaderText.setText('available game files:')
        self.gameList.index = -1
        self.elements = self.elementsFiles[:]

        # Get a list of files with the name '*.tros'
        logDir = getPath(user, gameDir)
        makeDirs(logDir)
        fileList = []

        for fname in os.listdir(logDir):
            if os.path.splitext(fname)[1] == gameExt:
                fileList.append(fname)

        # Assume all files are valid for now
        validFiles = fileList[:]

        self.gameInfo = {}
        oldFound = False

        for fname in fileList:
            try:
                game = RecordedGame(os.path.join(logDir, fname))
            except RecordedGameException:
                validFiles.remove(fname)
                continue
            except:
                log.warning('invalid file: %s', fname)
                continue
            else:
                if game.recordedGameVersion != recordedGameVersion:
                    validFiles.remove(fname)
                    oldFound = True

            self.gameInfo[os.path.splitext(fname)[0]] = game

        # Sort the games with most recent first.
        items = [(v.unixTimestamp, n) for n, v in self.gameInfo.iteritems()]
        items.sort(reverse=True)
        items = [n for v, n in items]
        self.gameList.setItems(items)

        if len(self.gameInfo) == 0:
            self.elements = self.elementsNoFiles[:]
            self.listHeaderText.setText('0 available game files:')
            if oldFound:
                self.noFiles1Text.setText('Some games were found from')
                self.noFiles2Text.setText('previous Trosnoth versions')
            else:
                self.noFiles1Text.setText('You have not yet run any')
                self.noFiles2Text.setText('games on this computer')
        else:
            self.gameList.setIndex(0)
            self.updateSidebar(0)
            if len(self.gameInfo) == 1:
                self.listHeaderText.setText('1 available game file:')
            else:
                self.listHeaderText.setText('{} available game files:'.format(
                    len(self.gameInfo)))

    def updateSidebar(self, listID):
        # Update the details on the sidebar
        displayName = self.gameList.getItem(listID)

        # Server title
        self.serverNameText.setText(self.gameInfo[displayName].alias)

        # Date and time of match
        datePython = map(int, self.gameInfo[displayName].dateTime.split(','))
        dateString = time.strftime('%a %d/%m/%y, %H:%M', datePython)
        self.dateText.setText(dateString)

        # Length of match
        dateUnix = time.mktime(datePython)
        if self.gameInfo[displayName].wasFinished():
            lastUnix = self.gameInfo[displayName].gameFinishedTimestamp

            lengthSeconds = int(lastUnix - dateUnix)
            lengthMinutes, lengthSeconds = divmod(lengthSeconds, 60)

            secPlural = ('s', '')[lengthSeconds == 1]
            minPlural = ('s', '')[lengthMinutes == 1]
            if lengthMinutes == 0:
                lengthString = '{} second{}'.format(lengthSeconds, secPlural)
            else:
                lengthString = '{} min{}, {} sec{}'.format(
                    lengthMinutes, minPlural, lengthSeconds, secPlural)

            self.lengthText.setText(lengthString)
        else:
            self.lengthText.setText('')

        # Enable the replay button
        if (self.gameInfo[displayName].replayFilename is not None
                and os.path.exists(self.gameInfo[displayName].replayFilename)):
            self.watchButton.setText('watch')
            self.noReplayText.setText('')
        else:
            self.watchButton.setText('')
            self.noReplayText.setText('unavailable')

        # Enabled the stats button
        if (self.gameInfo[displayName].statsFilename is not None
                and os.path.exists(self.gameInfo[displayName].statsFilename)):
            self.statsButton.setText('view')
            self.noStatsText.setText('')
        else:
            self.statsButton.setText('')
            self.noStatsText.setText('unavailable')

    def watchReplay(self, sender):
        '''Watch replay button was clicked.'''
        # Try to create a replay server.
        self.onReplay.execute(
            self.gameInfo[self.gameList.getItem()].replayFilename)

    def viewStats(self, sender=None):
        '''View stats button was clicked.'''
        game = self.gameInfo[self.gameList.getItem()]

        self.htmlPath = game.generateHtmlFile()
        browser.openPage(self.app, self.htmlPath)

    def draw(self, surface):
        super(SavedGameTab, self).draw(surface)

        rect = self.tabContainer._getTabRect()
        verLineX = rect.left + (rect.width * 0.6)
        horLineY = rect.top + (rect.height * 0.68)

        colour = self.app.theme.colours.replayTabBorder

        pygame.draw.line(surface, colour, (verLineX, rect.top),
                         (verLineX, rect.bottom),
                         self.tabContainer._getBorderWidth())
        pygame.draw.line(surface, colour, (verLineX, horLineY),
                         (rect.right, horLineY),
                         self.tabContainer._getBorderWidth())
コード例 #20
0
ファイル: savedGameMenu.py プロジェクト: iliescufm/pygame
    def __init__(self, app, tabContainer, onCancel=None, onReplay=None):
        super(SavedGameTab, self).__init__(app, 'Saved Games')
        self.app = app
        self.tabContainer = tabContainer
        self.onCancel = Event(listener=onCancel)
        self.onReplay = Event(listener=onReplay)

        font = self.app.screenManager.fonts.ampleMenuFont
        smallFont = self.app.screenManager.fonts.menuFont
        colours = app.theme.colours

        # Static text
        self.staticText = [
            TextElement(self.app, 'server details:', font,
                        ScaledLocation(960, 200, 'topright'),
                        colours.headingColour),
            TextElement(self.app, 'date and time:', font,
                        ScaledLocation(960, 370, 'topright'),
                        colours.headingColour),
            TextElement(self.app, 'replay:', font,
                        ScaledLocation(620, 550, 'topleft'),
                        colours.headingColour),
            TextElement(self.app, 'stats:', font,
                        ScaledLocation(620, 605, 'topleft'),
                        colours.headingColour)
        ]

        # Dynamic text
        self.listHeaderText = TextElement(self.app, 'available game files:',
                                          font, ScaledLocation(65, 200),
                                          colours.headingColour)
        self.noFiles1Text = TextElement(self.app, '', font,
                                        ScaledLocation(65, 260),
                                        colours.noGamesColour)
        self.noFiles2Text = TextElement(self.app, '', font,
                                        ScaledLocation(65, 310),
                                        colours.noGamesColour)
        self.serverNameText = TextElement(self.app, '', smallFont,
                                          ScaledLocation(960, 255, 'topright'),
                                          colours.startButton)
        self.serverDetailsText = TextElement(
            self.app, '', smallFont, ScaledLocation(960, 295, 'topright'),
            colours.startButton)
        self.dateText = TextElement(self.app, '', smallFont,
                                    ScaledLocation(960, 425, 'topright'),
                                    colours.startButton)
        self.lengthText = TextElement(self.app, '', smallFont,
                                      ScaledLocation(960, 465, 'topright'),
                                      colours.startButton)
        self.noReplayText = TextElement(self.app, '', smallFont,
                                        ScaledLocation(960, 550, 'topright'),
                                        colours.noGamesColour)
        self.noStatsText = TextElement(self.app, '', smallFont,
                                       ScaledLocation(960, 605, 'topright'),
                                       colours.noGamesColour)

        self.dynamicText = [
            self.listHeaderText, self.noFiles1Text, self.noFiles2Text,
            self.serverNameText, self.serverDetailsText, self.dateText,
            self.lengthText, self.noReplayText, self.noStatsText
        ]

        # Text buttons
        self.watchButton = TextButton(self.app,
                                      ScaledLocation(960, 550,
                                                     'topright'), '', font,
                                      colours.secondMenuColour, colours.white)
        self.watchButton.onClick.addListener(self.watchReplay)

        self.statsButton = TextButton(self.app,
                                      ScaledLocation(960, 605,
                                                     'topright'), '', font,
                                      colours.secondMenuColour, colours.white)
        self.statsButton.onClick.addListener(self.viewStats)

        self.refreshButton = TextButton(self.app,
                                        ScaledLocation(620, 665,
                                                       'topleft'), 'refresh',
                                        font, colours.secondMenuColour,
                                        colours.white)
        self.refreshButton.onClick.addListener(self.populateList)

        self.cancelButton = TextButton(self.app,
                                       ScaledLocation(960, 665, 'topright'),
                                       'cancel', font,
                                       colours.secondMenuColour, colours.white)
        self.cancelButton.onClick.addListener(self._cancel)

        self.loadFileButton = TextButton(
            self.app, ScaledLocation(960, 190, 'bottomright'), 'load file...',
            font, colours.mainMenuColour, colours.mainMenuHighlight)
        self.loadFileButton.onClick.addListener(self.showOpenDialog)

        self.buttons = [
            self.watchButton, self.statsButton, self.refreshButton,
            self.cancelButton, self.loadFileButton
        ]

        # Replay list
        self.gameList = ListBox(self.app, ScaledArea(65, 255, 500, 450), [],
                                smallFont, colours.listboxButtons)
        self.gameList.onValueChanged.addListener(self.updateSidebar)

        # Combine the elements
        self.elementsFiles = (self.staticText + self.dynamicText +
                              self.buttons + [self.gameList])
        self.elementsNoFiles = self.dynamicText + self.buttons

        # Populate the list of replays
        self.populateList()
コード例 #21
0
    def __init__(self, app, width=2, height=1):
        super(MapSizeBox, self).__init__(app, ScaledSize(400, 230),
                                         "Custom Size")
        labelFont = app.screenManager.fonts.bigMenuFont
        labelColour = app.theme.colours.dialogBoxTextColour
        btnFont = app.screenManager.fonts.bigMenuFont
        btnColour = app.theme.colours.dialogButtonColour
        highlightColour = app.theme.colours.black
        inputFont = app.screenManager.fonts.defaultTextBoxFont
        inputColour = app.theme.colours.grey

        self.widthBox = InputBox(app,
                                 Region(midleft=self.Relative(0.65, 0.25),
                                        size=self.Relative(0.15, 0.2)),
                                 str(width),
                                 font=inputFont,
                                 colour=inputColour,
                                 onClick=self.setFocus,
                                 onEnter=self.okClicked,
                                 validator=intValidator,
                                 maxLength=2)

        self.heightBox = InputBox(app,
                                  Region(midleft=self.Relative(0.65, 0.55),
                                         size=self.Relative(0.15, 0.2)),
                                  str(height),
                                  font=inputFont,
                                  colour=inputColour,
                                  onClick=self.setFocus,
                                  onEnter=self.okClicked,
                                  validator=intValidator,
                                  maxLength=2)

        # Add elements to screen
        self.elements = [
            TextElement(app, 'Half Width:', labelFont,
                        Location(self.Relative(0.6, 0.25), 'midright'),
                        labelColour),
            self.widthBox,
            TextElement(app, 'Height:', labelFont,
                        Location(self.Relative(0.6, 0.55), 'midright'),
                        labelColour),
            self.heightBox,
            TextButton(app,
                       Location(self.Relative(0.3, 0.9), 'center'),
                       'Ok',
                       btnFont,
                       btnColour,
                       highlightColour,
                       onClick=self.okClicked),
            TextButton(app,
                       Location(self.Relative(0.7, 0.9), 'center'),
                       'Cancel',
                       btnFont,
                       btnColour,
                       highlightColour,
                       onClick=self.cancelClicked),
        ]

        self.tabOrder = [self.widthBox, self.heightBox]
        self.setFocus(self.widthBox)
コード例 #22
0
class ScrollingText(Element):
    def __init__(self, app, area, text, colour, fonts, bgColour=None,
            textAlign='left', loop=False, startOff=False, antiAlias=False):
        super(ScrollingText,self).__init__(app)

        self.area = area
        self.border = False
        self.shadowColour = None
        self.loop = loop
        self.startOff = startOff
        self.bgColour = bgColour
        self.speed = 50

        self.offset = 0
        self.colour = colour
        self.fonts = fonts
        self.text = text
        self.textAlign = textAlign
        self.antiAlias = antiAlias
        self.dirty = False

        # A test to see whether the size has changed
        self.lastSize = app.screenManager.size

        self._setImage()

        self.autoScroll = False


        # Create up and down buttons for if there's autoscroll.
        if 'buttons' in fonts:
            font = fonts['buttons']
        else:
            font = app.fonts.scrollingButtonsFont
        pos = Location(AttachedPoint((0, 0), self._getRect, 'topright'),
                'topleft')
        self.upBtn = TextButton(app, pos, ' up', font, colour, (255,255,255))
        pos = Location(AttachedPoint((0,0), self._getRect, 'bottomright'),
                'bottomleft')
        self.dnBtn = TextButton(app, pos, ' down', font, colour, (255,255,255))

        self.onFinishedScrolling = Event()

    def setColour(self, colour):
        self.colour = colour
        self.dirty = True
        pos = Location(AttachedPoint((0,0), self._getRect, 'topright'),
                'topleft')
        if 'buttons' in self.fonts:
            font = self.fonts['buttons']
        else:
            font = self.app.fonts.scrollingButtonsFont
        self.upBtn = TextButton(self.app, pos, ' up', font, colour,
                (255,255,255))
        self.dnBtn = TextButton(self.app, pos, ' down', font, colour,
                (255,255,255))

    def setAutoscroll(self, hasAutoscroll):
        self.autoScroll = hasAutoscroll

    def setSpeed(self, speed):
        self.speed = speed

    def setBorder(self, hasBorder):
        self.border = hasBorder

    def setShadowColour(self, shadowColour):
        self.shadowColour = shadowColour
        self.dirty = True

    def _setImage(self):
        mainImage = self._setImageDetails(self.text, self.colour, self.fonts,
                self.textAlign)
        if self.shadowColour is None:
            self.image = mainImage
        else:
            shadowImage = self._setImageDetails(self.text, self.shadowColour,
                    self.fonts, self.textAlign)
            shadowOffset = (1, 1)
            size = mainImage.get_size()
            self.image = pygame.Surface(tuple([size[i] + shadowOffset[i] for i
                    in (0,1)]))
            if self.bgColour:
                self.image.fill(self.bgColour)
            else:
                key = uniqueColour((self.colour, self.shadowColour))
                self.image.fill(key)
                self.image.set_colorkey(key)
            self.image.blit(shadowImage, shadowOffset)
            self.image.blit(mainImage, (0,0))
        self.dirty = False

    def _setImageDetails(self, text, colour, fonts, align):
        margin = 50

        lines = text.split('\n')
        rendered = []
        heading1Font = fonts['h1']
        heading2Font = fonts['h2']
        bodyFont = fonts['body']
        x = 0

        width = self._getSize()[0] - 2 * margin
        while x < len(lines):
            line = lines[x]
            if line.startswith("<h1>") and line.endswith("</h1>"):
                style = "h1"
                line = line[4:len(line)-5]
                font = heading1Font
            elif line.startswith("<h2>") and line.endswith("</h2>"):
                style = "h2"
                line = line[4:len(line)-5]
                font = heading2Font
            else:
                style = "body"
                font = bodyFont

            newLines = wrapWords(self.app, line, font, width)
            line = newLines[0]
            del newLines[0]

            # Insert the new lines into the list of lines
            newLines.reverse()
            for l in newLines:
                if style == "h1":
                    l = "<h1>" + l + "</h1>"
                elif style == "h2":
                    l = "<h2>" + l + "</h2>"
                lines.insert(x + 1, l)


            if self.bgColour:
                img = font.render(self.app, line, self.antiAlias, colour,
                        self.bgColour)
            else:
                img = font.render(self.app, line, self.antiAlias, colour)
            rendered.append(img)
            x += 1

        height = 0
        width = self._getSize()[0]
        for r in rendered:
            height += r.get_height()

        newImage = pygame.Surface((width, height))
        if self.bgColour:
            newImage.fill(self.bgColour)
        else:
            key = uniqueColour((colour),)
            newImage.fill(key)
            newImage.set_colorkey(key)
        yPos = 0
        for r in rendered:
            if align == 'left':
                xPos = margin
            elif align == 'right':
                xPos = width - r.get_width() - margin
            elif align == 'middle':
                xPos = (width - r.get_width()) / 2
            else:
                raise ValueError("Not a valid alignment argument")

            newImage.blit(r, (xPos, yPos))
            yPos += r.get_height()
        if self.startOff:
            if self.loop:
                size = (width, height + self._getSize()[1])
            else:
                size = (width, height + 2 * self._getSize()[1])
        else:
            size = (width, height)

        image = pygame.Surface(size)
        if not self.bgColour:
            image.fill(key)
            image.set_colorkey(key)
        if self.startOff:
            image.blit(newImage, (0, self._getSize()[1]))
        else:
            image.blit(newImage, (0, 0))

        self.canScroll = image.get_height() > self._getSize()[1]
        self.reachedEnd = (not self.loop and self.offset == 0) or (self.loop
                and not self.canScroll)

        return image

    def returnToTop(self):
        self.offset = 0

    def _getRect(self):
        return self.area.getRect(self.app)

    def _getSize(self):
        return self._getRect().size

    def _getPt(self):
        return self._getRect().topleft

    def draw(self, screen):
        if self.dirty or self.app.screenManager.size != self.lastSize:
            self.lastSize = self.app.screenManager.size
            self._setImage()
        if not self.canScroll:
            # Our image won't cover the whole of the scrollingText
            height = self._getSize()[1] - self.image.get_height()
            rect = pygame.Rect(self._getPt()[0], self._getPt()[1] +
                    self.image.get_height(), self._getSize()[0], height)
            if self.bgColour:
                screen.fill(self.bgColour, rect)
        # Find the segment which will be drawn on screen
        rect = pygame.Rect((0, self.offset), self._getSize())
        screen.blit(self.image, self._getPt(), rect)

        if (self.loop and self.canScroll and self.offset + self._getSize()[1] >
                self.image.get_height()):
            # It's doing the looping
            rect = pygame.Rect((0, self.offset - self.image.get_height()),
                    self._getSize())
            screen.blit(self.image, self._getPt(), rect)

        if self.border:
            rect.topleft = self._getPt()
            pygame.draw.rect(screen, (0,0,0), rect, 4)

        if not self.autoScroll:
            self.upBtn.draw(screen)
            self.dnBtn.draw(screen)

    def processEvent(self, event):
        if self.autoScroll:
            # We don't consume any events.
            return event
        else:
            event = self.upBtn.processEvent(event)
            if not event: return
            event = self.dnBtn.processEvent(event)
            if not event: return

            return event

    def scroll(self, offset):
        if not self.canScroll:
            return
        if self.reachedEnd:
            if ((offset > 0 and self.offset > 0) or
                    (offset < 0 and self.offset == 0)):
               # They have already reached the end, and are trying to
               # go further that way - do nothing.
               return
        self.reachedEnd = False
        newOffset = offset + self.offset
        if not self.loop:
            if newOffset + self._getSize()[1] > self.image.get_height():
                # They've hit the bottom
                newOffset = self.image.get_height() - self._getSize()[1]
                self.onFinishedScrolling.execute()
                self.reachedEnd = True
            elif newOffset <= 0:
                # Hit the top
                newOffset = 0
                self.onFinishedScrolling.execute()
                self.reachedEnd = True
        self.offset = newOffset

        # For looping: make sure it loops around
        if self.loop:
            self.offset %= self.image.get_height()


    def _getSpeed(self):
        if hasattr(self.speed, 'getSpeed'):
            speed = self.speed.getSpeed(self.app)
        else:
            speed = self.speed
        return speed

    def tick(self, deltaT):
        if self.autoScroll:
            self.scroll(self._getSpeed() * deltaT)
        else:
            if self.upBtn.mouseOver:
                self.scroll(-self._getSpeed() * deltaT)
            elif self.dnBtn.mouseOver:
                self.scroll(self._getSpeed() * deltaT)
            self.upBtn.tick(deltaT)
            self.dnBtn.tick(deltaT)