Beispiel #1
0
class YourClass(ShowBase): 
  def __init__(self): 
    ShowBase.__init__(self) 
    self.disableMouse()
    self.pos3d=None
    self.nearPoint=None
    self.farPoint=None 
    self.camera.setPos(0, 60, 25) 
    self.camera.lookAt(0, 0, 0) 
    z = 0 
    self.plane = Plane(Vec3(0, 0, 1), Point3(0, 0, z)) 
    self.model = loader.loadModel("ralph") 
    self.model.reparentTo(render) 
    self.accept("mouse1",self.set)
    taskMgr.add(self.__getMousePos, "_YourClass__getMousePos") 
  
  def __getMousePos(self, task): 
    if base.mouseWatcherNode.hasMouse(): 
      mpos = base.mouseWatcherNode.getMouse() 
      self.pos3d = Point3() 
      self.nearPoint = Point3() 
      self.farPoint = Point3() 
      base.camLens.extrude(mpos, self.nearPoint, self.farPoint) 
      if self.plane.intersectsLine(self.pos3d, 
          render.getRelativePoint(camera, self.nearPoint), 
          render.getRelativePoint(camera, self.farPoint)): 
        print "Mouse ray intersects ground plane at ", self.pos3d 
       # self.model.setPos(render, pos3d) 
    return task.again 
  def set(self):
      self.model.setPos(render, self.pos3d) 
Beispiel #2
0
class CollisionManager:
    def __init__(self):
        self.line_dir = NodePath()

        base.cTrav = CollisionTraverser()
        self.col_handler = CollisionHandlerEvent()

        picker_node = CollisionNode("mouseRayNode")
        pickerNPos = base.camera.attachNewNode(picker_node)
        self.pickerRay = CollisionRay()
        picker_node.addSolid(self.pickerRay)

        plane_node = CollisionNode("base_plane")
        plane = base.render.attachNewNode(plane_node)
        self.plane_col = CollisionPlane(Plane(Vec3(0, 0, 1), Point3(0, 0, 0)))
        picker_node.addSolid(self.pickerRay)

        picker_node.setTag("rays", "mray")
        base.cTrav.addCollider(pickerNPos, self.col_handler)

        self.col_handler.addInPattern("%(rays)ft-into-%(type)it")
        self.col_handler.addOutPattern("%(rays)ft-out-%(type)it")
        self.col_handler.addAgainPattern("ray_again_all%("
                                         "rays"
                                         ")fh%("
                                         "type"
                                         ")ih")

        self.model = loader.loadModel("../models/chest.egg")
        self.model_node = NodePath("sdfafd")
        self.model.reparentTo(self.model_node)
        self.model_node.reparentTo(render)
        #
        #        self.text_node = TextNode("battle_text")
        #        self.text_node.setText("TEXTYTEXTYTEXTTEXT")
        #        self.text_node_path = render.attachNewNode(self.text_node)
        #        self.text_node_path.reparentTo(render)
        #        self.text_node_path.setPos(0,0,4)
        #        self.text_node_path.setHpr(0,0,0)
        #        self.text_node_path.setScale(1)
        #        #self.text_node_path.setTransparency(TransparencyAttrib.MAlpha)
        #        self.text_node.setTextColor((1,1,1,1))
        #        self.text_node.setAlign(TextNode.ALeft)

        self.placement_ghost = EditorObjects.PlacementGhost(
            0, "tower", base.object_scale)

        z = 0
        self.plane = Plane(Vec3(0, 0, 1), Point3(0, 0, z))

        taskMgr.add(self.ray_update, "updatePicker")
        taskMgr.add(self.get_mouse_plane_pos, "MousePositionOnPlane")
        taskMgr.add(self.task_mouse_press_check, "checkMousePress")

        self.input_init()

        self.pickable = None

    def input_init(self):
        self.DO = DirectObject()

        self.DO.accept('mouse1', self.mouse_click, ["1-down"])
        self.DO.accept('mouse1-up', self.mouse_click, ["1-up"])
        self.DO.accept('mouse3', self.mouse_click, ["3-down"])

        self.DO.accept('0', self.placement_ghost.change_player, [0])
        self.DO.accept('1', self.placement_ghost.change_player, [1])
        self.DO.accept('2', self.placement_ghost.change_player, [2])

        self.DO.accept('a', self.placement_ghost.change_type, ["army"])
        self.DO.accept('t', self.placement_ghost.change_type, ["tower"])

        self.DO.accept('control-s', base.xml_manager.save)

        self.DO.accept('mray-into-army', self.col_in_object)
        self.DO.accept('mray-out-army', self.col_out_object)
        self.DO.accept('mray-into-tower', self.col_in_object)
        self.DO.accept('mray-out-tower', self.col_out_object)

        self.DO.accept('ray_again_all', self.col_against_object)

    def col_against_object(self, entry):
        if entry.getIntoNodePath().getParent() != self.pickable:

            np_from = entry.getFromNodePath()
            np_into = entry.getIntoNodePath()
            self.selected_type = np_into.getTag("type")

            self.pickable = np_into.getParent()

    def col_in_object(self, entry):
        if base.state == "selecting":
            np_into = entry.getIntoNodePath()
            np_into.getParent().setColor(0.5, 0.5, 0.5, 1)

    def col_out_object(self, entry):
        np_into = entry.getIntoNodePath()
        try:
            np_into.getParent().clearColor()
        except:
            print "ERROR CLEARING COLOUR"

    def get_mouse_plane_pos(self, task):
        if base.mouseWatcherNode.hasMouse():
            mpos = base.mouseWatcherNode.getMouse()
            self.pos3d = Point3()
            nearPoint = Point3()
            farPoint = Point3()
            base.camLens.extrude(mpos, nearPoint, farPoint)
            if self.plane.intersectsLine(
                    self.pos3d, render.getRelativePoint(camera, nearPoint),
                    render.getRelativePoint(camera, farPoint)):
                #print "Mouse ray intersects ground plane at ", self.pos3d
                self.model_node.setPos(render, self.pos3d)
                self.placement_ghost.set_position(self.pos3d[0], self.pos3d[1])
        return task.again

    def ray_update(self, task):
        if base.mouseWatcherNode.hasMouse():
            mpos = base.mouseWatcherNode.getMouse()

            self.pickerRay.setFromLens(base.camNode, mpos.getX(), mpos.getY())
        return task.cont

    def task_mouse_place(self, task):
        if base.mouseWatcherNode.isButtonDown(MouseButton.one()):
            self.placing_object = True
            self.place_pos = (self.anchor_x, self.anchor_y)
            self.line_dir.remove()
            ls = LineSegs()
            ls.move_to(self.anchor_x, self.anchor_y, 1)
            ls.draw_to(self.model.getX(), self.model.getY(), 1)
            node = ls.create()
            angle1 = math.atan2(self.anchor_y - self.anchor_y,
                                self.anchor_x - self.anchor_x + 50)
            angle2 = math.atan2(self.anchor_y - self.model.getY(),
                                self.anchor_x - self.model.getY())
            final_angle = angle1 - angle2
            self.model.setHpr(final_angle, 0, 0)
            self.line_dir = NodePath(node)
            self.line_dir.reparentTo(render)
            return task.again
        else:
            self.line_dir.hide()
            taskMgr.add(self.task_mouse_press_check, "checkMousePress")
            return task.done

    def task_mouse_press_check(self, task):
        if base.mouseWatcherNode.isButtonDown(MouseButton.one()):
            #if self.multi_select == True:
            self.anchor_x, self.anchor_y = self.model.getX(), self.model.getY()
            taskMgr.add(self.task_mouse_place, "multibox")
            return task.done
        return task.again

    def mouse_click(self, status):
        print base.state
        if status == "1-down":
            if base.state == "placement":
                if self.placement_ghost.get_type() == "tower":
                    obj = self.placement_ghost.place("tower",
                                                     self.model.getX(),
                                                     self.model.getY())
                elif self.placement_ghost.get_type() == "army":
                    obj = self.placement_ghost.place("army", self.model.getX(),
                                                     self.model.getY())
                base.details_box.set_object(obj)
                base.change_state("modifying")
            elif base.state == "moving":
                obj = base.details_box.get_object()
                obj.set_position(self.pos3d[0], self.pos3d[1])
                base.change_state("modifying")
            elif base.state == "selecting" and self.pickable != None:
                obj = base.get_obj_from_node(self.pickable)
                base.details_box.set_object(obj, "selecting")
                base.change_state("modifying")
        elif status == "1-up":
            print "Mouse", status
        elif status == "3-down":
            if base.state == "placement":
                base.change_state("selecting")
            elif base.state == "selecting":
                base.change_state("placement")
Beispiel #3
0
class CollisionManager:
    def __init__(self):
        base.cTrav = CollisionTraverser()
        self.col_handler = CollisionHandlerEvent()

        self.selected = -1
        self.selected_node = None
        self.selecteds = []
        self.multi_select = False
        self.multi_selecting = False
        self.select_box = NodePath()

        picker_node = CollisionNode("mouseRayNode")
        pickerNPos = base.camera.attachNewNode(picker_node)
        self.pickerRay = CollisionRay()
        picker_node.addSolid(self.pickerRay)

        plane_node = CollisionNode("base_plane")
        plane = base.render.attachNewNode(plane_node)
        self.plane_col = CollisionPlane(Plane(Vec3(0, 0, 1), Point3(0, 0, 0)))
        picker_node.addSolid(self.pickerRay)

        picker_node.setTag("rays", "mray")
        base.cTrav.addCollider(pickerNPos, self.col_handler)

        self.col_handler.addInPattern("%(rays)ft-into-%(type)it")
        self.col_handler.addOutPattern("%(rays)ft-out-%(type)it")

        self.col_handler.addAgainPattern("ray_again_all%("
                                         "rays"
                                         ")fh%("
                                         "type"
                                         ")ih")

        self.DO = DirectObject()

        self.DO.accept('mray-into-army', self.col_in_object)
        self.DO.accept('mray-out-army', self.col_out_object)
        self.DO.accept('mray-into-battle', self.col_in_object)
        self.DO.accept('mray-out-battle', self.col_out_object)
        self.DO.accept('mray-into-tower', self.col_in_object)
        self.DO.accept('mray-out-tower', self.col_out_object)

        self.DO.accept('ray_again_all', self.col_against_object)

        if base.client == False:
            self.col_handler.addInPattern("%(player)ft-into-%(player)it")
            self.col_handler.addInPattern("%(type)ft-into-%(type)it")
            self.DO.accept('army-into-battle', self.col_army_against_battle)
            self.DO.accept('army-into-tower', self.col_army_against_tower)
            self.DO.accept('1-into-2', self.col_p1_into_p2)

        self.pickable = None

        self.DO.accept('mouse1', self.mouse_click, ["down"])
        self.DO.accept('mouse1-up', self.mouse_click, ["up"])
        self.DO.accept('mouse3-up', self.mouse_order)

        taskMgr.add(self.ray_update, "updatePicker")
        taskMgr.add(self.task_select_check, "updatePicker")
        taskMgr.add(self.get_mouse_plane_pos, "MousePositionOnPlane")

        z = 0
        self.plane = Plane(Vec3(0, 0, 1), Point3(0, 0, z))

        self.model = loader.loadModel("models/chest.egg")
        self.model.reparentTo(render)
        self.model.hide()
        cm = CardMaker("blah")
        cm.setFrame(-100, 100, -100, 100)
        pnode = render.attachNewNode(cm.generate())  #.lookAt(0, 0, -1)
        pnode.hide()

    def col_army_against_battle(self, entry):
        print "Army Joins!"
        #base.net_manager.battle_join(bat,army)
        army = entry.getFromNodePath()
        a_id = int(army.getParent().getTag("id"))
        a = base.armies[a_id]
        if a.state == "normal":
            battle = entry.getIntoNodePath()
            b_id = int(battle.getParent().getTag("id"))
            if base.single_player == False:
                base.net_manager.server_messager(
                    "battle_armyadd",
                    [b_id, a_id,
                     a.node_path.getX(),
                     a.node_path.getY()])

            a = base.armies[a_id]
            b = base.battles[b_id]
            b.add_army(a)

    def col_p1_into_p2(self, entry):
        if entry.getFromNodePath().getTag(
                "state") == "normal" and entry.getIntoNodePath().getTag(
                    "state") == "normal" and entry.getIntoNodePath().getTag(
                        "type") == "army" and entry.getFromNodePath().getTag(
                            "type") == "army":
            #base.net_manager.battle_start(a1,a2)
            army1 = entry.getFromNodePath()
            army2 = entry.getIntoNodePath()
            a1_id = int(army1.getParent().getTag("id"))
            a2_id = int(army2.getParent().getTag("id"))
            a1 = base.armies[a1_id]
            a2 = base.armies[a2_id]
            a1.stop()
            a2.stop()
            base.battles.append(TimObjects.Battle([a1, a2]))

    def col_army_against_tower(self, entry):
        print "TOWER COLLIDE", entry.getIntoNodePath().getParent().getTag("id")
        print entry.getIntoNodePath().getParent().getTag(
            "player"), "vs", entry.getFromNodePath().getParent().getTag(
                "player")
        if entry.getIntoNodePath().getParent().getTag(
                "player") != entry.getFromNodePath().getParent().getTag(
                    "player"):
            tower = entry.getIntoNodePath()
            tower_id = int(tower.getParent().getTag("id"))
            invader = int(entry.getFromNodePath().getParent().getTag("player"))
            if base.client == False and base.towers[tower_id].capture_check():
                base.towers[tower_id].change_owner(invader)
                if base.single_player == False:
                    base.net_manager.server_messager("tower_capture",
                                                     [tower_id, invader])

    def col_in_object(self, entry):
        np_into = entry.getIntoNodePath()
        np_into.getParent().setColor(0.5, 0.5, 0.5, 0.1)
        #self.global_text.setText(np_into.getName())
        if np_into.getTag("type") == "battle":
            print "You're in a battle"

        #print "in"

    def col_out_object(self, entry):
        np_into = entry.getIntoNodePath()
        #print "out"
        try:
            np_into.getParent().setColor(1, 1, 1, 1)
        except:
            print "ERROR CLEARING COLOUR"
        #self.global_text.setText("")

        self.pickable = None
        self.selected_type = "none"

    def col_against_object(self, entry):
        if entry.getIntoNodePath().getParent() != self.pickable:

            np_from = entry.getFromNodePath()
            np_into = entry.getIntoNodePath()
            self.selected_type = np_into.getTag("type")

            self.pickable = np_into.getParent()

    def mouse_click(self, status):
        print "click"
        in_statbar = base.vis_manager.statbar.mouse_in_bar()
        if self.pickable and in_statbar == False:
            if status == "down":
                if self.selected_type == "army":
                    if base.armies[int(self.pickable.getTag(
                            "id"))].state == "normal" or base.armies[int(
                                self.pickable.getTag("id"))].state == "new":
                        for obj in self.selecteds:
                            obj.deselect()
                            print obj.my_id, "deselected"
                        self.selecteds = []
                        self.pickable.setScale(0.95 * 10)
                        self.selected = int(self.pickable.getTag("id"))
                        self.selected_node = self.pickable
                        self.selecteds.append(base.armies[self.selected])
                        base.armies[self.selected].select()
                        print "You clicked on Army" + str(self.selected)
                        base.vis_manager.statbar.show_army(self.selected)
                elif self.selected_type == "tower":
                    for obj in self.selecteds:
                        obj.deselect()
                        print obj.my_id, "deselected"
                    self.selecteds = []
                    self.selected = int(self.pickable.getTag("id"))
                    self.selected_node = self.pickable
                    self.selecteds.append(base.towers[self.selected])
                    base.towers[self.selected].select()
                    print "You clicked on a tower"
                    base.vis_manager.statbar.show_tower(self.selected)
                elif self.selected_type == "battle":
                    self.selected = int(self.pickable.getTag("id"))
                    self.selected_node = self.pickable
                    print "You clicked on a battle"
                    base.vis_manager.statbar.show_battle(self.selected)

            if status == "up":
                if self.selected_type == "army":
                    self.pickable.setScale(1.0 * 10)
        elif status == "up" and self.multi_select == True:
            self.multi_select = False
            self.select_all_in_box()
        elif in_statbar == True:
            print "in box"
        elif self.pickable == None:
            for obj in self.selecteds:
                obj.deselect()
                print obj.my_id, "deselected"
            self.selecteds = []
            self.selected = -1
            self.selected_node = None
            base.vis_manager.statbar.reset_statbar()

    def select_all_in_box(self):
        for obj in self.selecteds:
            obj.deselect()
            print obj.my_id, "deselected"
        self.selecteds = []
        print "select units in box"
        for a in base.armies:
            if a.node_col.getTag("type") == "army" and (
                    a.state == "normal"
                    or a.state == "new") and a.player == base.player:
                x = a.get_x()
                y = a.get_y()
                if self.box_x < self.model.getX(
                ) and self.box_y > self.model.getY():
                    if x < self.model.getX(
                    ) and x > self.box_x and y > self.model.getY(
                    ) and y < self.box_y:
                        self.selecteds.append(a)
                        a.select()
                elif self.box_x < self.model.getX(
                ) and self.box_y < self.model.getY():
                    if x < self.model.getX(
                    ) and x > self.box_x and y < self.model.getY(
                    ) and y > self.box_y:
                        self.selecteds.append(a)
                        a.select()
                elif self.box_x > self.model.getX(
                ) and self.box_y < self.model.getY():
                    if x > self.model.getX(
                    ) and x < self.box_x and y < self.model.getY(
                    ) and y > self.box_y:
                        self.selecteds.append(a)
                        a.select()
                elif self.box_x > self.model.getX(
                ) and self.box_y > self.model.getY():
                    if x > self.model.getX(
                    ) and x < self.box_x and y > self.model.getY(
                    ) and y < self.box_y:
                        self.selecteds.append(a)
                        a.select()

    def task_select_check(self, task):
        if base.mouseWatcherNode.isButtonDown(MouseButton.one()):
            #if self.multi_select == True:
            self.box_x, self.box_y = self.model.getX(), self.model.getY()
            taskMgr.add(self.draw_multiselect_box, "multibox")
            return task.done
        return task.cont

    def draw_multiselect_box(self, task):
        if base.mouseWatcherNode.isButtonDown(MouseButton.one()):
            self.multi_select = True
            self.select_box.remove()
            ls = LineSegs()
            ls.move_to(self.box_x, self.box_y, 1)
            ls.draw_to(self.model.getX(), self.box_y, 1)
            ls.draw_to(self.model.getX(), self.model.getY(), 1)
            ls.draw_to(self.box_x, self.model.getY(), 1)
            ls.draw_to(self.box_x, self.box_y, 1)
            node = ls.create()
            #text = TextNode('text')
            #text.setText(str(self.box_x)+","+str(self.box_y)+"\n"+str(self.model.getX())+","+str(self.model.getY()))
            #textnp = NodePath(text)
            #textnp.setPos(self.box_x,self.box_y,1)
            #textnp.setHpr(0,-90,0)
            #textnp.setScale(20.0)
            self.select_box = NodePath(node)
            #textnp.reparentTo(self.select_box)
            self.select_box.reparentTo(render)
            return task.cont
        else:
            self.select_box.hide()
            taskMgr.add(self.task_select_check, "updatePicker")
            return task.done

    def mouse_order(self):
        print "mouse_order"
        #        if self.selected != -1 and base.armies[self.selected].state == "normal":
        #            print "orders sent"
        for a in self.selecteds:
            if a.node_col.getTag("type") == "army":
                if len(self.selecteds) > 1:
                    randomness = (len(self.selecteds) - 1) * 10
                    a.set_target(
                        True,
                        self.pos3d.getX() + random.randint(0, randomness) -
                        randomness / 2,
                        self.pos3d.getY() + random.randint(0, randomness) -
                        randomness / 2)
                else:
                    a.set_target(True, self.pos3d.getX(), self.pos3d.getY())

    def get_mouse_plane_pos(self, task):
        if base.mouseWatcherNode.hasMouse():
            mpos = base.mouseWatcherNode.getMouse()
            self.pos3d = Point3()
            nearPoint = Point3()
            farPoint = Point3()
            base.camLens.extrude(mpos, nearPoint, farPoint)
            if self.plane.intersectsLine(
                    self.pos3d, render.getRelativePoint(camera, nearPoint),
                    render.getRelativePoint(camera, farPoint)):
                #print "Mouse ray intersects ground plane at ", self.pos3d
                self.model.setPos(render, self.pos3d)
        return task.again

    def ray_update(self, task):
        if base.mouseWatcherNode.hasMouse():
            mpos = base.mouseWatcherNode.getMouse()

            self.pickerRay.setFromLens(base.camNode, mpos.getX(), mpos.getY())
        return task.cont
class CollisionManager:
    def __init__(self):
        self.line_dir = NodePath()

        base.cTrav = CollisionTraverser()
        self.col_handler = CollisionHandlerEvent()

        picker_node = CollisionNode("mouseRayNode")
        pickerNPos = base.camera.attachNewNode(picker_node)
        self.pickerRay = CollisionRay()
        picker_node.addSolid(self.pickerRay)

        plane_node = CollisionNode("base_plane")
        plane = base.render.attachNewNode(plane_node)
        self.plane_col = CollisionPlane(Plane(Vec3(0, 0, 1), Point3(0, 0, 0)))
        picker_node.addSolid(self.pickerRay)


        picker_node.setTag("rays","mray")
        base.cTrav.addCollider(pickerNPos, self.col_handler)

        self.col_handler.addInPattern("%(rays)ft-into-%(type)it")
        self.col_handler.addOutPattern("%(rays)ft-out-%(type)it")
        self.col_handler.addAgainPattern("ray_again_all%(""rays"")fh%(""type"")ih")

        self.model = loader.loadModel("../models/chest.egg")
        self.model_node = NodePath("sdfafd")
        self.model.reparentTo(self.model_node)
        self.model_node.reparentTo(render)
#
#        self.text_node = TextNode("battle_text")
#        self.text_node.setText("TEXTYTEXTYTEXTTEXT")
#        self.text_node_path = render.attachNewNode(self.text_node)
#        self.text_node_path.reparentTo(render)
#        self.text_node_path.setPos(0,0,4)
#        self.text_node_path.setHpr(0,0,0)
#        self.text_node_path.setScale(1)
#        #self.text_node_path.setTransparency(TransparencyAttrib.MAlpha)
#        self.text_node.setTextColor((1,1,1,1))
#        self.text_node.setAlign(TextNode.ALeft)

        self.placement_ghost = EditorObjects.PlacementGhost(0,"tower",base.object_scale)

        z=0
        self.plane = Plane(Vec3(0, 0, 1), Point3(0, 0, z))

        taskMgr.add(self.ray_update, "updatePicker")
        taskMgr.add(self.get_mouse_plane_pos, "MousePositionOnPlane")
        taskMgr.add(self.task_mouse_press_check, "checkMousePress")

        self.input_init()

        self.pickable=None

    def input_init(self):
        self.DO=DirectObject()

        self.DO.accept('mouse1', self.mouse_click, ["1-down"])
        self.DO.accept('mouse1-up', self.mouse_click, ["1-up"])
        self.DO.accept('mouse3', self.mouse_click, ["3-down"])

        self.DO.accept('0', self.placement_ghost.change_player, [0])
        self.DO.accept('1', self.placement_ghost.change_player, [1])
        self.DO.accept('2', self.placement_ghost.change_player, [2])

        self.DO.accept('a', self.placement_ghost.change_type, ["army"])
        self.DO.accept('t', self.placement_ghost.change_type, ["tower"])

        self.DO.accept('control-s', base.xml_manager.save)

        self.DO.accept('mray-into-army', self.col_in_object)
        self.DO.accept('mray-out-army', self.col_out_object)
        self.DO.accept('mray-into-tower', self.col_in_object)
        self.DO.accept('mray-out-tower', self.col_out_object)

        self.DO.accept('ray_again_all', self.col_against_object)

    def col_against_object(self,entry):
        if entry.getIntoNodePath().getParent() != self.pickable:

            np_from=entry.getFromNodePath()
            np_into=entry.getIntoNodePath()
            self.selected_type = np_into.getTag("type")

            self.pickable = np_into.getParent()

    def col_in_object(self,entry):
        if base.state == "selecting":
            np_into=entry.getIntoNodePath()
            np_into.getParent().setColor(0.5,0.5,0.5,1)

    def col_out_object(self,entry):
        np_into=entry.getIntoNodePath()
        try:
            np_into.getParent().clearColor()
        except:
            print "ERROR CLEARING COLOUR"

    def get_mouse_plane_pos(self, task):
        if base.mouseWatcherNode.hasMouse():
            mpos = base.mouseWatcherNode.getMouse()
            self.pos3d = Point3()
            nearPoint = Point3()
            farPoint = Point3()
            base.camLens.extrude(mpos, nearPoint, farPoint)
            if self.plane.intersectsLine(self.pos3d,
                render.getRelativePoint(camera, nearPoint),
                render.getRelativePoint(camera, farPoint)):
                #print "Mouse ray intersects ground plane at ", self.pos3d
                self.model_node.setPos(render, self.pos3d)
                self.placement_ghost.set_position(self.pos3d[0],self.pos3d[1])
        return task.again

    def ray_update(self,task):
        if base.mouseWatcherNode.hasMouse():
            mpos = base.mouseWatcherNode.getMouse()

            self.pickerRay.setFromLens(base.camNode, mpos.getX(),mpos.getY())
        return task.cont

    def task_mouse_place(self,task):
        if base.mouseWatcherNode.isButtonDown(MouseButton.one()):
            self.placing_object = True
            self.place_pos = (self.anchor_x,self.anchor_y)
            self.line_dir.remove()
            ls = LineSegs()
            ls.move_to(self.anchor_x,self.anchor_y,1)
            ls.draw_to(self.model.getX(),self.model.getY(),1)
            node = ls.create()
            angle1 = math.atan2(self.anchor_y - self.anchor_y,self.anchor_x - self.anchor_x+50)
            angle2 = math.atan2(self.anchor_y - self.model.getY(),self.anchor_x - self.model.getY());
            final_angle = angle1-angle2;
            self.model.setHpr(final_angle,0,0)
            self.line_dir = NodePath(node)
            self.line_dir.reparentTo(render)
            return task.again
        else:
            self.line_dir.hide()
            taskMgr.add(self.task_mouse_press_check, "checkMousePress")
            return task.done

    def task_mouse_press_check(self,task):
        if base.mouseWatcherNode.isButtonDown(MouseButton.one()):
            #if self.multi_select == True:
                self.anchor_x,self.anchor_y = self.model.getX(),self.model.getY()
                taskMgr.add(self.task_mouse_place, "multibox")
                return task.done
        return task.again

    def mouse_click(self,status):
        print base.state
        if status == "1-down":
            if base.state == "placement":
                if self.placement_ghost.get_type() == "tower":
                    obj = self.placement_ghost.place("tower",self.model.getX(),self.model.getY())
                elif self.placement_ghost.get_type() == "army":
                    obj = self.placement_ghost.place("army",self.model.getX(),self.model.getY())
                base.details_box.set_object(obj)
                base.change_state("modifying")
            elif base.state == "moving":
                obj = base.details_box.get_object()
                obj.set_position(self.pos3d[0],self.pos3d[1])
                base.change_state("modifying")
            elif base.state == "selecting" and self.pickable != None:
                obj = base.get_obj_from_node(self.pickable)
                base.details_box.set_object(obj,"selecting")
                base.change_state("modifying")
        elif status == "1-up":
            print "Mouse",status
        elif status == "3-down":
            if base.state == "placement":
                base.change_state("selecting")
            elif base.state == "selecting":
                base.change_state("placement")
class TowerDefense(ShowBase):
	def __init__(self):
		ShowBase.__init__(self)
		self.disableMouse()
		self.camera.setPos(40, -100, 160)
		self.camera.lookAt(40,-44.5,0)
		self.rows, self.cols = 9, 8
		#Start tile & end tile
		self.start, self.end = (0, 0), (8, 7)
		self.cellSize = 10
		#Plane used for intersection of mouseLine
		#To get coords of mouse
		self.mousePlane = Plane(Vec3(0, 0, 1), Point3(0, 0, 0))
		#No click has been made
		self.mousePressed = False
		self.displayTextObject = None
		#Holds the model for all tiles
		self.tiles = []
		for row in xrange(self.rows):
			self.tiles += [[0]*self.cols]
		#Holds the texture for the grass tiles
		self.grass = loader.loadTexture("models/textures/sponge.jpg")
		#Holds the models for all the towers
		self.towerModels = []
		for row in xrange(self.rows):
			self.towerModels += [[0]*self.cols]
		#Holds the G value of each tile for pathing
		self.tileNodes = []
		for row in xrange(self.rows):
			self.tileNodes += [[0]*self.cols]
		for row in xrange(self.rows):
			for col in xrange(self.cols):
				self.tileNodes[row][col] = Tile(self)
		#Holds the towers in a 2d array
		self.towers = []
		for row in xrange(self.rows):
			self.towers += [[0]*self.cols]
		self.board = [
						['s', 0, 0, 0, 0, 0, 0, 0],
						 [ 0, 0, 0, 0, 0, 0, 0, 0],
						 [ 0, 0, 0, 0, 0, 0, 0, 0],
						 [ 0, 0, 0, 0, 0, 0, 0, 0],
						 [ 0, 0, 0, 0, 0, 0, 0, 0],
						 [ 0, 0, 0, 0, 0, 0, 0, 0],
						 [ 0, 0, 0, 0, 0, 0, 0, 0],
						 [ 0, 0, 0, 0, 0, 0, 0, 0],
						 [ 0, 0, 0, 0, 0, 0, 0,'e']
					 ]
		self.drawBoard()
		self.drawBoardLines()
		self.drawBackground()
		
		#Stores all center points of each tile
		self.midPoints= []
		startX = 5 #X Coordinate of first Square's center
		startY = -5 #Y Coordinate of first Square's center
		for row in xrange(self.rows):
			self.midPoints += [[Point3(0,0,0)]*self.cols]
		for row in xrange(self.rows):
			for col in xrange(self.cols):
				self.midPoints[row][col] = Point3(
											startX+col*self.cellSize,
											startY-row*self.cellSize,
											0)
		self.createPath(self.start, self.end)
		
#Board Information
		#Towers
		self.arrowTowerModel = loader.loadModel(
			"models/towers/arrowTowerFolder/arrowTower")
		self.fireTowerModel = loader.loadModel(
			"models/towers/fireTowerFolder/fireTower")
		self.iceTowerModel = loader.loadModel(
			"models/towers/iceTowerFolder/iceTower")

#Main Menu
		self.mainFrame = DirectFrame(frameColor=(0, 0, 0, 1),
		                      frameSize=(-2, 2, -2, 2),
		                      pos=(0, 0, 0))
		instructionsText = "   Stefan Dasbach's Tower Defense\n\n\n"+\
							"Monsters move accross the screen\n" +\
							"from the green square to the red\nsquare."+\
							" Choose and build from among a \nrange" +\
							" of towers including Arrow, Fire,\nand" +\
							" Ice. Waves of monsters come in \n10 and" +\
							" will spawn every 15 seconds. You\ncan" +\
							" only build towers when creeps are\nnot" +\
							" alive.\n\nPress 'P' to play!"
		self.instructionsNode = OnscreenText(
									text=instructionsText,
									pos = (-0.9, 0.55),
									scale = (0.1),
								bg = (209/255.0, 168/255.0, 132/255.0, 1),
									frame = (1, 0, 0, 1),
									align = TextNode.ALeft
												)
		# self.fireProjectileModel = loader.loadModel(
		# 	"models/projectiles/fireProjectileFolder/fireProjectile")
		# self.iceProjectileModel = loader.loadModel(
		# "models/projectiles/iceProjectileFolder/iceProjectile")
		# 
		# self.iceProjectileModel.setScale(0.03,0.03,0.03)
		# self.iceProjectileModel.setPos(12,-5,0)
		# # self.iceProjectileModel.lookAt(15, -5, 0)
		# self.iceProjectileModel.reparentTo(self.render)
		
#Level information
		self.level = 1
		self.gold = 20
		self.lives = 20
		self.totalHp = 0
		self.arrowTowerCost = 10
		self.fireTowerCost = 25
		self.iceTowerCost = 30
		#Building period, True at beginning of game
		self.buildTime = True
		#Spawning/killing of creeps period, False at beginning
		self.fireTime = False
		self.displayGameInfoNode = None
		self.displayGameInfoNode1 = None
		
#Spawn Creeps
		self.numberOfCreeps = 10
		#Time for building
		self.waveTime = 15
		self.creeps = []
		self.hasSpawnedWave = False
		#Delay between spawning of each creep
		self.delayTime = 0
		self.interval = 0
		self.buildTimeDuration = 0
		self.alreadyInitedGame = False
		self.accept("p", self.initGame)
		
	def initGame(self):
		if self.alreadyInitedGame == False:
			self.instructionsNode.destroy()
			self.mainFrame.destroy()
			#Handle taskManager
			self.timerTask = self.taskMgr.add(self.timerTask, 'timerTask')
			self.mouseTask = self.taskMgr.add(self.mouseTask, 'mouseTask')
			self.fireTask = self.taskMgr.add(self.fireTask, 'fireTask')
			self.hpBarTask = self.taskMgr.add(self.hpBarTask, 'hpBarTask')
			self.displayGameInfo()
			self.displayTowerInfo()
			self.displayControls()
			#Selects tile
			self.accept("mouse1", self.selectTile)
			#Builds arrow Tower
			self.accept("a", self.buildTowerArrow)
			#Builds Fire Tower
			self.accept("f", self.buildTowerFire)
			#Builds Ice tower
			self.accept("i", self.buildTowerIce)
			#Quits the game
			self.accept("q", self.quit)
			self.alreadyInitedGame = True

#***********************   Board Display   ***********************
	#Displays a walkable tile or tower
	def drawTile(self, row, col):
		#Towers
		if self.board[row][col] < 0:
			if self.board[row][col] == -1: #Arrow Tower
				# tileMaker.setColor(0, 0, 0, 1)
				self.towerModels[row][col] = BuildArrowTowerModel(
											self, self.midPoints[row][col])
			elif self.board[row][col] == -2: #Fire tower
				# tileMaker.setColor(1, 136.0/255, 0, 1)
				self.towerModels[row][col] = BuildFireTowerModel(
											self, self.midPoints[row][col])
			elif self.board[row][col] == -3: #Ice tower
				self.towerModels[row][col] = BuildIceTowerModel(
											self, self.midPoints[row][col])
				# tileMaker.setColor(0, 0, 1, 1)
		#Board Tiles
		else: 
			tileMaker = CardMaker("board")
			cellSize = self.cellSize
			if self.board[row][col] == 0: #Normal/non-towered tile
				tileMaker.setColor(1, 1, 1, 1)
			elif self.board[row][col] == "s": #Start
				tileMaker.setColor(0, 1, 0, 1)
			elif self.board[row][col] == "e": #End
				tileMaker.setColor(173.0/255, 0, 0, 1)
			tileMaker.setFrame(
				col*cellSize, col*cellSize+cellSize,
				-row*cellSize-cellSize, -row*cellSize)
			self.tiles[row][col] = self.render.attachNewNode(\
									tileMaker.generate())
			self.tiles[row][col].setTexture(self.grass)
			self.tiles[row][col].lookAt(0,0,-1)
	
	#Draws all tiles from self.board
	def drawBoard(self):
		tileMaker = CardMaker("board")
		board = self.board
		cellSize = self.cellSize
		for row in xrange(len(board)):
			for col in xrange(len(board[0])):
				self.drawTile(row, col)
	
	#Draws grid line from start and end point
	#Basically adds visual separation of tiles
	def drawLine(self, start, end, thickness=1.5):
		segment = LineSegs()
		# segment.setColor(209/255.0, 168/255.0, 132/255.0, 1)
		segment.setColor(1, 1, 1, 1)
		segment.setThickness(thickness)
		segment.moveTo(start)
		segment.drawTo(end)
		line = self.render.attachNewNode(segment.create())
		
	#Draws all grid lines of the board
	def drawBoardLines(self):
		#Horizontal grid lines
		for row in xrange(self.rows):
			self.drawLine(Point3(0, -row*self.cellSize, 0.01), 
				Point3(self.cellSize*self.cols, -row*self.cellSize, 0.01))
		#Vertical grid lines
		for col in xrange(self.cols):
			self.drawLine(Point3(col*self.cellSize, 0, 0.01), 
				Point3(col*self.cellSize, -self.cellSize*self.rows, 0.01))
				
	def drawBackground(self):
		self.background = loader.loadModel("models/skySphere/skySphere")
		self.background.lookAt(0,0,-1)
		self.background.reparentTo(self.render)
	#**************************   A Star   **************************
	#Determines whether or not tile can be walked on
	def isPath(self, coord):
		row, col = coord[0], coord[1]
		if self.board[row][col] < 0: #Tower
			return False
		return True #Can walk on path

	#Determines if row and col on board or not
	def inBounds(self, coord):
		row, col = coord[0], coord[1]
		if row < len(self.board) and col < len(self.board[0]):
			if row >= 0 and col >=0:
				return True
		return False

	#A* Pathfinding Algorithm
	def createPath(self, start, end):
		#This array of array of objects keeps 
		#track of the G value of each tile

		openList = set()
		closedList = set()
		parentDict = dict()
		openList.add(start)
		newTile = start

		#If end in closedList, we've found our pathway to end
		#Or if we've exhausted all search tiles available (openList is empty)
		try:
			while (end not in closedList) or len(openList) != 0:
				#Lowest f-value among openList
				#newTile holds the coordinates of which tile to check
				newTile = self.getLowestFInOpen(start, end, openList)
				#Make self.tileNodes[newTile[0]][newTile[1]] and currentNode
				#Aliases to use currentNode instead to improve clarity
				currentNode = self.tileNodes[newTile[0]][newTile[1]]
				#Switch newTile to closedList
				openList.remove(newTile)
				closedList.add(newTile)
				#Adjacent tiles
				left = (newTile[0], newTile[1]-1)
			
				right = (newTile[0], newTile[1]+1)
			
				up = (newTile[0]-1, newTile[1])
			
				down = (newTile[0]+1, newTile[1])
			
				#Check if adjacent tiles in closedList/openList
				#If in closedList, already checked
				#If not in closedList, check if already in openList
				#If not in openList, add it, and record its parent tile
				#Down tile
				if self.inBounds(down) and self.isPath(down):
					downNode = self.tileNodes[newTile[0]+1][newTile[1]]
					#If not already checked
					if down not in closedList:
						#If should be added to openList	
						if down not in openList:
							downNode.setG(currentNode.getG() + 1)
							openList.add(down)
							#Assign newTile as down's parent tile
							parentDict[down] = (newTile)
						else:
							newG = currentNode.getG() + 1 #down so plus 1
							if downNode.getG() > newG:
								downNode.setG(newG)
								parentDict[down] = (newTile)
				#Right tile
				if self.inBounds(right) and self.isPath(right):
					rightNode = self.tileNodes[newTile[0]][newTile[1]+1]
					if right not in closedList:
						if right not in openList:
							rightNode.setG(currentNode.getG() + 1)
							openList.add(right)
							parentDict[right] = (newTile)
						else:
							newG = currentNode.getG() + 1 #right so plus 1
							if rightNode.getG() > newG:
								rightNode.setG(newG)
								parentDict[right] = (newTile)
				#Up tile
				if self.inBounds(up) and self.isPath(up):
					upNode = self.tileNodes[newTile[0]-1][newTile[1]]
					if up not in closedList:
						if up not in openList:
							upNode.setG(currentNode.getG() + 1)
							openList.add(up)
							parentDict[up] = (newTile)
						else:
							newG = currentNode.getG() + 1 #up so plus 1
							if upNode.getG() > newG:
								upNode.setG(newG)
								parentDict[up] = (newTile)
				#Left Tile
				if self.inBounds(left) and self.isPath(left):
					leftNode = self.tileNodes[newTile[0]][newTile[1]-1]
					if left not in closedList:
						if left not in openList:
							leftNode.setG(currentNode.getG() + 1)
							openList.add(left)
							parentDict[left] = (newTile)
						else:
							newG = currentNode.getG() + 1 #left so plus 1
							if leftNode.getG() > newG:
								leftNode.setG(newG)
								parentDict[left] = (newTile)
		except:
			return False

		self.tileSequence = self.getSequenceFromDict(parentDict)
		self.pathSequence = []
		for i in xrange(len(self.tileSequence)):
			self.pathSequence += [self.midPoints
										[self.tileSequence[i][0]]
										[self.tileSequence[i][1]]]
						
		return True
	#Finds lowest f value in openList
	def getLowestFInOpen(self, start, end, openList):
		lowestF = 10000000
		newTile = None
		for tile in openList:
			temp = self.getF(start, end, self.tileNodes[\
					tile[0]][tile[1]], tile[0], tile[1])
			if temp < lowestF:
				lowestF = temp
				newTile = tile
		return newTile

	#Distance from start to current tile
	def getG(self, current):
		return current.getG()
		# return abs(start[0]-current[0]) + abs(start[1]-current[1])

	#Distance from current tile to end
	def getH(self, start, end, current):
		return abs(end[1]-current[1]) + abs(end[0]-current[0])

	#Sum of g and h (total presumed distance from start to finish)
	def getF(self, start, end, current, row, col):
		g = self.getG(current)
		h = self.getH(start, end, (row,col))
		return g+h
	#Get sequence of steps from dictionary of points
	#and their parent points
	def getSequenceFromDict(self, parentDict):
		currentTile = self.end
		pathSequence = [currentTile]
		while currentTile != self.start:
			currentTile = parentDict[currentTile]
			pathSequence += [currentTile]
		return pathSequence[::-1]
	
#********************Task Manager***********************
	#Handles the switching between 
	#The building period and
	#The creep killing period
	def timerTask(self, task):
		if self.buildTime == True:
			#buildTimeDuration hasn't been set yet
			if self.buildTimeDuration == 0:
				for row in self.towers:
					for tower in row:
						#If this has been set to a tower
						if tower:
							if tower.shootProj != None and\
								not tower.shootProj.isGone():
								tower.shootProj.remove()
				self.buildTimeDuration = task.time + self.waveTime
				self.displayBuildTime(self.buildTimeDuration-task.time)
			#If a second has passed since updating the time
			elif self.buildTimeDuration-task.time < self.currentBuildTimeInt:
				self.displayNextWave.destroy()
				self.displayNextWaveTime.destroy()
				self.displayBuildTime(self.buildTimeDuration-task.time)
			#If buildTime has expired
			#Initiate fireTime, end buildTime
			if task.time > self.buildTimeDuration:
				self.displayNextWave.destroy()
				self.displayNextWaveTime.destroy()
				self.buildTime = False
				self.fireTime = True
				self.hasSpawnedWave = False
				self.buildTimeDuration = 0
				self.displayCreepHp = True
			return Task.cont
		#Start next level
		if self.fireTime == True:
			#Spawn wave
			if self.hasSpawnedWave == False:
				self.spawnWave(task)
				#Used to display CreepHP as soon as wave spawns
				if self.displayCreepHp == True:
					if self.displayGameInfoNode1 != None:
						self.displayGameInfoNode1.destroy()
					self.displayGameInfoNode.destroy()
					self.displayGameInfo()
				self.displayCreepHp = False
				return Task.cont
			#If all creeps killed/reached end
			#Initiate buildTime, end fireTime
			if self.isCreeps() == False:
				self.buildTime = True
				self.fireTime = False
				#Next level
				self.levelUp()
			return Task.cont
	#Manages the tracking of the mouse & its position
	def mouseTask(self, task):
		if base.mouseWatcherNode.hasMouse():
			tempMousePos = base.mouseWatcherNode.getMouse()
			pos3d = Point3()
			nearPoint = Point3()
			farPoint = Point3()
			base.camLens.extrude(tempMousePos, nearPoint, farPoint)
			if self.mousePlane.intersectsLine(pos3d,
				self.render.getRelativePoint(camera, nearPoint),
				self.render.getRelativePoint(camera, farPoint)):
				self.mousePos = (pos3d[0], pos3d[1])
		return Task.cont
	#Manages the firing of towers
	def fireTask(self, task):
		#Are creeps and are towers
		if len(self.creeps) > 0 and len(self.towers) > 0:
			for row in self.towers:
				for tower in row:
					#If this has been set to a tower
					if tower:
						#Tower fire isn't on cooldown
						# if not tower.isFiring():
						tower.fire(task)
							
		return Task.cont
	#Shows and positions hpBar
	def hpBarTask(self, task):
		for creep in self.creeps:
			#Is actually a creep
			if creep:
				creep.showHpBar(task)
		return Task.cont
	
#*************************Building Objects*************************
	#onClick of mouse selects a tile
	def selectTile(self):
		row, col = self.mousePos[1], self.mousePos[0]
		#Check if click is on the grid or not
		if (row < 0 and row > -self.rows*self.cellSize) and (
			col > 0 and col <  self.cols*self.cellSize):
			self.mousePressed = True
			self.currentRow = abs(int(row/10))
			self.currentCol = abs(int(col/10))
			#If displayText already exists, destroy and rewrite it
			if self.displayTextObject != None:
				self.displayTextObject.destroy()
			self.displayText()
	def buildTowerArrow(self):
		#Row and col of tile selected
		#A tile is selected
		if self.mousePressed == True:
			#Makes sure not building while attacking creeps
			if self.buildTime == False:
				self.displayTextObject.destroy()
				self.displayError("You cannot build while attacking")
			else:
				row = self.currentRow
				col = self.currentCol
				originalVal = self.board[row][col]
				self.board[row][col] = -1
				#Checks if the tower is blocking
				#Or if tower already built there
				#Create path return false if no path
				if (not self.createPath(self.start, self.end) or 
									  (row == 0 and col == 0) or 
									  (originalVal < 0) #Already a tower
									  ):
					self.board[row][col] = originalVal
					self.displayTextObject.destroy()
					self.displayError("You can't build there")
				elif self.gold < self.arrowTowerCost:
					self.board[row][col] = originalVal
					self.displayTextObject.destroy()
					self.displayError("Not enough gold")
				else:
					self.towers[row][col] = ArrowTower(
									self, self.midPoints[row][col])
					#Delete current square
					# self.tiles[row][col].removeNode()
					#Redraw it as tower
					self.drawTile(row, col)
					#Built a tower, so no longer highlighting tile
					self.mousePressed = False
					#No need for text; no tile selected
					self.displayTextObject.destroy()
					self.createPath(self.start, self.end)
					self.gold -= self.arrowTowerCost
					if self.displayGameInfoNode1 != None:
						self.displayGameInfoNode1.destroy()
					self.displayGameInfoNode.destroy()
					self.displayGameInfo()
	def buildTowerFire(self):
		#Row and col of tile selected
		#A tile is selected
		if self.mousePressed == True:
			#Makes sure not building while attacking creeps
			if self.buildTime == False:
				self.displayTextObject.destroy()
				self.displayError("You cannot build while attacking")
			else:
				row = self.currentRow
				col = self.currentCol
				originalVal = self.board[row][col]
				self.board[row][col] = -2
				#Checks if the tower is blocking
				#Or if tower already built there
				#Create path return false if no path
				if (not self.createPath(self.start, self.end) or 
									  (row == 0 and col == 0) or 
									  (originalVal < 0) #Already a tower
									  ):
					self.board[row][col] = originalVal
					self.displayTextObject.destroy()
					self.displayError("You can't build there")
				elif self.gold < self.fireTowerCost:
					self.board[row][col] = originalVal
					self.displayTextObject.destroy()
					self.displayError("Not enough gold")
				else:
					self.towers[row][col] = FireTower(
									self, self.midPoints[row][col])
					#Delete current square
					# self.tiles[row][col].removeNode()
					#Redraw it as tower
					self.drawTile(row, col)
					#Built a tower, so no longer highlighting tile
					self.mousePressed = False
					#No need for text; no tile selected
					self.displayTextObject.destroy()
					self.createPath(self.start, self.end)
					self.gold -= self.fireTowerCost
					if self.displayGameInfoNode1 != None:
						self.displayGameInfoNode1.destroy()
					self.displayGameInfoNode.destroy()
					self.displayGameInfo()
	def buildTowerIce(self):
		#Row and col of tile selected
		#A tile is selected
		if self.mousePressed == True:
			#Makes sure not building while attacking creeps
			if self.buildTime == False:
				self.displayTextObject.destroy()
				self.displayError("You cannot build while attacking")
			else:
				row = self.currentRow
				col = self.currentCol
				originalVal = self.board[row][col]
				self.board[row][col] = -3
				#Checks if the tower is blocking
				#Or if tower already built there
				#Create path return false if no path
				if (not self.createPath(self.start, self.end) or 
									  (row == 0 and col == 0) or 
									  (originalVal < 0) #Already a tower
									  ):
					self.board[row][col] = originalVal
					self.displayTextObject.destroy()
					self.displayError("You can't build there")
				elif self.gold < self.iceTowerCost:
					self.board[row][col] = originalVal
					self.displayTextObject.destroy()
					self.displayError("Not enough gold")
				else:
					self.towers[row][col] = IceTower(
							self, self.midPoints[row][col])
					#Delete current square
					# self.tiles[row][col].removeNode()
					#Redraw it as tower
					self.drawTile(row, col)
					#Built a tower, so no longer highlighting tile
					self.mousePressed = False
					#No need for text; no tile selected
					self.displayTextObject.destroy()
					self.createPath(self.start, self.end)
					self.gold -= self.iceTowerCost
					if self.displayGameInfoNode1 != None:
						self.displayGameInfoNode1.destroy()
					self.displayGameInfoNode.destroy()
					self.displayGameInfo()
		
#*************************UI Display*************************
	def displayText(self):
		text = "Row: " + str(self.currentRow)+\
			" Col: " + str(self.currentCol) +\
			"\nPress to build       ' a '  Arrow Tower" +\
			"       ' f '  Fire Tower"+\
			"       ' i '  Ice Tower"
		self.displayTextObject = OnscreenText(
								text=text, 
								pos = (0.005, 0.95), 
								scale = (0.05),
								bg = (209/255.0, 168/255.0, 132/255.0, 1),
								frame = (1, 0, 0, 1)
											  )
	def displayError(self, text):
		text = text
		self.displayTextObject = OnscreenText(
								text=text, 
								pos = (0.005, 0.91), 
								scale = (0.1),
								bg = (209/255.0, 168/255.0, 132/255.0, 1),
								frame = (1, 0, 0, 1)
											  )
	def displayBuildTime(self, time):
		text = "Next wave"
		self.displayNextWave = OnscreenText(
								text=text, 
								pos = (1.05, 0.91), 
								scale = (0.06),
								bg = (209/255.0, 168/255.0, 132/255.0, 1),
								frame = (1, 0, 0, 1)
											  )
		self.currentBuildTimeInt = int(time)
		text = str(self.currentBuildTimeInt)
		self.displayNextWaveTime = OnscreenText(
								text=text, 
								pos = (1.0485, 0.69), 
								scale = (0.2253),
								bg = (209/255.0, 168/255.0, 132/255.0, 1),
								frame = (1, 0, 0, 1)
											  )
	def displayGameInfo(self):
		text = "Level: " + str(self.level) + "\n" +\
			   "Gold:  " + str(self.gold) + "\n" +\
			   "Lives: " + str(self.lives)
		self.displayGameInfoNode = OnscreenText(
									text=text,
									pos = (-1.3, 0.88),
									scale = (0.09),
								bg = (209/255.0, 168/255.0, 132/255.0, 1),
									frame = (1, 0, 0, 1),
									align = TextNode.ALeft
												)
		#Has a value other than 0
		if self.fireTime == True:
			text = "Creep HP:   " + str(self.totalHp)
			self.displayGameInfoNode1 = OnscreenText(
										text=text,
										pos = (-1.12, 0.55),
										scale = (0.06),
								bg = (209/255.0, 168/255.0, 132/255.0, 1),
										frame = (1, 0, 0, 1)
													)
	def displayTowerInfo(self):
		text = "Arrow\nDmg: 10\nRate: 0.5s\nRange: 30\nCost: 10\n\n" +\
			   "Fire \nDmg: 7\nRate: 0.2s\nRange: 20\nCost: 25\n\n" +\
			   "Ice  \nDmg: 5\nRate: 0.5s\nRange: 25\nSlow: 60%\nCost: 30"
		self.displayTowerInfoNode = OnscreenText(
									text=text,
									pos = (-1.32, 0.0),
									scale = (0.05),
								bg = (209/255.0, 168/255.0, 132/255.0, 1),
									frame = (1, 0, 0, 1),
									align = TextNode.ALeft
												)
	def displayControls(self):
		text = "Select A Tile\n" +\
				"a - Arrow Tower\n" +\
				"f - Fire Tower\n" +\
				"i - Ice Tower\n" +\
				"q - quit"
		self.displayControlsNode = OnscreenText(
									text=text,
									pos = (.95, 0),
									scale = (0.05),
								bg = (209/255.0, 168/255.0, 132/255.0, 1),
									frame = (1, 0, 0, 1),
									align = TextNode.ALeft
												)
		
	def displayGameOver(self):
		text = "GAME OVER"
		self.displayGameOverNode = OnscreenText(
									text=text,
									pos = (0, 0),
									scale = (0.3),
									bg = (0, 0, 1, 1),
									frame = (1, 0, 0, 1)
												)
		sleep(1)
		sleep(5)
	def quit(self):
		sys.exit()
#********************* Spawn Creeps ************************
	def spawnWave(self, task):
		if self.interval < task.time:
			if len(self.creeps) < self.numberOfCreeps:
				self.spawnCreep()
				self.interval = task.time+1
			else:
				self.hasSpawnedWave = True
	def spawnCreep(self):
		if len(self.creeps) < self.numberOfCreeps:
			currentCreep = len(self.creeps)
			self.creeps.append(Creep(self, self.midPoints, currentCreep))
			self.creeps[currentCreep].spawn() #Most recently added creep
			self.creeps[currentCreep].move(self.pathSequence)
	#Checks to see if any creeps left
	def isCreeps(self):
		for creep in self.creeps:
			#Creep exists
			if creep:
				return True
		self.creeps = []
		return False

#********************* Level Handler ********************* 
	def levelUp(self):
		self.level += 1
		if self.displayGameInfoNode1 != None:
			self.displayGameInfoNode1.destroy()
		self.displayGameInfoNode.destroy()
		self.displayGameInfo()
Beispiel #6
0
class PointerSystem():
    """
        Handles user pointer (mouse) input. Contains information and
         functionality related to selecting and highlighting tiles.
    """
    def __init__(self, tileMap):
        self._tileMap = tileMap
        self._groundPlane = Plane(Point3(0, 0, 1), Point3(0, 0, 1))
        self._hoveredCoord = None  # The coordinates we are hovering over.
        self._highlightMode = None  # Targeter reference
        self._highlightModeParams = None  # Targeter params dict
        self._highlightedTiles = list()  # List of tile highlighted by pointer.
        self._previewTiles = list()  # List of tiles highlighted by preview.

        # Perform mouse raycasting every frame:
        taskMgr.add(self._updateHovered, "mouseScanning")

    def _updateHovered(self, task):
        """
            Updates the position of the Highlighter selector based on mouse
             position.
            Only updates if the value should change. Should not call every frame
             unless the user can shake his/her mouse really fast between tiles.
        """
        if base.mouseWatcherNode.hasMouse():  # If mouse is in the window:
            # Draw a line from the point on screen through the camera to the
            #  imaginary plane and check for intersections:
            mPos = base.mouseWatcherNode.getMouse()
            pos3D = Point3()  # Output stored here.
            nearPoint = Point3()
            farPoint = Point3()
            base.camLens.extrude(mPos, nearPoint, farPoint)  # Create a line
            # Check for intersection:
            if self._groundPlane.intersectsLine(
                    pos3D, render.getRelativePoint(base.cam, nearPoint),
                    render.getRelativePoint(base.cam, farPoint)):
                highlCoords = Point2D(int(pos3D.x), int(pos3D.y))
                # Ensure the calculated position is a valid tile:
                if self._hoveredCoord != highlCoords and\
                        self._tileMap.isFloor(highlCoords):
                    self._hoveredCoord = highlCoords
                    self._highlightTiles()
                elif self._hoveredCoord != None and\
                                         not self._tileMap.isFloor(highlCoords):
                    self._hoveredCoord = None
                    self._highlightTiles()
        return task.cont

    def setHighightMode(self, mode, params=None):
        """
            Sets the current method of highlighting nodes given a mode.
            Params allow for customizations specific to each mode, such as range
             or AOE size.
        """
        self._highlightMode = mode
        self._highlightModeParams = params
        # For special cases, show a preview highlight:
        if self._highlightMode == Targeter.SelfReachPosition:
            origin = self._highlightModeParams['origin']
            reach = self._highlightModeParams['reach']
            tiles = getAreaTiles(origin, self._tileMap, reach)
            self._highlightPreviewTiles(tiles)

    def resetHighlightMode(self):
        """
            Resets highlight mode to None and removes all highlighted tiles.
        """
        self._highlightMode = None
        self._highlightModeParams = dict()
        # Remove all previous highlights:
        while len(self._highlightedTiles) > 0:
            selector = self._highlightedTiles.pop(0)
            selector.destroy()
        while len(self._previewTiles) > 0:
            selector = self._previewTiles.pop(0)
            selector.destroy()

    def _highlightPreviewTiles(self, coordsList):
        """
            Preview highlights the given positions. Assumes valid positions.
        """
        # Remove all previous highlights:
        while len(self._previewTiles) > 0:
            selector = self._previewTiles.pop(0)
            selector.destroy()
        # Create new previewers for each position:
        count = 0
        for coord in coordsList:
            newHighlight = Selector("PreviewH %d" % count, PREVIEWER_TINT,
                                    True)
            newHighlight.showAt(coord)
            self._previewTiles.append(newHighlight)
            count += 1

    def _highlightTiles(self):
        """
            Highlights the tiles given by list of tile positions as highlighted
             by the player's pointer.
            Highlights in different ways depending on the highlightMode
        """
        # Remove all previous highlights:
        while len(self._highlightedTiles) > 0:
            selector = self._highlightedTiles.pop(0)
            selector.destroy()
        # Depending on the highlight mode, fill a list of highlighted positions:
        coordsList = list()  # List of Point2D()

        if self._highlightMode == Targeter.SelfPath and\
                                  self._hoveredCoord != None:
            # coordsList is the path to the tile from the current position.
            fromPos = self._highlightModeParams['origin']
            if self._hoveredCoord != fromPos:
                coordsList = findTilesFromTo(fromPos, self._hoveredCoord,
                                             self._tileMap)
        elif self._highlightMode == Targeter.SelfReachPosition and\
                                  self._hoveredCoord != None:
            if tileWithinRange(self._highlightModeParams['origin'],
                               self._highlightModeParams['reach'],
                               self._hoveredCoord):
                # Note, user is allowed to hit themselves!
                coordsList.append(self._hoveredCoord)

        if coordsList != None:
            count = 0
            for coord in coordsList:
                newHighlight = Selector("HighL %d" % count, HIGHLIGHTER_TINT)
                newHighlight.showAt(coord)
                self._highlightedTiles.append(newHighlight)
                count += 1

    def getHovered(self):
        return self._hoveredCoord