Example #1
0
        public Game(InMatchTeam _homeTeam, InMatchTeam _awayTeam)
        {
            atBatSimulator = new AtBatSimulator();
            plateAppearanceSimulator = new PlateAppearanceSimulator();
            baseRunningBatSimulator = new BaseRunningSimulator();
            defensivePlaySimulator = new DefensivePlaySimulator();
            baseStealingSimulator = new BaseStealingSimulator();

            home = _homeTeam;
            away = _awayTeam;
            fieldState = new FieldState();
            gameLog = new GameLog();
            gameLog.startInning(currentInning, homeTeamAtBat);
        }
Example #2
0
        public Table(int numplay, String _playername, int initstack, GameControl game)
        {
            players = new List<Player>(2);
            cards = new List<Card>(5);
            carddeck = new CardDeck();

            players.Add(new Human(_playername, initstack, game));
            mainplayer = (Human)players[0];
            gamelog = new GameLog();

            players.Add(new AIPlayer("Аркадий", initstack, game));
            sblind = 2;
            roundnum = 1;
        }
Example #3
0
    // 处理接收Kcp数据包
    private void DealKcpUpdateAndReceive()
    {
        // kcp 更新 驱动KCPUpdate
        m_runningTime = (uint)(Util.GetCurrMilliSeconds() - m_kcpStartTime);
        lock (m_lockKcp)
            CKcp.KcpUpdate(m_kcp, m_runningTime);

        // kcp receive
        while (true)
        {
            byte[] data;
            int    rcvSize, peekSize = 0;
            lock (m_lockKcp)
            {
                peekSize = CKcp.KcpPeeksize(m_kcp);
                if (peekSize <= 0)
                {
                    break;
                }
                data    = m_buffers.Rent(peekSize);
                rcvSize = CKcp.KcpRecv(m_kcp, data, peekSize);
            }

            int headSize = data[0] * 256 + data[1] + 2;
            if (rcvSize != peekSize || rcvSize != headSize)
            {
                GameLog.LogWarningFormat("收到的包size验证失败,headSize+2:{0}, realSize:{1}, peekSize:{2}",
                                         headSize, rcvSize, peekSize);
                continue;
            }

            lock (m_lockRcv)
            {
                byte[] realData = new byte[rcvSize - 2];
                Array.Copy(data, 2, realData, 0, rcvSize - 2);
                GameLog.LogFormat("收到kcp处理后的包,放入待接收队列,size:{0}, data:{1}", rcvSize - 2, realData.ToHex());
                m_queueRcvData.Enqueue(realData);
            }
        }
    }
Example #4
0
    IEnumerator Start()
    {
        GameObject uiRoot = GameObject.Find("UIRoot");

        // 加载窗口
        GameLog.Log("加载游戏窗口");
        _gameWindowHandle = ResourceManager.Instance.LoadAssetAsync <GameObject>("UIPanel/GameWindow");
        yield return(_gameWindowHandle);

        _window = _gameWindowHandle.InstantiateObject;
        _window.transform.SetParent(uiRoot.transform, false);

        // 退出按钮
        var exitBtn = _window.transform.BFSearch("Exit").GetComponent <Button>();

        exitBtn.onClick.AddListener(OnClickExit);

        // 加载模型
        {
            GameLog.Log("加载模型");
            if (Demo.Instance.PlayLevel == 1)
            {
                _monsterHandle            = ResourceManager.Instance.LoadAssetAsync <GameObject>("Entity/Level1/footman_Blue");
                _monsterHandle.Completed += MonsterHandle_Completed;
            }
            else if (Demo.Instance.PlayLevel == 2)
            {
                _monsterHandle            = ResourceManager.Instance.LoadAssetAsync <GameObject>("Entity/Level2/footman_Green");
                _monsterHandle.Completed += MonsterHandle_Completed;
            }
            else if (Demo.Instance.PlayLevel == 3)
            {
                _monsterHandle            = ResourceManager.Instance.LoadAssetAsync <GameObject>("Entity/Level3/footman_Red");
                _monsterHandle.Completed += MonsterHandle_Completed;
            }
        }

        // 加载头像
        this.StartCoroutine(LoadPhotoAsync());
    }
Example #5
0
            public static void Execute(object obj, ElapsedEventArgs args)
            {
                try
                {
                    GameLog.Debug("Job starting");

                    var now = DateTime.Now.Ticks;
                    foreach (var mailbox in Game.World.WorldData.Values <Mailbox>().Where(mb => mb.Full))
                    {
                        try
                        {
                            mailbox.Lock();
                            mailbox.Cleanup();
                            mailbox.Unlock();
                        }
                        catch (MessageStoreLocked)
                        {
                            GameLog.ErrorFormat("{0}: mailbox locked during cleanup...?", mailbox.Name);
                        }
                    }
                    foreach (var board in Game.World.WorldData.Values <Board>().Where(mb => mb.Full))
                    {
                        try
                        {
                            board.Lock();
                            board.Cleanup();
                            board.Unlock();
                        }
                        catch (MessageStoreLocked)
                        {
                            GameLog.ErrorFormat("{0}: board locked during cleanup...?", board.Name);
                        }
                    }
                    GameLog.Debug("Job complete");
                }
                catch (Exception e)
                {
                    GameLog.Error("Exception occured in job:", e);
                }
            }
Example #6
0
        public static void BuildStandalonePlayer()
        {
            var outputPath =
                Path.Combine(Environment.CurrentDirectory,
                             "Build/" + GetPlatformName()
                             .ToLower()); //EditorUtility.SaveFolderPanel("Choose Location of the Built Game", "", "");

            if (outputPath.Length == 0)
            {
                return;
            }

            var levels = GetLevelsFromBuildSettings();

            if (levels.Length == 0)
            {
                GameLog.Log("Nothing to build.");
                return;
            }

            var targetName = GetBuildTargetName(EditorUserBuildSettings.activeBuildTarget);

            if (targetName == null)
            {
                return;
            }
#if UNITY_5_4 || UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0
            BuildOptions option = EditorUserBuildSettings.development ? BuildOptions.Development : BuildOptions.None;
            BuildPipeline.BuildPlayer(levels, path + targetName, EditorUserBuildSettings.activeBuildTarget, option);
#else
            var buildPlayerOptions = new BuildPlayerOptions {
                scenes                  = levels,
                locationPathName        = outputPath + targetName,
                assetBundleManifestPath = GetAssetBundleManifestFilePath(),
                target                  = EditorUserBuildSettings.activeBuildTarget,
                options                 = EditorUserBuildSettings.development ? BuildOptions.Development : BuildOptions.None
            };
            BuildPipeline.BuildPlayer(buildPlayerOptions);
#endif
        }
Example #7
0
        public static void TestReplayMatchesHashCode(Contexts origin, GameLog gamelog, ITestOutputHelper output)
        {
            output.WriteLine("========================================");

            uint targetTick       = origin.gameState.tick.value;
            long expectedHashCode = origin.gameState.hashCode.value;


            var input         = gamelog.InputLog;
            var contexts      = new Contexts();
            var commandBuffer = new CommandQueue();
            var world         = new Simulation(contexts, commandBuffer, new DefaultViewService());

            world.Start(1, gamelog.LocalActorId, gamelog.AllActorIds);

            foreach (var(_, tickCommands) in input)
            {
                foreach (var(tickId, allCommands) in tickCommands)
                {
                    foreach (var(actorId, commands) in allCommands)
                    {
                        commandBuffer.Enqueue(tickId, actorId, commands.ToArray());
                    }
                }
            }

            while (contexts.gameState.tick.value < targetTick)
            {
                var debugEntity = origin.debug.GetEntities().FirstOrDefault(entity => entity.tick.value == contexts.gameState.tick.value);
                if (debugEntity != null)
                {
                    debugEntity.hashCode.value.ShouldBe(contexts.gameState.hashCode.value);
                }

                world.Update(1000);
            }

            output.WriteLine("Checking hashcode: " + expectedHashCode);
            contexts.gameState.hashCode.value.ShouldBe(expectedHashCode);
        }
    IEnumerator Start()
    {
        GameObject uiRoot = GameObject.Find("UIRoot");

        GameLog.Log("加载大厅窗口");
        _lobbyWindowHandle = ResourceManager.Instance.LoadAssetAsync <GameObject>("UIPanel/LobbyWindow");
        yield return(_lobbyWindowHandle);

        GameObject window = _lobbyWindowHandle.InstantiateObject;

        window.transform.SetParent(uiRoot.transform, false);

        // 关卡按钮
        var level1Btn = window.transform.BFSearch("Level1Button").GetComponent <Button>();

        level1Btn.onClick.AddListener(OnClickLevel1);
        var level2Btn = window.transform.BFSearch("Level2Button").GetComponent <Button>();

        level2Btn.onClick.AddListener(OnClickLevel2);
        var level3Btn = window.transform.BFSearch("Level3Button").GetComponent <Button>();

        level3Btn.onClick.AddListener(OnClickLevel3);

        // 下载按钮
        PatchDownloader downloader = PatchManager.Instance.CreateDLCDownloader("level3", 1, 1);

        _downloadBtn  = window.transform.BFSearch("DownloadBtn").GetComponent <Button>();
        _downloadTips = window.transform.BFSearch("DownloadTips").GetComponent <Text>();
        if (downloader.TotalDownloadBytes == 0)
        {
            _downloadBtn.gameObject.SetActive(false);
        }
        else
        {
            _downloadBtn.onClick.AddListener(OnClickDownload);
        }

        // 加载原生文件
        this.StartCoroutine(LoadRawFile());
    }
Example #9
0
        public PartialViewResult Answer(Guid questionId, Guid answerId)
        {
            var gameState = Session["GameState"] as GamePlayState;

            var answer = QuizDb.Answers.SingleOrDefault(x => x.Id == answerId);
            var game   = QuizDb.QuizGames.SingleOrDefault(x => x.Id == gameState.Game.Id);
            var player = QuizDb.GamePlayers.SingleOrDefault(x => x.Id == gameState.Player.Id);

            var log = new GameLog();

            log.Answer      = answer;
            log.Game        = game;
            log.Player      = player;
            log.LogDateTime = DateTime.Now;

            QuizDb.GameLogs.Add(log);
            QuizDb.SaveChanges();

            // Update
            var statService = new StatisticsService(QuizDb);

            statService.NotifyUpdates();

            var questionToDelete = gameState.QuestionsLeft.SingleOrDefault(x => x.Id == answer.Question.Id);

            gameState.QuestionsLeft.Remove(questionToDelete);

            // jetzt die Antwort mit Ergebnis zurückschicken


            // die Frage
            // die Antwort
            var model = new QuestionAnswerViewModel();

            model.Answers       = gameState.CurrentQuestion.Answers;
            model.GivenAnswer   = answer;
            model.CorrectAnswer = questionToDelete.Answers.FirstOrDefault(x => x.IsCorrect);

            return(PartialView("_Answer", model));
        }
Example #10
0
    public static bool LoadIso(string path)
    {
        VArtifactData ISO;
        long          tick = System.DateTime.Now.Ticks;

        try
        {
            ISO = new VArtifactData();
            string fullpath = path;
            string filename = Path.GetFileNameWithoutExtension(fullpath);
            //TextAsset ta = Resources.Load(fullpath,typeof(TextAsset)) as TextAsset;
            using (FileStream fs = new FileStream(fullpath, FileMode.Open, FileAccess.Read))
            {
                byte[] iso_buffer = new byte[(int)(fs.Length)];
                //byte[] iso_buffer = ta.bytes;
                ulong guid = CRC64.Compute(iso_buffer);
                fs.Read(iso_buffer, 0, (int)(fs.Length));
                fs.Close();
                if (ISO.Import(iso_buffer, new VAOption(false)))
                {
                    isos[guid]          = ISO;
                    isoNameId[filename] = guid;
                    Debug.Log("loadIso Time: " + (System.DateTime.Now.Ticks - tick));
                    return(true);
                }
                else
                {
                    ISO = null;
                    return(false);
                }
            }
        }
        catch (Exception e)
        {
            Debug.LogError("Failed to load file " + path);
            GameLog.HandleIOException(e, GameLog.EIOFileType.InstallFiles);
            ISO = null;
            return(false);
        }
    }
Example #11
0
    public void Redirect(Redirect redirect, bool isLogoff = false, int transmitDelay = 0)
    {
        GameLog.InfoFormat("Processing redirect");
        GlobalConnectionManifest.RegisterRedirect(this, redirect);
        GameLog.InfoFormat("Redirect: cid {0}", this.ConnectionId);
        GameLog.Info($"Redirect EncryptionKey is {Encoding.ASCII.GetString(redirect.EncryptionKey)}");
        if (isLogoff)
        {
            GlobalConnectionManifest.DeregisterClient(this);
        }
        redirect.Destination.ExpectedConnections.TryAdd(redirect.Id, redirect);

        var endPoint = Socket.RemoteEndPoint as IPEndPoint;

        byte[] addressBytes;

        if (Game.RedirectTarget != null)
        {
            addressBytes = Game.RedirectTarget.GetAddressBytes();
        }
        else
        {
            addressBytes = IPAddress.IsLoopback(endPoint.Address) ? IPAddress.Loopback.GetAddressBytes() : Game.IpAddress.GetAddressBytes();
        }

        Array.Reverse(addressBytes);

        var x03 = new ServerPacket(0x03);

        x03.Write(addressBytes);
        x03.WriteUInt16((ushort)redirect.Destination.Port);
        x03.WriteByte((byte)(redirect.EncryptionKey.Length + Encoding.ASCII.GetBytes(redirect.Name).Length + 7));
        x03.WriteByte(redirect.EncryptionSeed);
        x03.WriteByte((byte)redirect.EncryptionKey.Length);
        x03.Write(redirect.EncryptionKey);
        x03.WriteString8(redirect.Name);
        x03.WriteUInt32(redirect.Id);
        x03.TransmitDelay = transmitDelay == 0 ? 250 : transmitDelay;
        Enqueue(x03);
    }
Example #12
0
    public void SendCallback(IAsyncResult ar)
    {
        ClientState state = (ClientState)ar.AsyncState;
        Client      client;

        GameLog.DebugFormat($"EndSend: SocketConnected: {state.WorkSocket.Connected}, IAsyncResult: Completed: {ar.IsCompleted}, CompletedSynchronously: {ar.CompletedSynchronously}");

        try
        {
            SocketError errorCode;
            var         bytesSent = state.WorkSocket.EndSend(ar, out errorCode);
            if (!GlobalConnectionManifest.ConnectedClients.TryGetValue(state.Id, out client))
            {
                GameLog.ErrorFormat("Send: socket should not exist: cid {0}", state.Id);
                state.WorkSocket.Close();
                state.WorkSocket.Dispose();
                return;
            }

            if (bytesSent == 0 || errorCode != SocketError.Success)
            {
                GameLog.ErrorFormat("cid {0}: disconnected");
                client.Disconnect();
                throw new SocketException((int)errorCode);
            }
        }
        catch (SocketException e)
        {
            Game.ReportException(e);
            GameLog.Error($"Error Code: {e.ErrorCode}, {e.Message}");
            state.WorkSocket.Close();
        }
        catch (ObjectDisposedException)
        {
            //client.Disconnect();
            GameLog.Error($"ObjectDisposedException");
            state.WorkSocket.Close();
        }
        state.SendComplete.Set();
    }
Example #13
0
    IEnumerator AwakeRoutine()
    {
        FlatBuffersInitializer.Initialize(typeof(ProtocolInitializer).Assembly);
        MessageBuilder.Initialize();
        yield return(StartCoroutine(InitializeLog()));

        AppConfig appConfig = Singletons.Add <AppConfig>("Config/config.json");

        yield return(StartCoroutine(appConfig.Initialize()));

        Singletons.Add <CoexEngine>();

        if (!isHeadless)
        {
            UI.Instance.Show <SceneList>();
        }
        else
        {
            string   scene = null;
            string[] args  = Environment.GetCommandLineArgs();
            for (int i = 0; i < args.Length; ++i)
            {
                if (args[i] == "--scene" && i < args.Length - 1)
                {
                    scene = args[i + 1];
                    break;
                }
            }

            if (null != scene)
            {
                UnityEngine.SceneManagement.SceneManager.LoadScene(scene);
            }
            else
            {
                GameLog.Error("specify scene on command line, eg. --scene PacMan");
                Application.Quit();
            }
        }
    }
Example #14
0
 /// <summary>
 /// Confirm the exchange. Once both sides confirm, perform the exchange.
 /// </summary>
 /// <returns>Boolean indicating success.</returns>
 public void ConfirmExchange(User requestor)
 {
     if (_source == requestor)
     {
         GameLog.InfoFormat("Exchange: source ({0}) confirmed", _source.Name);
         _sourceConfirmed = true;
         _target.SendExchangeConfirmation(false);
     }
     if (_target == requestor)
     {
         GameLog.InfoFormat("Exchange: target ({0}) confirmed", _target.Name);
         _targetConfirmed = true;
         _source.SendExchangeConfirmation(false);
     }
     if (_sourceConfirmed && _targetConfirmed)
     {
         GameLog.Info("Exchange: Both sides confirmed");
         _source.SendExchangeConfirmation();
         _target.SendExchangeConfirmation();
         PerformExchange();
     }
 }
Example #15
0
    public void StartUpdate()
    {
        GameLog.Log("StartUpdate.Development:" + development);
#if UNITY_EDITOR
        if (development)
        {
            LoadModule.runtimeMode = false;
            StartCoroutine(LoadGameScene());
            return;
        }
#endif
        OnStart();

        if (_checking != null)
        {
            StopCoroutine(_checking);
        }

        _checking = Checking();

        StartCoroutine(_checking);
    }
    private void CreateDownloader()
    {
        PatchUpdater.Instance.CreateAutoDownloader();
        var downloader = PatchUpdater.Instance.AutoDownloader;

        // 如果下载列表为空
        if (downloader.TotalDownloadCount == 0)
        {
            GameLog.Log("Not found update web files.");
            PatchUpdater.Instance.Switch(EPatchStates.PatchDone);
        }
        else
        {
            GameLog.Log($"Found update web files : {downloader.TotalDownloadCount}");

            // 发现新更新文件后,挂起流程系统
            // 注意:开发者需要在下载前检测磁盘空间不足
            int  totalDownloadCount = downloader.TotalDownloadCount;
            long totalDownloadBytes = downloader.TotalDownloadBytes;
            PatchEventDispatcher.SendFoundUpdateFilesMsg(totalDownloadCount, totalDownloadBytes);
        }
    }
Example #17
0
    private void Update()
    {
        if (this.isDone)
        {
            return;
        }

        if (this.isPaused)
        {
            this._startTime     += this.GetTimeDelta();
            this._lastUpdateTime = this.GetWorldTime();
            return;
        }

        this._lastUpdateTime = this.GetWorldTime();

        if (this._onUpdate != null)
        {
            this._onUpdate(this.GetTimeElapsed());
        }

        GameLog.Log("{0},{1}", GetWorldTime(), GetFireTime());
        if (this.GetWorldTime() >= this.GetFireTime())
        {
            if (this._onComplete != null)
            {
                this._onComplete();
            }

            if (this.isLooped)
            {
                this._startTime = this.GetWorldTime();
            }
            else
            {
                this.isCompleted = true;
            }
        }
    }
Example #18
0
        public static void Execute(object obj, ElapsedEventArgs args)
        {
            try
            {
                GameLog.Debug("Job starting");
                foreach (var client in GlobalConnectionManifest.WorldClients)
                {
                    // Insert a "save client" message onto the queue for each client.
                    // We do this rather than sending a "checkpoint" message so we don't
                    // randomly have a packet occupying shitloads of CPU time blocking
                    // everything else.

                    World.ControlMessageQueue.Add(new HybrasylControlMessage(ControlOpcodes.SaveUser, client.Key));
                }
                GameLog.Debug("Job complete");
            }
            catch (Exception e)
            {
                Game.ReportException(e);
                GameLog.Error("Exception occured in job:", e);
            }
        }
Example #19
0
    public byte[] GetBytes()
    {
        var buffer = Encoding.ASCII.GetBytes(Name);

        GameLog.DebugFormat("buffer is {0} and Name is {1}", BitConverter.ToString(buffer), Name);

        // X quadrant, offset, Y quadrant, offset, length of the name, the name, plus a 64-bit(?!) ID
        var bytes = new List <Byte>();

        GameLog.DebugFormat("{0}, {1}, {2}, {3}, {4}, mappoint ID is {5}", XQuadrant, XOffset, YQuadrant,
                            YOffset, Name.Length, Id);

        bytes.Add((byte)XQuadrant);
        bytes.Add((byte)XOffset);
        bytes.Add((byte)YQuadrant);
        bytes.Add((byte)YOffset);
        bytes.Add((byte)Name.Length);
        bytes.AddRange(buffer);
        bytes.AddRange(BitConverter.GetBytes(Id));

        return(bytes.ToArray());
    }
Example #20
0
 public bool AddItem(string itemName, ushort quantity = 1)
 {
     if (CurrentItemCount < ItemLimit)
     {
         if (Items.ContainsKey(itemName))
         {
             Items[itemName] += quantity;
             GameLog.Info($"{itemName} [{quantity}] added to existing item in vault {OwnerGuid}");
         }
         else
         {
             Items.Add(itemName, quantity);
             GameLog.Info($"{itemName} [{quantity}] added as new item in vault {OwnerGuid}");
         }
         return(true);
     }
     else
     {
         GameLog.Info($"Attempt to add {itemName} [{quantity}] to vault {OwnerGuid}, but user doesn't have it?");
         return(false);
     }
 }
Example #21
0
 public void CheckHack()
 {
     if (Input.GetKeyDown(currentHackKey))
     {
         if (currentHackKey == hack.Last())
         {
             hacked ^= true;
             GameLog.Message($"hacked: {hacked}");
             cheating ^= true;
             GameLog.Message($"cheating: {cheating}");
             currentHackKey = hack[0];
         }
         else
         {
             currentHackKey = hack.Next(currentHackKey);
         }
     }
     else if (Input.anyKeyDown)
     {
         currentHackKey = hack[0];
     }
 }
Example #22
0
    private IEnumerator LoadPhotoAsync()
    {
        GameLog.Log("加载头像");
        if (Demo.Instance.PlayLevel == 1)
        {
            _photoHandle = ResourceManager.Instance.LoadAssetAsync <Sprite>("UITexture/Photos/eggs");
        }
        else if (Demo.Instance.PlayLevel == 2)
        {
            _photoHandle = ResourceManager.Instance.LoadAssetAsync <Sprite>("UITexture/Photos/apple");
        }
        else if (Demo.Instance.PlayLevel == 3)
        {
            _photoHandle = ResourceManager.Instance.LoadAssetAsync <Sprite>("UITexture/Photos/magic_fish");
        }

        yield return(_photoHandle);

        Image img = _window.transform.BFSearch("Photo").GetComponent <Image>();

        img.sprite = _photoHandle.AssetObject as Sprite;
    }
    // Start is called before the first frame update
    void Start()
    {
        GameLog.Log(Application.unityVersion);

        Type type = Type.GetType("Mono.Runtime");

        if (type != null)
        {
            MethodInfo displayName = type.GetMethod("GetDisplayName", BindingFlags.NonPublic | BindingFlags.Static);
            if (displayName != null)
            {
                GameLog.Log((displayName.Invoke(null, null)).ToString());
            }

            MethodInfo[] methods = type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
            for (int i = 0; i < methods.Length; i++)
            {
                MethodInfo m = methods[i];
                GameLog.Log((m.IsPublic ? "public " : (m.IsPrivate ? "private " : "")) + (m.IsStatic ? "static " : " ") + m.ReturnType.Name + " " + m.Name + " " + m.GetParameters().Length);
            }
        }
    }
Example #24
0
        public void UpdateAllManager()
        {
            if (pauseGame)
            {
                return;
            }
            float now = Time.unscaledTime;

            foreach (var info in mgrInfos)
            {
                float deltaTime = now - info.lastTick;
                info.active = deltaTime >= info.interval;
                if (info.active)
                {
                    info.deltaTime = deltaTime;
                    info.lastTick  = now;
                }
            }

            foreach (var info in mgrInfos)
            {
                if (!info.active)
                {
                    continue;
                }

                try
                {
                    info.manager.CommonUpdate();
                }
                catch (Exception ex)
                {
                    if (GameLog.EnableLog(GameLog.LV_DEV_ERROR))
                    {
                        GameLog.LogDevError(string.Format("UpdateAllManager {0} Error {1}", info.managerName, ex));
                    }
                }
            }
        }
Example #25
0
        public override Task <BooleanMessageReply> ResetPassword(ResetPasswordRequest request, ServerCallContext context)
        {
            try
            {
                if (Game.World.WorldData.TryGetAuthInfo(request.Username, out AuthInfo login))
                {
                    // Simple length check
                    if (request.NewPassword.Length > 8 || request.NewPassword.Length < 4)
                    {
                        return(Task.FromResult(new BooleanMessageReply()
                        {
                            Message = "Passwords must be between 4 and 8 characters",
                            Success = false
                        }));
                    }

                    login.PasswordHash = BCrypt.Net.BCrypt.HashPassword(request.NewPassword,
                                                                        BCrypt.Net.BCrypt.GenerateSalt(12));
                    login.LastPasswordChange     = DateTime.Now;
                    login.LastPasswordChangeFrom = context.Peer;
                    login.Save();
                }
                else
                {
                    return(Task.FromResult(new BooleanMessageReply()
                    {
                        Message = "Unknown user", Success = false
                    }));
                }
            }
            catch (Exception e)
            {
                GameLog.UserActivityError("grpc: ResetPassword: unknown exception {e}", e);
            }
            return(Task.FromResult(new BooleanMessageReply()
            {
                Message = "Unknown error", Success = false
            }));
        }
Example #26
0
    private void OnPlayerActorCreated(HeroActor actor, bool isFriend)
    {
        m_cameraManager.SetWorldCameraPosition(actor.transform.position);
        m_cameraManager.SetWorldCameraTarget(actor.transform);

        //m_joystick.axisX.directTransform = actor.transform;//todo 这个控制会比较舒服吗?

        m_PlayerActor = actor;
        m_PlayerUnit  = actor.battleEntity;
        var skillIDs = m_PlayerUnit.GetSkillList();

        if (skillIDs == null || skillIDs.Count < 4)
        {
            GameLog.LogError("OnPlayerActorCreated player配置的技能列表少于4个!id : " + m_PlayerUnit.GetID().ToString());
            return;
        }

        var prefab     = (GameObject)UI["MobaSkillItem"];
        var nodeAttack = (RectTransform)UI["NodeAttack"];
        var nodeSkill1 = (RectTransform)UI["NodeSkill1"];
        var nodeSkill2 = (RectTransform)UI["NodeSkill2"];
        var nodeSkill3 = (RectTransform)UI["NodeSkill3"];

        m_MobaSkillItemMap = new Dictionary <AbilityCastType, MobaSkillItem>();
        List <RectTransform> parents = new List <RectTransform> {
            nodeAttack, nodeSkill1, nodeSkill2, nodeSkill3
        };
        List <AbilityCastType> castTypes = new List <AbilityCastType> {
            AbilityCastType.ATTACK, AbilityCastType.SKILL1, AbilityCastType.SKILL2, AbilityCastType.SKILL3
        };

        for (int i = 0; i < 4; i++)
        {
            var castType = castTypes[i];
            var item     = GenerateOne(typeof(MobaSkillItem), prefab, parents[i]) as MobaSkillItem;
            item.Init(castType, m_PlayerUnit.GetAbility(castType), OnFingerDown, OnFingerDrag, OnFingerUp);
            m_MobaSkillItemMap.Add(castType, item);
        }
    }
Example #27
0
        /// <summary>
        /// Process all the given status ticks for a creature's active statuses.
        /// </summary>
        public void ProcessStatusTicks()
        {
            foreach (var kvp in _currentStatuses)
            {
                GameLog.DebugFormat("OnTick: {0}, {1}", Name, kvp.Value.Name);

                if (kvp.Value.Expired)
                {
                    var removed = RemoveStatus(kvp.Key);
                    GameLog.DebugFormat($"Status {kvp.Value.Name} has expired: removal was {removed}");
                }

                if (kvp.Value.ElapsedSinceTick >= kvp.Value.Tick)
                {
                    kvp.Value.OnTick();
                    if (this is User)
                    {
                        (this as User).SendStatusUpdate(kvp.Value);
                    }
                }
            }
        }
        public GameLog GameLogFor(
            string season,
            string playerName,
            string position    = "",
            bool sendToConsole = true)
        {
            if (!string.IsNullOrEmpty(position) && position == "KK")
            {
                position = "K";
            }
            var model = new PlayerReportModel
            {
                Season     = season,
                PlayerName = playerName,
                Position   = position
            };

            if (position == "K")
            {
                model.GameLog = _repo.GetKickerStats(model);
            }
            else
            {
                model.GameLog = _repo.GetGameStats(model);
            }

            if (sendToConsole)
            {
                _repo.SendToConsole(
                    model);
            }

            var gameLog = new GameLog
            {
                GameStatsList = model.GameLog
            };

            return(gameLog);
        }
Example #29
0
        // Start is called before the first frame update
        private async void Start()
        {
            var view = await viewSystem.OpenScreen <DemoListView>(listModel);

            var resourcePanel = await viewSystem.OpenScreen <DemoResourcePanelScreen>(resourceModel);

            listModel.AddTo(this);
            resourceModel.AddTo(this);

            listModel.Add.Do(x => GameLog.Log($"ADD NEW Demo List Item")).
            Do(x => this.itemsCounter++).
            Subscribe(x => CreateItemViewModel()).
            AddTo(this);

            listModel.ListItems.ObserveRemove().
            Do(x => x.Value.Dispose()).
            Subscribe().
            AddTo(this);

            view.Show();
            resourcePanel.Show();
        }
        public void Build(ViewsSettings settings)
        {
            addressableAssetSettings = AddressableAssetSettingsDefaultObject.Settings;

            if (settings.isActive == false)
            {
                return;
            }

            proceedViews.Clear();

            if (!settings)
            {
                GameLog.LogError($"EMPTY UiManagerSettings on UiAssemblyBuilder.Build");
                return;
            }

            Reset(settings);

            var skinsFolders   = settings.uiViewsSkinFolders;
            var defaultFolders = settings.uiViewsDefaultFolders;
            var groupName      = string.IsNullOrEmpty(settings.sourceName) ?
                                 settings.name : settings.sourceName;

            if (skinsFolders.Count > 0)
            {
                var views = LoadUiViews <IView>(skinsFolders);
                views.ForEach(x => AddView(settings, x, false, groupName));
            }

            if (defaultFolders.Count > 0)
            {
                var views = LoadUiViews <IView>(defaultFolders);
                views.ForEach(x => AddView(settings, x, true, groupName));
            }

            settings.MarkDirty();
        }
Example #31
0
    public void LoadSpawns(Map map)
    {
        if (map.SpawnDirectives?.Spawns == null)
        {
            return;
        }

        var spawnlist = new List <Xml.Spawn>();

        foreach (var spawn in map.SpawnDirectives.Spawns)
        {
            // This references another group
            if (!string.IsNullOrEmpty(spawn.Import))
            {
                if (Game.World.WorldData.TryGetValue(spawn.Import, out Xml.SpawnGroup group))
                {
                    // TODO: make recursive; this only supports one level of importing for now
                    spawnlist.AddRange(group.Spawns.Where(x => string.IsNullOrEmpty(x.Import)).ToList());
                    GameLog.SpawnInfo($"Map {map.Name}: imported {spawn.Import} successfully");
                }
                else
                {
                    GameLog.SpawnWarning($"Map {map.Name}: spawn import {spawn.Import} not found");
                }
            }
            else // Direct reference to a creature spawn
            {
                spawnlist.Add(spawn);
            }
        }
        if (string.IsNullOrEmpty(map.SpawnDirectives.Name))
        {
            map.SpawnDirectives.Name = SpawnMapKey(map.Id);
        }
        map.SpawnDirectives.Spawns = spawnlist;
        map.SpawnDirectives.MapId  = map.Id;
        Spawns.TryAdd(map.SpawnDirectives.Name, map.SpawnDirectives);
    }
Example #32
0
        public IEnumerator Initialize()
        {
            yield return(GameInitializer.Instance.StartCoroutine(BytesReader.Read(mConfigFileName, bytes =>
            {
                if (null == bytes)
                {
                    #if UNITY_EDITOR_WIN || UNITY_STANDALONE
                    File.WriteAllText(
                        Path.Combine(Application.streamingAssetsPath, mConfigFileName),
                        JsonUtility.ToJson(Instance, true),
                        Encoding.UTF8);
                    #endif
                    GameLog.ErrorFormat("Read Config {0} Failed", mConfigFileName);
                }
                else
                {
                    // NOTE(llisper): detect BOM mark
                    // http://stackoverflow.com/questions/26101859/why-is-file-readallbytes-result-different-than-when-using-file-readalltext
                    string json;
                    if (bytes.Length > 3 &&
                        bytes[0] == 0xEF &&
                        bytes[1] == 0xBB &&
                        bytes[2] == 0xBF)
                    {
                        json = Encoding.UTF8.GetString(bytes, 3, bytes.Length - 3);
                    }
                    else
                    {
                        json = Encoding.UTF8.GetString(bytes);
                    }
                    JsonUtility.FromJsonOverwrite(json, Instance);
                }
            })));

            StringBuilder log = new StringBuilder("AppConfig:\n");
            LogConfig(log, "AppConfig", this);
            GameLog.Info(log.ToString());
        }
Example #33
0
 public static GameLog GetInstance() { 
     if(null==_instance)
           _instance=new GameLog();
     return _instance;
 
 }
Example #34
0
        private void PostCombatResolving(Attack attack, GameLog gameLog, string defenderName,
            string attackerName, TimeSpan ts)
        {
            gameLog.Title = "Combat report: " + defenderName + " versus " + attackerName;
            gameLog.Timestamp = ts.TotalMilliseconds.ToString();

            // Deaths:
            if (attack.Target != null)
            {
                attack.Target.GameLogs.Add(gameLog);
                HandleCasualties(attack, attack.Target);
            }
            if (attack.Attacker != null)
            {
                attack.Attacker.GameLogs.Add(gameLog);
                HandleCasualties(attack, attack.Attacker);
            }
        }
Example #35
0
        private void calculateBattle(Attack attack)
        {
            rand = new Random();

            DateTime now = DateTime.UtcNow;
            TimeSpan ts = new TimeSpan(now.Ticks - startTime.Ticks);

            string defenderName = "";
            string attackerName = "";
            List<Combatant> attackers;
            List<Combatant> defenders;
            var gameLog = new GameLog();

            defenders = SetupAttackAndDefense(attack, ref defenderName, ref attackerName, out attackers);

            gameLog.Defenders = defenders.Select(d=> d.DescriptionShort).ToList();
            gameLog.Attackers = attackers.Select(a => a.DescriptionShort).ToList();

            int counter = 0;

            while (attackers.Count != 0 && defenders.Count != 0)
            {
                counter++;
                var defenseturn = new Turn(counter);
                var attackturn = new Turn(counter);

                gameLog.AttackTurns.Add(attackturn);
                gameLog.DefenseTurns.Add(defenseturn);

                combatantTurnMove(attackturn, attackers, defenders);
                combatantTurnMove(defenseturn, defenders, attackers);

                if (defenders.Count != 0)
                {

                    Actions(attackturn, attackers, defenders);

                    Actions(defenseturn, defenders, attackers);

                    if (counter == 10)
                    {
                        break;
                    }
                }
            }

            if (defenders.Count == 0)
                gameLog.Victor = "The attackers are victorious!";
            else
                gameLog.Victor = "The defenders are victorious!";

            // Damages:
            foreach (Combatant surviver in defenders)
            {
                if (surviver is Leader)
                {
                    int exp = 0;
                    exp += surviver.Kills * 12;
                    exp += surviver.DamageDealt / 12;
                    ((Leader)surviver).LeaderExp += exp;
                    break;
                }
            }

            PostCombatResolving(attack, gameLog, defenderName, attackerName, ts);
        }