Example #1
0
		/// <summary>
		/// Constructor fills in the menu contents.
		/// </summary>
		public GameOverScreen( GameResult gameResult )
			: base() {
			this.gameResult = gameResult;

			// start the title screen music
			AudioManager.PlayMusic( "Music_Win" );
		}
 private void Game_ResultChanged(ChessGame game, GameResult result)
 {
     string s = String.Empty;
     switch (result)
     {
         case GameResult.BlackCheckMate:
             s = "Black check mate";
             break;
         case GameResult.WhiteCheckMate:
             s = "White check mate";
             break;
         case GameResult.BlackKingTaken:
             s = "Black lost";
             break;
         case GameResult.WhiteKingTaken:
             s = "White lost";
             break;
         case GameResult.StaleMate:
             s = "Stale mate";
             break;
         case GameResult.BlackResigned:
             s = "Black resigned";
             break;
         case GameResult.WhiteResigned:
             s = "White resigned";
             break;
         case GameResult.Draw:
             s = "Draw";
             break;
     }
     if (s != String.Empty)
     {
         this.BoardForm.ShowResult(s);
     }
 }
Example #3
0
    protected string GetKnockedOutPlayerString(GameResult gameResult)
    {
        if (gameResult.KnockedOutBy == null)
            return string.Empty;

        return string.Format("knocked out by {0}", gameResult.KnockedOutBy.NickName);
    }
Example #4
0
        /// <summary>
        /// Generic elo algorithm
        /// </summary>
        public static void UpdateScores(ref int user1Rating, ref int user2Rating, GameResult result, int diff = 400, int kFactor = 10)
        {
            double est1 = 1 / Convert.ToDouble(1 + 10 ^ (user2Rating - user1Rating) / diff);
            double est2 = 1 / Convert.ToDouble(1 + 10 ^ (user1Rating - user2Rating) / diff);

            float sc1 = 0;
            float sc2 = 0;

            if (result == GameResult.Tie)
            {
                sc1 = 0.5f;
                sc2 = 0.5f;
            }
            else if (result == GameResult.WhiteWin)
            {
                sc1 = 1;
            }
            else if (result == GameResult.BlackWin)
            {
                sc2 = 1;
            }

            user1Rating = Convert.ToInt32(Math.Round(user1Rating + kFactor * (sc1 - est1)));
            user2Rating = Convert.ToInt32(Math.Round(user2Rating + kFactor * (sc2 - est2)));
        }
Example #5
0
	// Use this for initialization
	void Start ()
    {
        // Create a game result to send to the service
        GameResult result = new GameResult
        {
            GameId = GameClock.Instance.CurrentGameId,
            UserId = UserManager.Instance.Id,
            UserName = UserManager.Instance.Name,
            Score = ScoreManager.Instance.Score
        };

        // Serialize the game result into JSON
        string serializedResult = result.ToJson();

        // Setup HTTP request headers
        Dictionary<string, string> headers = new Dictionary<string, string>();
        headers.Add("Content-Type", "application/json");
        headers.Add("Content-Length", serializedResult.Length.ToString());
        headers.Add("X-ZUMO-APPLICATION", "tEtsHvgLHoRZKUATnELAkzCLWXARVl99");

        // Convert the serialized game result into a byte array
        byte[] body = Encoding.UTF8.GetBytes(serializedResult);

        WWW httpRequest = new WWW("http://blockparty.azure-mobile.net/tables/GameResult", body, headers);
        //WWW httpRequest = new WWW("http://localhost:49753/tables/GameResult", body, headers);
        StartCoroutine(OnHttpRequest(httpRequest));
    }
Example #6
0
 public void ProcessRequest(HttpContext context) {
     GameResult result = new GameResult();
     string m = context.Request.QueryString["method"];
     if (!string.IsNullOrEmpty(m)) {
         switch (m.ToLower()) {
             case "getranking"://获取排名
                 result = getRanking(context);
                 break;
             case "setscore":
                 result = setScore(context);
                 break;
             case "getscore":
                 result = getScore(context);
                 break;
             default:
                 result.errorCode = -1;
                 result.result = "不支持的方法调用!";
                 break;
         }
     } else {
         result.errorCode = -1;
         result.result = "不支持的方法调用!";
     }
     context.Response.ContentType = "application/json;charset=utf-8";            
     context.Response.Write(jsonHelper.Serialize(result));
     context.Response.End();
 }
        public async Task AddGame(GameResultModel gameModel)
        {
            using (var context = this.dbContext())
            {
                var game = new GameResult() { };
                game.InjectFrom(gameModel);

                if (gameModel.Hero != null)
                {
                    game.Hero = context.Heroes.Find(gameModel.Hero.Id);
                }

                if (gameModel.OpponentHero != null)
                {
                    game.OpponentHero = context.Heroes.Find(gameModel.OpponentHero.Id);
                }

                ArenaSessionModel arenaModel = null;
                ArenaSession arena = null;
                if (gameModel.ArenaSession != null)
                {
                    gameModel.Deck = null;
                    game.DeckKey = null;
                    game.Deck = null;

                    arenaModel = gameModel.ArenaSession;
                    arena = context.ArenaSessions.Query().FirstOrDefault(x => x.Id == arenaModel.Id);
                    if (arena == null)
                    {
                        throw new InvalidOperationException("Add arena using gameManager first!");
                    }
                    // context.Entry(arena).CurrentValues.SetValues(arenaModel);

                    AddGameToArena(game, arena);
                    SetEndDateIfNeeded(arena);
                    arena.Modified = DateTime.Now;
                }

                if (gameModel.Deck != null)
                {
                    game.Deck = context.Decks.Find(gameModel.Deck.Id);
                }

                context.Games.Add(game);

                await context.SaveChangesAsync();

                gameModel.InjectFrom(game);
                this.events.PublishOnBackgroundThread(new GameResultAdded(this, gameModel));
                if (arenaModel != null)
                {
                    arenaModel.InjectFrom(arena);
                    gameModel.ArenaSession = arenaModel;
                    arenaModel.Games.Add(gameModel);
                    var latestId = context.ArenaSessions.OrderByDescending(x => x.StartDate).Select(x => x.Id).FirstOrDefault();
                    this.events.PublishOnBackgroundThread(new ArenaSessionUpdated(arenaModel.Id, latestId == arenaModel.Id));
                }
            }
        }
Example #8
0
 /*
  * This method is called at the end of the game.
  *
  * Parameters:
  *     result - an instance of the GameResult class, which contains two boolean properties, Won and Invalid.
  *              The Invalid property is true if you lost because you sent an invalid command.
  */
 public void EndOfGame(GameResult result)
 {
     Console.WriteLine("End of game - " + (result.Won ? "Won!" : "Lost..."));
     if (result.Invalid)
     {
         Console.WriteLine("[WARNING] Invalid command");
     }
 }
 public GameStats(GameResult result, string opponentHero)
 {
     Coin = false;
     Result = result;
     GameMode = Game.GameMode.None;
     OpponentHero = opponentHero;
     StartTime = DateTime.Now;
     Logger.WriteLine("Started new game", "Gamestats");
     GameId = Guid.NewGuid();
 }
		public GameStats(GameResult result, string opponentHero, string playerHero)
		{
			Coin = false;
			Result = result;
			GameMode = GameMode.None;
			OpponentHero = opponentHero;
			PlayerHero = playerHero;
			StartTime = DateTime.Now;
			GameId = Guid.NewGuid();
		}
 public static double ToValue(GameResult result)
 {
     switch (result)
     {
         case GameResult.Loss: return 0;
         case GameResult.Draw: return 0.5;
         case GameResult.Win: return 1;
         default: throw new Exception();
     }
 }
Example #12
0
 /// <summary>
 /// Gets the game result representation and writes it using the writer.
 /// </summary>
 /// <param name="result">The result.</param>
 /// <returns>The game result representation.</returns>
 private string GetResultString(GameResult result)
 {
     switch (result)
     {
         case GameResult.White: return "1-0";
         case GameResult.Black: return "0-1";
         case GameResult.Draw: return "½-½";
     }
     return "*";
 }
Example #13
0
        private GameResult setScore(HttpContext context) {
            GameResult result = new GameResult();
            string data = context.Request.Params["data"];

            if (!string.IsNullOrEmpty(data)) {
                GameScore gs = null;
                try {
                   gs= Newtonsoft.Json.JsonConvert.DeserializeObject<GameScore>(data);
                
                
                } catch {

                }
                if (gs != null && !string.IsNullOrEmpty(gs.username)) {
                    lock (lockObj) {
                        List<GameScore> scoreList = ScoreList;
                        bool isupdate = false;
                        for (int i = scoreList.Count-1; i>=0 ; i--) {
                            if (gs.username == scoreList[i].username ) {
                                if (gs.score > scoreList[i].score) {
                                    scoreList.RemoveAt(i);
                                    break;
                                } else {
                                    return result;
                                }
                            }
                        }

                        for (int i = 0; i < scoreList.Count; i++) {
                            if (gs.score > scoreList[i].score) {
                                scoreList.Insert(i, gs);
                                dbGameHelper.Update(gs);
                                gs = null;
                                break;
                            }
                        }
                        if (gs != null) {
                            scoreList.Add(gs);
                            dbGameHelper.Update(gs);
                        }
                    }
                } else {
                    result.errorCode = -3;
                    result.result = "成绩提交格式非法!";
                }

            } else {

                result.errorCode = -3;
                result.result = "成绩提交格式非法!";
            }


            return result;
        }
Example #14
0
        public override GameResult GetResults()
        {
            GameResult r = new GameResult();

            r.IsSingleplayer = true;
            r.Time = time;
            r.Player1Score = playerOneField.GetScore;
            r.Difficulty = settings.Difficulty;

            return r;
        }
        private void EndGame(GameResult finalResult)
        {
            this.gameTimer.Stop();

            this.GameStatistics[Statistic.GameEndTime] = DateTime.Now;
            this.GameStatistics[Statistic.GameState] = finalResult;
            this.GameStatistics[Statistic.MinesRemaining] = this.Minesweeper.MinesRemaining;
            this.GameStatistics[Statistic.TimeElapsed] = this.Minesweeper.TimeElapsed;

            this.Settings.Statistics.Add(this.GameStatistics);
            this.Settings.Save();
        }
Example #16
0
 protected void CalculateScore(GameResult result)
 {
     switch (result)
     {
         case GameResult.Lose:
             PlayerTwo.Score++;
             break;
         case GameResult.Win:
             PlayerOne.Score++;
             break;
     }
 }
Example #17
0
        private void addButton_Click(object sender, EventArgs e)
        {
            GameResult newResult = new GameResult()
            {
                Difficulty = GameManager.Difficulty,
                Moves = GameManager.MovesCount,
                Time = GameManager.GameDuration
            };

            DatabaseManager.addResult(newResult, nameTextBox.Text);

            DialogResult = DialogResult.OK;
        }
 public EndGameWindow(GameResult gameStage)
 {
     InitializeComponent();
     switch (gameStage)
     {
             case GameResult.Won:
             this.Result.Text = "                      YOU WIN !!! \n                    WE ARE PROUD \n            OF YOUR BEER BELLY!!! :)";
             break;
             case GameResult.Lost:
             this.Result.Text = "     YOU   LOOSE :( \n      Next time try harder...";
             break;
     }
 }
Example #19
0
        public override GameResult GetResults()
        {
            GameResult r = new GameResult();

            r.IsSingleplayer = false;
            r.Player1Won = p1Won;
            r.Time = timePlayed;
            r.Player1Score = localPlayerField.GetScore;
            r.Player2Score = remotePlayerField.GetScore;
            r.Difficulty = settings.Difficulty;

            return r;
        }
Example #20
0
 public ResultsScreen(GameResult results, bool isNetwork)
 {
     this.results = results;
     this.isNetwork = isNetwork;
     backGroundImage = new Image();
     gameoverText = new Text();
     infoText = new Text();
     results = new GameResult();
     time = new Text();
     p1Score = new Text();
     p2Score = new Text();
     cursor = new Cursor();
 }
Example #21
0
 private void PrintResult(GameResult result)
 {
     switch(result)
     {
         case GameResult.Quit:
             this.CellData.Print(8, 1, "You've ended the game!", Color.White);
             break;
         case GameResult.Failed:
             this.CellData.Print(5, 1, "Your're have failed to Escape!", Color.White);
             break;
         case GameResult.Win:
             this.CellData.Print(5, 1, "You've Escaped the Castle!", Color.White);
             break;
     }
 }
        public ActionResult CreatePrediction(int id, GameResult gameResult)
        {
            string currentUserName = User.Identity.Name;
            ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.UserName == currentUserName);

            this.db.Predictions.Add(new Prediction
               {
                   GameId = id,
                   PredictedResult = gameResult,
                   User = currentUser,
               });

            this.db.SaveChanges();

            return Content(string.Format("<li>{0}: {1}</li>", currentUser.UserName, gameResult.ToPredictionString()));
        }
Example #23
0
 private static void DisplayWinner(Weapon computerChoice, GameResult result)
 {
     Console.Write("I chose " + computerChoice.ToString() + ". ");
     switch (result)
     {
         case (GameResult.ComputerWins):
             Console.Write("I win!");
             break;
         case (GameResult.UserWins):
             Console.Write("You win!");
             break;
         case (GameResult.Tie):
             Console.Write("I guess we're both winners!");
             break;
     }
     Console.WriteLine();
 }
Example #24
0
        private GameResult getScore(HttpContext context) {
            GameResult result = new GameResult();
            string username = context.Request.Params["username"];
            if (!string.IsNullOrEmpty(username)) {
                GameScore gs = new GameScore() { username = username };
                lock (lockObj) {
                    foreach (GameScore score in ScoreList) {
                        if (score.username == username) {
                            gs.score = score.score;
                            break;
                        }
                    }
                }
                result.data = jsonHelper.Serialize(gs);
            }

            return result;
        }
Example #25
0
        public void ShowGameSatgeView(GameResult gameStage)
        {
            var endGameWindow = new EndGameWindow(gameStage)
            {
                Height = AppSettings.WindowHeight,
                Width = AppSettings.WindowWidth,
                ResizeMode = ResizeMode.NoResize,
                WindowStartupLocation = WindowStartupLocation.CenterScreen,
                Background = new ImageBrush(new BitmapImage(new Uri(AppSettings.WindowBackgraund))),
                Icon = new BitmapImage(new Uri(AppSettings.WindowIcon))
            };
            endGameWindow.Show();

            foreach (Window window in Application.Current.Windows.Cast<Window>().Where(window => window.Title == "The Beer Belly Game"))
            {
                window.Close();
            }
        }
 public void ShowBalloon()
 {
     var gameResult = new GameResult
         {
             Hero = new Hero("mage")
                 {
                     Name = "Mage"
                 },
             OpponentHero = new Hero("mage")
                 {
                     Name = "Mage"
                 }
         };
     gameResult.Victory = true;
     var title = "New game tracked.";
     var vm = IoC.Get<GameResultBalloonViewModel>();
     vm.SetGameResult(gameResult.ToModel());
     events.PublishOnBackgroundThread(new TrayNotification(title, vm, 10000));
     throw new ArgumentNullException();
 }
 public GameFinishedEventArgs(IMinigame game, GameResult result)
 {
     Game   = game;
     Result = result;
 }
    public override void OnServerDisconnect(NetworkConnection conn)
    {
        if (conn.identity == null)
        {
            return;
        }
        var dcPlayer = conn.identity.GetComponent <PlayerNetworkControl>();

        if (dcPlayer == null)
        {
            return;
        }
        Debug.Log("Player: " + dcPlayer.slot + " quit the game");

        // remove player
        usedSlot[dcPlayer.slot] = false;
        players.Remove(dcPlayer.slot);

        // check for game state
        switch (state)
        {
        case GameState.PREPARE:
            // if game is not started yet then we do not need to do anything
            break;

        case GameState.STARTING:
            // if game is starting then mean there is already 2 players
            // we need reset game state back to Prepare
            CancelInvoke(nameof(OnUpdateCountDown));

            state            = GameState.PREPARE;
            sharedData.state = state;
            break;

        case GameState.STARTED:
            // if game is already started mean we need to cancel SpawnCandy and destroy all candy

            CancelInvoke(nameof(SpawnCandy));
            // destroy all canndies
            foreach (GameObject go in candies.Values)
            {
                NetworkServer.Destroy(go);
            }
            candies.Clear();

            // we show result screen with one winner and player quit reason
            var result = new GameResult();
            result.playerAPoint = dcPlayer.slot == "A" ? -1 : players["A"].points;
            result.playerBPoint = dcPlayer.slot == "B" ? -1 : players["B"].points;

            state                 = GameState.FINISHED;
            sharedData.state      = state;
            sharedData.gameTime   = 0;
            sharedData.gameResult = result;

            break;

        case GameState.FINISHED:
            // if game is finished mean all cancel callback and thing is done. we just need to check
            // if number player is zero then game reset back to Prepare
            if (numPlayers == 0)
            {
                state            = GameState.PREPARE;
                sharedData.state = state;
            }
            break;
        }

        base.OnServerDisconnect(conn);
    }
        //  Run once only
        //  Run on 17/12/2018

        /*public async Task AddDivisionsAsync()
         * {
         *
         *  var dataSources = new List<Division>()
         *  {
         *      new Division()
         *      {
         *
         *          DivisionName = "NL First Division 18/19",
         *          DivisionCode = "DIV1",
         *      },
         *      new Division()
         *      {
         *          DivisionName = "NL Second Division 18/19",
         *          DivisionCode = "DIV2"
         *      },
         *      new Division()
         *      {
         *          DivisionName = "NL Third Division 18/19",
         *          DivisionCode = "DIV3",
         *      }
         *  };
         *
         *  foreach (var item in dataSources)
         *  {
         *      await _wpbService.CreateDivisionAsync(item);
         *  }
         * }
         *
         * /// <summary>
         * /// Only need to run this function once
         * /// RUN COMPLETE
         * /// </summary>
         * /// <returns></returns>
         * public async Task GetFixturesDataAsync()
         * {
         *  //  Get all the fixtures dataSources
         *  var fixturesDataSource = await _wpbService.GetFixtureDataSources();
         *
         *  foreach (var src in fixturesDataSource)
         *  {
         *      var fixturesResults =
         *          ParseDataSource.ParseFixturesDataSource(src, src.ClassNameNode);
         *
         *      foreach (var ftr in fixturesResults)
         *      {
         *          try
         *          {
         *              //  get Home team details
         *              var teamHome = await _wpbService.GetTeamByTeamName(ftr.FixtureHomeTeamName);
         *              var teamAway = await _wpbService.GetTeamByTeamName(ftr.FixtureAwayTeamName);
         *
         *              if (teamHome != null && teamAway != null)
         *              {
         *                  var newFixture = new Fixture()
         *                  {
         *                      FixtureDate = ftr.FixtureDate,
         *                      HomeTeamId = teamHome.Id,
         *                      HomeTeamName = teamHome.TeamName,
         *                      HomeTeamCode = teamHome.TeamCode,
         *                      AwayTeamId = teamAway.Id,
         *                      AwayTeamName = teamAway.TeamName,
         *                      AwayTeamCode = teamAway.TeamCode,
         *                      //  already have the subdivision in both Home or Away team
         *                      SubDivisionId = teamHome.SubDivisionId
         *                  };
         *
         *                  //  Check for null values!!
         *                  await _wpbService.CreateFixtureAsync(newFixture);
         *              }
         *              else
         *              {
         *                  throw new System.ArgumentException(
         *                      "Detected null values in either teamHome, teamAway or subDivision variable!");
         *              }
         *          }
         *          catch (Exception err)
         *          {
         *              var msg = err.ToString();
         *          }
         *      }
         *  }
         *
         * }
         */

        public async Task GetMatchResultsAsync()
        {
            //  Get all the data sources for results
            var resultsDataSource = await _wpbService.GetAllResultDataSourceAsync();

            foreach (var result in resultsDataSource)
            {
                var matchResults =
                    ParseDataSource.ParseResultDataSource(result, result.ClassNameNode);

                foreach (var game in matchResults)
                {
                    try
                    {
                        var teamHome = await _wpbService.GetTeamByTeamName(game.HomeTeamName);

                        var teamAway = await _wpbService.GetTeamByTeamName(game.AwayTeamName);

                        if (teamHome != null && teamAway != null)
                        {
                            var winningTeam   = (game.WinningTeamName == teamHome.TeamName) ? teamHome : teamAway;
                            var encodedResult = EncodeGameResult(teamHome.TeamName, teamAway.TeamName, result.TimeStamp);

                            var newResult = new GameResult()
                            {
                                TimeStamp       = game.TimeStamp,
                                HomeTeamId      = teamHome.Id,
                                HomeTeamName    = teamHome.TeamName,
                                HomeTeamCode    = teamHome.TeamCode,
                                AwayTeamId      = teamAway.Id,
                                AwayTeamName    = teamAway.TeamName,
                                AwayTeamCode    = teamAway.TeamCode,
                                Score           = game.Score,
                                WinningTeamName = winningTeam.TeamName,
                                WinningTeamCode = winningTeam.TeamCode,
                                //  already have the subdivision in both Home or Away team
                                SubDivisionId = teamHome.SubDivisionId,
                                EncodedResult = encodedResult
                            };

                            var resultExist = await _wpbService.GameResultExistAsync(newResult.EncodedResult);

                            //  only add if not in db
                            if (resultExist == false)
                            {
                                await _wpbService.CreateGameResultAsync(newResult);
                            }
                        }
                        else
                        {
                            throw new System.ArgumentException(
                                      "Detected null values in either teamHome, teamAway or subDivision variable!");
                        }
                    }
                    catch (Exception err)
                    {
                        var msg = err.ToString();
                    }
                }
            }

            //  add new report tracker object
            var newReportRun = new ReportTracker()
            {
                ReportTypeCode = ModelHelpers.REPORT_RSLT
            };
            await _wpbService.CreateReportHistory(newReportRun);
        }
Example #30
0
 static bool TestWon(GameResult result, bool testPlayingWhite)
 {
     return((testPlayingWhite && result == GameResult.WhiteWin) ||
            (!testPlayingWhite && result == GameResult.BlackWin));
 }
 public override void ApplyEffect(GameResult gameResult, float dt)
 {
 }
        public static int[] EncodeGameResultAsArray(GameResult en)
        {
            var vals = Utilities.GetValues <GameResult>().Cast <int>();

            return(vals.Select(v => v == (int)en ? 1 : 0).ToArray());
        }
 public virtual void OnCollision(GameResult gameResult, IControlable collider)
 {
     weaponInfo.OnCollision(gameResult, collider);
 }
 private string GetReferenceToPlayer1(GameResult finalResultOfTheGame)
 {
     return((finalResultOfTheGame.Player1.PlayerType == GamePlayer.TypeOfPlayer.Human)
                         ? "You "
                         : "The player 1 ");
 }
 public virtual void OnCreation(GameResult gameResult, IControlable host)
 {
     this.host     = host;
     this.lifeTime = new LifeSpan(host.LifeTime);
 }
        public void OnAction(GameResult gameResult, float dt)
        {
            ShipStateChange cost;
            ActionResult    actionResult = new ActionResult(gameResult);

            if (activated && source.ShipState.MeetsCost(cost = (-costs.RunningCost * dt)) && AcquireTarget())
            {
                if (OnRunning(actionResult, dt))
                {
                    if (actionResult.ApplyCosts)
                    {
                        source.ShipState.Change(cost);
                    }
                    if (actionResult.PlaySound)
                    {
                        actionSounds.Running.Play(dt);
                    }
                }
                else
                {
                    activated = false;
                }
                return;
            }
            else if (Ready && source.ShipState.MeetsCost(cost = (-costs.ActivationCost)) && AcquireTarget())
            {
                if (OnActivated(actionResult, dt))
                {
                    if (actionResult.ResetDelay)
                    {
                        delay.Empty();
                    }
                    if (actionResult.ApplyCosts)
                    {
                        source.ShipState.Change(cost);
                    }
                    if (actionResult.PlaySound)
                    {
                        actionSounds.Activated.Play();
                    }
                    if (costs.RunningCost != null)
                    {
                        activated = true;
                    }
                }
                return;
            }
            else if (activated && costs.DeActivationCost != null && source.ShipState.MeetsCost(cost = (-costs.DeActivationCost)) && AcquireTarget())
            {
                if (OnDeActivated(actionResult, dt))
                {
                    if (actionResult.ApplyCosts)
                    {
                        actionSounds.DeActivated.Play();
                    }
                    if (actionResult.PlaySound)
                    {
                        source.ShipState.Change(cost);
                    }
                }
                activated = false;
                return;
            }
            activated = false;
        }
 public static void MapFrom(this GameResultModel target, GameResult source)
 {
     target.InjectFrom(source);
     target.ArenaSession = source.ArenaSession.ToModel();
 }
Example #38
0
 public void SetSplitResult(int playerNumber, GameResult result)
 {
     _splitResults[playerNumber - 1] = result;
 }
 public DeclareGameResultAction(PlayerModel localPlayer, PlayerModel dealer, GameResult result)
 {
     LocalPlayer = localPlayer;
     Dealer      = dealer;
     Result      = result;
 }
Example #40
0
 /// <summary>
 /// Initializes a <see cref="GameEndEntry"/>.
 /// </summary>
 /// <param name="result">The result.</param>
 public GameEndEntry(GameResult result)
     : base(MoveTextEntryType.GameEnd)
 {
     Result = result;
 }
Example #41
0
 /*
  * This method is called at the end of the game.
  *
  * Parameters:
  *     result - an instance of the GameResult enum, which can be GameResult.WON, GameResult.TIED or GameResult.LOST.
  */
 public void EndOfGame(GameResult result)
 {
     Console.WriteLine("End of game - " + result.ToString());
 }
 public void OnCreation(GameResult gameResult, IShip source, IAction actionSource)
 {
     this.weaponInfo.OnCreation(gameResult, this, source, actionSource);
 }
Example #43
0
        private void ProceedRound(int column, int row)
        {
            try
            {
                string s;
                /// Validation.
                if (column < 0 || column > 2 || row < 0 || row > 2)
                {
                    s = "Out of range. Please select again.";
                    MessageBox.Show(s, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    AppendLogToUI(s);
                    return;
                }
                int index = GetArrayIndexByPosition(column, row);
                if (MarkList.Contains(index))
                {
                    s = "This position is already filled. Please select the other.";
                    MessageBox.Show(s, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                /// Mark the position.
                MarkList.Add(index);
                MarkPosition(column, row);
                //char targetChar;
                //Color targetColor;
                //if (CurrentPlayer == Player.Player1)
                //{
                //    targetChar = Mark.Cross;
                //    targetColor = Color.Red;
                //}
                //else
                //{
                //    targetChar = Mark.Nough;
                //    targetColor = Color.Blue;
                //}
                //TlpGrid.Controls.Remove(TlpGrid.GetControlFromPosition(column, row));
                //TlpGrid.Controls.Add(new Label()
                //{
                //    ForeColor = targetColor,
                //    Font = new Font("Arial", 60, FontStyle.Bold),
                //    Dock = DockStyle.None,
                //    Anchor = AnchorStyles.None,
                //    TextAlign = ContentAlignment.MiddleCenter,
                //    AutoSize = true,
                //    Text = targetChar.ToString()
                //}, column, row);
                /// Analyze.
                GameResult gameResult = AnalyzeResult(MarkList);
                if (gameResult != GameResult.GameContinue)
                {
                    s = "";
                    switch (gameResult)
                    {
                    case GameResult.Player1Win:
                        s = "Player One Win !!!";
                        break;

                    case GameResult.Player2Win:
                        s = (GameMode)CbxMode.SelectedValue == GameMode.TwoPlayers ? "Player Two Win !!!" : "Computer Win !!!";
                        break;

                    case GameResult.Draw:
                        s = "Draw";
                        break;
                    }
                    AppendLogToUI(s);
                    MessageBox.Show(s, "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    InitializeGame();
                    return;
                }
                /// Round Result.
                s = "";
                if (CurrentPlayer == Player.Player1)
                {
                    CurrentPlayer = Player.Player2;
                    s             = (GameMode)CbxMode.SelectedValue == GameMode.TwoPlayers ? Helpers.EnumExtensionMethods.GetEnumDescription(CurrentPlayer) : "Computer turn.";
                }
                else
                {
                    CurrentPlayer = Player.Player1;
                    s             = Helpers.EnumExtensionMethods.GetEnumDescription(CurrentPlayer);
                }
                AppendLogToUI("{0} turn. Please mark a postion.", s);
                /// Computer decision.
                if (CurrentPlayer == Player.Player2 && (GameMode)CbxMode.SelectedValue == GameMode.VsComputer)
                {
                    int nextIndex = DecideByComputer(MarkList);
                    if (nextIndex < 1 && nextIndex > 9)
                    {
                        AppendLogToUI("Computer cannot decide.");
                        return;
                    }
                    int nextIndexm1 = nextIndex - 1;
                    ProceedRound(nextIndexm1 % 3, nextIndexm1 / 3);
                }
            }
            catch (Exception ex) { Logger?.Error(ex); }
        }
Example #44
0
        protected void End(GameResult result)
        {
            var msg = result.IsWin ? $"Winner: '{result.Winner}'" : "Draw";

            Console.WriteLine(msg);
        }
Example #45
0
 /// <summary>
 /// Called when a player wins a round. There can be more than one winner per round.
 /// </summary>
 /// <param name="player">The winning player</param>
 /// <param name="result">The winning player hand</param>
 protected override void OnDeclareWinner(Player player, GameResult result)
 {
     base.OnDeclareWinner(player, result);
     helper.OnDeclareWinner(player, result);
 }
Example #46
0
 private void ScoreKeeper_GameCompleted(string chapter, int level, int star, int score, GameResult result, bool dailyChallenge)
 {
     if (result == GameResult.ReachedTarget)
     {
         InvokeRepeating(nameof(ShootStar), 0f, GameSettings.StarShooterFreq);
     }
 }
 public void OnCreation(GameResult gameResult, IWeaponsLogic weaponInfo)
 {
     this.weaponInfo.OnCreation(gameResult, this, weaponInfo);
 }
 public override void OnCreation(GameResult gameResult, IControlable host)
 {
     this.lifeTime = new LifeSpan();
     this.host     = host;
     this.shipHost = host as IShip;
 }
Example #49
0
 public UpdateGameResultCommand(string matchId, GameResult result)
 {
     MatchId = matchId;
     Result = result;
 }
    public void LogNewRound(int roundNumber, Gesture?anotherPlayerChoise, Gesture?thisPlayerChoise, GameResult state)
    {
        var logInstance = Instantiate(roundIreItemViewPrefab).GetComponent <RoundItemView>();

        logInstance.UpdateItem(roundNumber, anotherPlayerChoise, thisPlayerChoise, state);
        logInstance.transform.SetParent(transform, false);

        var thisPlayerStep = Instantiate(stepPrefab);

        thisPlayerStep.SetStep(roundNumber, thisPlayerChoise);
        thisPlayerStep.transform.SetParent(thisPlayerStepsContainer, false);
        thisPlayerStep.transform.SetAsFirstSibling();

        var anotherPlayerStep = Instantiate(opponentStepPrefab);

        anotherPlayerStep.SetStep(roundNumber, anotherPlayerChoise);
        anotherPlayerStep.transform.SetParent(anotherPlayerStepsContainer, false);
        anotherPlayerStep.transform.SetAsFirstSibling();


        steps.Add(thisPlayerStep);
        steps.Add(anotherPlayerStep);

        var height = 75f * steps.Count / 2 + 7f;

        scrollContent.sizeDelta = new Vector2(scrollContent.sizeDelta.x, height);
        roundItemViews.Add(logInstance);
    }
 public void AddGameResult(GameResult result, string opponentHero)
 {
     Games.Add(new GameStats(result, opponentHero));
 }
        //returns a list of userIds and the amount of points they received/lost for the win/loss, and if the user lost/gained a rank
        //UserId, Points added/removed, rank before, rank modify state, rank after
        /// <summary>
        /// Retrieves and updates player scores/wins
        /// </summary>
        /// <returns>
        /// A list containing a value tuple with the
        /// Player object
        /// Amount of points received/lost
        /// The player's current rank
        /// The player's rank change state (rank up, derank, none)
        /// The players new rank (if changed)
        /// </returns>
        public List <(Player, int, Rank, RankChangeState, Rank)> UpdateTeamScoresAsync(Competition competition, Lobby lobby, GameResult game, Rank[] ranks, bool win, HashSet <ulong> userIds, Database db)
        {
            var updates = new List <(Player, int, Rank, RankChangeState, Rank)>();

            foreach (var userId in userIds)
            {
                var player = db.Players.Find(competition.GuildId, userId);
                if (player == null)
                {
                    continue;
                }

                //This represents the current user's rank
                var maxRank = ranks.Where(x => x.Points < player.Points).OrderByDescending(x => x.Points).FirstOrDefault();

                int             updateVal;
                RankChangeState state   = RankChangeState.None;
                Rank            newRank = null;

                if (win)
                {
                    updateVal = (int)((maxRank?.WinModifier ?? competition.DefaultWinModifier) * lobby.LobbyMultiplier);
                    if (lobby.HighLimit != null)
                    {
                        if (player.Points > lobby.HighLimit)
                        {
                            updateVal = (int)(updateVal * lobby.ReductionPercent);
                        }
                    }
                    player.Points += updateVal;
                    player.Wins++;
                    newRank = ranks.Where(x => x.Points <= player.Points).OrderByDescending(x => x.Points).FirstOrDefault();
                    if (newRank != null)
                    {
                        if (maxRank == null)
                        {
                            state = RankChangeState.RankUp;
                        }
                        else if (newRank.RoleId != maxRank.RoleId)
                        {
                            state = RankChangeState.RankUp;
                        }
                    }
                }
                else
                {
                    //Loss modifiers are always positive values that are to be subtracted
                    updateVal = maxRank?.LossModifier ?? competition.DefaultLossModifier;
                    if (lobby.MultiplyLossValue)
                    {
                        updateVal = (int)(updateVal * lobby.LobbyMultiplier);
                    }

                    player.Points -= updateVal;
                    if (!competition.AllowNegativeScore && player.Points < 0)
                    {
                        player.Points = 0;
                    }
                    player.Losses++;
                    //Set the update value to a negative value for returning purposes.
                    updateVal = -Math.Abs(updateVal);

                    if (maxRank != null)
                    {
                        if (player.Points < maxRank.Points)
                        {
                            state   = RankChangeState.DeRank;
                            newRank = ranks.Where(x => x.Points <= player.Points).OrderByDescending(x => x.Points).FirstOrDefault();
                        }
                    }
                }

                updates.Add((player, updateVal, maxRank, state, newRank));
                var oldUpdate = db.ScoreUpdates.FirstOrDefault(x => x.ChannelId == lobby.ChannelId && x.GameNumber == game.GameId && x.UserId == userId);
                if (oldUpdate == null)
                {
                    var update = new ScoreUpdate
                    {
                        GuildId      = competition.GuildId,
                        ChannelId    = game.LobbyId,
                        UserId       = userId,
                        GameNumber   = game.GameId,
                        ModifyAmount = updateVal
                    };
                    db.ScoreUpdates.Add(update);
                }
                else
                {
                    oldUpdate.ModifyAmount = updateVal;
                    db.ScoreUpdates.Update(oldUpdate);
                }

                db.Update(player);
            }
            db.SaveChanges();
            return(updates);
        }
        protected void AddGameToArena(GameResult game, ArenaSession arena)
        {
            game.ArenaSessionId = arena.Id;
            game.ArenaSession = arena;
            arena.Games.Add(game);

            if (game.Victory)
            {
                arena.Wins++;
            }
            else
            {
                arena.Losses++;
            }
        }
        public ServiceResult <GameResult> PerformAction(int playerId)
        {
            //Check Cooldown
            var player          = _playerService.Get(playerId);
            var elapsedSeconds  = DateTime.UtcNow.Subtract(player.LastActionExecutedDateTime).TotalSeconds;
            var cooldownSeconds = _appSettings.DefaultCooldown;

            if (player.CurrentFuelPlayerItem != null)
            {
                cooldownSeconds = player.CurrentFuelPlayerItem.Item.ActionCooldownSeconds;
            }

            if (elapsedSeconds < cooldownSeconds)
            {
                var waitSeconds = Math.Ceiling(cooldownSeconds - elapsedSeconds);
                var waitText    = $"You are still a bit tired. You have to wait another {waitSeconds} seconds.";
                return(new ServiceResult <GameResult>
                {
                    Data = new GameResult {
                        Player = player
                    },
                    Messages = new List <ServiceMessage> {
                        new ServiceMessage {
                            Code = "Cooldown", Message = waitText
                        }
                    }
                });
            }

            var hasAttackItem     = player.CurrentAttackPlayerItem != null;
            var positiveGameEvent = _positiveGameEventService.GetRandomPositiveGameEvent(hasAttackItem);

            if (positiveGameEvent == null)
            {
                return(new ServiceResult <GameResult> {
                    Messages =
                        new List <ServiceMessage>
                    {
                        new ServiceMessage
                        {
                            Code = "Error",
                            Message = "Something went wrong getting the Positive Game Event.",
                            MessagePriority = MessagePriority.Error
                        }
                    }
                });
            }

            var negativeGameEvent = _negativeGameEventService.GetRandomNegativeGameEvent();

            var oldLevel = player.GetLevel();

            player.Money      += positiveGameEvent.Money;
            player.Experience += positiveGameEvent.Experience;

            var newLevel = player.GetLevel();

            var levelMessages = new List <ServiceMessage>();

            //Check if we leveled up
            if (oldLevel < newLevel)
            {
                levelMessages = new List <ServiceMessage> {
                    new ServiceMessage {
                        Code = "LevelUp", Message = $"Congratulations, you arrived at level {newLevel}"
                    }
                };
            }

            //Consume fuel
            var fuelMessages = ConsumeFuel(player);

            var attackMessages = new List <ServiceMessage>();

            //Consume attack when we got some loot
            if (positiveGameEvent.Money > 0)
            {
                attackMessages.AddRange(ConsumeAttack(player));
            }

            var defenseMessages           = new List <ServiceMessage>();
            var negativeGameEventMessages = new List <ServiceMessage>();

            if (negativeGameEvent != null)
            {
                //Check defense consumption
                if (player.CurrentDefensePlayerItem != null)
                {
                    negativeGameEventMessages.Add(new ServiceMessage {
                        Code = "DefenseWithGear", Message = negativeGameEvent.DefenseWithGearDescription
                    });
                    defenseMessages.AddRange(ConsumeDefense(player, negativeGameEvent.DefenseLoss));
                }
                else
                {
                    negativeGameEventMessages.Add(new ServiceMessage {
                        Code = "DefenseWithoutGear", Message = negativeGameEvent.DefenseWithoutGearDescription
                    });

                    //If we have no defense item, consume the defense loss from Fuel and Attack
                    defenseMessages.AddRange(ConsumeFuel(player, negativeGameEvent.DefenseLoss));
                    defenseMessages.AddRange(ConsumeAttack(player, negativeGameEvent.DefenseLoss));
                }
            }

            var warningMessages = GetWarningMessages(player);

            player.LastActionExecutedDateTime = DateTime.UtcNow;

            //Save Player
            _database.SaveChanges();

            var gameResult = new GameResult
            {
                Player                    = player,
                PositiveGameEvent         = positiveGameEvent,
                NegativeGameEvent         = negativeGameEvent,
                NegativeGameEventMessages = negativeGameEventMessages
            };

            var serviceResult = new ServiceResult <GameResult>
            {
                Data = gameResult
            };

            //Add all the messages to the player
            serviceResult.WithMessages(levelMessages);
            serviceResult.WithMessages(warningMessages);
            serviceResult.WithMessages(fuelMessages);
            serviceResult.WithMessages(attackMessages);
            serviceResult.WithMessages(defenseMessages);

            return(serviceResult);
        }
 public override void OnTargetDeath(GameResult gameResult)
 {
 }
Example #56
0
 public void SetPlayerResult(int playerNumber, GameResult result)
 {
     _playerResults[playerNumber - 1] = result;
 }
Example #57
0
 public override void ShowGameOver(GameResult info)
 {
     throw new NotImplementedException( );
 }
Example #58
0
        public void LoadExistingData()
        {
            Rounds.Clear();
            PlayerPairings.Clear();

            var files = _storage.GetHatRoundPaths();

            foreach (var file in files)
            {
                try
                {
                    var doc = new XmlDocument();
                    using (var stream = new FileStream(file, FileMode.Open))
                    {
                        doc.Load(stream);
                    }
                    var teams = doc.SelectNodes("/HatRound/Teams/Team");

                    // Basic validation
                    if (teams.Count == 0 || teams.Count % 2 != 0)
                    {
                        throw new Exception();
                    }

                    var teamList = new List <Team>();
                    var i        = 1;
                    foreach (XmlNode team in teams)
                    {
                        //var teamName = team.SelectSingleNode("Name").InnerText;
                        Team t       = new Team(i);
                        var  players = team.SelectNodes("Players/Player");

                        // Basic validation
                        if (players.Count == 0)
                        {
                            throw new Exception();
                        }

                        foreach (XmlNode player in players)
                        {
                            var    name = player.SelectSingleNode("Name").InnerText;
                            Player p    = PlayerProvider.GetPlayer(name);

                            // Player list may have changed throughout the day, so accept this difference
                            if (p != null)
                            {
                                t.AddPlayer(p);
                            }
                        }
                        GameResult gameResult = (GameResult)Enum.Parse(typeof(GameResult), team.SelectSingleNode("GameResult").InnerText);
                        if (gameResult != GameResult.NoneYet)
                        {
                            t.GameDone(gameResult);
                        }

                        teamList.Add(t);
                        i++;
                    }
                    var round = new HatRound(teamList, file);
                    AddRound(round);
                }
                catch (Exception)
                {
                    throw new InvalidRoundException(string.Format("Round file {0} is an invalid file", file));
                }
            }
        }
 public void OnGameEnd(GameResult result)
 {
     timer.TimerStop();
     if (result == GameResult.won) AddToScore(Mathf.CeilToInt(timer.TimeLeft * 10), Vector3.zero, ScoreType.time, false);
     AddToScore(Mathf.CeilToInt(-doubt * 5), Vector3.zero, ScoreType.doubt, false);
     StartCoroutine(OnGameEndCoroutine());
 }
Example #60
0
 public override void OnCreation(GameResult gameResult, IControlable host)
 {
     this.target = host.Target;
     base.OnCreation(gameResult, host);
     CheckTarget();
 }