def __init__(self, arenaId, token): self.arenaId = arenaId self.token = token self.amp = None self.port = None self.processDied = False self.startCalled = False self.ready = False self.onReady = Event(['result']) self.onExit = Event(['protocol', 'reason']) self.onInfoChanged = Event(['proxy']) self.status = 'starting up...' self.players = 0 self.paused = False self.teamInfo = [ { 'shots': True, 'caps': True }, { 'shots': True, 'caps': True }, ]
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]
def __init__(self, app, area, font, borderColour=(0, 0, 0)): super(TabContainer, self).__init__(app) self.onTabSelected = Event() # area is that of the entire space including tab headers self.area = area self.font = font self._borderWidth = ScaledScalar(3) self.borderColour = borderColour nextTab = lambda: self._tabSelected( (self.selectedIndex + 1) % len(self.tabs)) lastTab = lambda: self._tabSelected( (self.selectedIndex - 1) % len(self.tabs)) self.nextTabKey = Hotkey(app, pygame.K_TAB, pygame.KMOD_CTRL) self.nextTabKey.onTriggered.addListener(nextTab) self.lastTabKey = Hotkey(app, pygame.K_TAB, pygame.KMOD_CTRL | pygame.KMOD_SHIFT) self.lastTabKey.onTriggered.addListener(lastTab) self.tabs = [] self.tabHeaders = TabHeaderRow(app, self) self.selectedIndex = -1 self.tabHeaders._update() self.elements = [self.tabHeaders, self.lastTabKey, self.nextTabKey] self.tabHeaders._update()
class RadioButtonGroup(framework.CompoundElement): def __init__(self, app): super(RadioButtonGroup, self).__init__(app) self.elements = [] self.selectedIndex = -1 self.onSelectionChanged = Event() self.by_value = {} def add(self, radioButton): self.elements.append(radioButton) self.by_value[radioButton.value] = radioButton radioButton._joinGroup(self) def getSelectedValue(self): if self.selectedIndex == -1: return None else: return self.elements[self.selectedIndex].value def selected(self, radioButton): if radioButton in self.by_value: radioButton = self.by_value[radioButton] assert radioButton in self.elements, ("Cannot select a radiobutton " "that isn't in this group") newIndex = self.elements.index(radioButton) if newIndex == self.selectedIndex: return if self.selectedIndex != -1: self.elements[self.selectedIndex].deselected() self.selectedIndex = newIndex radioButton.selected() self.onSelectionChanged.execute(self.selectedIndex)
class LifeSpan(object): ''' Used by anything which may end at some point (e.g., level, trigger, server). Allows registration of things which should also be torn down when this LifeSpan ends. ''' def __init__(self, parent=None, parents=None): self.ended = False self.onEnded = Event([]) if parent: parent.onEnded.addListener(self.stop) if parents: for p in parents: p.onEnded.addListener(self.stop) def stop(self): if self.ended: return self.ended = True self.onEnded() # Prevent this lifespan being used after it's ended self.onEnded.clear() self.onEnded = None
class Menu(object): ''' @param name the caption of this menu @param items a sequence of MenuItem objects to be displayed in this menu ''' def __init__(self, name, items=(), listener=None): self.name = name self.items = list(items) self.onAction = Event() # (action) if listener is not None: self.onAction.addListener(listener) for item in items: item.onAction.addListener(self.onAction.execute) def popItem(self, index): item = self.items.pop(index) item.onAction.removeListener(self.onAction.execute) return item def removeItem(self, item): self.popItem(self.items.index(item)) def insertItem(self, pos, item): self.items.insert(pos, item) item.onAction.addListener(self.onAction.execute) def appendItem(self, item): self.insertItem(len(self.items), item)
def __init__(self, app, area, bounds=None, snap=False): super(Slider, self).__init__(app) self.app = app self.area = area self.beingDragged = False self.snap = snap if not bounds: bounds = 0, 100 self.lowBound, self.highBound = bounds self.unscaledSlider = 20 self.sliderRectWidth = int(self.unscaledSlider * app.screenManager.scaleFactor) self.lineColour = (0, 192, 0) self.sliderColour = (0, 255, 0) self.onValueChanged = Event() self.onSlide = Event() self.largeArea = ScaledArea( self.area.point.val[0] + self.unscaledSlider / 2, self.area.point.val[1], self.area.size.val[0] - self.unscaledSlider + 1, self.area.size.val[1]) self.area, self.largeArea = self.largeArea, self.area self.sliderVal = self.highBound
class Hotkey(Element): def __init__(self, app, key, modifiers): super(Hotkey, self).__init__(app) self.onTriggered = Event() self.key = key self.mods = modifiers def processEvent(self, event): if event.type == pygame.KEYDOWN: if self.testEquals(event.key, event.mod): self.onTriggered.execute() return return event def __str__(self): return keyboard.shortcutName(self.key, self.mods) def testEquals(self, key, modifiers, mapping=None): 'Checks if the key press matches this shortcut.' # First test: key equality. if key <> self.key: return False # Second test: modifier compatibility. for kmod, modName in keyboard.KMOD_NAMES: if self.mods & kmod: if not (modifiers & kmod): return False elif modifiers & kmod: return False # Testing modifiers as done above ignores left/right status. return True
def __init__(self, app, world, onChange=None): CompoundElement.__init__(self, app) self.world = world self.playerId = NO_PLAYER self.readyMenu = ReadyMenu(self, 0) self.levelMenu = LevelMenu(self, MENU_WIDTH) self.teamMenu = TeamMenu(self, 2 * MENU_WIDTH) self.sizeMenu = SizeMenu(self, 3 * MENU_WIDTH) self.durationMenu = DurationMenu(self, 4 * MENU_WIDTH) self.onChange = Event() if onChange is not None: self.onChange.addListener(onChange) self.subMenu = GameVoteSubMenu(app) font = app.screenManager.fonts.ingameMenuFont self.elements = [ SolidRect( app, (0, 64, 192), None, Region(topleft=Abs(0, 0), width=Abs(4 * MENU_WIDTH), height=Abs(font.getHeight(app) + 2))), self.subMenu, self.readyMenu.button, self.levelMenu.button, self.teamMenu.button, self.sizeMenu.button, self.durationMenu.button, ]
class TextBoxCell(Cell): def __init__(self, app, row, column): super(TextBoxCell, self).__init__(app, row, column) textAlign = self.styleGet('textAlign') self.inputBox = InputBox( self.app, Area( CellAttachedPoint((0, 0), self, textAlign), self._getUsableRect().size, textAlign), font=self.styleGet('font'), colour=self.styleGet('foreColour')) self.inputBox.onEdit.addListener(self._valueChanged) self.elements = [self.inputBox] self._oldText = '' self._readOnly = True self.setReadOnly(False) self.onValueChanged = Event() def _valueChanged(self, sender): self._oldText = self.inputBox.getValue() self.onValueChanged.execute(self) def setReadOnly(self, readOnly): if readOnly == self._readOnly: return self._readOnly = readOnly if readOnly: self.inputBox.onClick.removeListener(self._boxClicked) else: self.inputBox.onClick.addListener(self._boxClicked) self.setFocus(None) def lostFocus(self): self.setFocus(None) def setText(self, text): if text != self._oldText: self.inputBox.setValue(text) self._styleChanged = True self._oldText = text def getText(self): return self._oldText def setMaxLength(self, length): self.inputBox.setMaxLength(length) def setValidator(self, validator): self.inputBox.setValidator(validator) def _update(self): self.inputBox.setFont(self.styleGet('font')) self.inputBox.setFontColour(self.styleGet('foreColour')) bgColour = self.styleGet('backColour') if bgColour is not None: self.inputBox.setBackColour(bgColour) textAlign = self.styleGet('textAlign') self.inputBox.area.anchor = textAlign self.inputBox.area.point.attachedAt = textAlign
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
def __init__(self, app): self.app = app self.game = None self.trosnothClient = None self.onGameOpened = Event() # (game, authTag) self.onReplayOpened = Event() # (game) self.onGameClosed = Event()
def __init__(self, name, action=None, listener=None, enabled=True): self.name = name self.onClick = Event() # (MenuItem) self.onAction = Event() # (action) self.action = action self.enabled = enabled if listener is not None: self.onClick.addListener(listener)
def __init__(self, name, items=(), listener=None): self.name = name self.items = list(items) self.onAction = Event() # (action) if listener is not None: self.onAction.addListener(listener) for item in items: item.onAction.addListener(self.onAction.execute)
def __init__(self, parent=None, parents=None): self.ended = False self.onEnded = Event([]) if parent: parent.onEnded.addListener(self.stop) if parents: for p in parents: p.onEnded.addListener(self.stop)
def __init__(self, game, authTagManager=None, *args, **kwargs): self.game = game self.authTagManager = authTagManager self.connectedClients = set() self.onShutdown = Event() # () self.running = True self._alreadyShutdown = False
def start(self): super(GoalSetterBot, self).start() self.onTick = Event() self.onOrderFinished = Event() self.recentGoals = {} self.clearRecent = None self.mainGoal = self.MainGoalClass(self, None) self.mainGoal.start()
def __init__(self, game, aiClass, fromLevel, nick=None, *args, **kwargs): super(AIAgent, self).__init__(game=game, *args, **kwargs) self.aiClass = aiClass self.fromLevel = fromLevel self._initialisationNick = nick self.ai = None self.team = None self.requestedNick = None self._onBotSet = Event([]) self._loop = WeakLoopingCall(self, '_tick')
def __init__(self, app, size, caption, subCaption=None): CompoundElement.__init__(self, app) self.showing = False self.size = size self._edge = MoveableBoxEdge(self.app, self, caption, subCaption) self.setColours(self.defaultBorderColour, self.defaultTitleColour, self.defaultBackgroundColour) self.onClose = Event()
def __init__(self, app, area, initValue='', validator=None, font=None, colour=(255, 255, 255), maxLength=None, onClick=None, onEnter=None, onTab=None, onEsc=None, onEdit=None): super(InputBox, self).__init__(app) self.area = area self.onClick = Event() if onClick is not None: self.onClick.addListener(onClick) self.onEnter = Event() if onEnter is not None: self.onEnter.addListener(onEnter) self.onTab = Event() if onTab is not None: self.onTab.addListener(onTab) self.onEsc = Event() if onEsc is not None: self.onEsc.addListener(onEsc) self.onEdit = Event() if onEdit is not None: self.onEdit.addListener(onEdit) if validator: self.validator = validator else: self.validator = lambda x: True if font: self.font = font else: self.font = self.app.screenManager.fonts.defaultTextBoxFont self.value = initValue self.maxLength = maxLength self.fontColour = (0, 0, 0) self.backColour = colour self.cursorColour = (255, 0, 0) self._cursorVisible = True self._timeToFlash = self.cursorFlashTime # Calculate the white part of the input area self.cursorIndex = len(self.value) self.offset = 0
def __init__(self, app, key, mapping=None): ''' key may be a physical pygame key or a string where mapping[pygameKey] = key ''' super(MappingHotkey, self).__init__(app) self.key = key self.onActivated = Event() if mapping is None: mapping = {} self.mapping = mapping
class GameVoteMenu(CompoundElement): def __init__(self, app, world, onChange=None): CompoundElement.__init__(self, app) self.world = world self.playerId = NO_PLAYER self.readyMenu = ReadyMenu(self, 0) self.levelMenu = LevelMenu(self, MENU_WIDTH) self.teamMenu = TeamMenu(self, 2 * MENU_WIDTH) self.sizeMenu = SizeMenu(self, 3 * MENU_WIDTH) self.durationMenu = DurationMenu(self, 4 * MENU_WIDTH) self.onChange = Event() if onChange is not None: self.onChange.addListener(onChange) self.subMenu = GameVoteSubMenu(app) font = app.screenManager.fonts.ingameMenuFont self.elements = [ SolidRect( app, (0, 64, 192), None, Region(topleft=Abs(0, 0), width=Abs(4 * MENU_WIDTH), height=Abs(font.getHeight(app) + 2))), self.subMenu, self.readyMenu.button, self.levelMenu.button, self.teamMenu.button, self.sizeMenu.button, self.durationMenu.button, ] def update(self, player): self.playerId = player.id self.readyMenu.updateTitle(player) self.levelMenu.updateTitle(player) self.teamMenu.updateTitle(player) self.sizeMenu.updateTitle(player) self.durationMenu.updateTitle(player) if self.subMenu.manager.menu is not None: self.subMenu.manager.menu.update() def showSubMenu(self, menu): menu.update() if self.subMenu.manager.menu is menu or self.subMenu.hidden: self.subMenu.hide() self.subMenu.manager.setDefaultMenu(menu) self.subMenu.location = menu.button.pos def hideSubMenu(self): if not self.subMenu.hidden: self.subMenu.hide()
class MenuManager(object): def __init__(self, defaultMenu=None): self.defaultMenu = defaultMenu self.menu = defaultMenu self.menuStack = [] self.onShowMenu = Event() # (menu) def setDefaultMenu(self, defaultMenu): default = len(self.menuStack) == 0 and self.menu is self.defaultMenu self.defaultMenu = defaultMenu if default or self.menu is None: self.menu = defaultMenu self.onShowMenu.execute(defaultMenu) def reset(self): self.menu = self.defaultMenu self.menuStack = [] self.onShowMenu.execute(self.defaultMenu) def cancel(self): if len(self.menuStack) > 0: self.menu = self.menuStack.pop() else: self.menu = self.defaultMenu self.onShowMenu.execute(self.menu) def showMenu(self, menu): self.menuStack.append(self.menu) self.menu = menu self.onShowMenu.execute(menu)
class SettingsMenu(framework.CompoundElement): def __init__(self, app, onClose=None, onRestart=None, showThemes=False, showSound=True, showDisplay=True, showKeymap=True): super(SettingsMenu, self).__init__(app) self.onClose = Event() if onClose is not None: self.onClose.addListener(onClose) self.onRestart = Event() if onRestart is not None: self.onRestart.addListener(onRestart) area = ScaledArea(50, 140, 924, 570) bg = pygame.Surface((924, 500)) bg.fill(app.theme.colours.settingsMenu) if app.displaySettings.alphaOverlays: bg.set_alpha(192) font = app.screenManager.fonts.bigMenuFont self.tabContainer = TabContainer(self.app, area, font, app.theme.colours.settingsTabBorder) bp = elements.SizedPicture( app, bg, Location(AttachedPoint((0, 0), self.tabContainer._getTabRect)), TabSize(self.tabContainer)) if showDisplay: displayTab = DisplaySettingsTab(app, onClose=self.onClose.execute) self.tabContainer.addTab(displayTab) if showKeymap: keymapTab = KeymapTab(app, onClose=self.onClose.execute) self.tabContainer.addTab(keymapTab) if showSound: soundTab = SoundSettingsTab(app, onClose=self.onClose.execute) self.tabContainer.addTab(soundTab) if showThemes: themeTab = ThemeTab(app, onClose=self.onClose.execute, onRestart=self.onRestart.execute) self.tabContainer.addTab(themeTab) self.elements = [bp, self.tabContainer]
def __init__( self, game, noAuth=False, agentCallback=None, *args, **kwargs): self.game = game self.noAuth = noAuth self.agentCallback = agentCallback self.connectedClients = set() self.onShutdown = Event() # () self.onConnectionEstablished = Event(['protocol']) self.onConnectionLost = Event(['protocol']) self.running = True self._alreadyShutdown = False
class ConnectionFailedDialog(DialogBox): 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) def processEvent(self, event): if event.type == pygame.KEYDOWN and event.key in (pygame.K_KP_ENTER, pygame.K_RETURN): self.onEnter.execute() return None else: return super(ConnectionFailedDialog, self).processEvent(event)
def __init__(self, app, colour, onCancel=None, speed=None, loop=True, startOff=False, backText='back to main menu', highlight=(255, 255, 255)): super(CreditsScreen, self).__init__(app) self.colour = colour self.highlight = highlight self.onCancel = Event() if onCancel is not None: self.onCancel.addListener(onCancel) f = open(getPath(startupMenu, 'credits.txt'), 'rU', encoding='utf-8') area = ScaledArea(50, 130, 900, 540) fonts = { 'body': self.app.fonts.creditsFont, 'h1': self.app.fonts.creditsH1, 'h2': self.app.fonts.creditsH2 } text = f.read() if not startOff: # Make at least some room on top and bottom text = '\n' * 3 + text + '\n' * 2 self.credits = scrollingText.ScrollingText(self.app, area, text, self.colour, fonts, textAlign='middle', loop=loop, startOff=startOff) self.credits.setShadowColour((192, 192, 192)) self.credits.setAutoscroll(True) if speed is None: speed = 80 self.credits.setSpeed(ScalingSpeed(speed)) self.credits.setBorder(False) self.backText = backText cancelButton = self.button(backText, self.onCancel.execute, (-50, -30), 'bottomright') self.elements = [self.credits, cancelButton]
def __init__(self, world, *args, **kwargs): super(Game, self).__init__(*args, **kwargs) self.world = world self.onServerCommand = Event() # (msg) world.onPlayerRemoved.addListener(self.playerRemoved)
def __init__(self, app, row, column): super(TextBoxCell, self).__init__(app, row, column) textAlign = self.styleGet('textAlign') self.inputBox = InputBox( self.app, Area( CellAttachedPoint((0, 0), self, textAlign), self._getUsableRect().size, textAlign), font=self.styleGet('font'), colour=self.styleGet('foreColour')) self.inputBox.onEdit.addListener(self._valueChanged) self.elements = [self.inputBox] self._oldText = '' self._readOnly = True self.setReadOnly(False) self.onValueChanged = Event()
def connectionMade(self): self.onConnectionLost = Event() super(TrosnothClientProtocol, self).connectionMade() self.validated = False self.settings_deferred = defer.Deferred() self.getSettingsCalled = False