Exemple #1
0
 def _create_text_fields(self, radius, width):
     test_letter = 'W'
     # the larger back side text field
     x,z = 0,0
     y = (width/2.0+Hexagon.text_distance)
     text = TextNode('')
     #font = loader.loadFont("cmss12.egg")
     #text.setFont(font)
     text.setGlyphScale(1.1*radius)
     text.setTextColor(0,0,0,1)
     self.back_side_text = self.root_node_path.attachNewNode(text)
     self.back_side_text.node().setText(test_letter)
     self.back_side_text.setH(180)
     center_node_on_xyz(self.back_side_text, x, y, z)
     self.back_side_text_z = self.back_side_text.getZ()
     # the six front side text fields
     self.front_side_text_coordinates = []
     for _i, phi in enumerate(range(0,360,60)):
         text = TextNode('')
         #text.setFont(font)
         text.setGlyphScale(0.45*radius)
         text.setTextColor(0,0,0,1)
         text_path = self.root_node_path.attachNewNode(text)
         self.front_side_text.append(text_path)
         x,z = rotate_phi_degrees_clockwise(phi, (0,radius/1.6))
         text_path.node().setText(test_letter)
         center_node_on_xyz(text_path, x, -y, z)
         self.front_side_text_coordinates.append((x,-y,z))
Exemple #2
0
 def __createCurrentModeLabel(self):
     self.text = TextNode('node name')
     self.text.setText("Current mode: None")
     self.textNodePath = aspect2d.attachNewNode(self.text)
     self.textNodePath.setScale(0.03)
     self.textNodePath.setX(-base.getAspectRatio() - 0.2)
     self.textNodePath.setZ(-0.95)
Exemple #3
0
    def __init__(self,juego):

        self.juego=juego

        self.puntuacion1 = TextNode('puntuacion1')
        self.puntuacion1.setText(str(self.juego.puntos1))
        nodo1 = self.juego.aspect2d.attachNewNode(self.puntuacion1)
        nodo1.setScale(0.1)
        nodo1.setPos(-0.5,0, 0.7)
        #nodo1.setPos(-0.5,-0.5)

        self.puntuacion2= TextNode('puntuacion1')
        self.puntuacion2.setText(str(self.juego.puntos2))
        nodo2 = self.juego.aspect2d.attachNewNode(self.puntuacion2)
        nodo2.setScale(0.1)
        nodo2.setPos(0.5,0,0.7)


        self.victoria= TextNode('victoria')
        self.victoria.setText("")
        #self.victoria.setWordwrap(7.0)
        nodo3 = self.juego.aspect2d.attachNewNode(self.victoria)
        nodo3.setScale(0.2)
        nodo3.setPos(-1.1,0,0)

        self.jugando=True
Exemple #4
0
	def __init__(self):
		ShowBase.__init__(self)
		
		self.decisions = []
		self.isReady = False
		self.red = 0
		self.messageNode = TextNode("Message")
		self.choiceOneNode = TextNode("ChoiceOne")
		self.choiceTwoNode = TextNode("ChoiceTwo")
		self.instructionsNode = TextNode("Instructions")
		
		self.messageNode.setText('"Antigone, stop screaming!"')
		self.choiceOneNode.setText("[stop]")
		self.choiceTwoNode.setText("[scream louder]")
		self.instructionsNode.setText("Use the arrow keys to make a choice.")
		
		base.setBackgroundColor(self.red, 0, 0)
		base.disableMouse()
		props = WindowProperties()
		props.setTitle("Antigo Me")
		base.win.requestProperties(props)
		
		self.textDisplay()
		self.showText()
		
		self.isReady = True
		
		self.accept("arrow_left", self.decision, [0])
		self.accept("arrow_right", self.decision, [1])
Exemple #5
0
 def __init__(self):
     self.avatar = None
     self.panel = None
     self.icon = None
     self.chatBalloon = None
     self.chatButton = NametagGlobals.noButton
     self.chatReversed = False
     self.font = None
     self.chatFont = None
     self.chatType = NametagGlobals.CHAT
     self.chatBalloonType = NametagGlobals.CHAT_BALLOON
     self.nametagColor = NametagGlobals.NametagColors[NametagGlobals.CCNormal]
     self.chatColor = NametagGlobals.ChatColors[NametagGlobals.CCNormal]
     self.speedChatColor = self.chatColor[0][1]
     self.nametagHidden = False
     self.chatHidden = False
     self.thoughtHidden = False
     self.textNode = TextNode('text')
     self.textNode.setWordwrap(self.TEXT_WORD_WRAP)
     self.textNode.setAlign(TextNode.ACenter)
     self.chatTextNode = TextNode('chatText')
     self.chatTextNode.setWordwrap(self.CHAT_TEXT_WORD_WRAP)
     self.chatTextNode.setGlyphScale(ChatBalloon.TEXT_GLYPH_SCALE)
     self.chatTextNode.setGlyphShift(ChatBalloon.TEXT_GLYPH_SHIFT)
     self.tickTaskName = self.getUniqueName() + '-tick'
     self.tickTask = taskMgr.add(self.tick, self.tickTaskName, sort=45)
 def fontHasCharacters(name, font=font):
     if font:
         tn = TextNode('NameCheck')
         tn.setFont(font)
         for c in name:
             if not tn.hasCharacter(ord(c)):
                 notify.info('name contains bad char: %s' % TextEncoder().encodeWtext(c))
                 return OTPLocalizer.NCBadCharacter % TextEncoder().encodeWtext(c)
def printText(name, message, color):
    text = TextNode(name)
    text.setText(message)
    x,y,z = color
    text.setTextColor(x,y,z, 1)
    text3d = NodePath(text)
    text3d.reparentTo(render)
    return text3d
 def fontHasCharacters(name, font = font):
     if font:
         tn = TextNode('NameCheck')
         tn.setFont(font)
         for c in name:
             if not tn.hasCharacter(ord(c)):
                 notify.info('name contains bad char: %s' % TextEncoder().encodeWtext(c))
                 return OTPLocalizer.NCBadCharacter % TextEncoder().encodeWtext(c)
Exemple #9
0
    def printText(self, name, message, color, parent=render):
        text = TextNode(
            name
        )  # create a TextNode. Note that 'name' is not the text, rather it is a name that identifies the object.
        text.setText(message)  # Here we set the text of the TextNode
        x, y, z = color  # break apart the color tuple
        text.setTextColor(x, y, z, 1)  # Set the text color from the color tuple

        text3d = NodePath(text)  # Here we create a NodePath from the TextNode, so that we can manipulate it 'in world'
        text3d.reparentTo(parent)
        return text3d  # return the NodePath for further use
 def createText(self, number, position, color):
     text = TextNode('winText%d' % number)
     text.setAlign(TextNode.ACenter)
     text.setTextColor(color)
     text.setFont(ToontownGlobals.getSignFont())
     text.setText('')
     noteText = aspect2d.attachNewNode(text)
     noteText.setScale(0.2)
     noteText.setPos(position)
     noteText.stash()
     return text, noteText
 def createDistanceLabel(self, number, color):
     text = TextNode('distanceText-%d' % number)
     text.setAlign(TextNode.ACenter)
     text.setTextColor(color)
     text.setFont(ToontownGlobals.getSignFont())
     text.setText('10 ft')
     node = self.root.attachNewNode(text)
     node.setBillboardPointEye()
     node.setScale(2.5)
     node.setZ(5.0)
     return node, text
Exemple #12
0
 def writeTextToScreen(self, x, y, z, wordwrap=10):
     """Write the text"""
     self.myText = TextNode(self.text)
     self.myText.setText(self.text)
     myFont = loader.loadFont(self.font)
     self.myText.setFont(myFont)
     self.myText.setWordwrap(wordwrap)
     self.textNodePath = self.parent.attachNewNode(self.myText)
     self.textNodePath.setScale(self.scale)
     #self.textNodePath.setBillboardPointEye()
     self.setMyPosition(x, y, z)
     self.textNodePath.setTransparency(1)
Exemple #13
0
class CatalogItemPage(NodePath):
    def __init__(self, parent, category, pageNum):
        NodePath.__init__(self, parent.attachNewNode(category))

        self.parent = parent
        self.pageNum = pageNum
        self.category = category
        self.catalogItems = []
        self.itemFrames = []
        self.textNode = None

    def addCatalogItem(self, item):
        if not item in self.catalogItems:
            self.catalogItems.append(item)

    def setCatalogItems(self, catalogItems):
        self.catalogItems = catalogItems

    def generatePage(self):
        pageText = '%s - %s' % (self.category, self.pageNum)
        self.textNode = TextNode(pageText)
        self.textNode.setText(pageText)
        self.textNode.setFont(ToontownGlobals.getInterfaceFont())
        self.textNode = self.attachNewNode(self.textNode)
        self.textNode.setPos(*CatalogGlobals.ItemPageTextLoc)
        self.textNode.setScale(CatalogGlobals.ItemPageTextScale)
        self.textNode.setColor(0, 0, 0, 1)
        for (x, item) in enumerate(self.catalogItems):
            itemFrame = CatalogItemPanel(parent=self,
                                         parentCatalogScreen=self.parent,
                                         item=item)
            itemFrame.load()
            itemFrame.setPos(*CatalogGlobals.CatalogPropPos[x])
            self.itemFrames.append(itemFrame)

    def lockItems(self):
        for itemFrame in self.itemFrames:
            itemFrame.lockItem()

    def updateItems(self, gifting):
        for itemFrame in self.itemFrames:
            itemFrame.updateButtons(gifting)

    def cleanup(self):
        for item in self.catalogItems:
            if hasattr(item, 'destroy'):
                item.destroy()

        for itemFrame in self.itemFrames:
            itemFrame.destroy()

        NodePath.removeNode(self)
Exemple #14
0
 def createMessage(self):
     """Write the text"""
     self.myText = TextNode(self.text)
     self.myText.setText(self.text)
     myFont = loader.loadFont(self.font)
     self.myText.setFont(myFont)
     self.myText.setWordwrap(40)
     self.textNodePath = aspect2d.attachNewNode(self.myText)
     self.textNodePath.setScale(self.scale)
     self.textNodePath.setPos(Vec3(self.x, 0, self.y))
     self.textNodePath.setTransparency(1)
     self.textNodePath.setColor(globals.colors['guiyellow'])
     taskMgr.add(self.fadeMessage, 'fadeMessageTask')
 def addball(self, NUM):
     #pos = Vec3(random.uniform(-7, 7), random.uniform(-7, 7), random.uniform(-7, 7))
    
     
     a = random.uniform((-8 + (self.addx)), (8 + self.addx))
     b = random.uniform((-8 + (self.addy)), (8 + self.addy))
     c = random.uniform((-8 + (self.addz)), (8 + self.addz))
     pos = Vec3(a,b,c)
     f = loader.loadModel("models/ball")
     f.setPos(pos)
     f.setScale(.8)
     f.reparentTo(render)
     f.setCollideMask(0)
     text = NUM
     newTextNode = TextNode('text') # Create a new TextNode
     newTextNode.setText(text) # Set the TextNode text
     newTextNode.setAlign(TextNode.ACenter) # Set the text align
     newTextNode.setWordwrap(6.0) # Set the word wrap
     text_generate = newTextNode.generate() # Generate a NodePath
     newTextNodePath = render.attachNewNode(text_generate) # Attach the NodePath to the render tree
     newTextNodePath.setPos(a,b,(c + 0.6))
     newTextNodePath.setColor(255, 0, 0,1)
     newTextNodePath.setScale(2)
     #self.V = self.V + 1
     #self.negy = (10%(self.V))*(-7)
     #self.posy = (10%(self.V)+3)*(-7)
     return pos    
Exemple #16
0
class CatalogItemPage(NodePath):
    def __init__(self, parent, category, pageNum):
        NodePath.__init__(self, parent.attachNewNode(category))

        self.parent = parent
        self.pageNum = pageNum
        self.category = category
        self.catalogItems = []
        self.itemFrames = []
        self.textNode = None

    def addCatalogItem(self, item):
        if not item in self.catalogItems:
            self.catalogItems.append(item)

    def setCatalogItems(self, catalogItems):
        self.catalogItems = catalogItems

    def generatePage(self):
        pageText = '%s - %s' % (self.category, self.pageNum)
        self.textNode = TextNode(pageText)
        self.textNode.setText(pageText)
        self.textNode.setFont(ToontownGlobals.getInterfaceFont())
        self.textNode = self.attachNewNode(self.textNode)
        self.textNode.setPos(*CatalogGlobals.ItemPageTextLoc)
        self.textNode.setScale(CatalogGlobals.ItemPageTextScale)
        self.textNode.setColor(0, 0, 0, 1)
        for (x, item) in enumerate(self.catalogItems):
            itemFrame = CatalogItemPanel(parent=self, parentCatalogScreen=self.parent, item=item)
            itemFrame.load()
            itemFrame.setPos(*CatalogGlobals.CatalogPropPos[x])
            self.itemFrames.append(itemFrame)

    def lockItems(self):
        for itemFrame in self.itemFrames:
            itemFrame.lockItem()

    def updateItems(self, gifting):
        for itemFrame in self.itemFrames:
            itemFrame.updateButtons(gifting)

    def cleanup(self):
        for item in self.catalogItems:
            if hasattr(item, 'destroy'):
                item.destroy()

        for itemFrame in self.itemFrames:
            itemFrame.destroy()

        NodePath.removeNode(self)
    def addball(self, NUM):
	X =  "Person_pics/" + NUM + '.jpeg' 
	tex = loader.loadTexture(X)
	f = loader.loadModel("models/ball1.egg")
        f.setTexGen(TextureStage.getDefault(), TexGenAttrib.MEyeSphereMap)
        a = random.uniform((-8 + (self.addx)), (8 + self.addx))
        b = random.uniform((-8 + (self.addy)), (8 + self.addy))
        c = random.uniform((-8 + (self.addz)), (8 + self.addz))
        pos = Vec3(a,b,c)
        f.setTexture(tex, 1)
        f.setPos(pos)
        f.setScale(.8)
        f.reparentTo(render)
        f.setCollideMask(0)
        text = NUM
        newTextNode = TextNode('text') # Create a new TextNode
        newTextNode.setText(text) # Set the TextNode text
        newTextNode.setAlign(TextNode.ACenter) # Set the text align
        newTextNode.setWordwrap(6.0) # Set the word wrap
        text_generate = newTextNode.generate() # Generate a NodePath
        newTextNodePath = render.attachNewNode(text_generate) # Attach the NodePath to the render tree
        newTextNodePath.setPos(a,b,(c + 0.6))
        newTextNodePath.setColor(255, 0, 0,1)
        newTextNodePath.setScale(.5)
        return pos    
Exemple #18
0
 def createTextCard(self):
     """Text Card stored current Scroll Value"""
     self.myText = TextNode('scrollValue')
     self.setCurrentValue(0)
     self.myText.setFont(self.font)
     self.myText.setCardColor(globals.colors['guiblue3'])
     self.myText.setFrameColor(globals.colors['guiblue2'])
     self.myText.setFrameAsMargin(0, 0, 0, 0)
     self.myText.setFrameLineWidth(3)
     self.myText.setCardAsMargin(.1, .1, .1, .1)
     textNodePath = aspect2d.attachNewNode(self.myText)
     textNodePath.setScale(0.09)
     textNodePath.setPos(self.posInitX - 0.04, 0, self.posInitY + 0.175)
     self.myWidgets.append(textNodePath)
    def __init__(self, bat_np, t, x, y, col):
        rate = 2
        z = 20
        scale = 12
        scale_up = 15
        text_node = TextNode("battle_text")
        text_node.setText(t)
        text_node_path = bat_np.attachNewNode(text_node)
        text_node_path.reparentTo(render)
        text_node_path.setPos(x, y, 0)
        text_node_path.setHpr(0, -90, 0)
        text_node_path.setScale(scale)
        text_node_path.setTransparency(TransparencyAttrib.MAlpha)
        text_node.setTextColor(col)
        text_node.setAlign(TextNode.ACenter)
        node_scl_up = text_node_path.scaleInterval(
            rate, Point3(scale_up, scale_up, scale_up))
        node_z_up = text_node_path.posInterval(rate, Point3(x, y, z * 2))
        node_z_up2 = text_node_path.posInterval(rate, Point3(x, y, z * 2))
        node_fade_down = text_node_path.colorScaleInterval(
            rate, (col[0], col[1], col[2], 0))
        node_func_death = Func(self.destroy)
        t_para = Parallel(node_scl_up, node_z_up, node_fade_down)
        t_seq = Sequence(t_para, node_func_death)

        t_seq.start()

        self.tnp = text_node_path
Exemple #20
0
 def addball(self, NUM):
     # pos = Vec3(random.uniform(-7, 7), random.uniform(-7, 7), random.uniform(-7, 7))
     if self.model == True and self.text == True:
         self.f.remove()
         self.newTextNodePath2.remove()
     a = random.uniform(-7, 7)
     b = random.uniform(-7, 7)
     c = random.uniform(-7, 7)
     pos = Vec3(a, b, c)
     tex = loader.loadTexture("cra/textures/e.jpeg")
     self.f = loader.loadModel("cra/models/ball1.egg")
     self.f.setTexGen(TextureStage.getDefault(), TexGenAttrib.MEyeSphereMap)
     self.f.setTexture(tex, 1)
     self.f.setPos(pos)
     self.f.setScale(1.5)
     self.f.reparentTo(render)
     self.f.setCollideMask(0)
     text = NUM
     newTextNode = TextNode("text")  # Create a new TextNode
     newTextNode.setText(text)  # Set the TextNode text
     newTextNode.setAlign(TextNode.ACenter)  # Set the text align
     newTextNode.setWordwrap(6.0)  # Set the word wrap
     text_generate = newTextNode.generate()  # Generate a NodePath
     self.newTextNodePath2 = render.attachNewNode(text_generate)  # Attach the NodePath to the render tree
     self.newTextNodePath2.setPos(a, b, (c + 0.3))
     self.newTextNodePath2.setColor(255, 0, 0, 1)
     self.newTextNodePath2.setScale(0.6)
     return pos
 def createDistanceLabel(self, number, color):
     text = TextNode('distanceText-%d' % number)
     text.setAlign(TextNode.ACenter)
     text.setTextColor(color)
     text.setFont(ToontownGlobals.getSignFont())
     text.setText('10 ft')
     node = self.root.attachNewNode(text)
     node.setBillboardPointEye()
     node.setScale(2.5)
     node.setZ(5.0)
     return (node, text)
 def createText(self, number, position, color):
     text = TextNode('winText%d' % number)
     text.setAlign(TextNode.ACenter)
     text.setTextColor(color)
     text.setFont(ToontownGlobals.getSignFont())
     text.setText('')
     noteText = aspect2d.attachNewNode(text)
     noteText.setScale(0.2)
     noteText.setPos(position)
     noteText.stash()
     return (text, noteText)
Exemple #23
0
    def center(self, prsn_name , m):
        if (m < 5):
            self.i = self.i + 1
            X = 'Person_pics/' + prsn_name + '.jpeg' 
	    tex = loader.loadTexture(X)
	    self.sphere = loader.loadModel("models/ball1")
	    self.sphere.setTexGen(TextureStage.getDefault(), TexGenAttrib.MEyeSphereMap)
	    self.sphere.setTexture(tex, 1)
            self.sphere.reparentTo(render)
            gx = self.sx
            y = self.sy
            z = self.sz
            pos = (gx,y,z)
            self.addx =gx
            self.addy =y
            self.addz =z
            self.sphere.setPos(1, self.sy, 1)
            self.sphere.setScale(.9)
            self.sy = -14*(self.i)
            
            
        else :
       
            x = m/5 
            j = m%5
            if ( j == 0):
                self.sy = 1
                self.i = 1
            else :
                self.sy = -14*(self.i)
                
               
            self.sx = 40*(x)
            self.sphere = loader.loadModel("models/ball1")
            self.sphere.reparentTo(render)
            gx = self.sx
            y = self.sy
            z = self.sz
            self.addx =gx
            self.addy =y
            self.addz =z
            
            pos = (gx, y, 1)
            self.sphere.setPos(pos)
            #self.sphere.setScale(.9)
            self.i = self.i + 1
            self.sphere.setScale(.9)
        text = prsn_name
        newTextNode = TextNode('text') # Create a new TextNode
        newTextNode.setText(text) # Set the TextNode text
        newTextNode.setAlign(TextNode.ACenter) # Set the text align
        newTextNode.setWordwrap(6.0) # Set the word wrap
        text_generate = newTextNode.generate() # Generate a NodePath
        newTextNodePath = render.attachNewNode(text_generate) # Attach the NodePath to the render tree
        newTextNodePath.setPos(gx, y, (z + 2))
        newTextNodePath.setColor(0, 0, 255,1)
        newTextNodePath.setScale(.5)
        return pos
 def __init__(self, cr):
     DistributedMinigame.__init__(self, cr)
     self.gameFSM = ClassicFSM.ClassicFSM(
         "DistributedCogThiefGame",
         [
             State.State("off", self.enterOff, self.exitOff, ["play"]),
             State.State("play", self.enterPlay, self.exitPlay, ["cleanup"]),
             State.State("cleanup", self.enterCleanup, self.exitCleanup, []),
         ],
         "off",
         "cleanup",
     )
     self.addChildGameFSM(self.gameFSM)
     self.cameraTopView = (0, 0, 55, 0, -90.0, 0)
     self.barrels = []
     self.cogInfo = {}
     self.lastTimeControlPressed = 0
     self.stolenBarrels = []
     self.useOrthoWalk = base.config.GetBool("cog-thief-ortho", 1)
     self.resultIval = None
     self.gameIsEnding = False
     self.__textGen = TextNode("cogThiefGame")
     self.__textGen.setFont(ToontownGlobals.getSignFont())
     self.__textGen.setAlign(TextNode.ACenter)
     return
Exemple #25
0
 def __init__(self, text_color=(1,1,1), max_nr_rows=3, nr_char_per_row=20,
              frame_color=(0,0,0), frame_padding=0.4, frame_line_width=2,
              background_color=(1,1,0), background_padding=0.8):
     #print "TextBoard::init"
     # everything that belongs to this TextBoard will be stored under the root node
     self.root_node_path = render.attachNewNode(PandaNode(''))
     # create the text node that will be the TextBoard
     self.text_node = TextNode('')
     self.text_node_path = self.root_node_path.attachNewNode(self.text_node)
     self.set_max_nr_rows(max_nr_rows)
     r,g,b = text_color
     self.set_text_color(r, g, b)
     self.text_node.setAlign(TextNode.ALeft)  # TextNode.ALeft, TextNode.ACenterba
     letter_width, letter_height = self._compute_letter_size()
     self.max_row_length = nr_char_per_row * letter_width
     self.text_node.setWordwrap(self.max_row_length)
     width, height = self._compute_max_text_size()
     self.text_node_path.setPos(0.5*background_padding,-0.01,-letter_height)
     self.background_node_path = self.root_node_path.attachNewNode(PandaNode('background_node'))
     self._create_background(self.background_node_path, width+background_padding, height+background_padding+letter_height)
     self.frame_node_path = self.root_node_path.attachNewNode(PandaNode('frame_node'))
     self._create_frame(self.frame_node_path, width+background_padding, height+background_padding+letter_height)
     r,g,b = frame_color
     self.set_frame_color(r, g, b)
     self.set_frame_line_width(frame_line_width)
     r,g,b = background_color
     self.set_background_color(r, g, b)
 def __init__(self, cr):
     DistributedMinigame.__init__(self, cr)
     self.gameFSM = ClassicFSM.ClassicFSM('DistributedCogThiefGame', [State.State('off', self.enterOff, self.exitOff, ['play']), State.State('play', self.enterPlay, self.exitPlay, ['cleanup']), State.State('cleanup', self.enterCleanup, self.exitCleanup, [])], 'off', 'cleanup')
     self.addChildGameFSM(self.gameFSM)
     self.cameraTopView = (0, 0, 55, 0, -90.0, 0)
     self.barrels = []
     self.cogInfo = {}
     self.lastTimeControlPressed = 0
     self.stolenBarrels = []
     self.useOrthoWalk = base.config.GetBool('cog-thief-ortho', 1)
     self.resultIval = None
     self.gameIsEnding = False
     self.__textGen = TextNode('cogThiefGame')
     self.__textGen.setFont(ToontownGlobals.getSignFont())
     self.__textGen.setAlign(TextNode.ACenter)
     return
 def chat_create(self, n, scl):
     self.chat_labels = []
     self.chat_nps = []
     gap = 0.00
     for l in range(n):
         #lbl = DirectLabel(text = "chatline"+str(l), text_fg = (1,1,1,1),text_mayChange = True,
         #                  pos=(0.05,0,-0.3+(0.5*l*(scl+0.08))), scale=scl, frameColor=(1,1,1,0), text_align = TextNode.ALeft)
         lbl = TextNode('node name')
         lbl.setText("")
         textNodePath = aspect2d.attachNewNode(lbl)
         textNodePath.setScale(scl)
         textNodePath.setColor(1, 1, 1, 1)
         textNodePath.setPos(0.05, 0, -0.3 + (0.5 * l * (scl + 0.08)))
         self.chat_nps.append(textNodePath)
         self.chat_labels.append(lbl)
     print "Chatbox created"
Exemple #28
0
 def generatePage(self):
     pageText = '%s - %s' % (self.category, self.pageNum)
     self.textNode = TextNode(pageText)
     self.textNode.setText(pageText)
     self.textNode.setFont(ToontownGlobals.getInterfaceFont())
     self.textNode = self.attachNewNode(self.textNode)
     self.textNode.setPos(*CatalogGlobals.ItemPageTextLoc)
     self.textNode.setScale(CatalogGlobals.ItemPageTextScale)
     self.textNode.setColor(0, 0, 0, 1)
     for (x, item) in enumerate(self.catalogItems):
         itemFrame = CatalogItemPanel(parent=self,
                                      parentCatalogScreen=self.parent,
                                      item=item)
         itemFrame.load()
         itemFrame.setPos(*CatalogGlobals.CatalogPropPos[x])
         self.itemFrames.append(itemFrame)
Exemple #29
0
 def createTitleCard(self, name, text, wordwrap, x, z, scale=0.025):
     """Default Title label for gui controls"""
     self.myTitle = TextNode(name)
     self.myTitle.setFont(self.font)
     self.myTitle.setText(text)
     self.myTitle.setWordwrap(wordwrap)
     self.myTitle.setTextColor(globals.colors['guiwhite'])
     self.myTitle.setCardColor(globals.colors['guiblue3'])
     self.myTitle.setFrameColor(globals.colors['guiblue2'])
     self.myTitle.setFrameAsMargin(.3, .5, .5, .5)
     self.myTitle.setFrameLineWidth(3)
     self.myTitle.setCardAsMargin(.3, .5, .5, .5)
     textNodePath = aspect2d.attachNewNode(self.myTitle)
     textNodePath.setScale(scale)
     textNodePath.setPos(x, 0, z)
     self.myWidgets.append(textNodePath)
    def __init__(self):
        ShowBase.__init__(self)
        base.setBackgroundColor(0.0, 0.0, 0.2)

        self.player = Player()

        dirCont =  os.listdir(os.getcwd())
        x = 30
        self.files = []
        for name in dirCont:
            if name == "$RECYCLE.BIN":
                break
            filePath = os.path.join(os.getcwd(), name)
            fileSize = os.path.getsize(filePath)
            tmpSphere = self.loader.loadModel("models/misc/sphere")
            scale = float( float(fileSize) / float(1024) )
            if scale < 0.2:
                scale = 0.9
            tmpSphere.setScale(scale)
            tmpSphere.reparentTo(self.render)
            tmpSphere.setPos(-10, 30 + x, 0)
            tmpSphere.setColor(1, 1, 0)

            text = TextNode('file stuffff')
            text.setText(name)
            textNodePath = tmpSphere.attachNewNode(text)
            textNodePath.setPos(5, 0, 0)

            self.files.append(tmpSphere)
            x += 25

        self.files[1].setScale(2, 2, 2)

        # Draw text in bottom left corner
        text = OnscreenText(text = 'NanoCommander v0.0.1',
                            pos = (-0.9, -.9),
                            scale = 0.05,
                            fg=(1, 1, 1, 1),
                            bg=(0, 0, 0, 0))
        text = OnscreenText(text = os.getcwd(),
                            pos = (0.8, -.9),
                            scale = 0.05,
                            fg=(1, 1, 1, 1),
                            bg=(0, 0, 0, 0))

        base.accept("escape", sys.exit)
    def __init__(self,bat_np,t,x,y,col):
        rate = 2
        z = 20
        scale = 12
        scale_up = 15
        text_node = TextNode("battle_text")
        text_node.setText(t)
        text_node_path = bat_np.attachNewNode(text_node)
        text_node_path.reparentTo(render)
        text_node_path.setPos(x,y,0)
        text_node_path.setHpr(0,-90,0)
        text_node_path.setScale(scale)
        text_node_path.setTransparency(TransparencyAttrib.MAlpha)
        text_node.setTextColor(col)
        text_node.setAlign(TextNode.ACenter)
        node_scl_up = text_node_path.scaleInterval(rate, Point3(scale_up, scale_up, scale_up))
        node_z_up = text_node_path.posInterval(rate, Point3(x, y, z*2))
        node_z_up2 = text_node_path.posInterval(rate, Point3(x, y, z*2))
        node_fade_down = text_node_path.colorScaleInterval(rate, (col[0],col[1],col[2],0))
        node_func_death = Func(self.destroy)
        t_para = Parallel(node_scl_up,node_z_up,node_fade_down)
        t_seq = Sequence(t_para,node_func_death)

        t_seq.start()

        self.tnp = text_node_path
Exemple #32
0
    def place_markers(self,nodes):
        for n in range(len(nodes)):
            town_node = NodePath("town")
            town = loader.loadModel("models/infantry_counter.egg")
            x = (nodes[n+1]["x"]-map_center[0])*amplification
            y = (nodes[n+1]["y"]-map_center[1])*amplification
            town.setPos(x,y,0)
            if nodes[n+1]["type"] == "city":
                scale = 12
            elif nodes[n+1]["type"] == "town":
                scale = 7
            elif nodes[n+1]["type"] == "village":
                scale = 4
            town.setScale(scale,scale,scale)
            town.reparentTo(town_node)
            town_node.reparentTo(render)

            text_node = TextNode("town_text_node")
            text_node.setText(nodes[n+1]["name"])
            text_node_path = town.attachNewNode(text_node)
            text_node_path.setPos(1,0,0)
            text_node_path.setHpr(0,-90,0)
            text_node_path.setScale(scale/2)
            text_node_path.setTransparency(TransparencyAttrib.MAlpha)
            text_node.setTextColor(0.8, 0.1, 0.1, 1)
            text_node.setAlign(TextNode.ALeft)
 def _createPartyEditorPage(self):
     page = DirectFrame(self.frame)
     page.setName('PartyPlannerEditorPage')
     self.LayoutTitleLabel = DirectLabel(parent=page, relief=None, text=TTLocalizer.PartyPlannerEditorTitle, pos=self.gui.find('**/title_locator').getPos() + Point3(0.0, 0.0, 0.075), scale=self.titleScale)
     self.costLabel = DirectLabel(parent=page, pos=(-0.74, 0.0, 0.17), relief=None, text=TTLocalizer.PartyPlannerTotalCost % 0, text_align=TextNode.ACenter, scale=TTLocalizer.PPcostLabel, textMayChange=True)
     self.partyGridBackground = DirectFrame(parent=page, relief=None, geom=self.gui.find('**/partyGrid_flat'))
     self.partyGroundsLabel = DirectLabel(parent=page, relief=None, text=TTLocalizer.PartyPlannerPartyGrounds, text_font=ToontownGlobals.getSignFont(), text_fg=VBase4(1.0, 0.0, 0.0, 1.0), text_scale=TTLocalizer.PPpartyGroundsLabel, pos=self.gui.find('**/step_05_partyGrounds_text_locator').getPos(), scale=0.1)
     self.activityBackground = DirectFrame(parent=page, relief=None, geom=self.gui.find('**/activitiesDecorations_flat1'), pos=(0.0, 0.0, 0.04))
     pos = self.gui.find('**/step_05_instructions_locator').getPos()
     self.instructionLabel = DirectLabel(parent=page, relief=None, text=' ', text_pos=(pos[0], pos[2]), text_scale=TTLocalizer.PPinstructionLabel, textMayChange=True, geom=self.gui.find('**/instructions_flat'))
     self.elementTitleLabel = DirectLabel(parent=page, relief=None, text=' ', pos=self.gui.find('**/step_05_activitiesName_text_locator').getPos() + Point3(0.0, 0.0, 0.04), text_scale=TTLocalizer.PPelementTitleLabel, textMayChange=True)
     self.elementPriceNode = TextNode('ElementPrice')
     self.elementPriceNode.setAlign(TextNode.ALeft)
     self.elementPriceNode.setTextColor(0.0, 0.0, 0.0, 1.0)
     self.elementPriceNode.setFont(ToontownGlobals.getToonFont())
     self.elementPrice = page.attachNewNode(self.elementPriceNode)
     self.elementPrice.setScale(TTLocalizer.PPelementPriceNode)
     self.elementPrice.setPos(self.gui.find('**/step_05_activityPrice_text_locator').getPos() + Point3(-0.02, 0.0, 0.04))
     self.elementDescriptionNode = TextNode('ElementDescription')
     self.elementDescriptionNode.setAlign(TextNode.ACenter)
     self.elementDescriptionNode.setWordwrap(8)
     self.elementDescriptionNode.setFont(ToontownGlobals.getToonFont())
     self.elementDescriptionNode.setTextColor(0.0, 0.0, 0.0, 1.0)
     self.elementDescription = page.attachNewNode(self.elementDescriptionNode)
     self.elementDescription.setScale(TTLocalizer.PPelementDescription)
     self.elementDescription.setPos(self.gui.find('**/step_05_activityDescription_text_locator').getPos() + Point3(0.0, 0.0, 0.04))
     self.totalMoney = base.localAvatar.getTotalMoney()
     catalogGui = loader.loadModel('phase_5.5/models/gui/catalog_gui')
     self.beanBank = DirectLabel(parent=page, relief=None, text=str(self.totalMoney), text_align=TextNode.ARight, text_scale=0.075, text_fg=(0.95, 0.95, 0, 1), text_shadow=(0, 0, 0, 1), text_pos=(0.495, -0.53), text_font=ToontownGlobals.getSignFont(), textMayChange=True, image=catalogGui.find('**/bean_bank'), image_scale=(0.65, 0.65, 0.65), scale=0.9, pos=(-0.75, 0.0, 0.6))
     catalogGui.removeNode()
     del catalogGui
     self.accept(localAvatar.uniqueName('moneyChange'), self.__moneyChange)
     self.accept(localAvatar.uniqueName('bankMoneyChange'), self.__moneyChange)
     self.partyEditor = PartyEditor(self, page)
     self.partyEditor.request('Hidden')
     pos = self.gui.find('**/step_05_add_text_locator').getPos()
     self.elementBuyButton = DirectButton(parent=page, relief=None, text=TTLocalizer.PartyPlannerBuy, text_pos=(pos[0], pos[2]), text_scale=TTLocalizer.PPelementBuyButton, geom=(self.gui.find('**/add_up'), self.gui.find('**/add_down'), self.gui.find('**/add_rollover')), geom3_color=VBase4(0.5, 0.5, 0.5, 1.0), textMayChange=True, pos=(0.0, 0.0, 0.04), command=self.partyEditor.buyCurrentElement)
     self.okWithPartyGroundsLayoutEvent = 'okWithPartyGroundsLayoutEvent'
     self.accept(self.okWithPartyGroundsLayoutEvent, self.okWithPartyGroundsLayout)
     self.okWithGroundsGui = TTDialog.TTGlobalDialog(dialogName=self.uniqueName('PartyEditorOkGui'), doneEvent=self.okWithPartyGroundsLayoutEvent, message=TTLocalizer.PartyPlannerOkWithGroundsLayout, style=TTDialog.YesNo, okButtonText=OTPLocalizer.DialogYes, cancelButtonText=OTPLocalizer.DialogNo)
     self.okWithGroundsGui.doneStatus = ''
     self.okWithGroundsGui.hide()
     return page
 def _createPartyEditorPage(self):
     page = DirectFrame(self.frame)
     page.setName('PartyPlannerEditorPage')
     self.LayoutTitleLabel = DirectLabel(parent=page, relief=None, text=TTLocalizer.PartyPlannerEditorTitle, pos=self.gui.find('**/title_locator').getPos() + Point3(0.0, 0.0, 0.075), scale=self.titleScale)
     self.costLabel = DirectLabel(parent=page, pos=(-0.74, 0.0, 0.17), relief=None, text=TTLocalizer.PartyPlannerTotalCost % 0, text_align=TextNode.ACenter, scale=TTLocalizer.PPcostLabel, textMayChange=True)
     self.partyGridBackground = DirectFrame(parent=page, relief=None, geom=self.gui.find('**/partyGrid_flat'))
     self.partyGroundsLabel = DirectLabel(parent=page, relief=None, text=TTLocalizer.PartyPlannerPartyGrounds, text_font=ToontownGlobals.getSignFont(), text_fg=VBase4(1.0, 0.0, 0.0, 1.0), text_scale=TTLocalizer.PPpartyGroundsLabel, pos=self.gui.find('**/step_05_partyGrounds_text_locator').getPos(), scale=0.1)
     self.activityBackground = DirectFrame(parent=page, relief=None, geom=self.gui.find('**/activitiesDecorations_flat1'), pos=(0.0, 0.0, 0.04))
     pos = self.gui.find('**/step_05_instructions_locator').getPos()
     self.instructionLabel = DirectLabel(parent=page, relief=None, text=' ', text_pos=(pos[0], pos[2]), text_scale=TTLocalizer.PPinstructionLabel, textMayChange=True, geom=self.gui.find('**/instructions_flat'))
     self.elementTitleLabel = DirectLabel(parent=page, relief=None, text=' ', pos=self.gui.find('**/step_05_activitiesName_text_locator').getPos() + Point3(0.0, 0.0, 0.04), text_scale=TTLocalizer.PPelementTitleLabel, textMayChange=True)
     self.elementPriceNode = TextNode('ElementPrice')
     self.elementPriceNode.setAlign(TextNode.ALeft)
     self.elementPriceNode.setTextColor(0.0, 0.0, 0.0, 1.0)
     self.elementPriceNode.setFont(ToontownGlobals.getToonFont())
     self.elementPrice = page.attachNewNode(self.elementPriceNode)
     self.elementPrice.setScale(TTLocalizer.PPelementPriceNode)
     self.elementPrice.setPos(self.gui.find('**/step_05_activityPrice_text_locator').getPos() + Point3(-0.02, 0.0, 0.04))
     self.elementDescriptionNode = TextNode('ElementDescription')
     self.elementDescriptionNode.setAlign(TextNode.ACenter)
     self.elementDescriptionNode.setWordwrap(8)
     self.elementDescriptionNode.setFont(ToontownGlobals.getToonFont())
     self.elementDescriptionNode.setTextColor(0.0, 0.0, 0.0, 1.0)
     self.elementDescription = page.attachNewNode(self.elementDescriptionNode)
     self.elementDescription.setScale(TTLocalizer.PPelementDescription)
     self.elementDescription.setPos(self.gui.find('**/step_05_activityDescription_text_locator').getPos() + Point3(0.0, 0.0, 0.04))
     self.totalMoney = base.localAvatar.getTotalMoney()
     catalogGui = loader.loadModel('phase_5.5/models/gui/catalog_gui')
     self.beanBank = DirectLabel(parent=page, relief=None, text=str(self.totalMoney), text_align=TextNode.ARight, text_scale=0.075, text_fg=(0.95, 0.95, 0, 1), text_shadow=(0, 0, 0, 1), text_pos=(0.495, -0.53), text_font=ToontownGlobals.getSignFont(), textMayChange=True, image=catalogGui.find('**/bean_bank'), image_scale=(0.65, 0.65, 0.65), scale=0.9, pos=(-0.75, 0.0, 0.6))
     catalogGui.removeNode()
     del catalogGui
     self.accept(localAvatar.uniqueName('moneyChange'), self.__moneyChange)
     self.accept(localAvatar.uniqueName('bankMoneyChange'), self.__moneyChange)
     self.partyEditor = PartyEditor(self, page)
     self.partyEditor.request('Hidden')
     pos = self.gui.find('**/step_05_add_text_locator').getPos()
     self.elementBuyButton = DirectButton(parent=page, relief=None, text=TTLocalizer.PartyPlannerBuy, text_pos=(pos[0], pos[2]), text_scale=TTLocalizer.PPelementBuyButton, geom=(self.gui.find('**/add_up'), self.gui.find('**/add_down'), self.gui.find('**/add_rollover')), geom3_color=VBase4(0.5, 0.5, 0.5, 1.0), textMayChange=True, pos=(0.0, 0.0, 0.04), command=self.partyEditor.buyCurrentElement)
     self.okWithPartyGroundsLayoutEvent = 'okWithPartyGroundsLayoutEvent'
     self.accept(self.okWithPartyGroundsLayoutEvent, self.okWithPartyGroundsLayout)
     self.okWithGroundsGui = TTDialog.TTGlobalDialog(dialogName=self.uniqueName('PartyEditorOkGui'), doneEvent=self.okWithPartyGroundsLayoutEvent, message=TTLocalizer.PartyPlannerOkWithGroundsLayout, style=TTDialog.YesNo, okButtonText=OTPLocalizer.DialogYes, cancelButtonText=OTPLocalizer.DialogNo)
     self.okWithGroundsGui.doneStatus = ''
     self.okWithGroundsGui.hide()
     return page
Exemple #35
0
    def __init__(self, text, x, z, scale, r, g, b):
        self.x = x
        self.z = z
        self.scale = scale
        self.r = r
        self.g = g
        self.b = b

        textnode = TextNode('fadingtext')
        textnode.setText(text)
        self.node = aspect2d.attachNewNode(textnode)
        self.node.setScale(self.scale)

        self.node.setTransparency(TransparencyAttrib.MAlpha)
        self.node.setPos(self.x, -1, self.z)
        self.node.setColorScale(LVecBase4f(self.r, self.g, self.b, 0.0))
        self.node.reparentTo(aspect2d)

        delay = 3.0
        seq = Sequence(self.fadeIn(delay), Wait(delay), self.fadeOut(delay))
        seq.start()
Exemple #36
0
    def __init__(self, mainReference):
        self.mainRef = mainReference
        
        self.winSizeX = self.mainRef.win.getProperties().getXSize() 
        self.winSizeY = self.mainRef.win.getProperties().getYSize()  

        # parent of all sprites
        sprites_root = self.createSpritesNodeSetup()
        
        # crosshair init
        self.crosshairSprite = self.createSprite('../../textures/crosshair.png', self.winSizeX/2, self.winSizeY/2, 16, 16, 1) 
        self.crosshairSprite.reparentTo(sprites_root)
        
        # health points
        hpText=TextNode('hp')
        hpText.setText( "HP: "+str(self.mainRef.player.healthPoints) )
        self.guiHp = self.mainRef.aspect2d.attachNewNode(hpText)
        self.guiHp.setScale(0.07)
        self.guiHp.setPos(-1.2,0,-0.9)
        
        # Ammo
        ammoText=TextNode('ammo')
        ammoText.setText( "AMMO: "+str(self.mainRef.player.activeWeapon.bullets) )
        self.guiAmmo = self.mainRef.aspect2d.attachNewNode(ammoText)
        self.guiAmmo.setScale(0.07)
        self.guiAmmo.setPos(-1.2,0,-0.9+0.1)
Exemple #37
0
    def loadMenu(self):
        #Load main menu
        #Add play icon
        click = loader.loadSfx("./sounds/correct.ogg")
        self.playicon = DirectButton(image="./GUI/cloud.png", scale=.3, pos=(-0.38,0,0.21), relief=None, state=DGG.NORMAL, command=self.playGame, clickSound=click)
        self.playicon.setScale(0.3)
        self.playicon.setTransparency(TransparencyAttrib.MAlpha)

        #Play text
        play = TextNode('Play')
        play.setText("\1menu\1 Play! \2")
        self.playNP = aspect2d.attachNewNode(play)
        self.playNP.setScale(0.18)
        self.playNP.setPos(-0.7,0,0.13)

        self.playerGUI.controls()

        #Exit text and icon
        self.exiticon = DirectButton(image="./GUI/cloud.png", scale=.3, pos=(0.48,0,0.21), relief=None, state=DGG.NORMAL, command=exit, clickSound=click)
        self.exiticon.setScale(0.3)
        self.exiticon.setTransparency(TransparencyAttrib.MAlpha)
        exitx = TextNode('Exit')
        exitx.setText("\1menu\1 Exit \2")
        self.exitxNP = aspect2d.attachNewNode(exitx)
        self.exitxNP.setScale(0.18)
        self.exitxNP.setPos(0.22,0,0.13)
Exemple #38
0
 def __init__(self,
              text_color=(1, 1, 1),
              max_nr_rows=3,
              nr_char_per_row=20,
              frame_color=(0, 0, 0),
              frame_padding=0.4,
              frame_line_width=2,
              background_color=(1, 1, 0),
              background_padding=0.8):
     #print "TextBoard::init"
     # everything that belongs to this TextBoard will be stored under the root node
     self.root_node_path = render.attachNewNode(PandaNode(''))
     # create the text node that will be the TextBoard
     self.text_node = TextNode('')
     self.text_node_path = self.root_node_path.attachNewNode(self.text_node)
     self.set_max_nr_rows(max_nr_rows)
     r, g, b = text_color
     self.set_text_color(r, g, b)
     self.text_node.setAlign(
         TextNode.ALeft)  # TextNode.ALeft, TextNode.ACenterba
     letter_width, letter_height = self._compute_letter_size()
     self.max_row_length = nr_char_per_row * letter_width
     self.text_node.setWordwrap(self.max_row_length)
     width, height = self._compute_max_text_size()
     self.text_node_path.setPos(0.5 * background_padding, -0.01,
                                -letter_height)
     self.background_node_path = self.root_node_path.attachNewNode(
         PandaNode('background_node'))
     self._create_background(self.background_node_path,
                             width + background_padding,
                             height + background_padding + letter_height)
     self.frame_node_path = self.root_node_path.attachNewNode(
         PandaNode('frame_node'))
     self._create_frame(self.frame_node_path, width + background_padding,
                        height + background_padding + letter_height)
     r, g, b = frame_color
     self.set_frame_color(r, g, b)
     self.set_frame_line_width(frame_line_width)
     r, g, b = background_color
     self.set_background_color(r, g, b)
Exemple #39
0
    def gameWonOrLost(self):
        if self.gameWon:
            if self.instance == 0:
                text = "U WON THE GAME !!1!1!!1\n lol just kidding. You won level one!\n press P to go to the next level\n(Fewer pictures, bigger maze) "
            if self.instance == 1:
                text = "GoOd JoB 1!!!1!1!! YOu KnoW tHE drILl! neXT leVEl comiNg up.\n press P to go to the next level"
            if self.instance == 2:
                text = "U WON THE GAME !!1!1!!1 YOu escaped the virus.\n(for realz this time YAY!)\nPress P to play again! "
        else:
            text = "You just lost the level you noob.\nLuckily, you get infinite chances.\nPress P to try again."

        self.text = TextNode('bleh')
        self.text.setAlign(TextNode.ACenter)
        self.text.setText(text)
        textNodePath = aspect2d.attachNewNode(self.text)
        textNodePath.setScale(0.09)
        self.text.setCardColor(0, 0, 0, 1)
        self.text.setCardAsMargin(20, 20, 20, 20)
        self.text.setCardDecal(True)
        self.gameOver = True
        self.imageObject.destroy()
        self.hasImageObject = False
Exemple #40
0
def printText(name, message, color):
    text = TextNode(name)
    text.setText(message)
    x, y, z = color
    text.setTextColor(x, y, z, 1)
    text3d = NodePath(text)
    text3d.reparentTo(render)
    return text3d
Exemple #41
0
 def center(self, prsn_name):
     self.sphere = loader.loadModel("models/ball")
     self.sphere.reparentTo(render)
     self.sphere.setPos(1, 1, 1)
     self.sphere.setScale(.9)
     text = prsn_name
     newTextNode = TextNode('text') # Create a new TextNode
     newTextNode.setText(text) # Set the TextNode text
     newTextNode.setAlign(TextNode.ACenter) # Set the text align
     newTextNode.setWordwrap(6.0) # Set the word wrap
     text_generate = newTextNode.generate() # Generate a NodePath
     newTextNodePath = render.attachNewNode(text_generate) # Attach the NodePath to the render tree
     newTextNodePath.setPos(1, 1, 2)
     newTextNodePath.setColor(255, 0, 0,1)
     newTextNodePath.setScale(.8)
Exemple #42
0
 def generatePage(self):
     pageText = '%s - %s' % (self.category, self.pageNum)
     self.textNode = TextNode(pageText)
     self.textNode.setText(pageText)
     self.textNode.setFont(ToontownGlobals.getInterfaceFont())
     self.textNode = self.attachNewNode(self.textNode)
     self.textNode.setPos(*CatalogGlobals.ItemPageTextLoc)
     self.textNode.setScale(CatalogGlobals.ItemPageTextScale)
     self.textNode.setColor(0, 0, 0, 1)
     for (x, item) in enumerate(self.catalogItems):
         itemFrame = CatalogItemPanel(parent=self, parentCatalogScreen=self.parent, item=item)
         itemFrame.load()
         itemFrame.setPos(*CatalogGlobals.CatalogPropPos[x])
         self.itemFrames.append(itemFrame)
    def __init__(self):
        self.avatar = None

        self.panel = None
        self.icon = None
        self.chatBalloon = None

        self.chatButton = NametagGlobals.noButton
        self.chatReversed = False

        self.font = None
        self.chatFont = None

        self.chatType = NametagGlobals.CHAT
        self.chatBalloonType = NametagGlobals.CHAT_BALLOON

        self.nametagColor = NametagGlobals.NametagColors[NametagGlobals.CCNormal]
        self.chatColor = NametagGlobals.ChatColors[NametagGlobals.CCNormal]
        self.speedChatColor = self.chatColor[0][1]

        self.nametagHidden = False
        self.chatHidden = False
        self.thoughtHidden = False

        # Create our TextNodes:
        self.textNode = TextNode('text')
        self.textNode.setWordwrap(self.TEXT_WORD_WRAP)
        self.textNode.setAlign(TextNode.ACenter)

        self.chatTextNode = TextNode('chatText')
        self.chatTextNode.setWordwrap(self.CHAT_TEXT_WORD_WRAP)
        self.chatTextNode.setGlyphScale(ChatBalloon.TEXT_GLYPH_SCALE)
        self.chatTextNode.setGlyphShift(ChatBalloon.TEXT_GLYPH_SHIFT)

        # Add the tick task:
        self.tickTaskName = self.getUniqueName() + '-tick'
        self.tickTask = taskMgr.add(self.tick, self.tickTaskName, sort=45)
Exemple #44
0
 def printText(self, name, message, color, parent=render): 
     text = TextNode(name) # create a TextNode. Note that 'name' is not the text, rather it is a name that identifies the object.
     text.setText(message) # Here we set the text of the TextNode
     x,y,z = color # break apart the color tuple
     text.setTextColor(x,y,z, 1) # Set the text color from the color tuple
 
     text3d = NodePath(text) # Here we create a NodePath from the TextNode, so that we can manipulate it 'in world'
     text3d.reparentTo(parent)
     return text3d # return the NodePath for further use
Exemple #45
0
class FadingText(object):
    """Display Text on the screen"""
    def __init__(self, path, text, messagePositions):
        self.path = path
        self.text = text
        self.fadeCount = 100.0
        self.messagePositions = messagePositions
        self.x = 0
        self.y = 0
        self.text = text
        self.scale = 0.04
        self.font = '%s/star5' % self.path
        self.myText = None
        self.textNodePath = None
        self.setMyPosition()
        self.createMessage()

    def getMyPosition(self):
        return self.y

    def setMyPosition(self):
        """Move message where other current messages are not"""
        self.x = -0.7
        for i in range(20):
            num = -0.97 + (0.10 * i)
            if num not in self.messagePositions:
                self.y = num
                return

    def createMessage(self):
        """Write the text"""
        self.myText = TextNode(self.text)
        self.myText.setText(self.text)
        myFont = loader.loadFont(self.font)
        self.myText.setFont(myFont)
        self.myText.setWordwrap(40)
        self.textNodePath = aspect2d.attachNewNode(self.myText)
        self.textNodePath.setScale(self.scale)
        self.textNodePath.setPos(Vec3(self.x, 0, self.y))
        self.textNodePath.setTransparency(1)
        self.textNodePath.setColor(globals.colors['guiyellow'])
        taskMgr.add(self.fadeMessage, 'fadeMessageTask')

    def removeMessage(self):
        """Remove the current Message"""
        self.textNodePath.removeNode()
        self.messagePositions.remove(self.y)

    def fadeMessage(self, task):
        """Fade the current Message"""
        if self.fadeCount <= 0:
            self.removeMessage()
            return Task.done
        else:
            self.fadeCount -= 0.3
            self.textNodePath.setAlphaScale(self.fadeCount / 100.0)
            return Task.cont
Exemple #46
0
def genTextNode(T):
	global aspect2d
	txt = TextNode(T)
	txt.setText(T)
	txtNode = aspect2d.attachNewNode(txt)
	txtNode.setScale(0.1)
	txtNode.setPos(Vec3(-1.0, 0, 0.92))
	txt.setTextColor(1,0,0,1)
	return txt
 def __init__(self, cr):
     DistributedMinigame.__init__(self, cr)
     self.gameFSM = ClassicFSM.ClassicFSM('DistributedCogThiefGame', [State.State('off', self.enterOff, self.exitOff, ['play']), State.State('play', self.enterPlay, self.exitPlay, ['cleanup']), State.State('cleanup', self.enterCleanup, self.exitCleanup, [])], 'off', 'cleanup')
     self.addChildGameFSM(self.gameFSM)
     self.cameraTopView = (0, 0, 55, 0, -90.0, 0)
     self.barrels = []
     self.cogInfo = {}
     self.lastTimeControlPressed = 0
     self.stolenBarrels = []
     self.resultIval = None
     self.gameIsEnding = False
     self.__textGen = TextNode('cogThiefGame')
     self.__textGen.setFont(ToontownGlobals.getSignFont())
     self.__textGen.setAlign(TextNode.ACenter)
     return
Exemple #48
0
 def __init__(self, ywn):
     '''
     Constructor
     '''
     
     self.ywn = ywn
     
     self.tooltip = TextNode('Tooltip')
     self.tooltip.setText("Every day in every way I'm getting better and better.")
     self.tooltip.setTextColor(1, 0.5, 0.5, 1)
     self.tooltip.setShadow(0.05, 0.05)
     self.tooltip.setShadowColor(0, 0, 0, 1)
     self.tooltipNodePath = self.ywn.aspect2d.attachNewNode(self.tooltip)
     self.tooltipNodePath.setScale(0.07)
     self.tooltipNodePath.setPos(-1,0,0.9)
     
     self.ywn.taskMgr.add(self.taskMouseTooltip, 'taskMouseToolip')
Exemple #49
0
 def __init__(self, name, parentNode):
     self.parentNode = parentNode
     
     self.nameTextNode = TextNode('nameTextNode')
     self.nameTextNode.setText(name)
     self.nameTextNode.setTextColor(Globals.COLOR_WHITE)
     self.nameTextNode.setShadow(0.05, 0.05)
     self.nameTextNode.setShadowColor(Globals.COLOR_WHITE)
     self.nameTextNode.set_align(TextNode.ACenter)
     self.nameTextNodeTextPath = aspect2d.attachNewNode(self.nameTextNode)
     self.nameTextNodeTextPath.setScale(Settings.CHAT_HEIGHT)
     
     self.hidden = True
     self.nameTextNodeTextPath.hide()
     self.fadeSeq = Sequence(LerpColorScaleInterval(self.nameTextNodeTextPath, 1, Globals.COLOR_TRANSPARENT),
                             Func(self.nameTextNodeTextPath.hide))
     
     self.reshowOnInView = False
Exemple #50
0
 def addOption(self, name, function):
     '''
     Add one option to the menu Node
     '''
     text = TextNode(name)
     text.setFont(self.font)
     text.setText(name)
     self.options.append((name, function))
     self.optionsModells.append(
         NodePath("test").attachNewNode(text))  # setPos fehlt
     self.optionsModells[-1].setColor(self.colorA)
     self.optionsModells[-1].setPos(0, 0, -len(self.optionsModells))
     self.menuNode.attachNewNode(text)
 def __init__(self, cr):
     DistributedMinigame.__init__(self, cr)
     self.gameFSM = ClassicFSM.ClassicFSM('DistributedCogThiefGame', [State.State('off', self.enterOff, self.exitOff, ['play']), State.State('play', self.enterPlay, self.exitPlay, ['cleanup']), State.State('cleanup', self.enterCleanup, self.exitCleanup, [])], 'off', 'cleanup')
     self.addChildGameFSM(self.gameFSM)
     toon = base.localAvatar
     camera.reparentTo(toon)
     camera.setPos(0,-15,5)
     camera.setHpr(0, -5, 0)
     self.barrels = []
     self.cogInfo = {}
     self.lastTimeControlPressed = 0
     self.stolenBarrels = []
     self.useOrthoWalk = config.GetBool('cog-thief-ortho', 0)
     self.resultIval = None
     self.gameIsEnding = False
     self.__textGen = TextNode('cogThiefGame')
     self.__textGen.setFont(ToontownGlobals.getSignFont())
     self.__textGen.setAlign(TextNode.ACenter)
     return
Exemple #52
0
 def create_town(self,text,x,y):
     scale = 4
     town_node = NodePath("town")
     town = loader.loadModel("models/infantry_counter.egg")
     town.setScale(scale,scale,scale)
     town.reparentTo(town_node)
     text_node = TextNode("town_text_node")
     text_node.setText(text)
     text_node_path = town.attachNewNode(text_node)
     text_node_path.setPos(1,0,0)
     text_node_path.setHpr(0,-90,0)
     text_node_path.setScale(scale/2)
     text_node_path.setTransparency(TransparencyAttrib.MAlpha)
     text_node.setTextColor(0.8, 0.1, 0.1, 1)
     text_node.setAlign(TextNode.ALeft)
     town_node.reparentTo(render)
     town_node.setPos(x,y,0)
     print "Town Made",x,y
Exemple #53
0
 def centerF(self, prsn_name):
     if self.model == True and self.text == True:
         self.sphere.remove()
         self.newTextNodePath1.remove()
     X = "cra/textures/" + prsn_name + ".jpeg"
     tex = loader.loadTexture(X)
     self.sphere = loader.loadModel("cra/models/ball1.egg")
     self.sphere.setTexGen(TextureStage.getDefault(), TexGenAttrib.MEyeSphereMap)
     self.sphere.setTexture(tex, 1)
     self.sphere.reparentTo(render)
     self.sphere.setPos(1, 1, 1)
     self.sphere.setScale(2.5)
     text = prsn_name
     newTextNode = TextNode("text")  # Create a new TextNode
     newTextNode.setText(text)  # Set the TextNode text
     newTextNode.setAlign(TextNode.ACenter)  # Set the text align
     newTextNode.setWordwrap(6.0)  # Set the word wrap
     text_generate = newTextNode.generate()  # Generate a NodePath
     self.newTextNodePath1 = render.attachNewNode(text_generate)  # Attach the NodePath to the render tree
     self.newTextNodePath1.setPos(1, 1, 2)
     self.newTextNodePath1.setColor(255, 0, 0, 1)
     self.newTextNodePath1.setScale(0.8)
Exemple #54
0
    def showStartScreen(self):
        '''
        the first screen with "press any Key"
        the device with the first key press will be the first player
        '''
        self._notify.info("Initializing StartScreen")

        self.wii = []

        # StartScreen Node
        self.startNode = NodePath("StartNode")
        self.startNode.reparentTo(render)
        self.startNode.setPos(-5, 15, 3)

        # Headline model
        headline = loader.loadModel("data/models/logo.egg")
        headline.setX(4.7)
        headline.setY(-4)
        headline.setZ(-2)
        headline.setP(90)
        headline.reparentTo(self.startNode)

        # Press any key text
        presskey = TextNode("PressAnyKey")
        presskey.setFont(self.font)
        presskey.setText(_("Press any key!!"))
        textNodePath = NodePath("PressAnyNode")
        textNodePath.attachNewNode(presskey)
        textNodePath.setPos(0, 10, -9.5)
        textNodePath.reparentTo(self.startNode)

        # Show the start screen
        self.startNode.show()

        # LICHT
        plight = PointLight('plight')
        plight.setColor(VBase4(10, 10, 10, 1))
        plnp = self.startNode.attachNewNode(plight)
        plnp.setPos(20, -800, 30)
        self.startNode.setLight(plnp)

        # Camera
        self.camera = base.makeCamera(base.win)

        self._notify.info("StarScreen initialized")
Exemple #55
0
 def loadGUI(self):
     self.gui = loader.loadModel('phase_13/models/parties/trampolineGUI')
     self.gui.reparentTo(base.a2dTopLeft)
     self.gui.setPos(0.115, 0, -1)
     self.gui.hide()
     self.toonIndicator = self.gui.find('**/trampolineGUI_MovingBar')
     jumpLineLocator = self.gui.find('**/jumpLine_locator')
     guiBean = self.gui.find('**/trampolineGUI_GreenJellyBean')
     self.gui.find('**/trampolineGUI_GreenJellyBean').stash()
     self.guiBeans = [ guiBean.instanceUnderNode(jumpLineLocator, self.uniqueName('guiBean%d' % i)) for i in xrange(self.numJellyBeans) ]
     self.guiBeans[-1].setScale(1.5)
     heightTextNode = TextNode(self.uniqueName('TrampolineActivity.heightTextNode'))
     heightTextNode.setFont(ToontownGlobals.getSignFont())
     heightTextNode.setAlign(TextNode.ALeft)
     heightTextNode.setText('0.0')
     heightTextNode.setShadow(0.05, 0.05)
     heightTextNode.setShadowColor(0.0, 0.0, 0.0, 1.0)
     heightTextNode.setTextColor(1.0, 1.0, 1.0, 1.0)
     self.heightText = jumpLineLocator.attachNewNode(heightTextNode)
     self.heightText.setX(0.15)
     self.heightText.setScale(0.1)
     self.heightText.setAlphaScale(0.0)
     self.quitEarlyButtonModels = loader.loadModel('phase_3.5/models/gui/inventory_gui')
     quitEarlyUp = self.quitEarlyButtonModels.find('**//InventoryButtonUp')
     quitEarlyDown = self.quitEarlyButtonModels.find('**/InventoryButtonDown')
     quitEarlyRollover = self.quitEarlyButtonModels.find('**/InventoryButtonRollover')
     self.quitEarlyButton = DirectButton(parent=base.a2dTopRight, relief=None, text=TTLocalizer.PartyTrampolineQuitEarlyButton, text_fg=(1, 1, 0.65, 1), text_pos=(0, -0.23), text_scale=0.7, image=(quitEarlyUp, quitEarlyDown, quitEarlyRollover), image_color=(1, 0, 0, 1), image_scale=(20, 1, 11), pos=(-0.183, 0, -0.4), scale=0.09, command=self.leaveTrampoline)
     self.quitEarlyButton.stash()
     self.flashText = OnscreenText(text='', pos=(0.0, -0.45), scale=0.2, fg=(1.0, 1.0, 0.65, 1.0), align=TextNode.ACenter, font=ToontownGlobals.getSignFont(), mayChange=True)
     self.timer = PartyUtils.getNewToontownTimer()
     self.timer.posInTopRightCorner()
     return
Exemple #56
0
class PartyCog(FSM):
    notify = directNotify.newCategory('PartyCog')
    HpTextGenerator = TextNode('HpTextGenerator')
    hpText = None
    height = 7

    def __init__(self,
                 parentNode,
                 id,
                 bounceSpeed=3,
                 bounceHeight=1,
                 rotateSpeed=1,
                 heightShift=1,
                 xMoveSpeed=0,
                 xMoveDistance=0,
                 bounceOffset=0):
        self.id = id
        FSM.__init__(self, 'PartyCogFSM-%d' % self.id)
        self.showFacingStatus = False
        self.xMoveSpeed = xMoveSpeed
        self.xMoveDistance = xMoveDistance
        self.heightShift = heightShift
        self.bounceSpeed = bounceSpeed
        self.bounceHeight = bounceHeight
        self.rotateSpeed = rotateSpeed
        self.parentNode = parentNode
        self.bounceOffset = bounceOffset
        self.hitInterval = None
        self.kaboomTrack = None
        self.resetRollIval = None
        self.netTimeSentToStartByHit = 0
        self.load()
        self.request('Down')
        return

    def load(self):
        self.root = NodePath('PartyCog-%d' % self.id)
        self.root.reparentTo(self.parentNode)
        path = 'phase_13/models/parties/cogPinata_'
        self.actor = Actor(
            path + 'actor', {
                'idle': path + 'idle_anim',
                'down': path + 'down_anim',
                'up': path + 'up_anim',
                'bodyHitBack': path + 'bodyHitBack_anim',
                'bodyHitFront': path + 'bodyHitFront_anim',
                'headHitBack': path + 'headHitBack_anim',
                'headHitFront': path + 'headHitFront_anim'
            })
        self.actor.reparentTo(self.root)
        self.temp_transform = Mat4()
        self.head_locator = self.actor.attachNewNode('temphead')
        self.bodyColl = CollisionTube(0, 0, 1, 0, 0, 5.75, 0.75)
        self.bodyColl.setTangible(1)
        self.bodyCollNode = CollisionNode('PartyCog-%d-Body-Collision' %
                                          self.id)
        self.bodyCollNode.setCollideMask(ToontownGlobals.PieBitmask)
        self.bodyCollNode.addSolid(self.bodyColl)
        self.bodyCollNodePath = self.root.attachNewNode(self.bodyCollNode)
        self.headColl = CollisionTube(0, 0, 3, 0, 0, 3.0, 1.5)
        self.headColl.setTangible(1)
        self.headCollNode = CollisionNode('PartyCog-%d-Head-Collision' %
                                          self.id)
        self.headCollNode.setCollideMask(ToontownGlobals.PieBitmask)
        self.headCollNode.addSolid(self.headColl)
        self.headCollNodePath = self.root.attachNewNode(self.headCollNode)
        self.arm1Coll = CollisionSphere(1.65, 0, 3.95, 1.0)
        self.arm1Coll.setTangible(1)
        self.arm1CollNode = CollisionNode('PartyCog-%d-Arm1-Collision' %
                                          self.id)
        self.arm1CollNode.setCollideMask(ToontownGlobals.PieBitmask)
        self.arm1CollNode.addSolid(self.arm1Coll)
        self.arm1CollNodePath = self.root.attachNewNode(self.arm1CollNode)
        self.arm2Coll = CollisionSphere(-1.65, 0, 3.45, 1.0)
        self.arm2Coll.setTangible(1)
        self.arm2CollNode = CollisionNode('PartyCog-%d-Arm2-Collision' %
                                          self.id)
        self.arm2CollNode.setCollideMask(ToontownGlobals.PieBitmask)
        self.arm2CollNode.addSolid(self.arm2Coll)
        self.arm2CollNodePath = self.root.attachNewNode(self.arm2CollNode)
        splatName = 'splat-creampie'
        self.splat = globalPropPool.getProp(splatName)
        self.splat.setBillboardPointEye()
        self.splatType = globalPropPool.getPropType(splatName)
        self.pieHitSound = globalBattleSoundCache.getSound(
            'AA_wholepie_only.ogg')
        self.upSound = globalBattleSoundCache.getSound('AV_jump_to_side.ogg')
        self.hole = loader.loadModel('phase_13/models/parties/cogPinataHole')
        self.hole.setTransparency(True)
        self.hole.setP(-90.0)
        self.hole.setScale(3)
        self.hole.setBin('ground', 3)
        self.hole.reparentTo(self.parentNode)

    def unload(self):
        self.request('Off')
        self.clearHitInterval()
        if self.hole is not None:
            self.hole.removeNode()
            self.hole = None
        if self.actor is not None:
            self.actor.cleanup()
            self.actor.removeNode()
            self.actor = None
        if self.root is not None:
            self.root.removeNode()
            self.root = None
        if self.kaboomTrack is not None and self.kaboomTrack.isPlaying():
            self.kaboomTrack.finish()
        self.kaboomTrack = None
        if self.resetRollIval is not None and self.resetRollIval.isPlaying():
            self.resetRollIval.finish()
        self.resetRollIval = None
        if self.hitInterval is not None and self.hitInterval.isPlaying():
            self.hitInterval.finish()
        self.hitInterval = None
        del self.upSound
        del self.pieHitSound
        return

    def enterStatic(self):
        pass

    def exitStatic(self):
        pass

    def enterActive(self, startTime):
        self.root.setR(0.0)
        updateTask = Task.Task(self.updateTask)
        updateTask.startTime = startTime
        taskMgr.add(updateTask, 'PartyCog.update-%d' % self.id)

    def exitActive(self):
        taskMgr.remove('PartyCog.update-%d' % self.id)
        taskMgr.remove('PartyCog.bounceTask-%d' % self.id)
        self.clearHitInterval()
        self.resetRollIval = self.root.hprInterval(0.5,
                                                   Point3(
                                                       self.root.getH(), 0.0,
                                                       0.0),
                                                   blendType='easeInOut')
        self.resetRollIval.start()
        self.actor.stop()

    def enterDown(self):
        if self.oldState == 'Off':
            downAnimControl = self.actor.getAnimControl('down')
            self.actor.pose('down', downAnimControl.getNumFrames() - 1)
            return
        self.clearHitInterval()
        startScale = self.hole.getScale()
        endScale = Point3(5, 5, 5)
        self.hitInterval = Sequence(
            LerpFunc(self.setAlongSpline,
                     duration=1.0,
                     fromData=self.currentT,
                     toData=0.0),
            LerpScaleInterval(self.hole,
                              duration=0.175,
                              scale=endScale,
                              startScale=startScale,
                              blendType='easeIn'),
            Parallel(
                SoundInterval(self.upSound,
                              volume=0.6,
                              node=self.actor,
                              cutOff=PartyGlobals.PARTY_COG_CUTOFF),
                ActorInterval(self.actor, 'down', loop=0)),
            LerpScaleInterval(self.hole,
                              duration=0.175,
                              scale=Point3(3, 3, 3),
                              startScale=endScale,
                              blendType='easeOut'))
        self.hitInterval.start()

    def exitDown(self):
        self.root.setR(0.0)
        self.root.setH(0.0)
        self.targetDistance = 0.0
        self.targetFacing = 0.0
        self.currentT = 0.0
        self.setAlongSpline(0.0)
        self.clearHitInterval()
        startScale = self.hole.getScale()
        endScale = Point3(5, 5, 5)
        self.hitInterval = Sequence(
            LerpScaleInterval(self.hole,
                              duration=0.175,
                              scale=endScale,
                              startScale=startScale,
                              blendType='easeIn'),
            Parallel(
                SoundInterval(self.upSound,
                              volume=0.6,
                              node=self.actor,
                              cutOff=PartyGlobals.PARTY_COG_CUTOFF),
                ActorInterval(self.actor, 'up', loop=0)),
            Func(self.actor.loop, 'idle'),
            LerpScaleInterval(self.hole,
                              duration=0.175,
                              scale=Point3(3, 3, 3),
                              startScale=endScale,
                              blendType='easeOut'))
        self.hitInterval.start()

    def filterDown(self, request, args):
        if request == 'Down':
            return None
        else:
            return self.defaultFilter(request, args)
        return None

    def setEndPoints(self, start, end, amplitude=1.7):
        self.sinAmplitude = amplitude
        self.sinPeriod = (end.getX() - start.getX()) / 2
        self.sinDisplacement = start.getY()
        self.startPoint = start
        self.endPoint = end
        self.currentT = 0.0
        self.targetDistance = 0.0
        self.currentFacing = 0.0
        self.targetFacing = 0.0
        self.setAlongSpline(self.currentT)
        self.hole.setPos(self.root.getPos())
        self.hole.setZ(0.02)

    def rockBackAndForth(self, task):
        t = task.startTime + task.time
        angle = math.sin(t) * 20.0
        self.root.setR(angle)
        return task.cont

    def updateDistance(self, distance):
        self.targetDistance = clamp(distance, -1.0, 1.0)

    def updateTask(self, task):
        self.rockBackAndForth(task)
        if self.targetDistance > self.currentT:
            self.currentT += min(0.01, self.targetDistance - self.currentT)
            self.setAlongSpline(self.currentT)
        elif self.targetDistance < self.currentT:
            self.currentT += max(-0.01, self.targetDistance - self.currentT)
            self.setAlongSpline(self.currentT)
        if self.currentT < 0.0:
            self.targetFacing = -90.0
        elif self.currentT > 0.0:
            self.targetFacing = 90.0
        else:
            self.targetFacing = 0.0
        if self.targetFacing > self.currentFacing:
            self.currentFacing += min(10,
                                      self.targetFacing - self.currentFacing)
        elif self.targetFacing < self.currentFacing:
            self.currentFacing += max(-10,
                                      self.targetFacing - self.currentFacing)
        self.root.setH(self.currentFacing)
        return task.cont

    def setAlongSpline(self, t):
        t = t + 1.0
        dist = (self.endPoint.getX() - self.startPoint.getX()) / 2.0
        x = self.startPoint.getX() + t * dist
        y = self.startPoint.getY() - math.sin(
            t * 2 * math.pi) * self.sinAmplitude
        self.root.setPos(x, y, 0)

    def startBounce(self):
        taskMgr.add(self.bounce, 'PartyCog.bounceTask-%d' % self.id)

    def bounce(self, task):
        self.root.setZ(
            math.sin((self.bounceOffset + task.time) * self.bounceSpeed) *
            self.bounceHeight + self.heightShift)
        return task.cont

    def setPos(self, position):
        self.root.setPos(position)

    def respondToPieHit(self, timestamp, position, hot=False, direction=1.0):
        if self.netTimeSentToStartByHit < timestamp:
            self.__showSplat(position, direction, hot)
            if self.netTimeSentToStartByHit < timestamp:
                self.netTimeSentToStartByHit = timestamp
        else:
            self.notify.debug(
                'respondToPieHit self.netTimeSentToStartByHit = %s' %
                self.netTimeSentToStartByHit)

    def clearHitInterval(self):
        if self.hitInterval is not None and self.hitInterval.isPlaying():
            self.hitInterval.clearToInitial()
        return

    def __showSplat(self, position, direction, hot=False):
        if self.kaboomTrack is not None and self.kaboomTrack.isPlaying():
            self.kaboomTrack.finish()
        self.clearHitInterval()
        splatName = 'splat-creampie'
        self.splat = globalPropPool.getProp(splatName)
        self.splat.setBillboardPointEye()
        self.splat.reparentTo(render)
        self.splat.setPos(self.root, position)
        self.splat.setAlphaScale(1.0)
        if not direction == 1.0:
            self.splat.setColorScale(PartyGlobals.CogActivitySplatColors[0])
            if self.currentFacing > 0.0:
                facing = 'HitFront'
            else:
                facing = 'HitBack'
        else:
            self.splat.setColorScale(PartyGlobals.CogActivitySplatColors[1])
            if self.currentFacing > 0.0:
                facing = 'HitBack'
            else:
                facing = 'HitFront'
        if hot:
            targetscale = 0.75
            part = 'head'
        else:
            targetscale = 0.5
            part = 'body'

        def setSplatAlpha(amount):
            self.splat.setAlphaScale(amount)

        self.hitInterval = Sequence(
            ActorInterval(self.actor, part + facing, loop=0),
            Func(self.actor.loop, 'idle'))
        self.hitInterval.start()
        self.kaboomTrack = Parallel(
            SoundInterval(self.pieHitSound,
                          volume=1.0,
                          node=self.actor,
                          cutOff=PartyGlobals.PARTY_COG_CUTOFF),
            Sequence(
                Func(self.splat.showThrough),
                Parallel(
                    Sequence(
                        LerpScaleInterval(self.splat,
                                          duration=0.175,
                                          scale=targetscale,
                                          startScale=Point3(0.1, 0.1, 0.1),
                                          blendType='easeOut'), Wait(0.175)),
                    Sequence(
                        Wait(0.1),
                        LerpFunc(setSplatAlpha,
                                 duration=1.0,
                                 fromData=1.0,
                                 toData=0.0,
                                 blendType='easeOut'))),
                Func(self.splat.cleanup), Func(self.splat.removeNode)))
        self.kaboomTrack.start()
        return

    def showHitScore(self, number, scale=1):
        if number <= 0:
            return
        if self.hpText:
            self.hideHitScore()
        self.HpTextGenerator.setFont(ToontownGlobals.getSignFont())
        if number < 0:
            self.HpTextGenerator.setText(str(number))
        else:
            self.HpTextGenerator.setText('+' + str(number))
        self.HpTextGenerator.clearShadow()
        self.HpTextGenerator.setAlign(TextNode.ACenter)
        r = 1
        g = 1
        b = 0
        a = 1
        self.HpTextGenerator.setTextColor(r, g, b, a)
        self.hpTextNode = self.HpTextGenerator.generate()
        self.hpText = render.attachNewNode(self.hpTextNode)
        self.hpText.setScale(scale)
        self.hpText.setBillboardPointEye()
        self.hpText.setBin('fixed', 100)
        self.hpText.setPos(self.root, 0, 0, self.height / 2)
        seq = Task.sequence(
            self.hpText.lerpPos(Point3(
                self.root.getX(render), self.root.getY(render),
                self.root.getZ(render) + self.height + 1.0),
                                0.25,
                                blendType='easeOut'), Task.pause(0.25),
            self.hpText.lerpColor(Vec4(r, g, b, a), Vec4(r, g, b, 0), 0.1),
            Task.Task(self.__hideHitScoreTask))
        taskMgr.add(seq, 'PartyCogHpText' + str(self.id))

    def __hideHitScoreTask(self, task):
        self.hideHitScore()
        return Task.done

    def hideHitScore(self):
        if self.hpText:
            taskMgr.remove('PartyCogHpText' + str(self.id))
            self.hpText.removeNode()
            self.hpText = None
        return

    def getHeadLocation(self):
        self.actor.getJoints(jointName='head')[0].getNetTransform(
            self.temp_transform)
        self.head_locator.setMat(self.temp_transform)
        return self.head_locator.getZ(self.root)
class PartyPlanner(DirectFrame, FSM):
    notify = DirectNotifyGlobal.directNotify.newCategory('PartyPlanner')

    def __init__(self, doneEvent = None):
        FSM.__init__(self, 'PartyPlannerFSM')
        DirectFrame.__init__(self)
        self.doneEvent = doneEvent
        self.stateArray = ['Off',
         'Welcome',
         'PartyEditor',
         'Guests',
         'Date',
         'Time',
         'Invitation',
         'Farewell']
        self.partyTime = base.cr.toontownTimeManager.getCurServerDateTime()
        self.partyNowTime = base.cr.toontownTimeManager.getCurServerDateTime()
        minutesToNextFifteen = 15 - self.partyTime.minute % 15
        self.cleanPartyTime = self.partyTime + timedelta(minutes=minutesToNextFifteen, seconds=-self.partyTime.second)
        self.partyTime = self.cleanPartyTime
        self.guests = []
        self.isPrivate = False
        self.selectedCalendarGuiDay = None
        self.gui = loader.loadModel('phase_4/models/parties/partyPlannerGUI')
        self.partyDuration = timedelta(hours=PartyGlobals.DefaultPartyDuration)
        self.timeTypeToMaxValue = {'hour': 23,
         'minute': 59}
        self.timeTypeToChangeAmount = {'hour': (1, -1),
         'minute': (15, -15),
         'ampm': (1, -1)}
        self.partyInfo = None
        self.asapMinuteRounding = base.config.GetInt('party-asap-minute-rounding', PartyGlobals.PartyPlannerAsapMinuteRounding)
        self.load()
        self.request('Welcome')
        return

    def enterWelcome(self, *args):
        self.prevButton['state'] = DirectGuiGlobals.DISABLED
        self.prevButton.hide()
        self.nextButton['state'] = DirectGuiGlobals.NORMAL
        self.welcomePage.show()
        self.partyPlannerHead.reparentTo(self.welcomePage)
        self.partyPlannerHead.startBlink()
        self.partyPlannerHead.startLookAround()
        self.nametagNP.reparentTo(self.welcomePage)
        self.chatNP.reparentTo(self.welcomePage)

    def exitWelcome(self):
        self.welcomePage.hide()
        self.prevButton.show()
        self.partyPlannerHead.stopBlink()
        self.partyPlannerHead.stopLookAround()

    def enterPartyEditor(self, *args):
        self.prevButton['state'] = DirectGuiGlobals.NORMAL
        self.nextButton['state'] = DirectGuiGlobals.DISABLED
        self.nextButton.hide()
        self.partyEditorPage.show()
        self.okWithGroundsGui.doneStatus = ''
        self.partyEditor.request('Idle')

    def exitPartyEditor(self):
        self.partyEditor.request('Hidden')
        self.partyEditorPage.hide()

    def enterGuests(self, *args):
        self.prevButton['state'] = DirectGuiGlobals.NORMAL
        self.nextButton['state'] = DirectGuiGlobals.NORMAL
        self.nextButton.show()
        self.guestPage.show()

    def exitGuests(self):
        self.guests = []
        for friendCheckBox in self.friendList['items']:
            if friendCheckBox['indicatorValue']:
                self.guests.append(friendCheckBox.getPythonTag('id'))

        self.guestPage.hide()

    def enterDate(self, *args):
        self.prevButton.show()
        self.prevButton['state'] = DirectGuiGlobals.NORMAL
        if self.selectedCalendarGuiDay is None:
            self.nextButton['state'] = DirectGuiGlobals.DISABLED
            self.nextButton.hide()
            self.makePartyNowButton.show()
        self.datePage.show()
        return

    def exitDate(self):
        self.datePage.hide()
        self.nextButton.show()
        if self.selectedCalendarGuiDay is not None:
            self.partyTime = self.cleanPartyTime
            self.alterPartyTime(year=self.selectedCalendarGuiDay.myDate.year, month=self.selectedCalendarGuiDay.myDate.month, day=self.selectedCalendarGuiDay.myDate.day)
        else:
            self.partyNowTime = self.calcAsapTime()
            self.partyTime = self.partyNowTime
        return

    def calcAsapTime(self):
        curServerTime = base.cr.toontownTimeManager.getCurServerDateTime()
        baseTime = curServerTime
        baseTime = baseTime.replace(baseTime.year, baseTime.month, baseTime.day, baseTime.hour, baseTime.minute, second=0, microsecond=0)
        minute = curServerTime.minute
        remainder = minute % self.asapMinuteRounding
        if remainder:
            baseTime += timedelta(minutes=self.asapMinuteRounding - remainder)
        else:
            baseTime += timedelta(minutes=self.asapMinuteRounding)
        return baseTime

    def enterTime(self, *args):
        self.prevButton.show()
        self.prevButton['state'] = DirectGuiGlobals.NORMAL
        self.nextButton.show()
        self.timePage.show()
        self.timePageRecapToontownTimeLabel2['text'] = '%s' % PartyUtils.formatDateTime(self.partyTime)
        self.timePageRecapLocalTimeLabel['text'] = '%s%s' % (TTLocalizer.PartyPlannerTimeLocalTime, PartyUtils.formatDateTime(self.partyTime, inLocalTime=True))

    def exitTime(self):
        self.timePage.hide()
        self.nextButton.show()

    def enterInvitation(self, *args):
        self.prevButton['state'] = DirectGuiGlobals.NORMAL
        self.nextButton.hide()
        defaultInviteTheme = PartyGlobals.InviteTheme.GenericMale
        if hasattr(base.cr, 'newsManager') and base.cr.newsManager:
            if ToontownGlobals.VICTORY_PARTY_HOLIDAY in base.cr.newsManager.getHolidayIdList():
                defaultInviteTheme = PartyGlobals.InviteTheme.VictoryParty
            elif ToontownGlobals.KARTING_TICKETS_HOLIDAY in base.cr.newsManager.getHolidayIdList() or ToontownGlobals.CIRCUIT_RACING_EVENT in base.cr.newsManager.getHolidayIdList():
                defaultInviteTheme = PartyGlobals.InviteTheme.Racing
            elif ToontownGlobals.VALENTINES_DAY in base.cr.newsManager.getHolidayIdList():
                defaultInviteTheme = PartyGlobals.InviteTheme.Valentoons
        if self.partyInfo is not None:
            del self.partyInfo
        activityList = self.partyEditor.partyEditorGrid.getActivitiesOnGrid()
        decorationList = self.partyEditor.partyEditorGrid.getDecorationsOnGrid()
        endTime = self.partyTime + self.partyDuration
        self.partyInfo = PartyInfo(0, 0, self.partyTime.year, self.partyTime.month, self.partyTime.day, self.partyTime.hour, self.partyTime.minute, endTime.year, endTime.month, endTime.day, endTime.hour, endTime.minute, self.isPrivate, defaultInviteTheme, activityList, decorationList, 0)
        if self.noFriends or len(self.getInvitees()) == 0:
            self.inviteVisual.setNoFriends(True)
            self.invitationTitleLabel['text'] = TTLocalizer.PartyPlannerConfirmTitleNoFriends
            self.inviteButton['text'] = TTLocalizer.PartyPlannerInviteButtonNoFriends
            self.selectedInviteThemeLabel.stash()
            self.nextThemeButton.stash()
            self.prevThemeButton.stash()
            self.setInviteTheme(defaultInviteTheme)
        else:
            self.inviteVisual.setNoFriends(False)
            self.invitationTitleLabel['text'] = TTLocalizer.PartyPlannerConfirmTitle
            self.inviteButton['text'] = TTLocalizer.PartyPlannerInviteButton
            self.selectedInviteThemeLabel.unstash()
            self.nextThemeButton.unstash()
            self.prevThemeButton.unstash()
            self.setInviteTheme(defaultInviteTheme)
        self.inviteVisual.updateInvitation(base.localAvatar.getName(), self.partyInfo)
        self.invitationPage.show()
        return

    def __prevTheme(self):
        self.nextThemeButton.show()
        prevTheme = self.currentInvitationTheme - 1
        while prevTheme not in self.inviteThemes:
            prevTheme -= 1
            if prevTheme == self.currentInvitationTheme:
                self.notify.warning('No previous invite theme found.')
                break
            elif prevTheme < 0:
                prevTheme = len(self.inviteVisual.inviteThemesIdToInfo) - 1

        self.setInviteTheme(prevTheme)

    def __nextTheme(self):
        self.prevThemeButton.show()
        nextTheme = self.currentInvitationTheme + 1
        while nextTheme not in self.inviteThemes:
            nextTheme += 1
            if nextTheme == self.currentInvitationTheme:
                self.notify.warning('No next invite theme found.')
                break
            elif nextTheme >= len(self.inviteVisual.inviteThemesIdToInfo):
                nextTheme = 0

        self.setInviteTheme(nextTheme)

    def setInviteTheme(self, themeNumber):
        self.currentInvitationTheme = themeNumber
        self.selectedInviteThemeLabel['text'] = '%s %s (%d/%d)' % (self.inviteVisual.inviteThemesIdToInfo[self.currentInvitationTheme][1],
         TTLocalizer.PartyPlannerInvitationTheme,
         self.inviteThemes.index(self.currentInvitationTheme) + 1,
         len(self.inviteThemes))
        self.partyInfo.inviteTheme = self.currentInvitationTheme
        self.inviteVisual.updateInvitation(base.localAvatar.getName(), self.partyInfo)

    def exitInvitation(self):
        self.invitationPage.hide()
        self.nextButton.show()

    def enterFarewell(self, goingBackAllowed):
        self.farewellPage.show()
        if goingBackAllowed:
            self.prevButton.show()
        else:
            self.prevButton.hide()
        self.nextButton.hide()
        self.partyPlannerHead.reparentTo(self.farewellPage)
        self.partyPlannerHead.startBlink()
        self.partyPlannerHead.startLookAround()
        self.nametagNP.reparentTo(self.farewellPage)
        self.chatNP.reparentTo(self.farewellPage)

    def exitFarewell(self):
        self.farewellPage.hide()
        self.nextButton.show()
        self.prevButton.show()
        self.partyPlannerHead.stopBlink()
        self.partyPlannerHead.stopLookAround()

    def load(self):
        self.frame = DirectFrame(parent=aspect2d, geom=self.gui.find('**/background'), relief=None, scale=0.85, pos=(0.05, 0.0, 0.1))
        self.titleScale = TTLocalizer.PPtitleScale
        self._createNavButtons()
        self.welcomePage = self._createWelcomePage()
        self.welcomePage.hide()
        self.datePage = self._createDatePage()
        self.datePage.hide()
        self.timePage = self._createTimePage()
        self.timePage.hide()
        self.guestPage = self._createGuestPage()
        self.guestPage.hide()
        self.partyEditorPage = self._createPartyEditorPage()
        self.partyEditorPage.hide()
        self.invitationPage = self._createInvitationPage()
        self.invitationPage.hide()
        self.farewellPage = self._createFarewellPage()
        self.farewellPage.hide()
        return

    def _createNavButtons(self):
        self.quitButton = DirectButton(parent=self.frame, relief=None, geom=(self.gui.find('**/cancelButton_up'), self.gui.find('**/cancelButton_down'), self.gui.find('**/cancelButton_rollover')), command=self.__acceptExit)
        self.nextButton = DirectButton(parent=self.frame, relief=None, geom=(self.gui.find('**/bottomNext_button/nextButton_up'), self.gui.find('**/bottomNext_button/nextButton_down'), self.gui.find('**/bottomNext_button/nextButton_rollover')), command=self.__nextItem, state=DirectGuiGlobals.DISABLED)
        self.prevButton = DirectButton(parent=self.frame, relief=None, geom=(self.gui.find('**/bottomPrevious_button/previousButton_up'), self.gui.find('**/bottomPrevious_button/previousButton_down'), self.gui.find('**/bottomPrevious_button/previousButton_rollover')), command=self.__prevItem, state=DirectGuiGlobals.DISABLED)
        self.currentItem = None
        return

    def __createNametag(self, parent):
        if self.nametagGroup == None:
            self.nametagGroup = NametagGroup()
            self.nametagGroup.setFont(OTPGlobals.getInterfaceFont())
            self.nametagGroup.setActive(0)
            self.nametagGroup.setAvatar(self.partyPlannerHead)
            self.nametagGroup.manage(base.marginManager)
            self.nametagGroup.setColorCode(self.nametagGroup.CCNonPlayer)
            self.nametagGroup.getNametag2d().setContents(0)
            self.nametagNode = NametagFloat2d()
            self.nametagNode.setContents(Nametag.CName)
            self.nametagGroup.addNametag(self.nametagNode)
            self.nametagGroup.setName(base.cr.partyManager.getPartyPlannerName())
            self.nametagNP = parent.attachNewNode(self.nametagNode.upcastToPandaNode())
            nametagPos = self.gui.find('**/step_01_partymanPeteNametag_locator').getPos()
            self.nametagNP.setPosHprScale(nametagPos[0], 0, nametagPos[2], 0, 0, 0, 0.1, 1, 0.1)
            self.chatNode = NametagFloat2d()
            self.chatNode.setContents(Nametag.CSpeech | Nametag.CThought)
            self.nametagGroup.addNametag(self.chatNode)
            self.nametagGroup.setChat(TTLocalizer.PartyPlannerInstructions, CFSpeech)
            self.chatNP = parent.attachNewNode(self.chatNode.upcastToPandaNode())
            chatPos = self.gui.find('**/step_01_partymanPeteText_locator').getPos()
            self.chatNP.setPosHprScale(chatPos[0], 0, chatPos[2], 0, 0, 0, 0.08, 1, 0.08)
        return

    def clearNametag(self):
        if self.nametagGroup != None:
            self.nametagGroup.unmanage(base.marginManager)
            self.nametagGroup.removeNametag(self.nametagNode)
            self.nametagGroup.removeNametag(self.chatNode)
            self.nametagNP.removeNode()
            self.chatNP.removeNode()
            del self.nametagNP
            del self.chatNP
            del self.nametagNode
            del self.chatNode
            self.nametagGroup.setAvatar(NodePath())
            self.nametagGroup = None
        return

    def _createWelcomePage(self):
        self.nametagGroup = None
        page = DirectFrame(self.frame)
        page.setName('PartyPlannerWelcomePage')
        self.welcomeTitleLabel = DirectLabel(parent=page, relief=None, text=TTLocalizer.PartyPlannerWelcomeTitle, pos=self.gui.find('**/title_locator').getPos(), scale=self.titleScale)
        self.partyPlannerHead = ToonHead.ToonHead()
        partyPlannerStyle = base.cr.partyManager.getPartyPlannerStyle()
        self.partyPlannerHead.setupHead(partyPlannerStyle, forGui=True)
        self.partyPlannerHead.setPos(self.gui.find('**/step_01_partymanPete_locator').getPos())
        animal = partyPlannerStyle.getAnimal()
        if animal == 'cat' or animal == 'pig':
            headScale = 0.4
        elif animal == 'dog' or animal == 'bear':
            headScale = 0.45
        elif animal == 'rabbit':
            headScale = 0.35
        else:
            headScale = 0.3
        self.partyPlannerHead.setScale(headScale)
        self.partyPlannerHead.setH(180.0)
        self.partyPlannerHead.reparentTo(page)
        self.__createNametag(page)
        return page

    def _createDatePage(self):
        page = DirectFrame(self.frame)
        page.setName('PartyPlannerDatePage')
        self.createDateTitleLabel = DirectLabel(parent=page, relief=None, text=TTLocalizer.PartyPlannerDateTitle, pos=self.gui.find('**/title_locator').getPos(), scale=self.titleScale)
        pos = self.gui.find('**/step_06_sendInvitation_locator').getPos()
        self.makePartyNowButton = DirectButton(parent=page, relief=None, geom=(self.gui.find('**/send_up'), self.gui.find('**/send_down'), self.gui.find('**/send_rollover')), text=TTLocalizer.PartyPlannerPartyNow, text_pos=(pos[0], pos[2]), text_scale=0.05, command=self.__doMakePartyNow)
        curServerDate = base.cr.toontownTimeManager.getCurServerDateTime()
        self.calendarGuiMonth = CalendarGuiMonth(page, curServerDate, scale=0.95, pos=(-0.05, 0.0, -0.33), dayClickCallback=self._dayClickCallback, onlyFutureDaysClickable=True)
        return page

    def __doMakePartyNow(self):
        self.request('Invitation')

    def _dayClickCallback(self, calendarGuiDay):
        self.selectedCalendarGuiDay = calendarGuiDay
        self.nextButton['state'] = DirectGuiGlobals.NORMAL
        self.makePartyNowButton.hide()
        self.nextButton.show()

    def alterPartyTime(self, year = None, month = None, day = None, hour = None, minute = None):
        self.partyTime = datetime(year=self.positiveTime('year', year), month=self.positiveTime('month', month), day=self.positiveTime('day', day), hour=self.positiveTime('hour', hour), minute=self.positiveTime('minute', minute), tzinfo=self.partyTime.tzinfo)

    def positiveTime(self, type, amount):
        if amount is None:
            return getattr(self.partyTime, type)
        if type == 'hour' or type == 'minute':
            if amount < 0:
                return self.timeTypeToMaxValue[type] + 1 + self.timeTypeToChangeAmount[type][1]
            elif amount > self.timeTypeToMaxValue[type]:
                return 0
        return amount

    def _createTimePage(self):
        page = DirectFrame(self.frame)
        page.setName('PartyPlannerTimePage')
        self.createTimeTitleLabel = DirectLabel(parent=page, relief=None, text=TTLocalizer.PartyPlannerTimeTitle, pos=self.gui.find('**/title_locator').getPos(), scale=self.titleScale)
        self.clockImage = DirectFrame(parent=page, relief=None, geom=self.gui.find('**/toontownTime_background'))
        self.timePageToontownLabel = DirectLabel(parent=page, relief=None, text=TTLocalizer.PartyPlannerTimeToontown, pos=self.gui.find('**/step_03_toontown_locator').getPos(), scale=0.15, text_fg=(1.0, 0.0, 0.0, 1.0), text_font=ToontownGlobals.getSignFont())
        self.timePageTimeLabel = DirectLabel(parent=page, relief=None, text=TTLocalizer.PartyPlannerTimeTime, pos=self.gui.find('**/step_03_time_locator').getPos(), scale=0.15, text_fg=(1.0, 0.0, 0.0, 1.0), text_font=ToontownGlobals.getSignFont())
        self.timePageRecapLabel = DirectLabel(parent=page, relief=None, text=TTLocalizer.PartyPlannerTimeRecap, pos=self.gui.find('**/step_03_partyDateAndTime_locator').getPos(), scale=0.09)
        self.timePageRecapToontownTimeLabel1 = DirectLabel(parent=page, relief=None, text=TTLocalizer.PartyPlannerTimeToontownTime, pos=self.gui.find('**/step_03_toontownTime_locator').getPos(), scale=0.06)
        self.timePageRecapToontownTimeLabel2 = DirectLabel(parent=page, relief=None, text='%s' % PartyUtils.formatDateTime(self.partyTime), pos=self.gui.find('**/step_03_toontownDateAndTime_loactor').getPos(), textMayChange=True, scale=0.06)
        self.timePageRecapLocalTimeLabel = DirectLabel(parent=page, relief=None, text='%s%s' % (TTLocalizer.PartyPlannerTimeLocalTime, PartyUtils.formatDateTime(self.partyTime, inLocalTime=True)), pos=self.gui.find('**/step_03_localDateAndTime_loactor').getPos(), textMayChange=True, scale=0.06, text_fg=(1.0, 0.0, 0.0, 1.0))
        self.timeInputHourLabel, self.timeInputHourUpButton, self.timeInputHourDownButton = self.getTimeWidgets(page, 'hour')
        self.timeInputMinuteLabel, self.timeInputMinuteUpButton, self.timeInputMinuteDownButton = self.getTimeWidgets(page, 'minute')
        self.timeInputAmPmLabel, self.timeInputAmPmUpButton, self.timeInputAmPmDownButton = self.getTimeWidgets(page, 'ampm')
        self.timePagecolonLabel = DirectLabel(parent=page, relief=None, text=':', pos=self.gui.find('**/step_03_colon_locator').getPos(), scale=0.15)
        return page

    def getTimeWidgets(self, page, type):
        if type == 'ampm':
            data = self.getCurrentAmPm()
        else:
            data = getattr(self.partyTime, type)
            if data == 0 and type == 'minute':
                data = '00'
            else:
                if type == 'hour':
                    data = data % 12
                    if data == 0:
                        data = 12
                data = '%d' % data
        label = DirectLabel(parent=page, relief=None, text='%s' % data, textMayChange=True, pos=self.gui.find('**/step_03_%s_locator' % type).getPos(), scale=0.12)

        def changeValue(self, amount):
            if type == 'ampm':
                self.alterPartyTime(hour=(self.partyTime.hour + 12) % 24)
                newAmount = self.getCurrentAmPm()
                label['text'] = newAmount
            else:
                if type == 'hour':
                    newAmount = getattr(self.partyTime, type) + amount
                    newAmount = newAmount % 12
                    if self.timeInputAmPmLabel['text'] == TTLocalizer.PartyTimeFormatMeridiemPM:
                        newAmount = newAmount % 12 + 12
                    self.alterPartyTime(hour=newAmount)
                elif type == 'minute':
                    newAmount = getattr(self.partyTime, type) + amount
                    self.alterPartyTime(minute=newAmount)
                else:
                    PartyPlanner.notify.error('Invalid type for changeValue in PartyPlanner: %s' % type)
                newAmount = getattr(self.partyTime, type)
                if newAmount < 10 and type == 'minute':
                    label['text'] = '0%d' % newAmount
                else:
                    if type == 'hour':
                        newAmount = newAmount % 12
                        if newAmount == 0:
                            newAmount = 12
                    label['text'] = '%d' % newAmount
            self.timePageRecapToontownTimeLabel2['text'] = '%s' % PartyUtils.formatDateTime(self.partyTime)
            self.timePageRecapLocalTimeLabel['text'] = '%s%s' % (TTLocalizer.PartyPlannerTimeLocalTime, PartyUtils.formatDateTime(self.partyTime, inLocalTime=True))

        upButton = DirectButton(parent=page, relief=None, geom=(self.gui.find('**/%sButtonUp_up' % type), self.gui.find('**/%sButtonUp_down' % type), self.gui.find('**/%sButtonUp_rollover' % type)), command=changeValue, extraArgs=[self, self.timeTypeToChangeAmount[type][0]])
        downButton = DirectButton(parent=page, relief=None, geom=(self.gui.find('**/%sButtonDown_up' % type), self.gui.find('**/%sButtonDown_down' % type), self.gui.find('**/%sButtonDown_rollover' % type)), command=changeValue, extraArgs=[self, self.timeTypeToChangeAmount[type][1]])
        return (label, upButton, downButton)

    def getCurrentAmPm(self):
        if self.partyTime.hour < 12:
            return TTLocalizer.PartyTimeFormatMeridiemAM
        else:
            return TTLocalizer.PartyTimeFormatMeridiemPM

    def _createGuestPage(self):
        page = DirectFrame(self.frame)
        page.setName('PartyPlannerGuestPage')
        self.guestTitleLabel = DirectLabel(parent=page, relief=None, text=TTLocalizer.PartyPlannerGuestTitle, pos=self.gui.find('**/title_locator').getPos(), scale=self.titleScale)
        self.guestBackgroundLabel = DirectLabel(parent=page, relief=None, image=self.gui.find('**/guestListBackground_flat'), scale=(1.2, 1.0, 1.0))
        self.friendList = ScrolledFriendList(page, self.gui, makeItemsCheckBoxes=True)
        if len(base.localAvatar.friendsList) == 0:
            self.noFriends = True
        else:
            self.noFriends = False
            for friendPair in base.localAvatar.friendsList:
                self.friendList.addFriend(determineFriendName(friendPair), friendPair[0])

            self.friendList.scrollTo(0)
        pos = self.gui.find('**/step_04_partyWillBe_locator').getPos()
        self.publicPrivateLabel = DirectLabel(parent=page, relief=None, text=TTLocalizer.PartyPlannerPublicPrivateLabel, text_align=TextNode.ACenter, text_scale=0.065, pos=pos)
        self.publicDescriptionLabel = DirectLabel(parent=page, relief=None, text=TTLocalizer.PartyPlannerPublicDescription, text_align=TextNode.ACenter, text_scale=TTLocalizer.PPpbulicDescriptionLabel, pos=(pos[0] - 0.52, pos[1], pos[2]))
        self.publicDescriptionLabel.stash()
        self.privateDescriptionLabel = DirectLabel(parent=page, relief=None, text=TTLocalizer.PartyPlannerPrivateDescription, text_align=TextNode.ACenter, text_scale=TTLocalizer.PPprivateDescriptionLabel, pos=(pos[0] + 0.55, pos[1], pos[2]))
        self.privateDescriptionLabel.stash()
        pos = self.gui.find('**/step_04_public_locator').getPos()
        self.publicButton = DirectButton(parent=page, relief=None, geom=(self.gui.find('**/publicButton_up'),
         self.gui.find('**/publicButton_down'),
         self.gui.find('**/publicButton_rollover'),
         self.gui.find('**/publicButton_inactive')), text=TTLocalizer.PartyPlannerPublic, text_pos=(pos[0], pos[2]), text_scale=TTLocalizer.PPpublicButton, command=self.__doTogglePublicPrivate)
        self.publicButton['state'] = DirectGuiGlobals.DISABLED
        self.publicButton.bind(DirectGuiGlobals.ENTER, self.__enterPublic)
        self.publicButton.bind(DirectGuiGlobals.EXIT, self.__exitPublic)
        pos = self.gui.find('**/step_04_private_locator').getPos()
        self.privateButton = DirectButton(parent=page, relief=None, geom=(self.gui.find('**/privateButton_up'),
         self.gui.find('**/privateButton_down'),
         self.gui.find('**/privateButton_rollover'),
         self.gui.find('**/privateButton_inactive')), text=TTLocalizer.PartyPlannerPrivate, text_pos=(pos[0], pos[2]), text_scale=TTLocalizer.PPprivateButton, command=self.__doTogglePublicPrivate)
        self.privateButton.bind(DirectGuiGlobals.ENTER, self.__enterPrivate)
        self.privateButton.bind(DirectGuiGlobals.EXIT, self.__exitPrivate)
        self.checkAllButton = DirectButton(parent=page, relief=None, geom=(self.gui.find('**/checkAllButton_up'), self.gui.find('**/checkAllButton_down'), self.gui.find('**/checkAllButton_rollover')), command=self.__doCheckAll)
        self.uncheckAllButton = DirectButton(parent=page, relief=None, geom=(self.gui.find('**/uncheckAllButton_up'), self.gui.find('**/uncheckAllButton_down'), self.gui.find('**/uncheckAllButton_rollover')), command=self.__doUncheckAll)
        return page

    def __doCheckAll(self):
        for friendBox in self.friendList['items']:
            friendBox['indicatorValue'] = True

    def __doUncheckAll(self):
        for friendBox in self.friendList['items']:
            friendBox['indicatorValue'] = False

    def __enterPrivate(self, mouseEvent):
        self.privateDescriptionLabel.unstash()

    def __exitPrivate(self, mouseEvent):
        self.privateDescriptionLabel.stash()

    def __enterPublic(self, mouseEvent):
        self.publicDescriptionLabel.unstash()

    def __exitPublic(self, mouseEvent):
        self.publicDescriptionLabel.stash()

    def __doTogglePublicPrivate(self):
        if self.isPrivate:
            self.isPrivate = False
            self.privateButton['state'] = DirectGuiGlobals.NORMAL
            self.publicButton['state'] = DirectGuiGlobals.DISABLED
        else:
            self.isPrivate = True
            self.privateButton['state'] = DirectGuiGlobals.DISABLED
            self.publicButton['state'] = DirectGuiGlobals.NORMAL

    def _createPartyEditorPage(self):
        page = DirectFrame(self.frame)
        page.setName('PartyPlannerEditorPage')
        self.LayoutTitleLabel = DirectLabel(parent=page, relief=None, text=TTLocalizer.PartyPlannerEditorTitle, pos=self.gui.find('**/title_locator').getPos() + Point3(0.0, 0.0, 0.075), scale=self.titleScale)
        self.costLabel = DirectLabel(parent=page, pos=(-0.74, 0.0, 0.17), relief=None, text=TTLocalizer.PartyPlannerTotalCost % 0, text_align=TextNode.ACenter, scale=TTLocalizer.PPcostLabel, textMayChange=True)
        self.partyGridBackground = DirectFrame(parent=page, relief=None, geom=self.gui.find('**/partyGrid_flat'))
        self.partyGroundsLabel = DirectLabel(parent=page, relief=None, text=TTLocalizer.PartyPlannerPartyGrounds, text_font=ToontownGlobals.getSignFont(), text_fg=VBase4(1.0, 0.0, 0.0, 1.0), text_scale=TTLocalizer.PPpartyGroundsLabel, pos=self.gui.find('**/step_05_partyGrounds_text_locator').getPos(), scale=0.1)
        self.activityBackground = DirectFrame(parent=page, relief=None, geom=self.gui.find('**/activitiesDecorations_flat1'), pos=(0.0, 0.0, 0.04))
        pos = self.gui.find('**/step_05_instructions_locator').getPos()
        self.instructionLabel = DirectLabel(parent=page, relief=None, text=' ', text_pos=(pos[0], pos[2]), text_scale=TTLocalizer.PPinstructionLabel, textMayChange=True, geom=self.gui.find('**/instructions_flat'))
        self.elementTitleLabel = DirectLabel(parent=page, relief=None, text=' ', pos=self.gui.find('**/step_05_activitiesName_text_locator').getPos() + Point3(0.0, 0.0, 0.04), text_scale=TTLocalizer.PPelementTitleLabel, textMayChange=True)
        self.elementPriceNode = TextNode('ElementPrice')
        self.elementPriceNode.setAlign(TextNode.ALeft)
        self.elementPriceNode.setTextColor(0.0, 0.0, 0.0, 1.0)
        self.elementPriceNode.setFont(ToontownGlobals.getToonFont())
        self.elementPrice = page.attachNewNode(self.elementPriceNode)
        self.elementPrice.setScale(TTLocalizer.PPelementPriceNode)
        self.elementPrice.setPos(self.gui.find('**/step_05_activityPrice_text_locator').getPos() + Point3(-0.02, 0.0, 0.04))
        self.elementDescriptionNode = TextNode('ElementDescription')
        self.elementDescriptionNode.setAlign(TextNode.ACenter)
        self.elementDescriptionNode.setWordwrap(8)
        self.elementDescriptionNode.setFont(ToontownGlobals.getToonFont())
        self.elementDescriptionNode.setTextColor(0.0, 0.0, 0.0, 1.0)
        self.elementDescription = page.attachNewNode(self.elementDescriptionNode)
        self.elementDescription.setScale(TTLocalizer.PPelementDescription)
        self.elementDescription.setPos(self.gui.find('**/step_05_activityDescription_text_locator').getPos() + Point3(0.0, 0.0, 0.04))
        self.totalMoney = base.localAvatar.getTotalMoney()
        catalogGui = loader.loadModel('phase_5.5/models/gui/catalog_gui')
        self.beanBank = DirectLabel(parent=page, relief=None, text=str(self.totalMoney), text_align=TextNode.ARight, text_scale=0.075, text_fg=(0.95, 0.95, 0, 1), text_shadow=(0, 0, 0, 1), text_pos=(0.495, -0.53), text_font=ToontownGlobals.getSignFont(), textMayChange=True, image=catalogGui.find('**/bean_bank'), image_scale=(0.65, 0.65, 0.65), scale=0.9, pos=(-0.75, 0.0, 0.6))
        catalogGui.removeNode()
        del catalogGui
        self.accept(localAvatar.uniqueName('moneyChange'), self.__moneyChange)
        self.accept(localAvatar.uniqueName('bankMoneyChange'), self.__moneyChange)
        self.partyEditor = PartyEditor(self, page)
        self.partyEditor.request('Hidden')
        pos = self.gui.find('**/step_05_add_text_locator').getPos()
        self.elementBuyButton = DirectButton(parent=page, relief=None, text=TTLocalizer.PartyPlannerBuy, text_pos=(pos[0], pos[2]), text_scale=TTLocalizer.PPelementBuyButton, geom=(self.gui.find('**/add_up'), self.gui.find('**/add_down'), self.gui.find('**/add_rollover')), geom3_color=VBase4(0.5, 0.5, 0.5, 1.0), textMayChange=True, pos=(0.0, 0.0, 0.04), command=self.partyEditor.buyCurrentElement)
        self.okWithPartyGroundsLayoutEvent = 'okWithPartyGroundsLayoutEvent'
        self.accept(self.okWithPartyGroundsLayoutEvent, self.okWithPartyGroundsLayout)
        self.okWithGroundsGui = TTDialog.TTGlobalDialog(dialogName=self.uniqueName('PartyEditorOkGui'), doneEvent=self.okWithPartyGroundsLayoutEvent, message=TTLocalizer.PartyPlannerOkWithGroundsLayout, style=TTDialog.YesNo, okButtonText=OTPLocalizer.DialogYes, cancelButtonText=OTPLocalizer.DialogNo)
        self.okWithGroundsGui.doneStatus = ''
        self.okWithGroundsGui.hide()
        return page

    def okWithPartyGroundsLayout(self):
        self.okWithGroundsGui.hide()
        if self.okWithGroundsGui.doneStatus == 'ok':
            self.__nextItem()

    def setNextButtonState(self, enabled):
        if enabled:
            self.nextButton['state'] = DirectGuiGlobals.NORMAL
            self.nextButton.show()
        else:
            self.nextButton['state'] = DirectGuiGlobals.DISABLED
            self.nextButton.hide()

    def _createInvitationPage(self):
        self.__handleHolidays()
        page = DirectFrame(self.frame)
        page.setName('PartyPlannerInvitationPage')
        self.invitationTitleLabel = DirectLabel(parent=page, relief=None, text=TTLocalizer.PartyPlannerConfirmTitle, textMayChange=True, pos=self.gui.find('**/title_locator').getPos(), scale=self.titleScale)
        self.invitationBackground = DirectFrame(parent=page, relief=None, geom=self.gui.find('**/invitationBackground'))
        self.inviteVisual = InviteVisual(page)
        self.selectedInviteThemeLabel = DirectLabel(parent=page, relief=None, pos=self.gui.find('**/step_06_theme_locator').getPos(), text='', text_scale=0.06, textMayChange=True)
        self.nextThemeButton = DirectButton(parent=page, relief=None, geom=(self.gui.find('**/topNext_button/nextButton_up'), self.gui.find('**/topNext_button/nextButton_down'), self.gui.find('**/topNext_button/nextButton_rollover')), command=self.__nextTheme)
        self.prevThemeButton = DirectButton(parent=page, relief=None, geom=(self.gui.find('**/topPrevious_button/previousButton_up'), self.gui.find('**/topPrevious_button/previousButton_down'), self.gui.find('**/topPrevious_button/previousButton_rollover')), command=self.__prevTheme)
        pos = self.gui.find('**/step_06_sendInvitation_locator').getPos()
        self.inviteButton = DirectButton(parent=page, relief=None, geom=(self.gui.find('**/send_up'), self.gui.find('**/send_down'), self.gui.find('**/send_rollover')), text=TTLocalizer.PartyPlannerInviteButton, textMayChange=True, text_scale=0.05, text_pos=(pos[0], pos[2]), command=self.__handleComplete)
        return page

    def __handleHolidays(self):
        self.inviteThemes = list(range(len(PartyGlobals.InviteTheme)))
        if hasattr(base.cr, 'newsManager') and base.cr.newsManager:
            holidayIds = base.cr.newsManager.getHolidayIdList()
            if ToontownGlobals.VALENTINES_DAY not in holidayIds:
                self.inviteThemes.remove(PartyGlobals.InviteTheme.Valentoons)
            if ToontownGlobals.VICTORY_PARTY_HOLIDAY not in holidayIds:
                self.inviteThemes.remove(PartyGlobals.InviteTheme.VictoryParty)
            if ToontownGlobals.WINTER_DECORATIONS not in holidayIds and ToontownGlobals.WACKY_WINTER_DECORATIONS not in holidayIds:
                self.inviteThemes.remove(PartyGlobals.InviteTheme.Winter)

    def _createFarewellPage(self):
        page = DirectFrame(self.frame)
        page.setName('PartyPlannerFarewellPage')
        self.confirmTitleLabel = DirectLabel(parent=page, relief=None, text=TTLocalizer.PartyPlannerConfirmationAllOkTitle, textMayChange=True, pos=self.gui.find('**/title_locator').getPos(), scale=self.titleScale)
        pos = self.gui.find('**/step_07_close_text_locator').getPos()
        self.closePlannerButton = DirectButton(parent=page, relief=None, geom=(self.gui.find('**/close_up'), self.gui.find('**/close_down'), self.gui.find('**/close_rollover')), text=TTLocalizer.PartyPlannerClosePlanner, text_scale=0.055, text_pos=(pos[0], pos[2]), command=self.__acceptExit)
        return page

    def close(self):
        self.ignore('addPartyResponseReceived')
        self.ignore(localAvatar.uniqueName('moneyChange'))
        self.ignore(localAvatar.uniqueName('bankMoneyChange'))
        self.timeInputHourUpButton.destroy()
        self.timeInputHourDownButton.destroy()
        self.timeInputMinuteUpButton.destroy()
        self.timeInputMinuteDownButton.destroy()
        self.timeInputAmPmUpButton.destroy()
        self.timeInputAmPmDownButton.destroy()
        self.privateButton.destroy()
        self.publicButton.destroy()
        self.makePartyNowButton.destroy()
        self.checkAllButton.destroy()
        self.uncheckAllButton.destroy()
        self.elementBuyButton.destroy()
        self.nextThemeButton.destroy()
        self.prevThemeButton.destroy()
        self.inviteButton.destroy()
        self.closePlannerButton.destroy()
        self.ignore(self.okWithPartyGroundsLayoutEvent)
        if hasattr(self, 'okWithGroundsGui'):
            self.okWithGroundsGui.cleanup()
            del self.okWithGroundsGui
        if hasattr(self, 'frame') and not self.frame.isEmpty():
            messenger.send(self.doneEvent)
            self.hide()
            self.cleanup()
            self.friendList.removeAndDestroyAllItems()
            self.friendList.destroy()
            self.calendarGuiMonth.destroy()
            self.frame.destroy()
        self.partyPlannerHead.delete()
        self.partyPlannerHead.removeNode()
        self.clearNametag()
        self.partyEditor.request('Cleanup')
        self.partyEditor = None
        self.destroy()
        del self
        return

    def __handleComplete(self):
        self.inviteButton['state'] = DirectGuiGlobals.DISABLED
        self.prevButton['state'] = DirectGuiGlobals.DISABLED
        endTime = self.partyTime + self.partyDuration
        hostId = base.localAvatar.doId
        self.partyActivities = self.partyEditor.partyEditorGrid.getActivitiesOnGrid()
        decorations = self.partyEditor.partyEditorGrid.getDecorationsOnGrid()
        invitees = self.getInvitees()
        self.accept('addPartyResponseReceived', self.processAddPartyResponse)
        base.cr.partyManager.sendAddParty(hostId, self.partyTime.strftime('%Y-%m-%d %H:%M:%S'), endTime.strftime('%Y-%m-%d %H:%M:%S'), self.isPrivate, self.currentInvitationTheme, self.partyActivities, decorations, invitees)

    def getInvitees(self):
        invitees = []
        for friendBox in self.friendList['items']:
            if friendBox['indicatorValue']:
                invitees.append(friendBox.getPythonTag('id'))

        return invitees

    def processAddPartyResponse(self, hostId, errorCode):
        PartyPlanner.notify.debug('processAddPartyResponse : hostId=%d errorCode=%s' % (hostId, PartyGlobals.AddPartyErrorCode.getString(errorCode)))
        goingBackAllowed = False
        if errorCode == PartyGlobals.AddPartyErrorCode.AllOk:
            goingBackAllowed = False
            self.confirmTitleLabel['text'] = TTLocalizer.PartyPlannerConfirmationAllOkTitle
            if self.noFriends or len(self.getInvitees()) == 0:
                confirmRecapText = TTLocalizer.PartyPlannerConfirmationAllOkTextNoFriends
            else:
                confirmRecapText = TTLocalizer.PartyPlannerConfirmationAllOkText
        elif errorCode == PartyGlobals.AddPartyErrorCode.ValidationError:
            self.confirmTitleLabel['text'] = TTLocalizer.PartyPlannerConfirmationErrorTitle
            confirmRecapText = TTLocalizer.PartyPlannerConfirmationValidationErrorText
        elif errorCode == PartyGlobals.AddPartyErrorCode.DatabaseError:
            self.confirmTitleLabel['text'] = TTLocalizer.PartyPlannerConfirmationErrorTitle
            confirmRecapText = TTLocalizer.PartyPlannerConfirmationDatabaseErrorText
        elif errorCode == PartyGlobals.AddPartyErrorCode.TooManyHostedParties:
            goingBackAllowed = False
            self.confirmTitleLabel['text'] = TTLocalizer.PartyPlannerConfirmationErrorTitle
            confirmRecapText = TTLocalizer.PartyPlannerConfirmationTooManyText
        self.nametagGroup.setChat(confirmRecapText, CFSpeech)
        self.request('Farewell', goingBackAllowed)

    def __acceptExit(self):
        PartyPlanner.notify.debug('__acceptExit')
        if hasattr(self, 'frame'):
            self.hide()
            messenger.send(self.doneEvent)

    def __nextItem(self):
        messenger.send('wakeup')
        if self.state == 'PartyEditor' and self.okWithGroundsGui.doneStatus != 'ok':
            self.okWithGroundsGui.show()
            return
        if self.state == 'PartyEditor' and self.noFriends:
            self.request('Date')
            self.selectedCalendarGuiDay = None
            self.calendarGuiMonth.clearSelectedDay()
            return
        if self.state == 'Guests':
            self.selectedCalendarGuiDay = None
            self.calendarGuiMonth.clearSelectedDay()
        if self.state == 'Time':
            if self.partyTime < base.cr.toontownTimeManager.getCurServerDateTime():
                self.okChooseFutureTimeEvent = 'okChooseFutureTimeEvent'
                self.acceptOnce(self.okChooseFutureTimeEvent, self.okChooseFutureTime)
                self.chooseFutureTimeDialog = TTDialog.TTGlobalDialog(dialogName=self.uniqueName('chooseFutureTimeDialog'), doneEvent=self.okChooseFutureTimeEvent, message=TTLocalizer.PartyPlannerChooseFutureTime, style=TTDialog.Acknowledge)
                self.chooseFutureTimeDialog.show()
                return
        self.requestNext()
        return

    def okChooseFutureTime(self):
        if hasattr(self, 'chooseFutureTimeDialog'):
            self.chooseFutureTimeDialog.cleanup()
            del self.chooseFutureTimeDialog
        if hasattr(self, 'okChooseFutureTimeEvent'):
            self.ignore(self.okChooseFutureTimeEvent)

    def __prevItem(self):
        messenger.send('wakeup')
        if self.state == 'Date' and self.noFriends:
            self.request('PartyEditor')
            return
        if self.state == 'Invitation' and self.selectedCalendarGuiDay is None:
            self.request('Guests')
            return
        self.requestPrev()
        return

    def __moneyChange(self, newMoney):
        if hasattr(self, 'totalMoney'):
            self.totalMoney = base.localAvatar.getTotalMoney()
        if hasattr(self, 'beanBank'):
            self.beanBank['text'] = str(int(self.totalMoney))
Exemple #58
0
class DistributedCogThiefGame(DistributedMinigame):
    notify = directNotify.newCategory('DistributedCogThiefGame')
    ToonSpeed = CTGG.ToonSpeed
    StageHalfWidth = 200.0
    StageHalfHeight = 100.0
    BarrelScale = 0.25
    TOON_Z = 0
    UPDATE_SUITS_TASK = 'CogThiefGameUpdateSuitsTask'
    REWARD_COUNTDOWN_TASK = 'cogThiefGameRewardCountdown'
    ControlKeyLimitTime = 1.0

    def __init__(self, cr):
        DistributedMinigame.__init__(self, cr)
        self.gameFSM = ClassicFSM.ClassicFSM('DistributedCogThiefGame', [
            State.State('off', self.enterOff, self.exitOff, ['play']),
            State.State('play', self.enterPlay, self.exitPlay, ['cleanup']),
            State.State('cleanup', self.enterCleanup, self.exitCleanup, [])
        ], 'off', 'cleanup')
        self.addChildGameFSM(self.gameFSM)
        self.cameraTopView = (0, 0, 55, 0, -90.0, 0)
        self.barrels = []
        self.cogInfo = {}
        self.lastTimeControlPressed = 0
        self.stolenBarrels = []
        self.useOrthoWalk = base.config.GetBool('cog-thief-ortho', 1)
        self.resultIval = None
        self.gameIsEnding = False
        self.__textGen = TextNode('cogThiefGame')
        self.__textGen.setFont(ToontownGlobals.getSignFont())
        self.__textGen.setAlign(TextNode.ACenter)
        return

    def getTitle(self):
        return TTLocalizer.CogThiefGameTitle

    def getInstructions(self):
        return TTLocalizer.CogThiefGameInstructions

    def getMaxDuration(self):
        return 0

    def load(self):
        self.notify.debug('load')
        DistributedMinigame.load(self)
        self.music = base.loadMusic('phase_4/audio/bgm/MG_CogThief.ogg')
        self.initCogInfo()
        for barrelIndex in xrange(CTGG.NumBarrels):
            barrel = loader.loadModel(
                'phase_4/models/minigames/cogthief_game_gagTank')
            barrel.setPos(CTGG.BarrelStartingPositions[barrelIndex])
            barrel.setScale(self.BarrelScale)
            barrel.reparentTo(render)
            barrel.setTag('barrelIndex', str(barrelIndex))
            collSphere = CollisionSphere(0, 0, 0, 4)
            collSphere.setTangible(0)
            name = 'BarrelSphere-%d' % barrelIndex
            collSphereName = self.uniqueName(name)
            collNode = CollisionNode(collSphereName)
            collNode.setFromCollideMask(CTGG.BarrelBitmask)
            collNode.addSolid(collSphere)
            colNp = barrel.attachNewNode(collNode)
            handler = CollisionHandlerEvent()
            handler.setInPattern('barrelHit-%fn')
            base.cTrav.addCollider(colNp, handler)
            self.accept('barrelHit-' + collSphereName, self.handleEnterBarrel)
            nodeToHide = '**/gagMoneyTen'
            if barrelIndex % 2:
                nodeToHide = '**/gagMoneyFive'
            iconToHide = barrel.find(nodeToHide)
            if not iconToHide.isEmpty():
                iconToHide.hide()
            self.barrels.append(barrel)

        self.gameBoard = loader.loadModel(
            'phase_4/models/minigames/cogthief_game')
        self.gameBoard.find('**/floor_TT').hide()
        self.gameBoard.find('**/floor_DD').hide()
        self.gameBoard.find('**/floor_DG').hide()
        self.gameBoard.find('**/floor_MM').hide()
        self.gameBoard.find('**/floor_BR').hide()
        self.gameBoard.find('**/floor_DL').hide()
        zone = self.getSafezoneId()
        if zone == ToontownGlobals.ToontownCentral:
            self.gameBoard.find('**/floor_TT').show()
        elif zone == ToontownGlobals.DonaldsDock:
            self.gameBoard.find('**/floor_DD').show()
        elif zone == ToontownGlobals.DaisyGardens:
            self.gameBoard.find('**/floor_DG').show()
        elif zone == ToontownGlobals.MinniesMelodyland:
            self.gameBoard.find('**/floor_MM').show()
        elif zone == ToontownGlobals.TheBrrrgh:
            self.gameBoard.find('**/floor_BR').show()
        elif zone == ToontownGlobals.DonaldsDreamland:
            self.gameBoard.find('**/floor_DL').show()
        else:
            self.gameBoard.find('**/floor_TT').show()
        self.gameBoard.setPosHpr(0, 0, 0, 0, 0, 0)
        self.gameBoard.setScale(1.0)
        self.toonSDs = {}
        avId = self.localAvId
        toonSD = CogThiefGameToonSD.CogThiefGameToonSD(avId, self)
        self.toonSDs[avId] = toonSD
        toonSD.load()
        self.loadCogs()
        self.toonHitTracks = {}
        self.toonPieTracks = {}
        self.sndOof = base.loadSfx('phase_4/audio/sfx/MG_cannon_hit_dirt.ogg')
        self.sndRewardTick = base.loadSfx(
            'phase_3.5/audio/sfx/tick_counter.ogg')
        self.sndPerfect = base.loadSfx('phase_4/audio/sfx/ring_perfect.ogg')
        self.timer = ToontownTimer.ToontownTimer()
        self.timer.posInTopRightCorner()
        self.timer.hide()
        purchaseModels = loader.loadModel('phase_4/models/gui/purchase_gui')
        self.jarImage = purchaseModels.find('**/Jar')
        self.jarImage.reparentTo(hidden)
        self.rewardPanel = DirectLabel(parent=hidden,
                                       relief=None,
                                       pos=(-0.173, 0.0, -0.55),
                                       scale=0.65,
                                       text='',
                                       text_scale=0.2,
                                       text_fg=(0.95, 0.95, 0, 1),
                                       text_pos=(0, -.13),
                                       text_font=ToontownGlobals.getSignFont(),
                                       image=self.jarImage)
        self.rewardPanelTitle = DirectLabel(parent=self.rewardPanel,
                                            relief=None,
                                            pos=(0, 0, 0.06),
                                            scale=0.08,
                                            text=TTLocalizer.CannonGameReward,
                                            text_fg=(0.95, 0.95, 0, 1),
                                            text_shadow=(0, 0, 0, 1))
        return

    def unload(self):
        self.notify.debug('unload')
        DistributedMinigame.unload(self)
        del self.music
        self.removeChildGameFSM(self.gameFSM)
        del self.gameFSM
        self.gameBoard.removeNode()
        del self.gameBoard
        for barrel in self.barrels:
            barrel.removeNode()

        del self.barrels
        for avId in self.toonSDs.keys():
            toonSD = self.toonSDs[avId]
            toonSD.unload()

        del self.toonSDs
        self.timer.destroy()
        del self.timer
        self.rewardPanel.destroy()
        del self.rewardPanel
        self.jarImage.removeNode()
        del self.jarImage
        del self.sndRewardTick

    def onstage(self):
        self.notify.debug('onstage')
        DistributedMinigame.onstage(self)
        self.gameBoard.reparentTo(render)
        lt = base.localAvatar
        lt.reparentTo(render)
        self.__placeToon(self.localAvId)
        lt.setSpeed(0, 0)
        self.moveCameraToTop()
        toonSD = self.toonSDs[self.localAvId]
        toonSD.enter()
        toonSD.fsm.request('normal')
        self.stopGameWalk()
        for cogIndex in xrange(self.getNumCogs()):
            suit = self.cogInfo[cogIndex]['suit'].suit
            pos = self.cogInfo[cogIndex]['pos']
            suit.reparentTo(self.gameBoard)
            suit.setPos(pos)
            suit.nametag3d.stash()
            suit.nametag.destroy()

        for avId in self.avIdList:
            self.toonHitTracks[avId] = Wait(0.1)

        self.toonRNGs = []
        for i in xrange(self.numPlayers):
            self.toonRNGs.append(RandomNumGen.RandomNumGen(self.randomNumGen))

        self.sndTable = {
            'hitBySuit': [None] * self.numPlayers,
            'falling': [None] * self.numPlayers
        }
        for i in xrange(self.numPlayers):
            self.sndTable['hitBySuit'][i] = base.loadSfx(
                'phase_4/audio/sfx/MG_Tag_C.ogg')
            self.sndTable['falling'][i] = base.loadSfx(
                'phase_4/audio/sfx/MG_cannon_whizz.ogg')

        base.playMusic(self.music, looping=1, volume=0.8)
        self.introTrack = self.getIntroTrack()
        self.introTrack.start()
        return

    def offstage(self):
        self.notify.debug('offstage')
        self.gameBoard.hide()
        self.music.stop()
        for barrel in self.barrels:
            barrel.hide()

        for avId in self.toonSDs.keys():
            self.toonSDs[avId].exit()

        for avId in self.avIdList:
            av = self.getAvatar(avId)
            if av:
                av.resetLOD()

        self.timer.reparentTo(hidden)
        self.rewardPanel.reparentTo(hidden)
        if self.introTrack.isPlaying():
            self.introTrack.finish()
        del self.introTrack
        DistributedMinigame.offstage(self)

    def handleDisabledAvatar(self, avId):
        self.notify.debug('handleDisabledAvatar')
        self.notify.debug('avatar ' + str(avId) + ' disabled')
        self.toonSDs[avId].exit(unexpectedExit=True)
        del self.toonSDs[avId]
        DistributedMinigame.handleDisabledAvatar(self, avId)

    def setGameReady(self):
        if not self.hasLocalToon:
            return
        self.notify.debug('setGameReady')
        if DistributedMinigame.setGameReady(self):
            return
        for avId in self.remoteAvIdList:
            toon = self.getAvatar(avId)
            if toon:
                toon.reparentTo(render)
                self.__placeToon(avId)
                toon.useLOD(1000)
                toonSD = CogThiefGameToonSD.CogThiefGameToonSD(avId, self)
                self.toonSDs[avId] = toonSD
                toonSD.load()
                toonSD.enter()
                toonSD.fsm.request('normal')
                toon.startSmooth()

    def setGameStart(self, timestamp):
        if not self.hasLocalToon:
            return
        self.notify.debug('setGameStart')
        DistributedMinigame.setGameStart(self, timestamp)
        if not base.config.GetBool('cog-thief-endless', 0):
            self.timer.show()
            self.timer.countdown(CTGG.GameTime, self.__gameTimerExpired)
        self.clockStopTime = None
        self.rewardPanel.reparentTo(base.a2dTopRight)
        self.scoreMult = MinigameGlobals.getScoreMult(self.cr.playGame.hood.id)
        self.__startRewardCountdown()
        if self.introTrack.isPlaying():
            self.introTrack.finish()
        self.gameFSM.request('play')
        return

    def enterOff(self):
        self.notify.debug('enterOff')

    def exitOff(self):
        pass

    def enterPlay(self):
        self.notify.debug('enterPlay')
        self.startGameWalk()
        self.spawnUpdateSuitsTask()
        self.accept('control', self.controlKeyPressed)
        self.pieHandler = CollisionHandlerEvent()
        self.pieHandler.setInPattern('pieHit-%fn')

    def exitPlay(self):
        self.ignore('control')
        if self.resultIval and self.resultIval.isPlaying():
            self.resultIval.finish()
            self.resultIval = None
        return

    def enterCleanup(self):
        self.__killRewardCountdown()
        if hasattr(self, 'jarIval'):
            self.jarIval.finish()
            del self.jarIval
        for key in self.toonHitTracks:
            ival = self.toonHitTracks[key]
            if ival.isPlaying():
                ival.finish()

        self.toonHitTracks = {}
        for key in self.toonPieTracks:
            ival = self.toonPieTracks[key]
            if ival.isPlaying():
                ival.finish()

        self.toonPieTracks = {}
        for key in self.cogInfo:
            cogThief = self.cogInfo[key]['suit']
            cogThief.cleanup()

        self.removeUpdateSuitsTask()
        self.notify.debug('enterCleanup')

    def exitCleanup(self):
        pass

    def __placeToon(self, avId):
        toon = self.getAvatar(avId)
        if toon:
            index = self.avIdList.index(avId)
            toon.setPos(CTGG.ToonStartingPositions[index])
            toon.setHpr(0, 0, 0)

    def moveCameraToTop(self):
        camera.reparentTo(render)
        p = self.cameraTopView
        camera.setPosHpr(p[0], p[1], p[2], p[3], p[4], p[5])
        base.camLens.setMinFov(46 / (4. / 3.))
        camera.setZ(camera.getZ() +
                    base.config.GetFloat('cog-thief-z-camera-adjust', 0.0))

    def destroyGameWalk(self):
        self.notify.debug('destroyOrthoWalk')
        if self.useOrthoWalk:
            self.gameWalk.destroy()
            del self.gameWalk
        else:
            self.notify.debug('TODO destroyGameWalk')

    def initGameWalk(self):
        self.notify.debug('startOrthoWalk')
        if self.useOrthoWalk:

            def doCollisions(oldPos, newPos, self=self):
                x = bound(newPos[0], CTGG.StageHalfWidth, -CTGG.StageHalfWidth)
                y = bound(newPos[1], CTGG.StageHalfHeight,
                          -CTGG.StageHalfHeight)
                newPos.setX(x)
                newPos.setY(y)
                return newPos

            orthoDrive = OrthoDrive(self.ToonSpeed,
                                    customCollisionCallback=doCollisions,
                                    instantTurn=True)
            self.gameWalk = OrthoWalk(orthoDrive,
                                      broadcast=not self.isSinglePlayer())
        else:
            self.gameWalk = CogThiefWalk.CogThiefWalk('walkDone')
            forwardSpeed = self.ToonSpeed / 2.0
            base.mouseInterfaceNode.setForwardSpeed(forwardSpeed)
            multiplier = forwardSpeed / ToontownGlobals.ToonForwardSpeed
            base.mouseInterfaceNode.setRotateSpeed(
                ToontownGlobals.ToonRotateSpeed * 4)

    def initCogInfo(self):
        for cogIndex in xrange(self.getNumCogs()):
            self.cogInfo[cogIndex] = {
                'pos': Point3(CTGG.CogStartingPositions[cogIndex]),
                'goal': CTGG.NoGoal,
                'goalId': CTGG.InvalidGoalId,
                'suit': None
            }

        return

    def loadCogs(self):
        suitTypes = ['ds', 'ac', 'bc', 'ms']
        for suitIndex in xrange(self.getNumCogs()):
            st = self.randomNumGen.choice(suitTypes)
            suit = CogThief.CogThief(suitIndex, st, self, self.getCogSpeed())
            self.cogInfo[suitIndex]['suit'] = suit

    def handleEnterSphere(self, colEntry):
        if self.gameIsEnding:
            return
        intoName = colEntry.getIntoNodePath().getName()
        fromName = colEntry.getFromNodePath().getName()
        debugInto = intoName.split('/')
        debugFrom = fromName.split('/')
        self.notify.debug(
            'handleEnterSphere gametime=%s %s into %s' %
            (self.getCurrentGameTime(), debugFrom[-1], debugInto[-1]))
        intoName = colEntry.getIntoNodePath().getName()
        if 'CogThiefSphere' in intoName:
            parts = intoName.split('-')
            suitNum = int(parts[1])
            self.localToonHitBySuit(suitNum)

    def localToonHitBySuit(self, suitNum):
        self.notify.debug('localToonHitBySuit %d' % suitNum)
        timestamp = globalClockDelta.localToNetworkTime(
            globalClock.getFrameTime(), bits=32)
        pos = self.cogInfo[suitNum]['suit'].suit.getPos()
        self.sendUpdate(
            'hitBySuit',
            [self.localAvId, timestamp, suitNum, pos[0], pos[1], pos[2]])
        self.showToonHitBySuit(self.localAvId, timestamp)
        self.makeSuitRespondToToonHit(timestamp, suitNum)

    def hitBySuit(self, avId, timestamp, suitNum, x, y, z):
        if not self.hasLocalToon:
            return
        if self.gameFSM.getCurrentState().getName() not in ['play']:
            self.notify.warning('ignoring msg: av %s hit by suit' % avId)
            return
        if self.gameIsEnding:
            return
        self.notify.debug('avatar ' + ` avId ` + ' hit by a suit')
        if avId != self.localAvId:
            self.showToonHitBySuit(avId, timestamp)
            self.makeSuitRespondToToonHit(timestamp, suitNum)

    def showToonHitBySuit(self, avId, timestamp):
        toon = self.getAvatar(avId)
        if toon == None:
            return
        rng = self.toonRNGs[self.avIdList.index(avId)]
        curPos = toon.getPos(render)
        oldTrack = self.toonHitTracks[avId]
        if oldTrack.isPlaying():
            oldTrack.finish()
        toon.setPos(curPos)
        toon.setZ(self.TOON_Z)
        parentNode = render.attachNewNode('mazeFlyToonParent-' + ` avId `)
        parentNode.setPos(toon.getPos())
        toon.reparentTo(parentNode)
        toon.setPos(0, 0, 0)
        startPos = parentNode.getPos()
        dropShadow = toon.dropShadow.copyTo(parentNode)
        dropShadow.setScale(toon.dropShadow.getScale(render))
        trajectory = Trajectory.Trajectory(0,
                                           Point3(0, 0, 0),
                                           Point3(0, 0, 50),
                                           gravMult=1.0)
        oldFlyDur = trajectory.calcTimeOfImpactOnPlane(0.0)
        trajectory = Trajectory.Trajectory(0,
                                           Point3(0, 0, 0),
                                           Point3(0, 0, 50),
                                           gravMult=0.55)
        flyDur = trajectory.calcTimeOfImpactOnPlane(0.0)
        avIndex = self.avIdList.index(avId)
        endPos = CTGG.ToonStartingPositions[avIndex]

        def flyFunc(t,
                    trajectory,
                    startPos=startPos,
                    endPos=endPos,
                    dur=flyDur,
                    moveNode=parentNode,
                    flyNode=toon):
            u = t / dur
            moveNode.setX(startPos[0] + u * (endPos[0] - startPos[0]))
            moveNode.setY(startPos[1] + u * (endPos[1] - startPos[1]))
            flyNode.setPos(trajectory.getPos(t))

        flyTrack = Sequence(LerpFunctionInterval(flyFunc,
                                                 fromData=0.0,
                                                 toData=flyDur,
                                                 duration=flyDur,
                                                 extraArgs=[trajectory]),
                            name=toon.uniqueName('hitBySuit-fly'))
        geomNode = toon.getGeomNode()
        startHpr = geomNode.getHpr()
        destHpr = Point3(startHpr)
        hRot = rng.randrange(1, 8)
        if rng.choice([0, 1]):
            hRot = -hRot
        destHpr.setX(destHpr[0] + hRot * 360)
        spinHTrack = Sequence(LerpHprInterval(geomNode,
                                              flyDur,
                                              destHpr,
                                              startHpr=startHpr),
                              Func(geomNode.setHpr, startHpr),
                              name=toon.uniqueName('hitBySuit-spinH'))
        parent = geomNode.getParent()
        rotNode = parent.attachNewNode('rotNode')
        geomNode.reparentTo(rotNode)
        rotNode.setZ(toon.getHeight() / 2.0)
        oldGeomNodeZ = geomNode.getZ()
        geomNode.setZ(-toon.getHeight() / 2.0)
        startHpr = rotNode.getHpr()
        destHpr = Point3(startHpr)
        pRot = rng.randrange(1, 3)
        if rng.choice([0, 1]):
            pRot = -pRot
        destHpr.setY(destHpr[1] + pRot * 360)
        spinPTrack = Sequence(LerpHprInterval(rotNode,
                                              flyDur,
                                              destHpr,
                                              startHpr=startHpr),
                              Func(rotNode.setHpr, startHpr),
                              name=toon.uniqueName('hitBySuit-spinP'))
        i = self.avIdList.index(avId)
        soundTrack = Sequence(Func(base.playSfx,
                                   self.sndTable['hitBySuit'][i]),
                              Wait(flyDur * (2.0 / 3.0)),
                              SoundInterval(self.sndTable['falling'][i],
                                            duration=flyDur * (1.0 / 3.0)),
                              name=toon.uniqueName('hitBySuit-soundTrack'))

        def preFunc(self=self, avId=avId, toon=toon, dropShadow=dropShadow):
            forwardSpeed = toon.forwardSpeed
            rotateSpeed = toon.rotateSpeed
            if avId == self.localAvId:
                self.stopGameWalk()
            else:
                toon.stopSmooth()
            if forwardSpeed or rotateSpeed:
                toon.setSpeed(forwardSpeed, rotateSpeed)
            toon.dropShadow.hide()

        def postFunc(self=self,
                     avId=avId,
                     oldGeomNodeZ=oldGeomNodeZ,
                     dropShadow=dropShadow,
                     parentNode=parentNode):
            if avId == self.localAvId:
                base.localAvatar.setPos(endPos)
                if hasattr(self, 'gameWalk'):
                    toon = base.localAvatar
                    toon.setSpeed(0, 0)
                    self.startGameWalk()
            dropShadow.removeNode()
            del dropShadow
            toon = self.getAvatar(avId)
            if toon:
                toon.dropShadow.show()
                geomNode = toon.getGeomNode()
                rotNode = geomNode.getParent()
                baseNode = rotNode.getParent()
                geomNode.reparentTo(baseNode)
                rotNode.removeNode()
                del rotNode
                geomNode.setZ(oldGeomNodeZ)
            if toon:
                toon.reparentTo(render)
                toon.setPos(endPos)
            parentNode.removeNode()
            del parentNode
            if avId != self.localAvId:
                if toon:
                    toon.startSmooth()

        preFunc()
        slipBack = Parallel(
            Sequence(ActorInterval(toon, 'slip-backward', endFrame=24),
                     Wait(CTGG.LyingDownDuration - (flyDur - oldFlyDur)),
                     ActorInterval(toon, 'slip-backward', startFrame=24)))
        if toon.doId == self.localAvId:
            slipBack.append(SoundInterval(self.sndOof))
        hitTrack = Sequence(Parallel(flyTrack, spinHTrack, spinPTrack,
                                     soundTrack),
                            slipBack,
                            Func(postFunc),
                            name=toon.uniqueName('hitBySuit'))
        self.notify.debug('hitTrack duration = %s' % hitTrack.getDuration())
        self.toonHitTracks[avId] = hitTrack
        hitTrack.start(globalClockDelta.localElapsedTime(timestamp))
        return

    def updateSuitGoal(self, timestamp, inResponseToClientStamp, suitNum,
                       goalType, goalId, x, y, z):
        if not self.hasLocalToon:
            return
        self.notify.debug(
            'updateSuitGoal gameTime=%s timeStamp=%s cog=%s goal=%s goalId=%s (%.1f, %.1f,%.1f)'
            % (self.getCurrentGameTime(), timestamp, suitNum,
               CTGG.GoalStr[goalType], goalId, x, y, z))
        cog = self.cogInfo[suitNum]
        cog['goal'] = goalType
        cog['goalId'] = goalId
        newPos = Point3(x, y, z)
        cog['pos'] = newPos
        suit = cog['suit']
        suit.updateGoal(timestamp, inResponseToClientStamp, goalType, goalId,
                        newPos)

    def spawnUpdateSuitsTask(self):
        self.notify.debug('spawnUpdateSuitsTask')
        for cogIndex in self.cogInfo:
            suit = self.cogInfo[cogIndex]['suit']
            suit.gameStart(self.gameStartTime)

        taskMgr.remove(self.UPDATE_SUITS_TASK)
        taskMgr.add(self.updateSuitsTask, self.UPDATE_SUITS_TASK)

    def removeUpdateSuitsTask(self):
        taskMgr.remove(self.UPDATE_SUITS_TASK)

    def updateSuitsTask(self, task):
        if self.gameIsEnding:
            return task.done
        for cogIndex in self.cogInfo:
            suit = self.cogInfo[cogIndex]['suit']
            suit.think()

        return task.cont

    def makeSuitRespondToToonHit(self, timestamp, suitNum):
        cog = self.cogInfo[suitNum]['suit']
        cog.respondToToonHit(timestamp)

    def handleEnterBarrel(self, colEntry):
        if self.gameIsEnding:
            return
        intoName = colEntry.getIntoNodePath().getName()
        fromName = colEntry.getFromNodePath().getName()
        debugInto = intoName.split('/')
        debugFrom = fromName.split('/')
        self.notify.debug(
            'handleEnterBarrel gameTime=%s %s into %s' %
            (self.getCurrentGameTime(), debugFrom[-1], debugInto[-1]))
        if 'CogThiefSphere' in intoName:
            parts = intoName.split('-')
            cogIndex = int(parts[1])
            barrelName = colEntry.getFromNodePath().getName()
            barrelParts = barrelName.split('-')
            barrelIndex = int(barrelParts[1])
            cog = self.cogInfo[cogIndex]['suit']
            if cog.barrel == CTGG.NoBarrelCarried and barrelIndex not in self.stolenBarrels:
                timestamp = globalClockDelta.localToNetworkTime(
                    globalClock.getFrameTime(), bits=32)
                if cog.suit:
                    cogPos = cog.suit.getPos()
                    collisionPos = colEntry.getContactPos(render)
                    self.sendUpdate('cogHitBarrel', [
                        timestamp, cogIndex, barrelIndex, cogPos[0], cogPos[1],
                        cogPos[2]
                    ])

    def makeCogCarryBarrel(self, timestamp, inResponseToClientStamp, cogIndex,
                           barrelIndex, x, y, z):
        if not self.hasLocalToon:
            return
        if self.gameIsEnding:
            return
        self.notify.debug(
            'makeCogCarryBarrel gameTime=%s timeStamp=%s cog=%s barrel=%s (%.1f, %.1f,%.1f)'
            % (self.getCurrentGameTime(), timestamp, cogIndex, barrelIndex, x,
               y, z))
        barrel = self.barrels[barrelIndex]
        self.notify.debug('barrelPos= %s' % barrel.getPos())
        cog = self.cogInfo[cogIndex]['suit']
        cogPos = Point3(x, y, z)
        cog.makeCogCarryBarrel(timestamp, inResponseToClientStamp, barrel,
                               barrelIndex, cogPos)

    def makeCogDropBarrel(self, timestamp, inResponseToClientStamp, cogIndex,
                          barrelIndex, x, y, z):
        if not self.hasLocalToon:
            return
        self.notify.debug(
            'makeCogDropBarrel gameTime=%s timeStamp=%s cog=%s barrel=%s (%.1f, %.1f,%.1f)'
            % (self.getCurrentGameTime(), timestamp, cogIndex, barrelIndex, x,
               y, z))
        barrel = self.barrels[barrelIndex]
        self.notify.debug('barrelPos= %s' % barrel.getPos())
        cog = self.cogInfo[cogIndex]['suit']
        cogPos = Point3(x, y, z)
        cog.makeCogDropBarrel(timestamp, inResponseToClientStamp, barrel,
                              barrelIndex, cogPos)

    def controlKeyPressed(self):
        if self.isToonPlayingHitTrack(self.localAvId):
            return
        if self.gameIsEnding:
            return
        if self.getCurrentGameTime(
        ) - self.lastTimeControlPressed > self.ControlKeyLimitTime:
            self.lastTimeControlPressed = self.getCurrentGameTime()
            self.notify.debug('controlKeyPressed')
            toonSD = self.toonSDs[self.localAvId]
            curState = toonSD.fsm.getCurrentState().getName()
            toon = self.getAvatar(self.localAvId)
            timestamp = globalClockDelta.localToNetworkTime(
                globalClock.getFrameTime(), bits=32)
            pos = toon.getPos()
            heading = toon.getH()
            self.sendUpdate(
                'throwingPie',
                [self.localAvId, timestamp, heading, pos[0], pos[1], pos[2]])
            self.showToonThrowingPie(self.localAvId, timestamp, heading, pos)

    def throwingPie(self, avId, timestamp, heading, x, y, z):
        if not self.hasLocalToon:
            return
        if self.gameFSM.getCurrentState().getName() not in ['play']:
            self.notify.warning('ignoring msg: av %s hit by suit' % avId)
            return
        self.notify.debug('avatar ' + ` avId ` + ' throwing pie')
        if avId != self.localAvId:
            pos = Point3(x, y, z)
            self.showToonThrowingPie(avId, timestamp, heading, pos)

    def showToonThrowingPie(self, avId, timestamp, heading, pos):
        toon = self.getAvatar(avId)
        if toon:
            tossTrack, pieTrack, flyPie = self.getTossPieInterval(
                toon, pos[0], pos[1], pos[2], heading, 0, 0, 0)

            def removePieFromTraverser(flyPie=flyPie):
                if base.cTrav:
                    if flyPie:
                        base.cTrav.removeCollider(flyPie)

            if avId == self.localAvId:
                flyPie.setTag('throwerId', str(avId))
                collSphere = CollisionSphere(0, 0, 0, 0.5)
                collSphere.setTangible(0)
                name = 'PieSphere-%d' % avId
                collSphereName = self.uniqueName(name)
                collNode = CollisionNode(collSphereName)
                collNode.setFromCollideMask(ToontownGlobals.PieBitmask)
                collNode.addSolid(collSphere)
                colNp = flyPie.attachNewNode(collNode)
                colNp.show()
                base.cTrav.addCollider(colNp, self.pieHandler)
                self.accept('pieHit-' + collSphereName, self.handlePieHitting)

            def matchRunningAnim(toon=toon):
                toon.playingAnim = None
                toon.setSpeed(toon.forwardSpeed, toon.rotateSpeed)
                return

            newTossTrack = Sequence(tossTrack, Func(matchRunningAnim))
            pieTrack = Parallel(newTossTrack, pieTrack)
            elapsedTime = globalClockDelta.localElapsedTime(timestamp)
            if elapsedTime < 16.0 / 24.0:
                elapsedTime = 16.0 / 24.0
            pieTrack.start(elapsedTime)
            self.toonPieTracks[avId] = pieTrack

    def getTossPieInterval(self,
                           toon,
                           x,
                           y,
                           z,
                           h,
                           p,
                           r,
                           power,
                           beginFlyIval=Sequence()):
        from toontown.toonbase import ToontownBattleGlobals
        from toontown.battle import BattleProps
        pie = toon.getPieModel()
        pie.setScale(0.9)
        flyPie = pie.copyTo(NodePath('a'))
        pieName = ToontownBattleGlobals.pieNames[toon.pieType]
        pieType = BattleProps.globalPropPool.getPropType(pieName)
        animPie = Sequence()
        if pieType == 'actor':
            animPie = ActorInterval(pie, pieName, startFrame=48)
        sound = loader.loadSfx('phase_3.5/audio/sfx/AA_pie_throw_only.ogg')
        t = power / 100.0
        dist = 100 - 70 * t
        time = 1 + 0.5 * t
        proj = ProjectileInterval(None,
                                  startPos=Point3(0, 0, 0),
                                  endPos=Point3(0, dist, 0),
                                  duration=time)
        relVel = proj.startVel

        def getVelocity(toon=toon, relVel=relVel):
            return render.getRelativeVector(toon, relVel) * 0.6

        toss = Track(
            (0,
             Sequence(
                 Func(toon.setPosHpr, x, y, z, h, p, r),
                 Func(pie.reparentTo, toon.rightHand),
                 Func(pie.setPosHpr, 0, 0, 0, 0, 0, 0),
                 Parallel(
                     ActorInterval(
                         toon, 'throw', startFrame=48, partName='torso'),
                     animPie), Func(toon.loop, 'neutral'))),
            (16.0 / 24.0, Func(pie.detachNode)))
        fly = Track(
            (14.0 / 24.0, SoundInterval(sound, node=toon)),
            (16.0 / 24.0,
             Sequence(
                 Func(flyPie.reparentTo, render),
                 Func(flyPie.setPosHpr, toon, 0.52, 0.97, 2.24, 0, -45, 0),
                 beginFlyIval,
                 ProjectileInterval(flyPie, startVel=getVelocity, duration=6),
                 Func(flyPie.detachNode))))
        return (toss, fly, flyPie)

    def handlePieHitting(self, colEntry):
        if self.gameIsEnding:
            return
        into = colEntry.getIntoNodePath()
        intoName = into.getName()
        if 'CogThiefPieSphere' in intoName:
            timestamp = globalClockDelta.localToNetworkTime(
                globalClock.getFrameTime(), bits=32)
            parts = intoName.split('-')
            suitNum = int(parts[1])
            pos = self.cogInfo[suitNum]['suit'].suit.getPos()
            if pos in CTGG.CogStartingPositions:
                self.notify.debug('Cog %d hit at starting pos %s, ignoring' %
                                  (suitNum, pos))
            else:
                self.sendUpdate('pieHitSuit', [
                    self.localAvId, timestamp, suitNum, pos[0], pos[1], pos[2]
                ])
                self.makeSuitRespondToPieHit(timestamp, suitNum)

    def pieHitSuit(self, avId, timestamp, suitNum, x, y, z):
        if not self.hasLocalToon:
            return
        if self.gameFSM.getCurrentState().getName() not in ['play']:
            self.notify.warning('ignoring msg: av %s hit by suit' % avId)
            return
        if self.gameIsEnding:
            return
        self.notify.debug('avatar ' + ` avId ` + ' hit by a suit')
        if avId != self.localAvId:
            self.makeSuitRespondToPieHit(timestamp, suitNum)

    def makeSuitRespondToPieHit(self, timestamp, suitNum):
        cog = self.cogInfo[suitNum]['suit']
        cog.respondToPieHit(timestamp)

    def sendCogAtReturnPos(self, cogIndex, barrelIndex):
        timestamp = globalClockDelta.localToNetworkTime(
            globalClock.getFrameTime(), bits=32)
        self.sendUpdate('cogAtReturnPos', [timestamp, cogIndex, barrelIndex])

    def markBarrelStolen(self, timestamp, inResponseToClientStamp,
                         barrelIndex):
        if not self.hasLocalToon:
            return
        if barrelIndex not in self.stolenBarrels:
            self.stolenBarrels.append(barrelIndex)
            barrel = self.barrels[barrelIndex]
            barrel.hide()
        if base.config.GetBool('cog-thief-check-barrels', 1):
            if not base.config.GetBool('cog-thief-endless', 0):
                if len(self.stolenBarrels) == len(self.barrels):
                    localStamp = globalClockDelta.networkToLocalTime(timestamp,
                                                                     bits=32)
                    gameTime = self.local2GameTime(localStamp)
                    self.clockStopTime = gameTime
                    self.notify.debug('clockStopTime = %s' % gameTime)
                    score = int(self.scoreMult * CTGG.calcScore(gameTime) +
                                0.5)
                    self.rewardPanel['text'] = str(score)
                    self.showResults()

    def __gameTimerExpired(self):
        self.notify.debug('game timer expired')
        self.showResults()

    def __startRewardCountdown(self):
        taskMgr.remove(self.REWARD_COUNTDOWN_TASK)
        taskMgr.add(self.__updateRewardCountdown, self.REWARD_COUNTDOWN_TASK)

    def __killRewardCountdown(self):
        taskMgr.remove(self.REWARD_COUNTDOWN_TASK)

    def __updateRewardCountdown(self, task):
        curTime = self.getCurrentGameTime()
        if self.clockStopTime is not None:
            if self.clockStopTime < curTime:
                self.notify.debug('self.clockStopTime < curTime %s %s' %
                                  (self.clockStopTime, curTime))
                self.__killRewardCountdown()
                curTime = self.clockStopTime
        if curTime > CTGG.GameTime:
            curTime = CTGG.GameTime
        score = int(self.scoreMult * CTGG.calcScore(curTime) + 0.5)
        if not hasattr(task, 'curScore'):
            task.curScore = score
        result = Task.cont
        if hasattr(self, 'rewardPanel'):
            self.rewardPanel['text'] = str(score)
            if task.curScore != score:
                if hasattr(self, 'jarIval'):
                    self.jarIval.finish()
                s = self.rewardPanel.getScale()
                self.jarIval = Parallel(Sequence(
                    self.rewardPanel.scaleInterval(0.15,
                                                   s * 3.0 / 4.0,
                                                   blendType='easeOut'),
                    self.rewardPanel.scaleInterval(0.15, s,
                                                   blendType='easeIn')),
                                        SoundInterval(self.sndRewardTick),
                                        name='cogThiefGameRewardJarThrob')
                self.jarIval.start()
            task.curScore = score
        else:
            result = Task.done
        return result

    def startGameWalk(self):
        if self.useOrthoWalk:
            self.gameWalk.start()
        else:
            self.gameWalk.enter()
            self.gameWalk.fsm.request('walking')

    def stopGameWalk(self):
        if self.useOrthoWalk:
            self.gameWalk.stop()
        else:
            self.gameWalk.exit()

    def getCogThief(self, cogIndex):
        return self.cogInfo[cogIndex]['suit']

    def isToonPlayingHitTrack(self, avId):
        if avId in self.toonHitTracks:
            track = self.toonHitTracks[avId]
            if track.isPlaying():
                return True
        return False

    def getNumCogs(self):
        result = base.config.GetInt('cog-thief-num-cogs', 0)
        if not result:
            safezone = self.getSafezoneId()
            result = CTGG.calculateCogs(self.numPlayers, safezone)
        return result

    def getCogSpeed(self):
        result = 6.0
        safezone = self.getSafezoneId()
        result = CTGG.calculateCogSpeed(self.numPlayers, safezone)
        return result

    def showResults(self):
        if not self.gameIsEnding:
            self.gameIsEnding = True
            for barrel in self.barrels:
                barrel.wrtReparentTo(render)

            for key in self.cogInfo:
                thief = self.cogInfo[key]['suit']
                thief.suit.setPos(100, 0, 0)
                thief.suit.hide()

            self.__killRewardCountdown()
            self.stopGameWalk()
            numBarrelsSaved = len(self.barrels) - len(self.stolenBarrels)
            resultStr = ''
            if numBarrelsSaved == len(self.barrels):
                resultStr = TTLocalizer.CogThiefPerfect
            elif numBarrelsSaved > 1:
                resultStr = TTLocalizer.CogThiefBarrelsSaved % {
                    'num': numBarrelsSaved
                }
            elif numBarrelsSaved == 1:
                resultStr = TTLocalizer.CogThiefBarrelSaved % {
                    'num': numBarrelsSaved
                }
            else:
                resultStr = TTLocalizer.CogThiefNoBarrelsSaved
            perfectTextSubnode = hidden.attachNewNode(
                self.__genText(resultStr))
            perfectText = hidden.attachNewNode('perfectText')
            perfectTextSubnode.reparentTo(perfectText)
            frame = self.__textGen.getCardActual()
            offsetY = -abs(frame[2] + frame[3]) / 2.0
            perfectTextSubnode.setPos(0, 0, offsetY)
            perfectText.setColor(1, 0.1, 0.1, 1)

            def fadeFunc(t, text=perfectText):
                text.setColorScale(1, 1, 1, t)

            def destroyText(text=perfectText):
                text.removeNode()

            def safeGameOver(self=self):
                if not self.frameworkFSM.isInternalStateInFlux():
                    self.gameOver()

            textTrack = Sequence(
                Func(perfectText.reparentTo, aspect2d),
                Parallel(
                    LerpScaleInterval(perfectText,
                                      duration=0.5,
                                      scale=0.3,
                                      startScale=0.0),
                    LerpFunctionInterval(fadeFunc,
                                         fromData=0.0,
                                         toData=1.0,
                                         duration=0.5)), Wait(2.0),
                Parallel(
                    LerpScaleInterval(perfectText, duration=0.5, scale=1.0),
                    LerpFunctionInterval(fadeFunc,
                                         fromData=1.0,
                                         toData=0.0,
                                         duration=0.5,
                                         blendType='easeIn')),
                Func(destroyText), WaitInterval(0.5), Func(safeGameOver))
            if numBarrelsSaved == len(self.barrels):
                soundTrack = SoundInterval(self.sndPerfect)
            else:
                soundTrack = Sequence()
            self.resultIval = Parallel(textTrack, soundTrack)
            self.resultIval.start()

    def __genText(self, text):
        self.__textGen.setText(text)
        return self.__textGen.generate()

    def getIntroTrack(self):
        base.camera.setPosHpr(0, -13.66, 13.59, 0, -51.6, 0)
        result = Sequence(
            Wait(2),
            LerpPosHprInterval(base.camera,
                               13,
                               Point3(self.cameraTopView[0],
                                      self.cameraTopView[1],
                                      self.cameraTopView[2]),
                               Point3(self.cameraTopView[3],
                                      self.cameraTopView[4],
                                      self.cameraTopView[5]),
                               blendType='easeIn'))
        return result
 def attachHostNameToSign(self, locator):
     if self.hostName == '':
         return
     nameText = TextNode('nameText')
     nameText.setCardAsMargin(0.1, 0.1, 0.1, 0.1)
     nameText.setCardDecal(True)
     nameText.setCardColor(1.0, 1.0, 1.0, 0.0)
     r = 232.0 / 255.0
     g = 169.0 / 255.0
     b = 23.0 / 255.0
     nameText.setTextColor(r, g, b, 1)
     nameText.setAlign(nameText.ACenter)
     nameText.setFont(ToontownGlobals.getBuildingNametagFont())
     nameText.setShadowColor(0, 0, 0, 1)
     nameText.setBin('fixed')
     if TTLocalizer.BuildingNametagShadow:
         nameText.setShadow(*TTLocalizer.BuildingNametagShadow)
     nameWordWrap = 11.0
     nameText.setWordwrap(nameWordWrap)
     scaleMult = 0.48
     houseName = self.hostName
     nameText.setText(houseName)
     textWidth = nameText.getWidth()
     xScale = 1.0 * scaleMult
     if textWidth > nameWordWrap:
         xScale = nameWordWrap / textWidth * scaleMult
     sign_origin = locator
     namePlate = sign_origin.attachNewNode(nameText)
     namePlate.setDepthWrite(0)
     namePlate.setPos(0, 0, 0)
     namePlate.setScale(xScale)
Exemple #60
0
 def loadSign(self):
     actNameForSign = self.activityName
     if self.activityId == PartyGlobals.ActivityIds.PartyJukebox40:
         actNameForSign = PartyGlobals.ActivityIds.getString(
             PartyGlobals.ActivityIds.PartyJukebox)
     elif self.activityId == PartyGlobals.ActivityIds.PartyDance20:
         actNameForSign = PartyGlobals.ActivityIds.getString(
             PartyGlobals.ActivityIds.PartyDance)
     self.sign = self.root.attachNewNode('%sSign' % self.activityName)
     self.signModel = self.party.defaultSignModel.copyTo(self.sign)
     self.signFlat = self.signModel.find('**/sign_flat')
     self.signFlatWithNote = self.signModel.find('**/sign_withNote')
     self.signTextLocator = self.signModel.find('**/signText_locator')
     textureNodePath = getPartyActivityIcon(self.party.activityIconsModel,
                                            actNameForSign)
     textureNodePath.setPos(0.0, -0.02, 2.2)
     textureNodePath.setScale(2.35)
     textureNodePath.copyTo(self.signFlat)
     textureNodePath.copyTo(self.signFlatWithNote)
     text = TextNode('noteText')
     text.setTextColor(0.2, 0.1, 0.7, 1.0)
     text.setAlign(TextNode.ACenter)
     text.setFont(OTPGlobals.getInterfaceFont())
     text.setWordwrap(10.0)
     text.setText('')
     self.noteText = self.signFlatWithNote.attachNewNode(text)
     self.noteText.setPosHpr(self.signTextLocator, 0.0, 0.0, 0.2, 0.0, 0.0,
                             0.0)
     self.noteText.setScale(0.2)
     self.signFlatWithNote.stash()
     self.signTextLocator.stash()