Beispiel #1
0
    //Корутина движения
    private IEnumerator Go()
    {
        if (alreadyCheat)
        {
            _gameCanvas.ShowInfoAboutEvent("Вы уже мухлевали на этом ходе :(");
            corutine = false;
            yield break;
        }

        bool tried = isCheating;

        yield return(new WaitUntil(() => isCheating == false));

        if (tried && isGonnaBeCathced)
        {
            if (Random.Range(0, 2) != 1)
            {
                NetworkGameController.aboutPlayer += "Игрок " + NickName + " не попался \n";
                alreadyCheat     = true;
                isGonnaBeCathced = false;
            }
            else
            {
                NetworkGameController.aboutPlayer += "Игрок " + NickName + " попался \n";
                corutine = false;
                _gameCanvas.gameObject.GetComponent <NetworkGameController>().cathedPlayer();
                yield break;
            }
        }
        else if (tried)
        {
            corutine = false;
            yield break;
        }


        bool endFirstStep           = false;
        int  num                    = way.Count;
        NetworkStreetPath somewhere = null;

        for (int i = 0; i < num; i++)
        {
            if (i != 0)
            {
                somewhere = _dbWork.GetPathById(way.Dequeue());
            }

            if (i == 0 && !endFirstStep)
            {
                somewhere = _dbWork.GetPathById(way.Dequeue());
                if (currentStreetPath.isBridge &&
                    (currentStreetPath.start.Equals(somewhere.start) ||
                     currentStreetPath.start.Equals(somewhere.end)))
                {
                    destination = currentStreetPath.start;
                    angle       = MapBuilder.Angle(transform.position, destination);
                    yield return(new WaitUntil(() => transform.position == destination));
                }
                else
                {
                    destination = currentStreetPath.end;
                    angle       = MapBuilder.Angle(transform.position, destination);
                    yield return(new WaitUntil(() => transform.position == destination));
                }

                endFirstStep = true;
                i--;
                continue;
            }

            if (i == num - 1)
            {
                destination = MapBuilder.GetCenter(somewhere.start, somewhere.end);
                angle       = MapBuilder.Angle(transform.position, destination);

                currentStreetPath = somewhere;
                yield return(new WaitUntil(() => transform.position == destination));
            }
            else
            {
                if (somewhere.isBridge && transform.position.Equals(somewhere.end))
                {
                    destination = somewhere.start;
                    angle       = MapBuilder.Angle(transform.position, destination);
                    yield return(new WaitUntil(() => transform.position == destination));
                }
                else
                {
                    destination = somewhere.end;
                    angle       = MapBuilder.Angle(transform.position, destination);
                    yield return(new WaitUntil(() => transform.position == destination));
                }
            }

            currentSteps++;
        }

        corutine = false;
        _gameCanvas.OnOffSavedButtons();
        if (tried && isGonnaBeCathced)
        {
            _gameCanvas.GetComponent <NetworkGameController>().nextStep();
        }
    }
    //открыть окно торговли с этим игроком
    public void onButtonClickTrade(int idPlayerSecond)
    {
        //открываем меню торговли
        ChangeMenu(4);
        //обновляем ссылку на дбворк
        _dBwork = getDbWork();
        //создаем список товаров на продажу
        NetworkTrade.CreateListThings(getCurrentPlayer(), _dBwork.GetPlayerbyId(idPlayerSecond));
        //вешаем скрипт на кнопку подтверждения предложения
        ApplyTrade.onClick.AddListener(() =>
                                       NetworkTrade.TradeApply(getCurrentPlayer(), _dBwork.GetPlayerbyId(idPlayerSecond), this, moneyFirstPlayer,
                                                               moneySecondPlayer));
        //назначаем имя первого игрока
        firstPlayer.GetComponentInChildren <Text>().text = getCurrentPlayer().NickName;
        //узнаем улицы первого игрока
        List <int> pathsFirstPlayer = _dBwork.GetMyPathes(getCurrentPlayer().IdPlayer);

        //если торгуем с другим игроком
        if (idPlayerSecond != getCurrentPlayer().IdPlayer)
        {
            //назначаем имя второго игрока
            secondPlayer.GetComponentInChildren <Text>().text = _dBwork.GetPlayerbyId(idPlayerSecond).NickName;

            //собираем список улиц первого игрока в первом скроле
            foreach (var path in pathsFirstPlayer)
            {
                //если улица заложена, то она не отображается доступной к продаже
                if (_dBwork.GetPathForBuy(path).IsBlocked)
                {
                    continue;
                }

                GameObject prefButton = Instantiate(prefButStreetForTrade);
                prefButton.GetComponentInChildren <Text>().text = _dBwork.GetPathById(path).namePath;
                prefButton.GetComponent <RectTransform>().SetParent(scrollFirstPlayerStreets.content, false);
                prefButton.GetComponent <Button>().onClick
                .AddListener(() =>
                             onButtonAddOrDeleteOfferStreet(prefButton, getCurrentPlayer(),
                                                            _dBwork.GetPlayerbyId(idPlayerSecond), path));
            }

            //создаем список улиц второго игрока
            List <int> pathsSecondPlayer = _dBwork.GetMyPathes(idPlayerSecond);

            //собираем список улиц второго игрока во втором скроле
            foreach (var path in pathsSecondPlayer)
            {
                //если улица заложена, то она не отображается доступной к продаже
                if (_dBwork.GetPathForBuy(path).IsBlocked)
                {
                    continue;
                }

                GameObject prefButton = Instantiate(prefButStreetForTrade);
                prefButton.GetComponentInChildren <Text>().text = _dBwork.GetPathById(path).namePath;
                prefButton.GetComponent <RectTransform>().SetParent(scrollSecondPlayerStreets.content, false);
                prefButton.GetComponent <Button>().onClick
                .AddListener(() =>
                             onButtonAddOrDeleteOfferStreet(prefButton, getCurrentPlayer(),
                                                            _dBwork.GetPlayerbyId(idPlayerSecond), path));
            }

            //отражаем максимальное количество денег первого игрока
            sliderMoneyFirst.maxValue = getCurrentPlayer().Money;
            //включаем слайдер первого игрока
            sliderMoneyFirst.gameObject.SetActive(true);
            //отражаем максимальное количество денег второго игрока
            sliderMoneySecond.maxValue = _dBwork.GetPlayerbyId(idPlayerSecond).Money;
            //включаем слайдер второго игрока
            sliderMoneySecond.gameObject.SetActive(true);

            //разрешаем заполнение игроком полей денег
            InputFieldMoneyFirst.gameObject.GetComponent <CanvasGroup>().interactable  = true;
            InputFieldMoneySecond.gameObject.GetComponent <CanvasGroup>().interactable = true;
        }
        //если открыли меню закладывания улиц
        else
        {
            //назначаем город вторым участником обмена
            secondPlayer.GetComponentInChildren <Text>().text = "Город";
            //Выключаем слайдеры
            sliderMoneyFirst.gameObject.SetActive(false);
            sliderMoneySecond.gameObject.SetActive(false);
            //запрещаем заполнение игроком полей денег
            InputFieldMoneyFirst.gameObject.GetComponent <CanvasGroup>().interactable  = false;
            InputFieldMoneySecond.gameObject.GetComponent <CanvasGroup>().interactable = false;

            //раскидываем улицы по скролам в зависимости от того заложены они или нет
            foreach (var path in pathsFirstPlayer)
            {
                GameObject prefButton = Instantiate(prefButStreetForTrade);
                prefButton.GetComponentInChildren <Text>().text = _dBwork.GetPathById(path).namePath;

                if (_dBwork.GetPathForBuy(path).IsBlocked)
                {
                    prefButton.GetComponent <RectTransform>().SetParent(scrollSecondPlayerStreets.content, false);
                }
                else
                {
                    prefButton.GetComponent <RectTransform>().SetParent(scrollFirstPlayerStreets.content, false);
                }

                prefButton.GetComponent <Button>().onClick
                .AddListener(() =>
                             onButtonAddOrDeleteOfferStreet(prefButton, getCurrentPlayer(),
                                                            getCurrentPlayer(), path));
            }
        }
    }
    //создание и заполнение карты, основываясь на данных из базы данных
    void Start()
    {
        NetworkDBwork data = Camera.main.GetComponent <NetworkDBwork>();

        data.OnSceneLoad();


        if (PhotonNetwork.isMasterClient)
        {
            NetworkStreetPath[] pathForBuys = data.GetAllPaths();
            for (int i = 1; i < pathForBuys.Length; i++)
            {
                GameObject newStreetPath = Instantiate(emptyStreet) as GameObject;
                newStreetPath.name = "StreetPath" + i;
                BoxCollider coll = newStreetPath.GetComponent <BoxCollider>();
                coll.size = new Vector3(GetVectorLength(pathForBuys[i].end - pathForBuys[i].start), 3, 8);

                if (pathForBuys[i].canBuy)
                {
                    newStreetPath.AddComponent <NetworkPathForBuy>();
                    newStreetPath.GetComponent <NetworkPathForBuy>().TakeData(data.GetPathForBuy(i));
                    newStreetPath.GetComponent <NetworkPathForBuy>().GetNeighbors();
                    data.updatePath(newStreetPath.GetComponent <NetworkPathForBuy>());
                }
                else
                {
                    newStreetPath.AddComponent <NetworkGovermentPath>();
                    newStreetPath.GetComponent <NetworkGovermentPath>().TakeData(data.GetGovermentPath(i));
                    if (newStreetPath.GetComponent <NetworkGovermentPath>().GetNameOfPrefab().Equals("Court"))
                    {
                        data.SetCourt(newStreetPath.GetComponent <NetworkGovermentPath>());
                    }
                    newStreetPath.GetComponent <NetworkGovermentPath>().GetNeighbors();
                    data.updatePath(newStreetPath.GetComponent <NetworkGovermentPath>());
                }
                newStreetPath.transform.rotation =
                    Quaternion.Euler(0f, Angle(pathForBuys[i].start, pathForBuys[i].end), 0f);
                newStreetPath.transform.position = GetCenter(pathForBuys[i].start, pathForBuys[i].end);
            }

            NetworkBuild[] builds = data.GetAllBuilds();

            for (int i = 1; i < builds.Length; i++)
            {
                GameObject newBuild = Instantiate(emptyBuild) as GameObject;
                newBuild.name = builds[i].NameBuild;

                newBuild.AddComponent <NetworkBuild>();
                newBuild.GetComponent <NetworkBuild>().TakeData(builds[i]);
                data.updateBuild(newBuild.GetComponent <NetworkBuild>());

                newBuild.transform.rotation = data.GetPathById(builds[i].IdStreetPath).transform.rotation;
                newBuild.transform.position = newBuild.GetComponent <NetworkBuild>().Place;
                newBuild.SetActive(newBuild.GetComponent <NetworkBuild>().Enable);
            }


            NetworkPlayer[] players = data.GetAllPlayers();

            for (int j = 1; j < players.Length; j++)
            {
                Debug.Log(players[j].NickName + "   " + players[j].isBot);
                int id1 = PhotonNetwork.AllocateViewID();
                if (!players[j].IsBot())
                {
                    GameObject newPlayer = Instantiate(emptyPlayer) as GameObject;
                    newPlayer.GetComponent <NetworkPlayer>().GetData(players[1]);
                    newPlayer.GetComponent <NetworkPlayer>().ViewId = id1;
                    newPlayer.transform.position = players[j].Destination;
                    data.updatePlayer(newPlayer.GetComponent <NetworkPlayer>());
                    transform.Find("/Town").GetComponent <Cameras>()
                    .SetCamera(newPlayer.GetComponentInChildren <Camera>());
                    newPlayer.GetComponent <PhotonView>().viewID = id1;
                }
                else
                {
                    GameObject newBot = Instantiate(emptyBot) as GameObject;
                    newBot.GetComponent <NetworkBot>().GetData(players[j]);
                    newBot.GetComponent <NetworkBot>().ViewId = id1;
                    newBot.transform.position = players[j].Destination;
                    data.updatePlayer(newBot.GetComponent <NetworkBot>());
                    newBot.GetComponent <PhotonView>().viewID = id1;
                }
            }

            data.createWays();
        }
        else
        {
            StartCoroutine(WaitForUpdate());
        }
    }
    //выбор ещё не активной вьюхи для отображения информации
    private void ChooseScrollView(ScrollRect scroll, int type, int idPath)
    {
        //idPath для зданий, для остальных он -1

        if (!scroll.IsActive())
        {
            scroll.gameObject.SetActive(true);
            //тип 1 - улицы
            switch (type)
            {
            case 1:
                CreateStreetsButtons();
                for (int index = 1; index < streetsPathsRectTransforms.Length; index++)
                {
                    RectTransform rectTransform = streetsPathsRectTransforms[index];
                    rectTransform.SetParent(scroll.content, false);

                    Debug.Log(rectTransform.GetSiblingIndex() + "     " + _dBwork.GetPathById(rectTransform.GetSiblingIndex()).NamePath);
                }

                //тип 2 - игроки
                break;

            case 2:
                CreatePlayersButtons();
                for (int index = 1; index < playersRectTransforms.Length; index++)
                {
                    RectTransform rectTransform = playersRectTransforms[index];
                    rectTransform.SetParent(scroll.content, false);
                }

                //тип 3 - здания
                break;

            case 3:
                CreateBuildsButtons(idPath);
                foreach (RectTransform rectTransform in buildsRectTransforms)
                {
                    rectTransform.SetParent(scroll.content, false);
                }

                break;
            }
        }
        else
        {
            if (type == 3 && currentPathB != idPath)
            {
                for (int i = scroll.content.childCount - 1; i >= 0; i--)
                {
                    Destroy(scroll.content.GetChild(i).gameObject);
                }

                CreateBuildsButtons(idPath);
                foreach (RectTransform rectTransform in buildsRectTransforms)
                {
                    rectTransform.SetParent(scroll.content, false);
                }
            }
            else
            {
                scroll.gameObject.SetActive(false);
                for (int i = scroll.content.childCount - 1; i >= 0; i--)
                {
                    Destroy(scroll.content.GetChild(i).gameObject);
                }
                //пока что корявнько так
                if (type == 1)
                {
                    ImportantInfoAboutStreetText.gameObject.SetActive(false);
                    ImportantInfoAboutStreetText.transform.parent.gameObject.SetActive(false);
                    buildsButton.gameObject.SetActive(false);
                }
            }


            CheckScrolls();
        }
    }
    IEnumerator WaitForUpdate()
    {
        NetworkDBwork data = Camera.main.GetComponent <NetworkDBwork>();

        while (!data.ready)
        {
            Debug.Log("Syncronization....");
            yield return(new WaitForSeconds(2f));
        }

        data.createWays();

        NetworkStreetPath[] pathForBuys = data.GetAllPaths();
        for (int i = 1; i < pathForBuys.Length; i++)
        {
            GameObject newStreetPath = Instantiate(emptyStreet) as GameObject;
            newStreetPath.name = "StreetPath" + i;
            BoxCollider coll = newStreetPath.GetComponent <BoxCollider>();
            coll.size = new Vector3(GetVectorLength(pathForBuys[i].end - pathForBuys[i].start), 3, 8);

            if (pathForBuys[i].canBuy)
            {
                newStreetPath.AddComponent <NetworkPathForBuy>();
                newStreetPath.GetComponent <NetworkPathForBuy>().TakeData(data.GetPathForBuy(i));
                newStreetPath.GetComponent <NetworkPathForBuy>().GetNeighbors();
                data.updatePath(newStreetPath.GetComponent <NetworkPathForBuy>());
            }
            else
            {
                newStreetPath.AddComponent <NetworkGovermentPath>();
                newStreetPath.GetComponent <NetworkGovermentPath>().TakeData(data.GetGovermentPath(i));
                if (newStreetPath.GetComponent <NetworkGovermentPath>().GetNameOfPrefab().Equals("Court"))
                {
                    data.SetCourt(newStreetPath.GetComponent <NetworkGovermentPath>());
                }
                newStreetPath.GetComponent <NetworkGovermentPath>().GetNeighbors();
                data.updatePath(newStreetPath.GetComponent <NetworkGovermentPath>());
            }
            newStreetPath.transform.rotation =
                Quaternion.Euler(0f, Angle(pathForBuys[i].start, pathForBuys[i].end), 0f);
            newStreetPath.transform.position = GetCenter(pathForBuys[i].start, pathForBuys[i].end);
        }

        NetworkBuild[] builds = data.GetAllBuilds();

        for (int i = 1; i < builds.Length; i++)
        {
            GameObject newBuild = Instantiate(emptyBuild) as GameObject;
            newBuild.name = builds[i].NameBuild;

            newBuild.AddComponent <NetworkBuild>();
            newBuild.GetComponent <NetworkBuild>().TakeData(builds[i]);
            data.updateBuild(newBuild.GetComponent <NetworkBuild>());

            newBuild.transform.rotation = data.GetPathById(builds[i].IdStreetPath).transform.rotation;
            newBuild.transform.position = newBuild.GetComponent <NetworkBuild>().Place;
            newBuild.SetActive(newBuild.GetComponent <NetworkBuild>().Enable);
        }


        NetworkPlayer[] players = data.GetAllPlayers();

        int  id1    = PhotonNetwork.AllocateViewID();
        bool hasOwn = false;

        for (int j = 1; j < players.Length; j++)
        {
            if (!players[j].IsBot())
            {
                GameObject newPlayer = Instantiate(emptyPlayer) as GameObject;
                newPlayer.GetComponent <NetworkPlayer>().GetData(players[j]);
                newPlayer.transform.position = players[j].Destination;
                newPlayer.transform.GetComponentInChildren <Camera>().gameObject.SetActive(false);
                data.updatePlayer(newPlayer.GetComponent <NetworkPlayer>());
                newPlayer.GetComponent <PhotonView>().viewID = players[j].ViewId;
            }
            else
            {
                if (!hasOwn)
                {
                    hasOwn = true;
                    GameObject newPlayer = Instantiate(emptyPlayer) as GameObject;
                    newPlayer.GetComponent <NetworkPlayer>().GetData(players[j], "newName" + id1);
                    newPlayer.transform.position = players[j].Destination;
                    data.updatePlayer(newPlayer.GetComponent <NetworkPlayer>());
                    newPlayer.GetComponent <PhotonView>().viewID = id1;
                    //TODO: заменить на имя зашедшего игрока
                    GetComponent <PhotonView>().RPC("ReplaceBotWithPlayer", PhotonTargets.Others, j, id1, "newName" + id1);
                }
                else
                {
                    GameObject newBot = Instantiate(emptyBot) as GameObject;
                    newBot.GetComponent <NetworkBot>().GetData(players[j]);
                    newBot.transform.position = players[j].Destination;
                    data.updatePlayer(newBot.GetComponent <NetworkBot>());
                    newBot.GetComponent <PhotonView>().viewID = players[j].ViewId;
                }
            }
        }
    }