public void CanExecute()
        {
            //arrange
            var gameRecord = new GameRecord
            {
                Id = Guid.NewGuid(),
                Moves = new[]{
                    new GameMoveRecord
                    {
                        X = 0,
                        Y = 0
                    }
                },
            };

            var repoMock = new Mock<IRepository>();
            repoMock.Setup(x => x.Query<GameRecord>()).Returns(new[] { gameRecord }.AsQueryable());
            repoMock.Setup(x => x.Update(It.IsAny<GameMoveRecord>())).Callback((object y) =>
            {
                var updateItem = y as GameMoveRecord;

                Assert.IsNotNull(updateItem);
                Assert.AreEqual(0, updateItem.Value);
            })
            .Verifiable();

            var command = new MakeMove(gameRecord.Id, 0, 0, 0);
            var handler = new MakeMoveHandler(repoMock.Object);

            //act
            handler.Execute(command);

            //assert
            repoMock.VerifyAll();
        }
Пример #2
0
    public virtual GameRecordMessage GameRecord(GameRecord game)
    {
        GameRecordMessage msg = new GameRecordMessage();

        msg.Game    = game;
        msg.Factory = this;

        return(msg);
    }
Пример #3
0
    // callback for gameplay events
    public void OnGameRecord(GameRecord record)
    {
        AudioClip playMe = null;

        Debug.Log("PLAY-BY-PLAY: " + record.ToString());

        switch (record.tag) // which kind of event was it?
        {
        case GameRecordTag.BotDied:
            playMe = onDieClips[quipCounter % onDieClips.Count];
            break;

        case GameRecordTag.BotFlipped:
            playMe = onHitClips[quipCounter % onHitClips.Count];
            break;

        case GameRecordTag.BotJointBroke:
            playMe = onHitClips[quipCounter % onHitClips.Count];
            break;

        case GameRecordTag.GameEnemyDeclared:
            playMe = introClips[quipCounter % introClips.Count];
            break;

        case GameRecordTag.GameFinished:
            playMe = outroClips[quipCounter % outroClips.Count];
            break;

        case GameRecordTag.GamePlayerDeclared:
            playMe = introClips[quipCounter % introClips.Count];
            break;

        case GameRecordTag.GamePrepared:
            playMe = introClips[quipCounter % introClips.Count];
            break;

        case GameRecordTag.GameStarted:
            playMe = crowdClips[quipCounter % crowdClips.Count];
            break;

        case GameRecordTag.BotTookDamage:
            playMe = onHitClips[quipCounter % onHitClips.Count];
            break;
        }

        if (!myAudioSource.isPlaying && playMe)   // don't interrupt yourself
        {
            myAudioSource.PlayOneShot(playMe, announcerVolume.Value);
        }
        else
        {
            Debug.Log("PLAY-BY-PLAY: overlapping voiceover queued...");
            pendingClip = playMe;
        }

        quipCounter++; // so we don't get repeats
    }
Пример #4
0
 void ApplyHistory(History h)
 {
     _position = h.AgentPosition;
     _gameState = h.GetGameState(GameDef);
     _gameRecord = new GameRecord(h.GameRecord.ToGameString());
     _dealtCards = h.GetDealtCards();
     _gameHistoryId = h.GameHistoryId;
     ShowGameState();
 }
Пример #5
0
    //動作偵測結束後的關卡後續處理
    IEnumerator afterSelection(string select, int num)
    {
        if (num == NUMBER)
        {
            if (answer == target)
            {
                layout.correctFeedback(true);
                correct++;

                // 開啟正確回饋音效
                audio_manager.modifyVolumn(CORRECT_VOL, 2);
                audio_manager.play(AudioManager.AudioName.Correct, 2);

                game_record.end(GameItem.Correct, correct, ROUND);
            }
            else
            {
                layout.errorFeedback(true);
                audio_manager.modifyVolumn(WRONG_VOL, 2);
                audio_manager.play(AudioManager.AudioName.Wrong, 2);

                game_record.end(GameItem.Error, correct, ROUND);
            }
            yield return(new WaitForSeconds(YESNO_DISPLAY_TIME));
        }
        else
        {
            game_record.end(GameItem.None, correct, ROUND);
        }

        // 回饋出現 FEEDBACK_DISPLAY_TIME 秒
        yield return(new WaitForSeconds(FEEDBACK_DISPLAY_TIME));

        layout.correctFeedback(false);
        layout.errorFeedback(false);

        if (select == "left")
        {
            // 玩家原本選擇左邊,回饋結束後關閉右選項
            layout.showRightOption(false);
        }
        else if (select == "right")
        {
            // 玩家原本選擇右邊,回饋結束後關閉左選項
            layout.showLeftOption(false);
        }
        else
        {
            // 左右都未選,結束後關閉選項
            layout.showRightOption(false);
            layout.showLeftOption(false);
        }

        // reset game_record
        game_record = new GameRecord();
    }
Пример #6
0
 public void StartGame(GameRecord game, PlayerProfile perspective)
 {
     this.game          = game;
     this.perspective   = perspective;
     this.playerObjects = new Dictionary <PlayerProfile, GameObject> ();
     this.frame         = 0;
     this.eventHead     = 0;
     this.playing       = true;
     this.ServerChangeScene("GameScene");
 }
 public override void OnRefresh(int message, object param = null)
 {
     if (message == 1)
     {
         GameRecord r = param as GameRecord;
         Control("Screen").GetComponent <Image>().sprite  = r.LoadTexture();
         Control("RecordName").GetComponent <Text>().text = r.Name;
         OnCreateRoom();
     }
 }
Пример #8
0
    public void AddRecord(string name, int score)
    {
        CheckAddRecord();

        GameRecord tempRecord = new GameRecord();

        tempRecord.gameName.Value = name;
        tempRecord.score.Value    = score;
        recordList.Add(tempRecord);
    }
Пример #9
0
        public void Add(GameRecord gameRecord)
        {
            using (GameContext db = new GameContext())
            {
                db.Players.Attach(gameRecord.Player);
                db.GameRecords.Add(gameRecord);

                db.SaveChanges();
            }
        }
Пример #10
0
 /// <summary>
 /// Creates a new game. Quickly copies all game parameters to the own members.
 /// The game is started by Run().
 /// </summary>
 internal GameRunner(GameDefinition gameDefinition, List <PlayerData> gamePlayers,
                     GameRecord dealRecord)
 {
     _gameDef    = gameDefinition;
     _dealRecord = dealRecord;
     foreach (PlayerData gamePlayer in gamePlayers)
     {
         _players.Add(gamePlayer);
     }
 }
Пример #11
0
 public void AddRecord(GameRecord record)
 {
     gameRecords.Add(record);
     gameRecords.Sort((a, b) => b.Score - a.Score);
     if (gameRecords.Count > maxElements)
     {
         gameRecords.RemoveAt(maxElements);
     }
     persist();
 }
Пример #12
0
        public void Test_HideOpponentCards()
        {
            TransformGameRecords tr = new TransformGameRecords {
                HideOpponentCards = true, HeroName = "Agent"
            };
            GameRecord gr = new GameRecord("13; Agent{10 0.5 3} Opp{15 1 -3}; 0d{Ac Ad} 1d{Kc 2d} 0c 1r1 d{2h 3h 4h} 1c 0c d{Jh} 1c 0c d{Qd} 1c 0c.");

            Assert.IsTrue(tr.Transform(gr));
            Assert.AreEqual("13; Agent{10 0.5 3} Opp{15 1 -3}; 0d{Ac Ad} 1d{? ?} 0c 1r1 d{2h 3h 4h} 1c 0c d{Jh} 1c 0c d{Qd} 1c 0c.", gr.ToGameString());
        }
Пример #13
0
    private void SaveMiddleData()
    {
        GameRecord _gameRecord = new GameRecord(CreateNowTimeData(), subjectResult);

        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter _binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        System.IO.MemoryStream _memoryStream = new System.IO.MemoryStream();

        _binaryFormatter.Serialize(_memoryStream, _gameRecord);
        PlayerPrefs.SetString("MiddleData", Convert.ToBase64String(_memoryStream.GetBuffer()));
    }
Пример #14
0
        public void Test_ResetResults()
        {
            TransformGameRecords tr = new TransformGameRecords {
                ResetResults = true
            };
            GameRecord gr = new GameRecord("13; Agent{10 0.5 3} Opp{15 1 -3}; 0d{Ac Ad} 1d{Kc 2d} 0c 1r1 d{2h 3h 4h} 1c 0c d{Jh} 1c 0c d{Qd} 1c 0c.");

            Assert.IsTrue(tr.Transform(gr));
            Assert.AreEqual("13; Agent{10 0.5 0} Opp{15 1 0}; 0d{Ac Ad} 1d{Kc 2d} 0c 1r1 d{2h 3h 4h} 1c 0c d{Jh} 1c 0c d{Qd} 1c 0c.", gr.ToGameString());
        }
Пример #15
0
        public void Test_FinalizeGames()
        {
            TransformGameRecords tr = new TransformGameRecords {
                FinalizeGames = true
            };
            GameRecord gr = new GameRecord("13; Agent{10 0.5 3} Opp{15 1 -3}; 0d{Ac Ad} 1d{Kc 2d} 0c 1r1;");

            Assert.IsTrue(tr.Transform(gr));
            Assert.AreEqual("13; Agent{10 0.5 3} Opp{15 1 -3}; 0d{Ac Ad} 1d{Kc 2d} 0c 1r1.", gr.ToGameString());
        }
Пример #16
0
 public void LoadRecords()
 {
     Records = new GameRecord[maxNumOfRecords + 1];
     for (int i = 0; i < maxNumOfRecords; i++)
     {
         Records[i].Score     = PlayerPrefs.GetInt(PLAYER_PREFS_SCORE + i, 0);
         Records[i].TurnsTook = PlayerPrefs.GetInt(PLAYER_PREFS_TURNS_TOOK + i, 0);
         Records[i].Finished  = PlayerPrefs.GetInt(PLAYER_PREFS_FINSHED + i, 0) != 0;
     }
 }
Пример #17
0
        public void Test_RenameNeq()
        {
            TransformGameRecords tr = new TransformGameRecords {
                RenameNeqName = "Agent", RenameNeqNewName = "Enemy"
            };
            GameRecord gr = new GameRecord("13; Agent{10 0.5 3} Opp{15 1 -3}; 0d{Ac Ad} 1d{Kc 2d} 0c 1r1 d{2h 3h 4h} 1c 0c d{Jh} 1c 0c d{Qd} 1c 0c.");

            Assert.IsTrue(tr.Transform(gr));
            Assert.AreEqual("13; Agent{10 0.5 3} Enemy{15 1 -3}; 0d{Ac Ad} 1d{Kc 2d} 0c 1r1 d{2h 3h 4h} 1c 0c d{Jh} 1c 0c d{Qd} 1c 0c.", gr.ToGameString());
        }
Пример #18
0
        public void Test_RemoveNoShowdown()
        {
            TransformGameRecords tr = new TransformGameRecords {
                RemoveNoShowdown = true
            };
            GameRecord gr = new GameRecord("13; Agent{10 0.5 3} Opp{15 1 -3}; 0d{Ac Ad} 1d{Kc 2d} 0c 1r1 d{2h 3h 4h} 1c 0c d{Jh} 1c 0c d{Qd} 1c 0c.");

            Assert.IsTrue(tr.Transform(gr));
            gr = new GameRecord("16; Opp{10 0.5 3} Agent{15 1 -3}; 0d{Ac Ad} 1d{Kc 2d} 0r1 1r1 0f.");
            Assert.IsFalse(tr.Transform(gr));
        }
Пример #19
0
 // Use this for initialization
 void Awake()
 {
     btn = GetComponent <Button>();
     img = GetComponent <Image>();
     btn.onClick.AddListener(delegate() {
         OnClick();
     });
     money      = GameObject.Find("money_text").GetComponent <Text>();
     gameRecord = GameRecord.getInstance();
     InitState();
 }
Пример #20
0
        public void Test_ParseFinished()
        {
            string gameString =
                "125;FellOmen2{20 5 80} Probe{-40 10 0}; 0d{9s 8s} 1d{Qh Jd} 0r10 1r10 0r10 d{5c 8d 6s} 1c 0c d{Th} 1c 0c d{2s} 1c 0c.";

            string     error = "";
            GameRecord gr;

            gr = GameRecord.Parse(gameString, out error);
            Assert.IsNotNull(gr);
            Assert.AreEqual("125", gr.Id);
            Assert.IsTrue(gr.IsGameOver);
            Assert.AreEqual(2, gr.Players.Count);
            Assert.AreEqual("FellOmen2", gr.Players[0].Name);
            Assert.AreEqual(20, gr.Players[0].Stack);
            Assert.AreEqual(5, gr.Players[0].Blind);
            Assert.AreEqual(80, gr.Players[0].Result);
            Assert.AreEqual("Probe", gr.Players[1].Name);
            Assert.AreEqual(-40, gr.Players[1].Stack);
            Assert.AreEqual(10, gr.Players[1].Blind);
            Assert.AreEqual(0, gr.Players[1].Result);
            Assert.AreEqual(14, gr.Actions.Count);
            VerifyActionRecord(0, Ak.d, "9s 8s", 0, gr.Actions[0]);
            VerifyActionRecord(1, Ak.d, "Qh Jd", 0, gr.Actions[1]);
            VerifyActionRecord(0, Ak.r, "", 10, gr.Actions[2]);
            VerifyActionRecord(1, Ak.r, "", 10, gr.Actions[3]);
            VerifyActionRecord(0, Ak.r, "", 10, gr.Actions[4]);
            VerifyActionRecord(-1, Ak.d, "5c 8d 6s", 0, gr.Actions[5]);
            VerifyActionRecord(1, Ak.c, "", 0, gr.Actions[6]);
            VerifyActionRecord(0, Ak.c, "", 0, gr.Actions[7]);
            VerifyActionRecord(-1, Ak.d, "Th", 0, gr.Actions[8]);
            VerifyActionRecord(1, Ak.c, "", 0, gr.Actions[9]);
            VerifyActionRecord(0, Ak.c, "", 0, gr.Actions[10]);
            VerifyActionRecord(-1, Ak.d, "2s", 0, gr.Actions[11]);
            VerifyActionRecord(1, Ak.c, "", 0, gr.Actions[12]);
            VerifyActionRecord(0, Ak.c, "", 0, gr.Actions[13]);

            // Make sure r at the end is parsed correctly (can be mixed with floating point)
            gameString = ";P0{20 5 80}; 0r123.";
            error      = "";
            gr         = GameRecord.Parse(gameString, out error);
            Assert.IsNotNull(gr);
            Assert.IsTrue(gr.IsGameOver);
            Assert.AreEqual(1, gr.Actions.Count);
            VerifyActionRecord(0, Ak.r, "", 123, gr.Actions[0]);

            // Check a negative amount of call
            gameString =
                "1; Pl1{174.2 1 13.4} Pl2{14.4 2 -14.4}; 0d{5d 5s} 1d{Ts 8c} 0r2 1c-3.6.";

            error = "";
            gr    = GameRecord.Parse(gameString, out error);
            VerifyActionRecord(1, Ak.c, "", -3.6, gr.Actions[3]);
        }
Пример #21
0
        public void Test_RemoveNoHeroMoves()
        {
            TransformGameRecords tr = new TransformGameRecords {
                RemoveNoHeroMoves = true, HeroName = "Agent"
            };
            GameRecord gr = new GameRecord("13; Agent{10 0.5 3} Opp{15 1 -3}; 0d{Ac Ad} 1d{Kc 2d} 0c 1r1 d{2h 3h 4h} 1c 0c d{Jh} 1c 0c d{Qd} 1c 0c.");

            Assert.IsTrue(tr.Transform(gr));
            gr = new GameRecord("16; Opp{10 0.5 3} Agent{15 1 -3}; 0d{Ac Ad} 1d{Kc 2d} 0f.");
            Assert.IsFalse(tr.Transform(gr));
        }
Пример #22
0
            public int CompareTo(object obj)
            {
                GameRecord other = obj as GameRecord;

                if (other == null)
                {
                    return(1);
                }

                return(string.Compare(this.ToString(), other.ToString()));
            }
Пример #23
0
        private string GetBaseDeckName(GameRecord gr)
        {
            string deckName = gr.MyDeckName;

            if (gr.IsExpedition() && deckName[deckName.Length - 3] == '-')
            {
                // Remove record
                deckName = deckName.Substring(0, deckName.Length - 6);
            }
            return(deckName);
        }
 public ActionResult Create([Bind(Include = "id,name,location,firstHalf,secondHalf,date,team,ptsFor,ptsAgainst,coachID")] GameRecord gameRecord)
 {
     gameRecord.Coach = db.nonPlayers.Find(gameRecord.coachID);
     if (ModelState.IsValid)
     {
         db.GameRecords.Add(gameRecord);
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View());
 }
Пример #25
0
 private static bool RecordAuthentic(GameRecord sealedRecord)
 {
     if (sealedRecord.MD5Hash == MakeHash(sealedRecord))
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
Пример #26
0
        public void OnGet()
        {
            GameRecord gameRecord = _db.GameRecords
                                    .Include(x => x.BotRecords)
                                    .ThenInclude(x => x.Competitor)
                                    .OrderByDescending(x => x.GameDate)
                                    .FirstOrDefault();

            BotRankings    = gameRecord?.BotRecords ?? new List <BotRecord>();
            AllFullResults = new List <FullResults>();
        }
 public ActionResult Edit([Bind(Include = "id,name,location,firstHalf,secondHalf,date,team,ptsFor,ptsAgainst,coachID")] GameRecord gameRecord)
 {
     if (ModelState.IsValid)
     {
         db.Entry(gameRecord).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.coachID = new SelectList(db.nonPlayers, "id", "fName", gameRecord.coachID);
     return(View(gameRecord));
 }
Пример #28
0
    public void Show(GameRecord record)
    {
        _recordId   = record.RecordID;
        _title.text = record.RecordName;
        _InitHeroDatas(record.TeamRecord, record.HeroRecord);
        _SetTeamHeroes();
        _HideHeroDisplay();
        _Register();

        gameObject.SetActive(true);
    }
Пример #29
0
 public PlayerData(Dictionary <string, HeroData> heroes, Dictionary <int, string> teamHeroes, List <Item> items)
 {
     _gameRecord = GameUtility.Instance.GetCurGameRecord();
     Heroes      = heroes;
     foreach (var pair in teamHeroes)
     {
         TeamHeroes.Add(pair.Key, Heroes[pair.Value]);
     }
     BackPack = new Dictionary <int, Item>();
     AddItems(items);
     _CheckBackpackSize();
 }
Пример #30
0
 public CheckerboardControl(GameObject gameObject)
 {
     m_GameObject = gameObject;
     m_View       = new CheckerboardView(gameObject.transform);
     m_View.MoveAnimationFinished += OnAnimationFinish;
     m_View.TouchDropEvent        += OnTouchDropEvent;
     m_Model = new CheckerboardModel();
     m_View.PlayZoomAnimation(m_Model.NodeMatrix);
     m_GameRecord = new GameRecord();
     m_GameRecord.PushFrame(m_Model.NodeMatrix);
     SerializeUtil.DataSaveWithPath(m_GameRecord, PathUtil.CurrentRecordPath);
 } // end CheckerboardControl
Пример #31
0
 public void SetData(GameRecord record, ToggleGroup toggleGroup)
 {
     _recordId       = record.RecordID;
     _name.text      = record.RecordName;
     _time.text      = record.UpdateTime;
     _heroCount.text = record.HeroRecord.Count.ToString();
     _itemCount.text = record.ItemRecord.Count.ToString();
     _toggle.group   = toggleGroup;
     _toggle.onValueChanged.RemoveAllListeners();
     _toggle.onValueChanged.AddListener(_SelectElement);
     _toggle.isOn = false;
 }
        public void CannotExecute_AlreadyExists()
        {
            //arrange
            var gameRecord = new GameRecord
            {
                Id = Guid.NewGuid(),
            };

            var repoMock = new Mock<IRepository>();
            repoMock.Setup(x => x.Query<GameRecord>()).Returns(new[] { gameRecord }.AsQueryable());

            var command = new CreateGame(gameRecord.Id);
            var handler = new CreateGameHandler(repoMock.Object);

            //act
            handler.Execute(command);

            //assert
            Assert.Fail();
        }
Пример #33
0
        public void CanExecute()
        {
            //arrange
            var gameRecord = new GameRecord
            {
                Id = Guid.NewGuid(),
                Moves = new List<GameMoveRecord>(),
            };

            var repoMock = new Mock<IRepository>();
            repoMock.Setup(x => x.Query<GameRecord>()).Returns(new[] { gameRecord }.AsQueryable());

            var query = new LoadGame(gameRecord.Id);
            var handler = new LoadGameHandler(repoMock.Object);

            //act
            var result = handler.Execute(query);

            //assert
            Assert.IsNotNull(result);
        }
 /// <summary>
 /// Run game for the duration of MAX_GAME_RUN_TIME and of no problems arise, kill it. 
 /// Fail: game does not start or crashes
 /// OK: Game runs fone for MAX_GAME_RUN_TIME 
 /// After: Task.UpdateListed
 /// </summary>
 void ProcessRunGame(GameRecord record)
 {
     string gameExeName = "";
     foreach (string file in Directory.EnumerateFiles(
         record.Author, "*.exe", SearchOption.AllDirectories))
     {
         if (gameExeName == "")
         {
             gameExeName = file;
         }
         else
         {
             stateQueueMutex.WaitOne();
             string msg = "Multiple game exes for the game, using " + gameExeName;
             messageQueue.Enqueue(msg);
             detailedMessages[record.Author].Add(msg);
             stateQueueMutex.ReleaseMutex();
             break;
         }
     }
     if (gameExeName == "")
     {
         // No game to run. Skip to update.
         taskQueue.Add(new Tuple<GameRecord, Task>(record, Task.UpdateListed));
     }
     else
     {
         Task currentTask = Task.RunGame;
         Task nextTask = Task.UpdateListed;
         string command = String.Format("\"{0}\"", gameExeName);
         GenericProcessor(record, currentTask, nextTask, command, MAX_GAME_RUN_TIME);
     }
 }
    /// <summary>
    /// Update the files/folders in the record from svn. A new batch of tasks to update each is added to the queue.
    /// Fail: Does not update for some reason.
    /// OK: Updated w/o problems.
    /// After: Task.Compile
    /// </summary>
    void ProcessUpdateListed(GameRecord record)
    {
        Task currentTask = Task.UpdateListed;

        foreach (var toUpdate in record.ToFetch)
        {
            Task nextTask = Task.None;
            bool addRetry = false;
            // The success of the last update will determine if to try again or if to try and compile.
            if (toUpdate == record.ToFetch.Last())
            {
                nextTask = Task.Compile;
                addRetry = true;
            }
            string command = String.Format("\"{0}\" up \"{1}\"", SVN_CLI_EXE, Path.Combine(Directory.GetCurrentDirectory(), record.Author, toUpdate));
            GenericProcessor(record, currentTask, nextTask, command, -1, addRetry);
        }
    }
Пример #36
0
    private Status GenericProcessor(GameRecord record, Task currentTask, Task nextTask, string command, int runTimeout = -1, bool addRetry = true)
    {
        Status returnStatus = Status.NA;

        if (activeCliProcess == null)
        {
            stateQueueMutex.WaitOne();
            stateQueue.Enqueue(new Tuple<GameRecord, Task, Status>(record, currentTask, Status.Wait));
            stateQueueMutex.ReleaseMutex();

            // split
            string exepart = command.Substring(0, command.IndexOf(".exe\"") + 5);
            string argpart = command.Substring(command.IndexOf(".exe\"") + 5);

            activeCliProcess = new Process();
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.WindowStyle = ProcessWindowStyle.Hidden;

            startInfo.FileName = exepart;
            startInfo.Arguments = argpart;

            // TODO: Sfxr is quickhack, better to do it in a way that is settable in tools for settings.ini
            if (currentTask == Task.RunGame || exepart.Contains("sfxr"))
            {
                startInfo.WorkingDirectory = Path.GetDirectoryName(exepart.Replace('"', ' ').Trim());
            }

            /*
            startInfo.FileName = "cmd.exe";
            startInfo.Arguments = "/C "+command;
            */

            startInfo.CreateNoWindow = true;
            startInfo.UseShellExecute = false;
            startInfo.RedirectStandardError = true;
            startInfo.RedirectStandardInput = true;
            startInfo.RedirectStandardOutput = true;

            activeCliProcess.StartInfo = startInfo;
            // TODO: DEBUG. REMOVE!!
            //return Status.OK;

            activeCliProcess.Start();

            //messageQueueMutex.WaitOne();
            //messageQueue.Enqueue("Running command " + command);
            //messageQueueMutex.ReleaseMutex();

            if (runTimeout == -1)
            {
                activeCliProcess.WaitForExit();
            }
            else
            {
                activeCliProcess.WaitForExit(runTimeout);
            }
            // The --password option for svn.exe does not work, therefore send it using stdin
            if (currentTask == Task.CommitListed)
            {
                if (SettingsFromIni.SvnInteractivePassword!=null)
                    activeCliProcess.StandardInput.WriteLine(SettingsFromIni.SvnInteractivePassword);
                activeCliProcess.WaitForExit(runTimeout);
            }
        }
        if (activeCliProcess.HasExited)
        {
            // THIS is probably CMD.exe exitcode
            if (activeCliProcess.ExitCode == 0)
            {
                stateQueueMutex.WaitOne();
                messageQueue.Enqueue("Process exited with CODE 0.");

                if (currentTask == Task.CheckForModified)
                {
                    newAndModifiedFileNames = new List<string>();
                    newAndModifiedFileStates = new List<char>();
                }

                StreamReader sr = activeCliProcess.StandardOutput;
                while (!sr.EndOfStream)
                {
                    String s = sr.ReadLine();
                    if (s != "")
                    {
                        if (currentTask == Task.CheckForModified)
                        {
                            string[] parts = s.Split();
                            newAndModifiedFileNames.Add(s.Substring(s.IndexOf("C:\\")));
                            newAndModifiedFileStates.Add(parts.First()[0]);
                        }

                        Trace.WriteLine(s);
                        //messageQueue.Enqueue(s);
                    }
                }

                stateQueue.Enqueue(new Tuple<GameRecord, Task, Status>(record, currentTask, Status.OK));
                returnStatus = Status.OK;

                stateQueueMutex.ReleaseMutex();

                // TODO: Check if it was successfull, //  update light bulb state and
                if (nextTask != Task.None)
                    taskQueue.Enqueue(new Tuple<GameRecord, Task>(record, nextTask));
            }
            else
            {
                stateQueueMutex.WaitOne();
                messageQueue.Enqueue("Process exited with CODE 1.");

                StreamReader sro = activeCliProcess.StandardOutput;
                while (!sro.EndOfStream)
                {
                    String s = sro.ReadLine();
                    if (s != "")
                    {
                        Trace.WriteLine(s);
                        //messageQueue.Enqueue(s);
                    }
                }
                StreamReader sre = activeCliProcess.StandardError;
                while (!sre.EndOfStream)
                {
                    String s = sre.ReadLine();
                    if (s != "")
                    {
                        Trace.WriteLine(s);
                        //messageQueue.Enqueue(s);
                    }
                }

                stateQueue.Enqueue(new Tuple<GameRecord, Task, Status>(record, currentTask, Status.Fail));
                returnStatus = Status.Fail;

                stateQueueMutex.ReleaseMutex();

                if (addRetry)
                    taskQueue.Enqueue(new Tuple<GameRecord, Task>(record, currentTask));
            }
        }
        else
        {
            activeCliProcess.Kill();
            stateQueueMutex.WaitOne();
            messageQueue.Enqueue("Process killed");
            stateQueue.Enqueue(new Tuple<GameRecord, Task, Status>(record, currentTask, Status.OK));
            returnStatus = Status.OK;
            stateQueueMutex.ReleaseMutex();

            // TODO: Check if it was successfull, //  update light bulb state and
            if (nextTask != Task.None)
                taskQueue.Enqueue(new Tuple<GameRecord, Task>(record, nextTask));
        }
        activeCliProcess = null;

        return returnStatus;
    }
Пример #37
0
 void ProcessAddListed(GameRecord record)
 {
     Task currentTask = Task.AddListed;
     foreach (var toAdd in record.toProcess)
     {
         Task nextTask = Task.None;
         bool addRetry = false;
         string command = String.Format("\"{0}\" {1} add \"{2}\"", SettingsFromIni.SvnCliExePath, SettingsFromIni.SvnOptions, toAdd);
         GenericProcessor(record, currentTask, nextTask, command, -1, addRetry);
     }
 }
Пример #38
0
 private void _ToFirstAdventure(GameRecord record, Adventurer adv)
 {
     _StatusEvent(UserStatus.Adventure);
     var stage = new Regulus.Project.ExiledPrincesses.Game.Stage.Adventure(adv, _Binder, _Zone);
     stage.ToToneEvent += (tone) =>
     {
         _AccountInfomation.Record = record;
         _ToTown(tone);
     };
     _StageMachine.Push(stage);
 }
Пример #39
0
    private void ReadGameInfoAndSettings()
    {
        IniFile settingsFile = new IniFile("settings.ini");
        SettingsFromIni.SvnCliExePath = settingsFile.GetSetting("settings", "svn_cli_exe");
        SettingsFromIni.SvnOptions = settingsFile.GetSetting("settings", "svn_options");
        SettingsFromIni.SvnInteractivePassword = settingsFile.GetSetting("settings", "svn_passwd");
        SettingsFromIni.MsbuildExePath = settingsFile.GetSetting("settings", "msbuild_exe");
        SettingsFromIni.VCSExePath = settingsFile.GetSetting("settings", "vcs_exe");

        NumberOfToolsInIni = Int32.Parse(settingsFile.GetSetting("tools", "number_of_tools"));

        // 1 based indexing!
        for (int i = 1; i <= NumberOfToolsInIni; i++)
        {
            string prefix = String.Format("tool{0}_", i);
            tools.Add(new ContentTool()
            {
                ToolExe = settingsFile.GetSetting("tools", prefix + "add_content_exe"),
                TemplateFile = settingsFile.GetSetting("tools", prefix + "content_template_file"),
                ContentDescription = settingsFile.GetSetting("tools", prefix + "content_description"),
                ContentSubfolder = settingsFile.GetSetting("tools", prefix + "content_subfolder"),
                ContentExt = settingsFile.GetSetting("tools", prefix + "content_ext")
            });
        }

        // Game
        WorkshopGame = new GameRecord(){
            PupilGroupName=settingsFile.GetSetting("gameinfo","pupil_group_name"),
            GameName=settingsFile.GetSetting("gameinfo","game_name"),
            SVNRepo=settingsFile.GetSetting("gameinfo","repository_url"),
            toProcess=new List<string>(){"."}, // Root folder
            Solution=settingsFile.GetSetting("gameinfo","solution_file"),
            ContentFolder=settingsFile.GetSetting("gameinfo","content_folder"),
            TemplateFolder=settingsFile.GetSetting("gameinfo","template_folder")
        };
    }
    private Status GenericProcessor(GameRecord record, Task currentTask, Task nextTask, string command, int runTimeout = -1, bool addRetry = true)
    {
        string msg;
        Status returnStatus = Status.NA;
        if (activeCliProcess == null)
        {
            stateQueueMutex.WaitOne();
            stateQueue.Enqueue(new Tuple<GameRecord, Task, Status>(record, currentTask, Status.Wait));
            stateQueueMutex.ReleaseMutex();

            // split
            string exepart = command.Substring(0, command.IndexOf(".exe\"")+5);
            string argpart = command.Substring(command.IndexOf(".exe\"")+5);

            activeCliProcess = new Process();
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.WindowStyle = ProcessWindowStyle.Hidden;

            startInfo.FileName = exepart;
            startInfo.Arguments = argpart;

            /*
            startInfo.FileName = "cmd.exe";
            startInfo.Arguments = "/C "+command;
            */

            startInfo.CreateNoWindow = true;
            startInfo.UseShellExecute = false;
            startInfo.RedirectStandardError = true;
            startInfo.RedirectStandardOutput = true;

            activeCliProcess.StartInfo = startInfo;
            activeCliProcess.Start();

            //messageQueueMutex.WaitOne();
            //messageQueue.Enqueue("Running command " + command);
            //messageQueueMutex.ReleaseMutex();

            if (runTimeout == -1)
            {
                if (!activeCliProcess.WaitForExit(MAX_TIMEOUT))
                {
                    activeCliProcess.Kill();
                    stateQueueMutex.WaitOne();
                    msg = "Process timeout: killed.";
                    messageQueue.Enqueue(msg);
                    detailedMessages[record.Author].Add(msg);
                    stateQueueMutex.ReleaseMutex();
                    Thread.Sleep(200);
                }
            }
            else
            {
                activeCliProcess.WaitForExit(runTimeout);
            }
        }
        if (activeCliProcess.HasExited)
        {

            // THIS is probably CMD.exe exitcode
            if (activeCliProcess.ExitCode == 0)
            {
                stateQueueMutex.WaitOne();
                msg = "Process exited with CODE 0.";
                messageQueue.Enqueue(msg);
                detailedMessages[record.Author].Add("\n"+msg);

                StreamReader sr = activeCliProcess.StandardOutput;
                while (!sr.EndOfStream)
                {
                    String s = sr.ReadLine();
                    if (s != "")
                    {
                        Trace.WriteLine(s);
                        detailedMessages[record.Author].Add(s);
                    }
                }

                stateQueue.Enqueue(new Tuple<GameRecord, Task, Status>(record, currentTask, Status.OK));
                returnStatus = Status.OK;

                stateQueueMutex.ReleaseMutex();

                // TODO: Check if it was successfull, //  update light bulb state and
                if (nextTask != Task.None)
                    taskQueue.Insert(0, new Tuple<GameRecord, Task>(record, nextTask));
            }
            else
            {
                stateQueueMutex.WaitOne();
                msg = "Process exited with CODE 1.";
                messageQueue.Enqueue(msg);
                detailedMessages[record.Author].Add("\n" + msg);

                StreamReader sro = activeCliProcess.StandardOutput;
                while (!sro.EndOfStream)
                {
                    String s = sro.ReadLine();
                    if (s != "")
                    {
                        Trace.WriteLine(s);
                        detailedMessages[record.Author].Add(s);
                    }
                }
                StreamReader sre = activeCliProcess.StandardError;
                while (!sre.EndOfStream)
                {
                    String s = sre.ReadLine();
                    if (s != "")
                    {
                        Trace.WriteLine(s);
                        detailedMessages[record.Author].Add(s);
                    }
                }

                stateQueue.Enqueue(new Tuple<GameRecord, Task, Status>(record, currentTask, Status.Fail));
                returnStatus = Status.Fail;

                stateQueueMutex.ReleaseMutex();

                if (addRetry)
                    taskQueue.Add(new Tuple<GameRecord, Task>(record, currentTask));
            }
        }
        else
        {
            activeCliProcess.Kill();
            stateQueueMutex.WaitOne();
            msg = "Process killed as scheduled.";
            messageQueue.Enqueue(msg);
            detailedMessages[record.Author].Add(msg);
            stateQueue.Enqueue(new Tuple<GameRecord, Task, Status>(record, currentTask, Status.OK));
            returnStatus = Status.OK;
            stateQueueMutex.ReleaseMutex();

            // TODO: Check if it was successfull, //  update light bulb state and
            if (nextTask != Task.None)
                taskQueue.Add(new Tuple<GameRecord, Task>(record, nextTask));
        }
        activeCliProcess = null;

        return returnStatus;
    }
Пример #41
0
 void ProcessCheckModified(GameRecord record)
 {
     Task currentTask = Task.CheckForModified;
     Task nextTask = Task.ChooseFromModified;
     bool addRetry = false;
     string command = String.Format("\"{0}\" {1} status \"{2}\"", SettingsFromIni.SvnCliExePath, SettingsFromIni.SvnOptions, Path.Combine(Directory.GetCurrentDirectory(), record.PupilGroupName));
     GenericProcessor(record, currentTask, nextTask, command, -1, addRetry);
 }
Пример #42
0
    void ProcessChooseModified(GameRecord record)
    {
        List<string> shortSelectionLabels = new List<string>();
        string basePath = Path.Combine(Directory.GetCurrentDirectory(), record.PupilGroupName, record.ContentFolder);
        foreach (var fn in newAndModifiedFileNames)
        {
            int nameStartPos = fn.IndexOf(record.ContentFolder) + record.ContentFolder.Length;
            string shortfn = fn.Substring(nameStartPos);
            shortSelectionLabels.Add(shortfn);
        }
        shortSelectionLabels.Add("Peruuta");

        MultiSelectWindow selectToSendWindow = new MultiSelectWindow("Valitse peliin lisättävä tiedosto", shortSelectionLabels.ToArray());
        selectToSendWindow.BorderColor = Color.DarkGray;
        selectToSendWindow.ItemSelected += ModifiedFileSelected;
        selectToSendWindow.DefaultCancel = shortSelectionLabels.Count - 1;
        Add(selectToSendWindow);
    }
Пример #43
0
 void ProcessCommitListed(GameRecord record)
 {
     Task currentTask = Task.CommitListed;
     foreach (var toCommit in record.toProcess)
     {
         string userName = Environment.UserName;
         Task nextTask = Task.None;
         bool addRetry = false;
         string command = String.Format("\"{0}\" {1} commit \"{2}\" -m \"Automated commit by {3}\"", SettingsFromIni.SvnCliExePath, SettingsFromIni.SvnOptions, toCommit, userName);
         GenericProcessor(record, currentTask, nextTask, command, 3000, addRetry);
     }
 }
Пример #44
0
 /// <summary>
 /// Compile the .sln with msbuild.
 /// Fail: Does not compile for some reason.
 /// OK: Game compiles without error.
 /// After: Task.UpdateListed
 /// </summary>
 void ProcessCompile(GameRecord record)
 {
     Task currentTask = Task.Compile;
     Task nextTask = Task.None;
     string command = String.Format("\"{0}\" /nologo /noconlog \"{1}\"", SettingsFromIni.MsbuildExePath, Path.Combine(Directory.GetCurrentDirectory(), record.PupilGroupName, record.Solution));
     GenericProcessor(record, currentTask, nextTask, command);
 }
Пример #45
0
    /// <summary>
    /// Run game for the duration of MAX_GAME_RUN_TIME and of no problems arise, kill it. 
    /// Fail: game does not start or crashes
    /// OK: Game runs fone for MAX_GAME_RUN_TIME 
    /// After: Task.UpdateListed
    /// </summary>
    void ProcessRunGame(GameRecord record)
    {
        string gameExeName = "";
        foreach (string file in Directory.EnumerateFiles(
            record.PupilGroupName, "*.exe", SearchOption.AllDirectories))
        {
            if (file.Contains("bin"))
            {
                if (gameExeName == "")
                {

                    gameExeName = file;
                }
                else
                {
                    stateQueueMutex.WaitOne();
                    messageQueue.Enqueue("Multiple game exes for the game, using " + gameExeName);
                    stateQueueMutex.ReleaseMutex();
                    break;
                }
            }
        }
        if (gameExeName == "")
        {
            // No game to run. Skip to update.
            taskQueue.Enqueue(new Tuple<GameRecord, Task>(record, Task.UpdateListed));
        }
        else
        {
            Task currentTask = Task.RunGame;
            Task nextTask = Task.None;
            string command = String.Format("\"{0}\"", gameExeName);
            GenericProcessor(record, currentTask, nextTask, command);
        }
    }
Пример #46
0
 void ProcessRunTool(GameRecord record)
 {
     Task currentTask = Task.RunTool;
     Task nextTask = Task.None;
     string command = String.Format("\"{0}\" \"{1}\"", currentTool.ToolExe, fileToEdit);
     GenericProcessor(record, currentTask, nextTask, command);
 }
 /// <summary>
 /// Compile the .sln with msbuild.
 /// Fail: Does not compile for some reason.
 /// OK: Game compiles without error.
 /// After: Task.UpdateListed
 /// </summary>
 void ProcessCompile(GameRecord record)
 {
     Task currentTask = Task.Compile;
     Task nextTask = Task.RunGame;
     string command = String.Format("\"{0}\" /nologo /noconlog \"{1}\"", MSBUILD_EXE, Path.Combine(Directory.GetCurrentDirectory(), record.Author, record.Solution));
     GenericProcessor(record, currentTask, nextTask, command);
 }
Пример #48
0
        private Adventurer _BuildAdventurer(string map ,GameRecord record)
        {
            ActorInfomation[] actors = record.GetContingentActors();

            var teammates = (from actor in actors select new Teammate(actor)).ToArray();
            var adv = new Adventurer();
            adv.Map = map;
            adv.Teammates = teammates;
            adv.Formation = Contingent.FormationType.Auxiliary;
            adv.Controller = this;
            return adv;
        }
    void ProcessCheckoutRepo(GameRecord record)
    {
        // Directory existance implies existing checkout
        if (Directory.Exists(record.Author))
        {
            taskQueue.Add(new Tuple<GameRecord, Task>(record, Task.UpdateListed));
        }
        else
        {
            Directory.CreateDirectory(record.Author);
            Task currentTask = Task.Checkout;
            Task nextTask = Task.UpdateListed;
            string command = String.Format("\"{0}\" co {1} \"{2}\" --depth empty", SVN_CLI_EXE, record.SVNRepo, Path.Combine(Directory.GetCurrentDirectory(), record.Author));

            GenericProcessor(record, currentTask, nextTask, command);
        }
    }
Пример #50
0
 private GameRecord _BuildFirstRecord()
 {
     var record = new GameRecord();
     record.Actors = new ActorInfomation[] { new ActorInfomation() { Prototype = 1, Id = Guid.NewGuid(), Exp = 0} };
     var contingent = new Regulus.Project.ExiledPrincesses.Contingent();
     contingent.Formation = Regulus.Project.ExiledPrincesses.Contingent.FormationType.Auxiliary;
     contingent.Members = new Guid[] { record.Actors[0].Id };
     record.Contingent = contingent;
     return record;
 }
Пример #51
0
    void ProcessCheckoutRepo(GameRecord record)
    {
        // Directory existance implies existing checkout
        if (Directory.Exists(record.PupilGroupName))
        {
            taskQueue.Enqueue(new Tuple<GameRecord, Task>(record, Task.UpdateListed));
        }
        else
        {
            Directory.CreateDirectory(record.PupilGroupName);
            Task currentTask = Task.Checkout;
            Task nextTask = Task.UpdateListed;
            string command = String.Format("\"{0}\" {1} co {2} \"{3}\"", SettingsFromIni.SvnCliExePath, SettingsFromIni.SvnOptions, record.SVNRepo, Path.Combine(Directory.GetCurrentDirectory(), record.PupilGroupName));

            GenericProcessor(record, currentTask, nextTask, command);
        }
    }
Пример #52
0
    /// <summary>
    /// Update the files/folders in the record from svn. A new batch of tasks to update each is added to the queue.
    /// Fail: Does not update for some reason.
    /// OK: Updated w/o problems.
    /// After: Task.Compile
    /// </summary>
    void ProcessUpdateListed(GameRecord record)
    {
        Task currentTask = Task.UpdateListed;

        foreach (var toUpdate in record.toProcess)
        {
            Task nextTask = Task.None;
            bool addRetry = false;
            string command = String.Format("\"{0}\" {1} up \"{2}\"", SettingsFromIni.SvnCliExePath, SettingsFromIni.SvnOptions, Path.Combine(Directory.GetCurrentDirectory(), record.PupilGroupName, toUpdate));
            GenericProcessor(record, currentTask, nextTask, command, -1, addRetry);
        }
    }