Beispiel #1
0
class ThiefHud(GameHud):
    def __init__(self, clientState):
        super().__init__(clientState)
        self.entryLabel = self.label(text='', mayChange=True)

        self.entry = DirectEntry(
            initialText='Type card name...',
            scale=0.05,
            focus=1,
            command=self.useThiefAbility,
            focusInCommand=lambda: self.entry.enterText(''))

        self.entry.hide()

        self.thiefAbilityButton = self.button(
            text="Faction Ability",
            scale=1,
            pos=(0, 0, -1),
            parent=self.endTurnButton,
            command=self.onThiefAbilityButton)

    def useThiefAbility(self, cardname):
        toDiscard = self.toDiscard.getPythonTag('card')
        toSteal = self.toSteal.getPythonTag('card')
        base.clientActions.useThiefAbility(toDiscard, toSteal, cardname)
        base.audioMaster.thiefAbilitySound.play()
        base.mouseHandler.targeting = False
        self.entry.hide()

    def onThiefAbilityButton(self):
        def chooseTarget(target):
            if target is None:
                base.mouseHandler.targeting = False
                showCard(self.toDiscard)
                return
            elif target.getPythonTag('zone') is not base.enemy.facedowns:
                return
            self.toSteal = target
            self.entry.show()

        def chooseDiscard(target):
            if target is None:
                base.mouseHandler.targeting = False
                return
            elif target.getPythonTag('zone') is not base.player.hand:
                return
            self.toDiscard = target
            hideCard(target)
            base.mouseHandler.startTargeting("Choose a target.", chooseTarget)

        base.mouseHandler.startTargeting("Choose a card to discard.",
                                         chooseDiscard)

    def redraw(self):
        super().redraw()

        # TODO: kludge
        if hasattr(self, 'thiefAbilityButton'):
            self.thiefAbilityButton.show()
Beispiel #2
0
class connectGUI():
    def __init__(self, _client):
        # Ref
        self.client = _client

        # create a host button
        self.btnConnect = DirectButton(
            # Scale and position
            scale=0.25,
            pos=(0, 0, 0),
            # Text
            text="Connect",
            # Frame
            # Functionality
            command=self.connect)

        # create the IP input field
        self.txtIP = DirectEntry(
            # scale and position
            pos=(0, 0, -.35),
            scale=0.25,
            width=9,
            # Text
            text="",
            text_align=TextNode.ACenter,
            initialText="127.0.0.1",
            numLines=1,
            # Functionality
            command=self.connect,
            focusInCommand=self.clearText)

        self.hide()

    def show(self):
        self.btnConnect.show()
        self.txtIP.show()

    def hide(self):
        self.btnConnect.hide()
        self.txtIP.hide()

    def clearText(self):
        """Function to clear the text that was previously entered in the
        IP input field"""
        self.txtIP.enterText("")
        #TODO: Do something with the ip

    def connect(self, ip=None):
        """Function which will be called by pressing the connect button
        or hit enter while the focus is on the inut field"""
        if ip == None: ip = self.txtIP.get(True)
        if ip != "":
            if self.client.connectionMgr.connectToServer(ip, 5001):
                gui = lobbyGUI(self.client)
                self.client.gui.hide()
                gui.show()
            else:
                return
Beispiel #3
0
class DeveloperConsole(InteractiveInterpreter, DirectObject):
  """The name says it all."""
  def __init__(self):
    sys.stdout = PseudoFile(self.writeOut)
    sys.stderr = PseudoFile(self.writeErr)
    tpErr = TextProperties()
    tpErr.setTextColor(1, 0.5, 0.5, 1)
    TextPropertiesManager.getGlobalPtr().setProperties("err", tpErr)
    #font = loader.loadFont("cmss12")
    self.frame = DirectFrame(parent = base.a2dTopCenter, text_align = TextNode.ALeft, text_pos = (-base.getAspectRatio() + TEXT_MARGIN[0], TEXT_MARGIN[1]), text_scale = 0.05, text_fg = (1, 1, 1, 1), frameSize = (-2.0, 2.0, -0.5, 0.0), frameColor = (0, 0, 0, 0.5), text = '')#, text_font = font)
    self.entry = DirectEntry(parent = base.a2dTopLeft, command = self.command, scale = 0.05, width = 1000.0, pos = (-0.02, 0, -0.48), relief = None, text_pos = (1.5, 0, 0), text_fg = (1, 1, 0.5, 1), rolloverSound = None, clickSound = None)#, text_font = font)
    self.otext = OnscreenText(parent = self.entry, scale = 1, align = TextNode.ALeft, pos = (1, 0, 0), fg = (1, 1, 0.5, 1), text = ':')#, font = font)
    self.lines = [''] * 9
    self.commands = []  # All previously sent commands
    self.cscroll = None # Index of currently navigated command, None if current
    self.command = ''   # Currently entered command
    self.block = ''     # Temporarily stores a block of commands
    self.hide()
    self.initialized = False
  
  def prevCommand(self):
    if self.hidden: return
    if len(self.commands) == 0: return
    if self.cscroll == None:
      self.cscroll = len(self.commands)
      self.command = self.entry.get()
    elif self.cscroll <= 0:
      return
    else:
      self.commands[self.cscroll] = self.entry.get()
    self.cscroll -= 1
    self.entry.set(self.commands[self.cscroll])
    self.entry.setCursorPosition(len(self.commands[self.cscroll]))
  
  def nextCommand(self):
    if self.hidden: return
    if len(self.commands) == 0: return
    if self.cscroll == None: return
    self.commands[self.cscroll] = self.entry.get()
    self.cscroll += 1
    if self.cscroll >= len(self.commands):
      self.cscroll = None
      self.entry.set(self.command)
      self.entry.setCursorPosition(len(self.command))
    else:
      self.entry.set(self.commands[self.cscroll])
      self.entry.setCursorPosition(len(self.commands[self.cscroll]))

  def writeOut(self, line, copy = True):
    if copy: sys.__stdout__.write(line)
    lines = line.split('\n')
    firstline = lines.pop(0)
    self.lines[-1] += firstline
    self.lines += lines
    self.frame['text'] = '\n'.join(self.lines[-9:])

  def writeErr(self, line, copy = True):
    if copy: sys.__stderr__.write(line)
    line = '\1err\1%s\2' % line
    lines = line.split('\n')
    firstline = lines.pop(0)
    self.lines[-1] += firstline
    self.lines += lines
    self.frame['text'] = '\n'.join(self.lines[-9:])

  def command(self, text):
    if not self.hidden:
      self.cscroll = None
      self.command = ''
      self.entry.set('')
      self.entry['focus'] = True
      self.writeOut(self.otext['text'] + ' ' + text + '\n', False)
      if text != '' and (len(self.commands) == 0 or self.commands[-1] != text):
        self.commands.append(text)
      
      # Insert plugins into the local namespace
      locals = __main__.__dict__
      #locals['manager'] = self.manager
      #for plugin in self.manager.named.keys():
      #  locals[plugin] = self.manager.named[plugin]
      locals['panda3d'] = panda3d
      
      # Run it and print the output.
      if not self.initialized:
        InteractiveInterpreter.__init__(self, locals = locals)
        self.initialized = True
      try:
        if self.runsource(self.block + '\n' + text) and text != '':
          self.otext['text'] = '.'
          self.block += '\n' + text
        else:
          self.otext['text'] = ':'
          self.block = ''      
      except Exception: # Not just "except", it will also catch SystemExit
        # Whoops! Print out a traceback.
        self.writeErr(traceback.format_exc())

  def toggle(self):
    if self.hidden:
      self.show()
    else:
      self.hide()

  def show(self):
    self.accept('arrow_up', self.prevCommand)
    self.accept('arrow_up-repeat', self.prevCommand)
    self.accept('arrow_down', self.nextCommand)
    self.accept('arrow_down-repeat', self.nextCommand)
    self.hidden = False
    self.entry['focus'] = True
    self.frame.show()
    self.entry.show()
    self.otext.show()

  def hide(self):
    self.ignoreAll()
    self.hidden = True
    self.entry['focus'] = False
    self.frame.hide()
    self.entry.hide()
    self.otext.hide()

  def destroy(self):
    sys.stdout = sys.__stdout__
    sys.stderr = sys.__stderr__
    self.ignoreAll()
    self.frame.destroy()
    self.entry.destroy()
    self.otext.destroy()
Beispiel #4
0
class DeveloperConsole(InteractiveInterpreter, DirectObject):
    """The name says it all."""
    def __init__(self, manager, xml):
        sys.stdout = PseudoFile(self.writeOut)
        sys.stderr = PseudoFile(self.writeErr)
        tpErr = TextProperties()
        tpErr.setTextColor(1, 0.5, 0.5, 1)
        TextPropertiesManager.getGlobalPtr().setProperties("err", tpErr)
        self.manager = manager
        font = loader.loadFont("cmss12")
        self.frame = DirectFrame(parent=base.a2dTopCenter,
                                 text_align=TextNode.ALeft,
                                 text_pos=(-base.getAspectRatio() +
                                           TEXT_MARGIN[0], TEXT_MARGIN[1]),
                                 text_scale=0.05,
                                 text_fg=(1, 1, 1, 1),
                                 frameSize=(-2.0, 2.0, -0.5, 0.0),
                                 frameColor=(0, 0, 0, 0.5),
                                 text='',
                                 text_font=font)
        self.entry = DirectEntry(parent=base.a2dTopLeft,
                                 command=self.command,
                                 scale=0.05,
                                 width=1000.0,
                                 pos=(-0.02, 0, -0.48),
                                 relief=None,
                                 text_pos=(1.5, 0, 0),
                                 text_fg=(1, 1, 0.5, 1),
                                 rolloverSound=None,
                                 clickSound=None,
                                 text_font=font)
        self.otext = OnscreenText(parent=self.entry,
                                  scale=1,
                                  align=TextNode.ALeft,
                                  pos=(1, 0, 0),
                                  fg=(1, 1, 0.5, 1),
                                  text=':',
                                  font=font)
        self.lines = [''] * 9
        self.commands = []  # All previously sent commands
        self.cscroll = None  # Index of currently navigated command, None if current
        self.command = ''  # Currently entered command
        self.block = ''  # Temporarily stores a block of commands
        self.hide()
        self.initialized = False

    def prevCommand(self):
        if self.hidden: return
        if len(self.commands) == 0: return
        if self.cscroll == None:
            self.cscroll = len(self.commands)
            self.command = self.entry.get()
        elif self.cscroll <= 0:
            return
        else:
            self.commands[self.cscroll] = self.entry.get()
        self.cscroll -= 1
        self.entry.set(self.commands[self.cscroll])
        self.entry.setCursorPosition(len(self.commands[self.cscroll]))

    def nextCommand(self):
        if self.hidden: return
        if len(self.commands) == 0: return
        if self.cscroll == None: return
        self.commands[self.cscroll] = self.entry.get()
        self.cscroll += 1
        if self.cscroll >= len(self.commands):
            self.cscroll = None
            self.entry.set(self.command)
            self.entry.setCursorPosition(len(self.command))
        else:
            self.entry.set(self.commands[self.cscroll])
            self.entry.setCursorPosition(len(self.commands[self.cscroll]))

    def writeOut(self, line, copy=True):
        if copy: sys.__stdout__.write(line)
        lines = line.split('\n')
        firstline = lines.pop(0)
        self.lines[-1] += firstline
        self.lines += lines
        self.frame['text'] = '\n'.join(self.lines[-9:])

    def writeErr(self, line, copy=True):
        if copy: sys.__stderr__.write(line)
        line = '\1err\1%s\2' % line
        lines = line.split('\n')
        firstline = lines.pop(0)
        self.lines[-1] += firstline
        self.lines += lines
        self.frame['text'] = '\n'.join(self.lines[-9:])

    def command(self, text):
        if not self.hidden:
            self.cscroll = None
            self.command = ''
            self.entry.set('')
            self.entry['focus'] = True
            self.writeOut(self.otext['text'] + ' ' + text + '\n', False)
            if text != '' and (len(self.commands) == 0
                               or self.commands[-1] != text):
                self.commands.append(text)

            # Insert plugins into the local namespace
            locals = __main__.__dict__
            locals['manager'] = self.manager
            for plugin in self.manager.named.keys():
                locals[plugin] = self.manager.named[plugin]
            locals['panda3d'] = panda3d

            # Run it and print the output.
            if not self.initialized:
                InteractiveInterpreter.__init__(self, locals=locals)
                self.initialized = True
            try:
                if self.runsource(self.block + '\n' + text) and text != '':
                    self.otext['text'] = '.'
                    self.block += '\n' + text
                else:
                    self.otext['text'] = ':'
                    self.block = ''
            except Exception:  # Not just "except", it will also catch SystemExit
                # Whoops! Print out a traceback.
                self.writeErr(traceback.format_exc())

    def toggle(self):
        if self.hidden:
            self.show()
        else:
            self.hide()

    def show(self):
        self.accept('arrow_up', self.prevCommand)
        self.accept('arrow_up-repeat', self.prevCommand)
        self.accept('arrow_down', self.nextCommand)
        self.accept('arrow_down-repeat', self.nextCommand)
        self.hidden = False
        self.entry['focus'] = True
        self.frame.show()
        self.entry.show()
        self.otext.show()

    def hide(self):
        self.ignoreAll()
        self.hidden = True
        self.entry['focus'] = False
        self.frame.hide()
        self.entry.hide()
        self.otext.hide()

    def destroy(self):
        sys.stdout = sys.__stdout__
        sys.stderr = sys.__stderr__
        self.ignoreAll()
        self.frame.destroy()
        self.entry.destroy()
        self.otext.destroy()
Beispiel #5
0
class DeveloperConsole(InteractiveInterpreter, DirectObject):
    def __init__(self):
        sys.stdout = PseudoFile(self.write_out)
        sys.stderr = PseudoFile(self.write_err)
        tp_err = TextProperties()
        tp_err.setTextColor(1, 0.5, 0.5, 1)
        TextPropertiesManager.getGlobalPtr().setProperties('err', tp_err)
        font = loader.loadFont('cmss12')
        self.frame = DirectFrame(parent=base.a2dTopCenter,
                                 text_align=TextNode.ALeft,
                                 text_pos=(base.a2dLeft + TEXT_MARGIN[0],
                                           TEXT_MARGIN[1]),
                                 text_scale=0.05,
                                 text_fg=(1, 1, 1, 1),
                                 frameSize=(-2.0, 2.0, -1, 0.0),
                                 frameColor=(0, 0, 0, 0.5),
                                 text='',
                                 text_font=font,
                                 sortOrder=4)
        self.entry = DirectEntry(parent=base.a2dTopLeft,
                                 command=self.command,
                                 scale=0.05,
                                 width=1000.0,
                                 pos=(-0.02, 0, -0.98),
                                 relief=None,
                                 text_pos=(1.5, 0, 0),
                                 text_fg=(1, 1, 0.5, 1),
                                 rolloverSound=None,
                                 clickSound=None,
                                 text_font=font)
        self.otext = OnscreenText(parent=self.entry,
                                  scale=1,
                                  align=TextNode.ALeft,
                                  pos=(1, 0, 0),
                                  fg=(1, 1, 0.5, 1),
                                  text=':',
                                  font=font)
        self.lines = [''] * 19
        self.commands = []  # All previously sent commands
        self.cscroll = None  # Index of currently navigated command, None if current
        self.command = ''  # Currently entered command
        self.block = ''  # Temporarily stores a block of commands
        self.hide()
        self.initialized = False

    def prev_command(self):
        if self.hidden:
            return
        if len(self.commands) == 0:
            return
        if self.cscroll is None:
            self.cscroll = len(self.commands)
            self.command = self.entry.get()
        elif self.cscroll <= 0:
            return
        else:
            self.commands[self.cscroll] = self.entry.get()
        self.cscroll -= 1
        self.entry.set(self.commands[self.cscroll])
        self.entry.setCursorPosition(len(self.commands[self.cscroll]))

    def next_command(self):
        if self.hidden:
            return
        if len(self.commands) == 0:
            return
        if self.cscroll is None:
            return
        self.commands[self.cscroll] = self.entry.get()
        self.cscroll += 1
        if self.cscroll >= len(self.commands):
            self.cscroll = None
            self.entry.set(self.command)
            self.entry.setCursorPosition(len(self.command))
        else:
            self.entry.set(self.commands[self.cscroll])
            self.entry.setCursorPosition(len(self.commands[self.cscroll]))

    def write_out(self, line, copy=True):
        if copy:
            sys.__stdout__.write(line)
        lines = line.split('\n')
        firstline = lines.pop(0)
        self.lines[-1] += firstline
        self.lines += lines
        self.frame['text'] = '\n'.join(self.lines[-19:])

    def write_err(self, line, copy=True):
        if copy:
            sys.__stderr__.write(line)
        line = '\1err\1%s\2' % line
        lines = line.split('\n')
        firstline = lines.pop(0)
        self.lines[-1] += firstline
        self.lines += lines
        self.frame['text'] = '\n'.join(self.lines[-19:])

    def command(self, text):
        if self.hidden:
            return

        self.cscroll = None
        self.command = ''
        self.entry.set('')
        self.entry['focus'] = True
        self.write_out(self.otext['text'] + ' ' + text + '\n', False)
        if text != '' and (len(self.commands) == 0
                           or self.commands[-1] != text):
            self.commands.append(text)

        if not self.initialized:
            InteractiveInterpreter.__init__(self)
            self.initialized = True
        try:
            if self.runsource(self.block + '\n' + text) and text != '':
                self.otext['text'] = '.'
                self.block += '\n' + text
            else:
                self.otext['text'] = ':'
                self.block = ''
        except Exception:
            self.write_err(traceback.format_exc())

    def toggle(self):
        if self.hidden:
            self.show()
        else:
            self.hide()

    def show(self):
        self.accept('arrow_up', self.prev_command)
        self.accept('arrow_up-repeat', self.prev_command)
        self.accept('arrow_down', self.next_command)
        self.accept('arrow_down-repeat', self.next_command)
        self.hidden = False
        self.entry['focus'] = True
        self.frame.show()
        self.entry.show()
        self.otext.show()

    def hide(self):
        self.ignoreAll()
        self.hidden = True
        self.entry['focus'] = False
        self.entry.set(self.entry.get()[:-1])
        self.frame.hide()
        self.entry.hide()
        self.otext.hide()

    def destroy(self):
        sys.stdout = sys.__stdout__
        sys.stderr = sys.__stderr__
        self.ignoreAll()
        self.frame.destroy()
        self.entry.destroy()
        self.otext.destroy()
Beispiel #6
0
class Pregame():
    def __init__(self, showbase):
        self.showbase = showbase

        self.ready = False

        self.background = DirectFrame(
            frameSize=(-1, 1, -1, 1),
            frameTexture='media/gui/mainmenu/menu.png',
            parent=self.showbase.render2d,
        )

        self.title = OnscreenText(text='Lobby!',
                                  fg=(1, 1, 1, 1),
                                  parent=self.background,
                                  pos=(-0.6, 0.1),
                                  scale=0.06)

        self.buttons = []
        controlButtons = Vec3(-0.60, 0, -0.79)
        # Toggle ready
        p = controlButtons + Vec3(-0.25, 0, 0)
        self.toggleReadyButton = DirectButton(
            text='Ready/Unready',
            pos=p,
            scale=0.048,
            relief=DGG.GROOVE,
            command=self.toggleReady,
        )
        self.buttons.append(self.toggleReadyButton)
        # Disconnect
        p = controlButtons + Vec3(0.0, 0.0, 0.0)
        self.disconnectButton = DirectButton(
            text='Disconnect',
            pos=p,
            scale=0.048,
            relief=DGG.GROOVE,
            command=self.disconnect,
        )
        self.buttons.append(self.disconnectButton)

        # Send message
        p = controlButtons + Vec3(0.25, 0.0, 0.0)
        self.sendMessageButton = DirectButton(
            text='Send Message',
            pos=p,
            scale=0.048,
            relief=DGG.GROOVE,
            command=self.sendMessage,
            extraArgs=[''],
        )
        self.buttons.append(self.sendMessageButton)
        # Message input
        self.message = DirectEntry(
            command=self.sendMessage,
            focusInCommand=self.clearText,
            frameSize=(-3, 3, -.5, 1),
            initialText='',
            parent=self.buttons[2],
            pos=(0, -0.6, -1.5),
            text_align=TextNode.ACenter,
        )

        self.showbase.gameData = GameData()

        self.showbase.users = []

        self.hide()

    def clearText(self):
        self.message.set('')

    def reset(self):
        self.messages = []
        self.showbase.users = []

    def updateLobby(self, task):
        temp = self.showbase.client.getData()
        for package in temp:
            if len(package) == 2:
                print 'Received: ', str(package)
                if package[0] == 'chat':
                    if len(package[1]) == 2:
                        self.messages.append(package[1])
                        print self.messages
                elif package[0] == 'client':
                    self.showbase.users.append(User(package[1]))
                    for user in self.showbase.users:
                        print user.name, user.ready
                    print 'all users'
                elif package[0] == 'ready':
                    for user in self.showbase.users:
                        if user.name == package[1][0]:
                            user.ready = package[1][1]
                    for user in self.showbase.users:
                        print user.name, user.ready
                    print 'all users'
                elif package[0] == 'disconnect':
                    for user in self.showbase.users:
                        if user.name == package[1]:
                            self.showbase.users.remove(user)
                    for user in self.showbase.users:
                        print user.name, user.ready
                    print 'all users'
                elif package[0] == 'gamedata':
                    self.showbase.gameData.unpackageData(package[1])
                elif package[0] == 'state':
                    print 'state: ', package[1]
                    if package[1] == 'preround':
                        self.showbase.startRound()
                        return task.done
        return task.again

    def toggleReady(self):
        self.ready = not self.ready
        self.showbase.client.sendData(('ready', self.ready))

    def disconnect(self):
        self.showbase.client.sendData(('disconnect', 'disconnect'))
        self.showbase.authCon = self.showbase.client
        self.showbase.returnToMenu()

    def sendMessage(self, message):
        if message == '':
            message = self.message.get()
        if message != '':
            self.showbase.client.sendData(('chat', message))
            self.message.set('')

    def hide(self):
        self.background.hide()
        self.message.hide()
        for b in self.buttons:
            b.hide()

        self.showbase.taskMgr.remove('Update Lobby')

    def show(self):
        self.background.show()
        self.message.show()
        for b in self.buttons:
            b.show()

        # Add the game loop procedure to the task manager.
        self.showbase.taskMgr.add(self.updateLobby, 'Update Lobby')
Beispiel #7
0
class Pregame():
	def __init__(self, showbase):
		self.showbase = showbase
		
		self.ready = False

		self.background = DirectFrame(
			frameSize = (-1, 1, -1, 1),
			frameTexture  = 'media/gui/mainmenu/menu.png',
			parent = self.showbase.render2d,
		)

		self.title = OnscreenText(
			text   = 'Lobby!',
			fg     = (1, 1, 1, 1),
			parent = self.background,
			pos    = (-0.6, 0.1),
			scale  = 0.06
		)

		self.buttons = []
		controlButtons = Vec3(-0.60, 0, -0.79)
		# Toggle ready
		p = controlButtons + Vec3(-0.25, 0, 0)
		self.toggleReadyButton = DirectButton(
			text = 'Ready/Unready',
			pos = p,
			scale = 0.048,
			relief = DGG.GROOVE,
			command = self.toggleReady,
		)
		self.buttons.append(self.toggleReadyButton)
		# Disconnect
		p = controlButtons + Vec3(0.0, 0.0, 0.0)
		self.disconnectButton = DirectButton(
			text = 'Disconnect',
			pos = p,
			scale = 0.048,
			relief = DGG.GROOVE,
			command = self.disconnect,
		)
		self.buttons.append(self.disconnectButton)

		# Send message
		p = controlButtons + Vec3(0.25, 0.0, 0.0)
		self.sendMessageButton = DirectButton(
			text = 'Send Message',
			pos = p,
			scale = 0.048,
			relief = DGG.GROOVE,
			command = self.sendMessage,
			extraArgs = [''],
		)
		self.buttons.append(self.sendMessageButton)
		# Message input
		self.message = DirectEntry(
			command = self.sendMessage,
			focusInCommand = self.clearText,
			frameSize   = (-3, 3, -.5, 1),
			initialText = '',
			parent      = self.buttons[2],
			pos         = (0, -0.6, -1.5),
			text_align  = TextNode.ACenter,
		)

		self.showbase.gameData = GameData()

		self.showbase.users = []

		self.hide()

	def clearText(self):
		self.message.set('')

	def reset(self):
		self.messages = []
		self.showbase.users = []

	def updateLobby(self, task):
		temp = self.showbase.client.getData()
		for package in temp:
			if len(package) == 2:
				print 'Received: ', str(package)
				if package[0] == 'chat':
					if len(package[1]) == 2:
						self.messages.append(package[1])
						print self.messages
				elif package[0] == 'client':
					self.showbase.users.append(User(package[1]))
					for user in self.showbase.users:
						print user.name, user.ready
					print 'all users'
				elif package[0] == 'ready':
					for user in self.showbase.users:
						if user.name == package[1][0]:
							user.ready = package[1][1]
					for user in self.showbase.users:
						print user.name, user.ready
					print 'all users'
				elif package[0] == 'disconnect':
					for user in self.showbase.users:
						if user.name == package[1]:
							self.showbase.users.remove(user)
					for user in self.showbase.users:
						print user.name, user.ready
					print 'all users'
				elif package[0] == 'gamedata':
					self.showbase.gameData.unpackageData(package[1])
				elif package[0] == 'state':
					print 'state: ', package[1]
					if package[1] == 'preround':
						self.showbase.startRound()
						return task.done
		return task.again
	
	def toggleReady(self):
		self.ready = not self.ready
		self.showbase.client.sendData(('ready', self.ready))
		
	def disconnect(self):
		self.showbase.client.sendData(('disconnect', 'disconnect'))
		self.showbase.authCon = self.showbase.client
		self.showbase.returnToMenu()
	
	def sendMessage(self, message):
		if message == '':
			message = self.message.get()
		if message != '':
			self.showbase.client.sendData(('chat', message))
			self.message.set('')

	def hide(self):
		self.background.hide()
		self.message.hide()
		for b in self.buttons:
			b.hide()

		self.showbase.taskMgr.remove('Update Lobby')
	
	def show(self):
		self.background.show()
		self.message.show()
		for b in self.buttons:
			b.show()

		# Add the game loop procedure to the task manager.
		self.showbase.taskMgr.add(self.updateLobby, 'Update Lobby')
Beispiel #8
0
class ThiefHud(GameHud):
    def __init__(self):
        super().__init__()
        self.entryLabel = self.label(text='', mayChange=True)

        self.entry = DirectEntry(
            initialText='Type card name...',
            scale=0.05,
            focus=1,
            command=self.useThiefAbility,
            focusInCommand=lambda: self.entry.enterText(''))

        self.entry.hide()

        self.thiefAbilityButton = self.button(
            text="Faction Ability",
            scale=1,
            pos=(0, 0, -1),
            parent=self.endPhaseButton,
            command=self.onThiefAbilityButton)

    def useThiefAbility(self, cardname):
        try:
            cardId = next(c for c in base.enemy.deck
                          if c.name == cardname).cardId
        except StopIteration:
            print("That is not the name of an enemy card.")
        else:
            toDiscardIndex = base.player.hand.index(
                self.toDiscard.getPythonTag('card'))
            toStealIndex = base.enemy.facedowns.index(
                self.toSteal.getPythonTag('card'))
            base.networkManager.useThiefAbility(toDiscardIndex, cardId,
                                                toStealIndex)
            base.mouseHandler.targeting = False
            self.entry.hide()

    def onThiefAbilityButton(self):
        def chooseTarget(target):
            if target is None:
                base.mouseHandler.targeting = False
                showCard(self.toDiscard)
                return
            elif target.getPythonTag('zone') is not base.enemy.facedowns:
                return
            self.toSteal = target
            self.entry.show()

        def chooseDiscard(target):
            if target is None:
                base.mouseHandler.targeting = False
                return
            elif target.getPythonTag('zone') is not base.player.hand:
                return
            self.toDiscard = target
            hideCard(target)
            base.mouseHandler.startTargeting("Choose a target.", chooseTarget)

        base.mouseHandler.startTargeting("Choose a card to discard.",
                                         chooseDiscard)

    def redraw(self):
        super().redraw()

        # TODO: kludge
        if hasattr(self, 'thiefAbilityButton'):
            if base.game.phase == Phase.startOfTurn:
                self.thiefAbilityButton.show()
            else:
                self.thiefAbilityButton.hide()
Beispiel #9
0
class MainMenu():
	def __init__(self, showbase):
		self.showbase = showbase
		
		self.status = OnscreenText(text = "", pos = Vec3(0, -0.35, 0), scale = 0.05, fg = (1, 0, 0, 1), align = TextNode.ACenter, mayChange = True)
		
		self.background = DirectFrame(
			frameSize = (-1, 1, -1, 1),
			frameTexture  = 'media/gui/mainmenu/menu.png',
			parent = self.showbase.render2d,
		)

		self.title = OnscreenText(
			text   = 'Main Menu',
			fg     = (1, 1, 1, 1),
			parent = self.background,
			pos    = (-0.6, 0.1),
			scale  = 0.06
		)

		self.ip = '127.0.0.1' # Should make this write to file... so that the user can save ip's...
		# yep thats a good idea, there will be a few things i guess that need to be done like this
		# like settings and keys and whatnot
		
		# Buttons
		self.buttons = []
		serverButtons = Vec3(-0.60, 0, -0.79)
		# Host
		self.params = ['3', '8']
		p = serverButtons + Vec3(-0.25, 0, 0)
		self.hostButton = DirectButton(text = 'Host', pos = p,  scale = 0.048, relief = DGG.GROOVE, command = self.showbase.hostGame, extraArgs = [self.params])
		self.buttons.append(self.hostButton)
		# Join
		p = serverButtons + Vec3(0.0, 0.0, 0.0)
		self.joinButton = DirectButton(text = 'Join', pos = p, scale = 0.048, relief = DGG.GROOVE, command = self.joinServer)
		self.buttons.append(self.joinButton)
		# Refresh
		if self.showbase.online:
			p = serverButtons + Vec3(0.25, 0, 0)
			self.refreshButton = DirectButton(text = "Refresh", pos = p, scale = 0.048, relief = DGG.GROOVE, command = self.refreshStart)
			self.buttons.append(self.refreshButton)
			self.refreshStart()
			
			chatFrameCenter = (0.0, 0.325)
			chatFrameSize = (2.5, 1.2)
			self.chat = DirectFrame(
							frameColor = (0, 0, 0, 1),
							frameSize = (chatFrameSize[0] / 2, -chatFrameSize[0] / 2,  chatFrameSize[1] / 2, -chatFrameSize[1] / 2),
							pos = (chatFrameCenter[0], 0, chatFrameCenter[1])
						)
			
			channelFrameSize = (chatFrameSize[0] / 4, chatFrameSize[1])
			channelFrameCenter = (- chatFrameSize[0] / 2 + channelFrameSize[0] / 2, 0)
			numItemsVisible = 8
			itemHeight = channelFrameSize[1] / (numItemsVisible + 1)
			self.channels = DirectScrolledList(
								parent = self.chat,
								pos = (channelFrameCenter[0], 0, channelFrameCenter[1]),
								frameSize = (-channelFrameSize[0] / 2, channelFrameSize[0] / 2, channelFrameSize[1] / 2, -channelFrameSize[1] / 2),
								frameColor = (1, 0, 0, 0.5),
								numItemsVisible = numItemsVisible,
								forceHeight = itemHeight,

								#itemFrame_frameSize = (-channelFrameSize[0] / 2.1, channelFrameSize[0] / 2.1, itemHeight, -channelFrameSize[1] + itemHeight),
								itemFrame_pos = (0, 0, channelFrameSize[1] / 2 - itemHeight),

								decButton_pos = (-0.2, 0, channelFrameCenter[1] - channelFrameSize[1] / 2 + itemHeight / 4),
								decButton_text = 'Prev',
								decButton_text_scale = 0.05,
								decButton_borderWidth = (0.005, 0.005),

								incButton_pos = (0.2, 0, channelFrameCenter[1] - channelFrameSize[1] / 2 + itemHeight / 4),
								incButton_text = 'Next',
								incButton_text_scale = 0.05,
								incButton_borderWidth = (0.005, 0.005),
							)

			b1 = DirectButton(text = ("Button1", "click!", "roll", "disabled"),
								text_scale = 0.1, borderWidth = (0.01, 0.01),
								relief = 2)
			
			b2 = DirectButton(text = ("Button2", "click!", "roll", "disabled"),
								text_scale = 0.1, borderWidth = (0.01, 0.01),
								relief = 2)
			
			l1 = DirectLabel(text = "Test1", text_scale = 0.1)
			l2 = DirectLabel(text = "Test2", text_scale = 0.1)
			l3 = DirectLabel(text = "Test3", text_scale = 0.1)

			self.channels.addItem(b1)
			self.channels.addItem(b2)
			self.channels.addItem(l1)
			self.channels.addItem(l2)
			self.channels.addItem(l3)

			for fruit in ['apple', 'pear', 'banana', 'orange', 'cake', 'chocolate']:
				l = DirectLabel(text = fruit, text_scale = 0.1)
				self.channels.addItem(l) 
			# need to add the chat stuff
			# i guess have like a chat manager which will hold an array of 'chat_instances'
			# and the chat manager can sort out which is displayed and which channel the text is sent from/received to
			# a bit more thinking needs to be done i guess
			# can discuss sometime (not really that important now :P)
			
			# also i guess the layout and shit will need to be sorted (for whoever is doing the designing)
			
			# current games list (need to implement this)
			# it should send a query to the master server to get the current list (just ip's atmo i guess)
			
			# options shit aswell needs to be sorted
			# maybe just an overlay or something
			
			# functionality for the host button (popup an overlay that will be able to set options and then 'start_game' button
			# then should auto connect and go to lobby (will be same as for all clients, except have a couple of different buttons i guess)
			# close game instead of disconnect, start game instead of ready (greyed until all others are ready), kick button i suppose
			
			# once the options are set the 'server_inst' should be started on the local computer (which will broadcast to master server, once host can successfully connect)
			# then game client will move to pregame state (connect to the server, and wait for others and ready)
		else:
			self.entry = DirectEntry(
							focusInCommand = self.clearText,
							frameSize   = (-3, 3, -.5, 1),
							initialText = self.ip,
							parent      = self.buttons[0],
							pos         = (0, -0.6, -1.5),
							text_align  = TextNode.ACenter,
						)
		self.hide()

	def refreshStart(self):
		self.refreshButton["state"] = DGG.DISABLED
		if self.showbase.authCon.getConnected():
			self.servers = []
			self.showbase.authCon.sendData('serverQuery')
			self.showbase.taskMgr.doMethodLater(0.25, self.queryServers, 'Server Query')

	def queryServers(self, task):
		finished = False
		temp = self.showbase.authCon.getData()
		for package in temp:
			if len(package) == 2:
				# Handle Server Query
				if package[0] == 'server':
					self.servers.append(package[1])
					print package[1]
				elif package[0] == 'final':
					self.refreshButton["state"] = DGG.NORMAL
					finished = True
				else:
					self.showbase.authCon.passData(package)
		if finished:
			return task.done
		return task.cont

	def joinChat(self):
		pass
		# Let the client mini auth with the lobby server(lobby_loop) by "Logging into the chat"
		# Since everything will be in the main menu? like a main chat window.. something similar to HoN i guess?
		# When the player opens the Join game by button, a list will be send from the lobby server telling it what games are active.
		# Then the player picks one and it connects via the host name/ip or whatever.
		# While this is busy happening the client stays connected to the lobby server.
		
	def joinServer(self):
		if self.showbase.online:
			self.ip = '127.0.0.1'
		else:
			self.ip = self.entry.get()
		self.status.setText('Attempting to join server @ ' + self.ip + '...')
		# attempt to connect to the game server
		self.showbase.client = Client(self.showbase, self.ip, 9099, compress = True)
		if self.showbase.client.getConnected():
			print 'Connected to server, Awaiting authentication...'
			self.showbase.client.sendData(('username', self.showbase.username))
			self.showbase.taskMgr.add(self.authorizationListener, 'Authorization Listener')
		else:
			self.status.setText('Could not Connect...')

	def authorizationListener(self, task):
		temp = self.showbase.client.getData()
		auth = False
		if temp != []:
			for package in temp:
				if len(package) == 2:
					if package[0] == 'auth':
						print 'Authentication Successful'
						auth = True
					elif package[0] == 'fail':
						self.status.setText('Authentication failed on server...')
						return task.done
					else:
						self.showbase.client.passData(package)
		if auth:
			self.showbase.startPregame()
			return task.done
		return task.again

	def clearText(self):
		self.entry.enterText('')

	def hide(self):
		self.showbase.taskMgr.remove('Server Query Timeout')
		self.background.hide()
		for b in self.buttons:
			b.hide()
		self.status.hide()
		if self.showbase.online:
			self.chat.hide()
			self.channels.hide()
		else:
			self.entry.hide()

	def show(self):
		self.background.show()
		for b in self.buttons:
			b.show()
		self.status.show()
		if self.showbase.online:
			self.chat.show()
			self.channels.show()
		else:
			self.entry.show()
Beispiel #10
0
class MainScreen():
    def __init__(self):

        self.txtPlayerName = DirectEntry(
            text="",
            scale=0.08,
            pos=(-0.15, 0, 0.6),
            initialText="Name",
            numLines = 1,
            width = 4,
            focus=False,
            focusInCommand=self.__clearText,
            focusOutCommand=self.__checkText)

        self.btnStart = DirectButton(
            text = "Start",
            # size of the button
            scale = (0.25, 0.25, 0.25),
            # set no relief
            relief = 1,
            frameColor = (0,0,0,0),
            # No sink in when press
            pressEffect = False,
            # position on the window
            pos = (0, 0, .3),
            # the event which is thrown on clickSound
            command = self.btnStart_Click,
            # sounds that should be played
            rolloverSound = None,
            clickSound = None)
        self.btnStart.setTransparency(1)

        self.btnHighscore = DirectButton(
            text = "Highscore",
            # size of the button
            scale = (0.25, 0.25, 0.25),
            # set no relief
            relief = 1,
            frameColor = (0,0,0,0),
            # No sink in when press
            pressEffect = False,
            # position on the window
            pos = (0, 0, 0),
            # the event which is thrown on clickSound
            command = self.btnHighscore_Click,
            # sounds that should be played
            rolloverSound = None,
            clickSound = None)
        self.btnHighscore.setTransparency(1)

        self.btnQuit = DirectButton(
            text = "Quit",
            # size of the button
            scale = (0.25, 0.25, 0.25),
            # set no relief
            relief = 1,
            frameColor = (0,0,0,0),
            # No sink in when press
            pressEffect = False,
            # position on the window
            pos = (0, 0, -.3),
            # the event which is thrown on clickSound
            command = self.btnQuit_Click,
            # sounds that should be played
            rolloverSound = None,
            clickSound = None)
        self.btnQuit.setTransparency(1)

    def show(self):
        self.txtPlayerName.show()
        self.btnStart.show()
        self.btnHighscore.show()
        self.btnQuit.show()

    def hide(self):
        self.txtPlayerName.hide()
        self.btnStart.hide()
        self.btnHighscore.hide()
        self.btnQuit.hide()


    def __clearText(self):
        if self.txtPlayerName.get() == "" or \
               self.txtPlayerName.get() == "Name":
            self.txtPlayerName.enterText("")

    def __checkText(self):
        if self.txtPlayerName.get() == "":
            self.txtPlayerName.enterText("Name")

    def btnStart_Click(self):
        self.hide()
        base.messenger.send("MainMenu_start")

    def btnHighscore_Click(self):
        self.hide()
        base.messenger.send("Highscore_show")

    def btnQuit_Click(self):
        base.messenger.send("MainMenu_quit")

    def getPlayername(self):
        return self.txtPlayerName.get()
Beispiel #11
0
class MainMenu():
    def __init__(self, showbase):
        self.showbase = showbase

        self.status = OnscreenText(text="",
                                   pos=Vec3(0, -0.35, 0),
                                   scale=0.05,
                                   fg=(1, 0, 0, 1),
                                   align=TextNode.ACenter,
                                   mayChange=True)

        self.background = DirectFrame(
            frameSize=(-1, 1, -1, 1),
            frameTexture='media/gui/mainmenu/menu.png',
            parent=self.showbase.render2d,
        )

        self.title = OnscreenText(text='Main Menu',
                                  fg=(1, 1, 1, 1),
                                  parent=self.background,
                                  pos=(-0.6, 0.1),
                                  scale=0.06)

        self.ip = '127.0.0.1'  # Should make this write to file... so that the user can save ip's...
        # yep thats a good idea, there will be a few things i guess that need to be done like this
        # like settings and keys and whatnot

        # Buttons
        self.buttons = []
        serverButtons = Vec3(-0.60, 0, -0.79)
        # Host
        self.params = ['3', '8']
        p = serverButtons + Vec3(-0.25, 0, 0)
        self.hostButton = DirectButton(text='Host',
                                       pos=p,
                                       scale=0.048,
                                       relief=DGG.GROOVE,
                                       command=self.showbase.hostGame,
                                       extraArgs=[self.params])
        self.buttons.append(self.hostButton)
        # Join
        p = serverButtons + Vec3(0.0, 0.0, 0.0)
        self.joinButton = DirectButton(text='Join',
                                       pos=p,
                                       scale=0.048,
                                       relief=DGG.GROOVE,
                                       command=self.joinServer)
        self.buttons.append(self.joinButton)
        # Refresh
        if self.showbase.online:
            p = serverButtons + Vec3(0.25, 0, 0)
            self.refreshButton = DirectButton(text="Refresh",
                                              pos=p,
                                              scale=0.048,
                                              relief=DGG.GROOVE,
                                              command=self.refreshStart)
            self.buttons.append(self.refreshButton)
            self.refreshStart()

            chatFrameCenter = (0.0, 0.325)
            chatFrameSize = (2.5, 1.2)
            self.chat = DirectFrame(
                frameColor=(0, 0, 0, 1),
                frameSize=(chatFrameSize[0] / 2, -chatFrameSize[0] / 2,
                           chatFrameSize[1] / 2, -chatFrameSize[1] / 2),
                pos=(chatFrameCenter[0], 0, chatFrameCenter[1]))

            channelFrameSize = (chatFrameSize[0] / 4, chatFrameSize[1])
            channelFrameCenter = (-chatFrameSize[0] / 2 +
                                  channelFrameSize[0] / 2, 0)
            numItemsVisible = 8
            itemHeight = channelFrameSize[1] / (numItemsVisible + 1)
            self.channels = DirectScrolledList(
                parent=self.chat,
                pos=(channelFrameCenter[0], 0, channelFrameCenter[1]),
                frameSize=(-channelFrameSize[0] / 2, channelFrameSize[0] / 2,
                           channelFrameSize[1] / 2, -channelFrameSize[1] / 2),
                frameColor=(1, 0, 0, 0.5),
                numItemsVisible=numItemsVisible,
                forceHeight=itemHeight,

                #itemFrame_frameSize = (-channelFrameSize[0] / 2.1, channelFrameSize[0] / 2.1, itemHeight, -channelFrameSize[1] + itemHeight),
                itemFrame_pos=(0, 0, channelFrameSize[1] / 2 - itemHeight),
                decButton_pos=(-0.2, 0, channelFrameCenter[1] -
                               channelFrameSize[1] / 2 + itemHeight / 4),
                decButton_text='Prev',
                decButton_text_scale=0.05,
                decButton_borderWidth=(0.005, 0.005),
                incButton_pos=(0.2, 0, channelFrameCenter[1] -
                               channelFrameSize[1] / 2 + itemHeight / 4),
                incButton_text='Next',
                incButton_text_scale=0.05,
                incButton_borderWidth=(0.005, 0.005),
            )

            b1 = DirectButton(text=("Button1", "click!", "roll", "disabled"),
                              text_scale=0.1,
                              borderWidth=(0.01, 0.01),
                              relief=2)

            b2 = DirectButton(text=("Button2", "click!", "roll", "disabled"),
                              text_scale=0.1,
                              borderWidth=(0.01, 0.01),
                              relief=2)

            l1 = DirectLabel(text="Test1", text_scale=0.1)
            l2 = DirectLabel(text="Test2", text_scale=0.1)
            l3 = DirectLabel(text="Test3", text_scale=0.1)

            self.channels.addItem(b1)
            self.channels.addItem(b2)
            self.channels.addItem(l1)
            self.channels.addItem(l2)
            self.channels.addItem(l3)

            for fruit in [
                    'apple', 'pear', 'banana', 'orange', 'cake', 'chocolate'
            ]:
                l = DirectLabel(text=fruit, text_scale=0.1)
                self.channels.addItem(l)
            # need to add the chat stuff
            # i guess have like a chat manager which will hold an array of 'chat_instances'
            # and the chat manager can sort out which is displayed and which channel the text is sent from/received to
            # a bit more thinking needs to be done i guess
            # can discuss sometime (not really that important now :P)

            # also i guess the layout and shit will need to be sorted (for whoever is doing the designing)

            # current games list (need to implement this)
            # it should send a query to the master server to get the current list (just ip's atmo i guess)

            # options shit aswell needs to be sorted
            # maybe just an overlay or something

            # functionality for the host button (popup an overlay that will be able to set options and then 'start_game' button
            # then should auto connect and go to lobby (will be same as for all clients, except have a couple of different buttons i guess)
            # close game instead of disconnect, start game instead of ready (greyed until all others are ready), kick button i suppose

            # once the options are set the 'server_inst' should be started on the local computer (which will broadcast to master server, once host can successfully connect)
            # then game client will move to pregame state (connect to the server, and wait for others and ready)
        else:
            self.entry = DirectEntry(
                focusInCommand=self.clearText,
                frameSize=(-3, 3, -.5, 1),
                initialText=self.ip,
                parent=self.buttons[0],
                pos=(0, -0.6, -1.5),
                text_align=TextNode.ACenter,
            )
        self.hide()

    def refreshStart(self):
        self.refreshButton["state"] = DGG.DISABLED
        if self.showbase.authCon.getConnected():
            self.servers = []
            self.showbase.authCon.sendData('serverQuery')
            self.showbase.taskMgr.doMethodLater(0.25, self.queryServers,
                                                'Server Query')

    def queryServers(self, task):
        finished = False
        temp = self.showbase.authCon.getData()
        for package in temp:
            if len(package) == 2:
                # Handle Server Query
                if package[0] == 'server':
                    self.servers.append(package[1])
                    print package[1]
                elif package[0] == 'final':
                    self.refreshButton["state"] = DGG.NORMAL
                    finished = True
                else:
                    self.showbase.authCon.passData(package)
        if finished:
            return task.done
        return task.cont

    def joinChat(self):
        pass
        # Let the client mini auth with the lobby server(lobby_loop) by "Logging into the chat"
        # Since everything will be in the main menu? like a main chat window.. something similar to HoN i guess?
        # When the player opens the Join game by button, a list will be send from the lobby server telling it what games are active.
        # Then the player picks one and it connects via the host name/ip or whatever.
        # While this is busy happening the client stays connected to the lobby server.

    def joinServer(self):
        if self.showbase.online:
            self.ip = '127.0.0.1'
        else:
            self.ip = self.entry.get()
        self.status.setText('Attempting to join server @ ' + self.ip + '...')
        # attempt to connect to the game server
        self.showbase.client = Client(self.showbase,
                                      self.ip,
                                      9099,
                                      compress=True)
        if self.showbase.client.getConnected():
            print 'Connected to server, Awaiting authentication...'
            self.showbase.client.sendData(('username', self.showbase.username))
            self.showbase.taskMgr.add(self.authorizationListener,
                                      'Authorization Listener')
        else:
            self.status.setText('Could not Connect...')

    def authorizationListener(self, task):
        temp = self.showbase.client.getData()
        auth = False
        if temp != []:
            for package in temp:
                if len(package) == 2:
                    if package[0] == 'auth':
                        print 'Authentication Successful'
                        auth = True
                    elif package[0] == 'fail':
                        self.status.setText(
                            'Authentication failed on server...')
                        return task.done
                    else:
                        self.showbase.client.passData(package)
        if auth:
            self.showbase.startPregame()
            return task.done
        return task.again

    def clearText(self):
        self.entry.enterText('')

    def hide(self):
        self.showbase.taskMgr.remove('Server Query Timeout')
        self.background.hide()
        for b in self.buttons:
            b.hide()
        self.status.hide()
        if self.showbase.online:
            self.chat.hide()
            self.channels.hide()
        else:
            self.entry.hide()

    def show(self):
        self.background.show()
        for b in self.buttons:
            b.show()
        self.status.show()
        if self.showbase.online:
            self.chat.show()
            self.channels.show()
        else:
            self.entry.show()