Example #1
0
        public static Role GetRole(PlayerGame playerRoom)
        {
            Roles.TryParse(playerRoom.Role, out Roles role);

            switch (role)
            {
            case Roles.Citizen:
                return(new CitizenRole(playerRoom.UserId));

            case Roles.Comissar:
                return(new ComissarRole(playerRoom.UserId));

            case Roles.Dead:
                return(new DeadRole(playerRoom.UserId));

            case Roles.Doctor:
                return(new DoctorRole(playerRoom.UserId));

            case Roles.Mafia:
                return(new MafiaRole(playerRoom.UserId));

            case Roles.Maniac:
                return(new ManiacRole(playerRoom.UserId));
            }
            return(null);
        }
Example #2
0
 public bool JoinGame(int game_id)
 {
     player = GetLoggedInUser();
     if (player.State == PlayerState.NotInGame)
     {
         game = _db.Games.Where(g => g.Id == game_id).FirstOrDefault();
         if (game != null && game.Player2Id == null && game.Player1Id != player.Id)
         {
             GetPlayer(game.Player1Id).State = PlayerState.ReadyToStart;
             player.State   = PlayerState.WaitingForStart;
             game.Player2Id = player.Id;
             game.Player2   = player;
             game.State     = GameState.WaitingForStart;
             player_game    = new PlayerGame()
             {
                 GameId = game.Id, Game = game, PlayerId = player.Id, Player = player
             };
             _db.PlayerGames.Add(player_game);
             _db.SaveChanges();
             player.CurrentPlayerGameId = player_game.Id;
             player.CurrentPlayerGame   = player_game;
             _db.SaveChanges();
             return(true);
         }
     }
     return(false);
 }
Example #3
0
        public ActionResult SignInExisting(Player player)
        {
            PlayerGame vm = new PlayerGame();

            vm.Player = player;
            return(View("MainMenu", vm));
        }
Example #4
0
        public void RemoveGameOwned()
        {
            var player = new Player {
                Id = 1, FirstName = "First 1", LastName = "Last 1"
            };
            var players = new List <Player> {
                player
            };
            var game = new Game {
                Id = 1, Name = "Game 1"
            };
            var games = new List <Game> {
                game
            };
            var playerGame = new PlayerGame {
                GameId = game.Id, PlayerId = player.Id
            };
            var playerGames = new List <PlayerGame> {
                playerGame
            };

            var context = _fixture.Context
                          .PlayersContain(players)
                          .GamesContain(games)
                          .PlayerGamesContain(playerGames);
            var playerRepository = new PlayerRepository(context);

            playerRepository.RemoveGameOwned(player.Id, game.Id);

            var result = playerRepository.GetAllGamesBy(player.Id);

            Assert.False(result.Any());
        }
        public IHttpActionResult GetOwMatchFilter(int PlayerID, [FromBody] owFilter filter)
        {
            List <string> names   = new List <string>();
            List <region> regions = new List <region>();
            List <int>    ids     = new List <int>();
            PlayerGame    p       = null;

            foreach (PlayerGame pg in db.PlayerGames.Where(x => x.IDGame == 1))
            {
                if (pg.IDGamer == PlayerID)
                {
                    p = pg;
                }
                else
                {
                    names.Add(pg.IdAPI);
                    regions.Add(region.us);
                    ids.Add(pg.IDGamer);
                }
            }
            if (p == null)
            {
                return(BadRequest());           //400
            }
            var player = OwAPI.GetPlayer(p.IdAPI, region.us, p.IDGamer);
            var a      = OwAPI.GetPlayer(names, regions, ids).Where(x => filterPlayer(x, filter));

            return(Ok(a));//201
        }
Example #6
0
 private void LeaveGame(GameCommand cmdReceived, PlayerGame playerGame, Game game)
 {
     if (playerGame == null)
     {
         new CommandFeedback(cmdReceived, enCommandStatus.Rejected, "User did not join this game").Save(this.FAppPrivate);
     }
     else
     {
         if (game == null)
         {
             new CommandFeedback(cmdReceived, enCommandStatus.Rejected, "Could not find this game").Save(this.FAppPrivate);
         }
         else
         {
             PlayerGame playerToRemove = game.PlayersInGame.Where(c => c.UserId == cmdReceived.UserId).FirstOrDefault();
             if (playerToRemove == null)
             {
                 new CommandFeedback(cmdReceived, enCommandStatus.Rejected, "Player not found in the game").Save(this.FAppPrivate);
             }
             else
             {
                 game.PlayersInGame.Remove(playerToRemove);
                 game.Save(this.FAppPublic);
                 playerToRemove.Delete(this.FAppPrivate);
                 new CommandFeedback(cmdReceived, enCommandStatus.Accepted, "Left the Game").Save(this.FAppPrivate);
             }
         }
     }
 }
Example #7
0
 private bool CheckModAndEngine(PlayerGame game)
 {
     if (game == null)
     {
         MessageBox.Show("No game is selected.");
         return(false);
     }
     else if (game.Engine == null)
     {
         MessageBox.Show("Mod " + game.Mod + " does not have an engine assigned to it. Please configure it.");
         lstMods.SelectedItem = lstMods.Items.Cast <Mod>().SingleOrDefault(m => m.Code == game.Mod.Code);
         tabMods.Focus();
         return(false);
     }
     else if (game.Engine.IsUnknown)
     {
         MessageBox.Show("Unknown game engine " + game.Engine + ". Please configure it.");
         lstEngines.SelectedItem = lstEngines.Items.Cast <Engine>().SingleOrDefault(e => e.Code == game.Engine.Code);
         tabEngines.Focus();
         return(false);
     }
     else if (game.Mod.IsUnknown)
     {
         MessageBox.Show("Unknown mod " + game.Mod + " for " + game.Engine + ". Please configure it.");
         lstMods.SelectedItem = lstMods.Items.Cast <Mod>().SingleOrDefault(m => m.Code == game.Mod.Code);
         tabMods.Focus();
         return(false);
     }
     else
     {
         return(true);
     }
 }
        public IEnumerable <OwPlayer> OwMatchFilter(int PlayerID, [FromUri] owFilter filter)
        {
            List <string> names   = new List <string>();
            List <region> regions = new List <region>();
            List <int>    ids     = new List <int>();
            PlayerGame    p       = null;

            foreach (PlayerGame pg in db.PlayerGames.Where(x => x.IDGame == 1))
            {
                if (pg.IDGamer == PlayerID)
                {
                    p = pg;
                }
                else
                {
                    names.Add(pg.IdAPI);
                    regions.Add(region.us);
                    ids.Add(pg.IDGamer);
                }
            }
            if (p == null)
            {
                return(null);          //BadRequest("Jogador que requisitou o match nΓ£o consta no banco"); //400
            }
            var player = OwAPI.GetPlayer(p.IdAPI, region.us, p.IDGamer);
            var a      = OwAPI.GetPlayer(names, regions, ids).Where(x => filterPlayer(x, filter));

            return(a);//201
        }
Example #9
0
 public bool CreateGame()
 {
     player = GetLoggedInUser();
     if (player.State == PlayerState.NotInGame)
     {
         player.State = PlayerState.WaitingForPlayer;
         _db.SaveChanges();
         game = new Game()
         {
             Player1Id = player.Id, Player1 = player, State = GameState.WaitingForPlayers
         };
         _db.Games.Add(game);
         _db.SaveChanges();
         player_game = new PlayerGame()
         {
             GameId = game.Id, Game = game, PlayerId = player.Id, Player = player
         };
         _db.PlayerGames.Add(player_game);
         _db.SaveChanges();
         player.CurrentPlayerGameId = player_game.Id;
         player.CurrentPlayerGame   = player_game;
         _db.SaveChanges();
         return(true);
     }
     return(false);
 }
Example #10
0
        public async Task <IHttpActionResult> PutPlayerGame(int id, PlayerGame playerGame)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != playerGame.ID)
            {
                return(BadRequest());
            }

            db.Entry(playerGame).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PlayerGameExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Example #11
0
 public void AddPlayer(PlayerGame player)
 {
     player.IsRed = !firstPlayer.IsRed;
     secondPlayer = player;
     Task.Run(() => Network.SendPacket(new ServerHello(!firstPlayer.IsRed, firstPlayer.Name), player.Stream));
     Task.Run(() => Network.SendPacket(new ServerHello(firstPlayer.IsRed, secondPlayer.Name), firstPlayer.Stream));
     Start();
 }
Example #12
0
        private void ListenClient(PlayerGame player)
        {
            while (true)
            {
                var clientUpdate = (ClientUpdate)Network.ReceivePacket(player.Stream);
                if (clientUpdate == null || player.StateInActUpdated)
                {
                    continue;
                }
                lock (firstPlayer.State)
                {
                    lock (secondPlayer.State)
                    {
                        /*
                         * if (firstPlayer.State.GameOver || secondPlayer.State.GameOver)
                         *  throw new Exception();
                         * if (firstPlayer.State.Animations == null || firstPlayer.State.Animations.Count == 0)
                         *  throw new Exception();
                         */
                        player.State.GiveCommandsFromClient(clientUpdate.Commands);
                        GameEngine.BeginAct(player.State);

                        /*
                         * if (firstPlayer.State.GameOver || secondPlayer.State.GameOver)
                         *  throw new Exception();
                         * if (firstPlayer.State.Animations == null || firstPlayer.State.Animations.Count == 0)
                         *  throw new Exception();
                         */
                        if (player.State.Animations.Contains(null))
                        {
                            throw new Exception();
                        }
                        player.StateInActUpdated = true;
                        //ΠŸΡ€ΠΈ ΠΏΠ°Ρ€Π°Π»Π»Π΅Π»ΡŒΠ½ΠΎΠΉ ΠΎΡ‚ΠΏΡ€Π°Π²ΠΊΠ΅
                        var updatedAnimations = player.State.Animations.ToList();
                        Task.Run(() => Network.SendPacket(new ServerUpdate(player.IsRed, updatedAnimations), firstPlayer.Stream));
                        Task.Run(() => Network.SendPacket(new ServerUpdate(player.IsRed, updatedAnimations), secondPlayer.Stream));

                        if (firstPlayer.StateInActUpdated && secondPlayer.StateInActUpdated)
                        {
                            GameEngine.EndAct(firstPlayer.State, secondPlayer.State);

                            /*
                             * if (firstPlayer.State.GameOver || secondPlayer.State.GameOver)
                             *  throw new Exception();
                             * if (firstPlayer.State.Animations == null || firstPlayer.State.Animations.Count == 0)
                             *  throw new Exception();
                             */
                            if (firstPlayer.State.Animations.Contains(null) || secondPlayer.State.Animations.Contains(null))
                            {
                                throw new Exception();
                            }
                            firstPlayer.StateInActUpdated = secondPlayer.StateInActUpdated = false;
                        }
                    }
                }
            }
        }
Example #13
0
        private void JoinGame(GameCommand cmdReceived, Player player, PlayerGame playerGame, Game game)
        {
            if (playerGame != null)
            {
                new CommandFeedback(cmdReceived, enCommandStatus.Rejected, "User already joined game").Save(this.FAppPrivate);
            }
            else
            {
                if (game == null)
                {
                    new CommandFeedback(cmdReceived, enCommandStatus.Rejected, "Game not found").Save(this.FAppPrivate);
                }
                else
                {
                    if (game.PlayersInGame.Count >= game.MaxNumberOfPlayers)
                    {
                        new CommandFeedback(cmdReceived, enCommandStatus.Rejected, "Already too many players in the game").Save(this.FAppPrivate);
                    }
                    else
                    {
                        PlayerGame newPlayerGame = new PlayerGame(game, cmdReceived.UserId, player.NickName);

                        foreach (MapTile tile in game.Map.MapTiles)
                        {
                            MapTile playerTile = new MapTile();
                            playerTile.TerrainType = -1;// tile.TerrainType;
                            playerTile.UserId      = newPlayerGame.UserId;
                            playerTile.Xpos        = tile.Xpos;
                            playerTile.Ypos        = tile.Ypos;

                            newPlayerGame.Map.MapTiles.Add(playerTile);

                            //set spawn, check if not occupied first
                            if (newPlayerGame.Spawn == null && tile.IsSpawningPoint)
                            {
                                if (game.PlayersInGame.Where(c => c.Spawn.Xpos == tile.Xpos && c.Spawn.Ypos == tile.Ypos).Count() == 0)
                                {
                                    //not used yet
                                    newPlayerGame.Spawn = playerTile;
                                    PlayerMapTile playerMapTile = new PlayerMapTile(game.Id, cmdReceived.UserId, playerTile);
                                    playerTile.TerrainType     = 100;
                                    playerTile.IsSpawningPoint = true;
                                    playerTile.IsAccessible    = true;
                                    playerMapTile.Save(this.FAppPrivate);
                                }
                            }
                        }


                        newPlayerGame.Save(this.FAppPrivate);
                        game.PlayersInGame.Add(newPlayerGame);
                        game.Save(this.FAppPublic);
                        new CommandFeedback(cmdReceived, enCommandStatus.Accepted, "Joined the game").Save(this.FAppPrivate);
                    }
                }
            }
        }
Example #14
0
        public ActionResult LoadGame(int id)
        {
            PlayerGame vm = new PlayerGame();

            vm.Characters = gameSerivce.FindListOfPlayerCharactersByPlayerId(id);
            vm.Player     = gameSerivce.FindPlayerById(id);

            return(View(vm));
        }
Example #15
0
        public void Delete(int playerid, int gameid)
        {
            PlayerGame playerGame = new PlayerGame {
                PlayerId = playerid, GameId = gameid
            };

            context.PlayerGame.Remove(playerGame);
            context.SaveChanges();
        }
        private void PlayerOnUpdated(PlayerGame gamedata)
        {
            var c = GameData.FirstOrDefault(x => x.Index.Equals(gamedata.Index));

            c.Name     = gamedata.Name;
            c.Pokemons = gamedata.Pokemons;

            Updated?.Invoke(GameData);
        }
Example #17
0
        private static void FillPlayerConfig(MilleBornesEntities context, Room roomEntity, Game newGame)
        {
            // Essayer en premier lieu avec le service, sinon
            // regarder directement dans la base de donnΓ©es.

            List <PlayerGame> playerGameSource = new List <PlayerGame>();

#if false
            try
            {
                using (var client = new LobbyGameProxy.LobbyServiceClient())
                {
                    var configEntries = client.GetPlayerConfig(roomEntity.Token);

                    foreach (var entry in configEntries)
                    {
                        var user = context.User
                                   .Where(us => us.LoggedInUser != null)
                                   .SingleOrDefault(us => us.LoggedInUser.Token == entry.UserToken);

                        if (user == null)
                        {
                            continue;
                        }

                        var playerGame = new PlayerGame()
                        {
                            Game          = newGame,
                            UserId        = user.UserId,
                            User          = user,
                            LastHeartbeat = DateTime.UtcNow,
                            Order         = entry.Order,
                            Team          = entry.Team + 1,
                            HasJoined     = user.UserId == roomEntity.MasterUserId
                        };
                    }
                }
            }
#endif
            //catch (Exception ex)
            //{
            playerGameSource = roomEntity.PlayerRoomState.Select((prs, inx) => new PlayerGame()
            {
                Game          = newGame,
                UserId        = prs.UserId,
                User          = prs.User,
                LastHeartbeat = DateTime.UtcNow,
                Order         = inx,
                Team          = prs.Team + 1,
                HasJoined     = prs.UserId == roomEntity.MasterUserId
            })
                               .ToList();
            //}

            newGame.PlayerGame = playerGameSource;
        }
Example #18
0
        public PlayerGame CreatePlayerGame(Player player, Game game)
        {
            PlayerGame playergame = new PlayerGame
            {
                GameId = game.Id,
                Score  = 0
            };

            return(playergame);
        }
Example #19
0
        public PlayerGame Update(PlayerGame playergame)
        {
            PlayerGame updatedPlayerGame = context.PlayerGame.Find(playergame.PlayerId, playergame.GameId);

            updatedPlayerGame.PlayerId = playergame.PlayerId;
            updatedPlayerGame.GameId   = playergame.GameId;
            updatedPlayerGame.Score    = playergame.Score;

            return(updatedPlayerGame);
        }
Example #20
0
        public async Task <IHttpActionResult> GetPlayerGame(int id)
        {
            PlayerGame playerGame = await db.PlayerGames.FindAsync(id);

            if (playerGame == null)
            {
                return(NotFound());
            }

            return(Ok(playerGame));
        }
Example #21
0
    private ResultPopup MakePopup(PlayerGame game_)
    {
        GameObject  resultPopupGameObj = Instantiate(gameObject);
        ResultPopup resultPopup        = resultPopupGameObj.GetComponent <ResultPopup>();

        resultPopup.game = game_;

        CanvasExtensions.Add(resultPopupGameObj);
        //resultPopupGameObj.GetComponent<RectTransform>().SetParent();

        return(resultPopup);
    }
        public void UpdatePlayerGame(PlayerGame game)
        {
            using (var db = new DataContext(_connectionString))
            {
                var playerRoomFromDb = (from u in db.GetTable <PlayerGame>()
                                        where u.UserId == game.UserId
                                        select u).FirstOrDefault();

                playerRoomFromDb.Role = game.Role;
                db.SubmitChanges();
            }
        }
Example #23
0
        public IHttpActionResult GetPlayerDota(int PlayerID)
        {
            PlayerGame pg = db.PlayerGames.Where(x => x.IDGamer == PlayerID && x.IDGame == (int)Games.Dota).FirstOrDefault();

            if (pg == null)
            {
                return(NotFound());
            }
            DotaPlayer a = DotaAPI.GetPlayer(pg.IdAPI, pg.IDGamer).Result;

            return(Ok(a));
        }
        public void TestCreatingMainDeck()
        {
            using (var context = new AppDbContext(CreateNewContextOptions()))
            {
                for (int i = 0; i < 20; i++)
                {
                    Card card = new Card
                    {
                        Name            = "DummyCard" + i.ToString(),
                        Cost            = i,
                        DefaultQuantity = 10
                    };

                    context.Cards.Add(card);
                    context.SaveChanges();
                }
                Player player1 = new Player {
                    Name = "ZTO"
                };
                Player player2 = new Player {
                    Name = "CS"
                };
                context.Players.Add(player1);
                context.Players.Add(player2);
                context.SaveChanges();
                Game game = new Game
                {
                    PlayerTurn = 0
                };
                context.SaveChanges();
                PlayerGame pg1 = new PlayerGame {
                    PlayerId = 1, GameId = 1
                };
                PlayerGame pg2 = new PlayerGame {
                    PlayerId = 2, GameId = 1
                };
                context.PlayerGames.Add(pg1);
                context.PlayerGames.Add(pg2);
                context.SaveChanges();
                DeckService deckService = new DeckService(context);
                deckService.CreateMainDeck(game.Id);
                var deck = deckService.GetDeck(1);

                int totalCount = deck.Cards.Select(x => x.Quantity).Sum();


                // should not add cards with a cost of 0
                Assert.Equal(19, deck.Cards.Count());
                Assert.Equal(190, totalCount);
            }
        }
Example #25
0
        public async Task <IHttpActionResult> PostPlayerGame(PlayerGame playerGame)
        {
            // return BadRequest("Use a rota especifica do jogo");
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            playerGame.Game  = db.Games.Find(playerGame.IDGame);
            playerGame.Gamer = db.Gamers.Find(playerGame.IDGamer);
            db.PlayerGames.Add(playerGame);
            await db.SaveChangesAsync();

            return(CreatedAtRoute("DefaultApi", new { id = playerGame.ID }, playerGame));
        }
Example #26
0
    private void Start()
    {
        if (game == null)
        {
            game = GetComponent <PlayerGame>();
        }

        if (board == null)
        {
            board = GetComponentInChildren <Board>();
        }

        Array.ForEach(board.Slots, slot => slot.mark = this);
    }
Example #27
0
        public async Task <IHttpActionResult> DeletePlayerGame(int id)
        {
            PlayerGame playerGame = await db.PlayerGames.FindAsync(id);

            if (playerGame == null)
            {
                return(NotFound());
            }

            db.PlayerGames.Remove(playerGame);
            await db.SaveChangesAsync();

            return(Ok(playerGame));
        }
Example #28
0
        public StatResult <Stat> AddStat(TeamGame teamGame, Player player, GameTime gameTime, StatType statType)
        {
            Stat stat = CreateGameEvent <Stat>(teamGame, gameTime);

            // Create the stat
            stat.StatTypeId = statType.Id;
            stat.StatName   = statType.StatName;
            // Id for Team and Game were already set by CreateGameEvent
            stat.Team = teamGame.Team;
            stat.Game = teamGame.Game;
            // Lineup has to exist
            stat.Lineup   = teamGame.Lineups.Last();
            stat.LineupId = stat.Lineup.Id;
            // Player could be null for Team stats
            stat.Player = player;
            if (stat.Player != null)
            {
                stat.PlayerId = stat.Player.Id;
            }
            // Possession could be null if it happens before a team estiblishes possession
            stat.Possession = teamGame.Game.Possessions.LastOrDefault();
            if (stat.Possession != null)
            {
                stat.PossessionId = stat.Possession.Id;
            }

            AddStatSummary(teamGame, stat);

            PlayerGame playerGame = teamGame.Players.FirstOrDefault(teamPlayer => teamPlayer.Player == player);

            if (playerGame == null)
            {
                throw new PlayerGameNotFoundException();
            }
            AddStatSummary(playerGame, stat);

            if (statType.WillEndPossession)
            {
                ChangePossession(teamGame.Game, gameTime);
            }

            StatResult <Stat> result = new StatResult <Stat>()
            {
                DependentStats = statType.DependentStats,
                Stat           = stat,
            };

            return(result);
        }
Example #29
0
    // Use this for initialization
    void Start()
    {
        // Initialize player fields
        player     = GameObjectLibrary.Player;
        playerBody = this.GetComponent <Rigidbody>();
        playerGame = this.GetComponent <PlayerGame>();

        // Initialize camera fields
        camera         = GameObjectLibrary.Camara;
        cameraMovement = camera.GetComponent <CameraMovement>();

        // Initialize velocity fields
        jumpVelocity    = new Vector3(0, 6.5f, 0);
        passiveVelocity = new Vector3(.17f, 0, 0);
    }
Example #30
0
        public bool StartGame(int board_size, List <Ship2> ships)
        {
            player = GetLoggedInUser();
            game   = _db.Games.Where(g => g.Player1Id == player.Id && g.State == GameState.WaitingForStart).FirstOrDefault();
            PlayerGame player_game1 = _db.PlayerGames.Where(pg => pg.GameId == game.Id && pg.PlayerId == game.Player1Id).FirstOrDefault();
            PlayerGame player_game2 = _db.PlayerGames.Where(pg => pg.GameId == game.Id && pg.PlayerId == game.Player2Id).FirstOrDefault();
            Player     player2      = GetPlayer(game.Player2Id);

            if (game != null)
            {
                player.State   = player2.State = PlayerState.InGame;
                game.State     = GameState.PlacingShips;
                game.BoardSize = board_size;
                foreach (Ship2 ship in ships)
                {
                    for (int i = 0; i < ship.Count; i++)
                    {
                        _db.Ships.Add(new Ship()
                        {
                            Name = ship.Name, Length = ship.Length, Lives = ship.Length, IsDestroyed = false, PlayerGameId = player_game1.Id, PlayerGame = player_game1, IsPlaced = false
                        });
                        _db.Ships.Add(new Ship()
                        {
                            Name = ship.Name, Length = ship.Length, Lives = ship.Length, IsDestroyed = false, PlayerGameId = player_game2.Id, PlayerGame = player_game2, IsPlaced = false
                        });
                    }
                    _db.SaveChanges();
                }
                for (int i = 0; i < board_size; i++)
                {
                    for (int j = 0; j < board_size; j++)
                    {
                        _db.BoardPieces.Add(new BoardPiece()
                        {
                            X = i, Y = j, PlayerGameId = player_game1.Id, PlayerGame = player_game1, IsHit = false
                        });
                        _db.BoardPieces.Add(new BoardPiece()
                        {
                            X = i, Y = j, PlayerGameId = player_game2.Id, PlayerGame = player_game2, IsHit = false
                        });
                    }
                    _db.SaveChanges();
                }
                _db.SaveChanges();
                return(true);
            }
            return(false);
        }
Example #31
0
        public void JoinGame(string gameID)
        {
            Trace.TraceInformation("JoinGame called " + gameID);
            Lee game;
            string playerId;

            game = GameConstants.Dal.LoadGame<Lee>(gameID) as Lee;
            
            if (game == null)
            {
                SendMessage("Game could not be found");

                return;
            }
            
            playerId = Context.User.Identity.GetUserId();

            

            //Check if the player has already been added to the game
              if (!game.PlayerGames.Any(p => p.PlayerId == playerId))
            {
                //Set the admin if this is the first person
                if (!game.PlayerGames.Any())
                {
                    game.Admin = playerId;
                    game.AdminName = Context.User.Identity.Name;
                }
                var playerGame = new PlayerGame()
                {
                    PlayerId = playerId,
                    Points = 0,
                    Name = Context.User.Identity.Name
                };
                game.PlayerGames.Add(playerGame);

                var playerIds = game.PlayerGames.Select(pg => pg.PlayerId);
                var players = GameConstants.Dal.GetPlayersFromIds(playerIds);
                GameConstants.Dal.SaveGame(game);
            }
            Groups.Add(Context.ConnectionId, game.Id).Wait();
            Groups.Add(Context.ConnectionId, UserPrefix + playerId).Wait();
            if (game.State == LeeState.WaitingForPlayers) UpdateClients(game);
            else UpdateClients(game, Clients.Caller);
        }
 public void AddPlayerGameToMySQL(PlayerGame playerGame)
 {
     var helper = new GameHelper();
     var hisGame = helper.GetGameFromMySQLByDate(playerGame.Game.Date);
     var sqlToExecute = String.Format(
         "insert into avDBSkaterRS (PlayerId, GameId, G, A, PIM,S,PP,SH,GW, TOI, PlusMinus, EVTOI,PPTOI,SHTOI, Hits,BlockedShots, AttemptsBlocked, ShotsMissed,GiveAways,TakeAways,FaceoffsWon,FaceoffsLost,PenaltiesTaken,PPAssists,ShAssists,GWAssists,EN,ENAssists)" +
         "values ({0},{1}, {2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17},{18},{19},{20},{21},{22},{23},{24},{25},{26},{27})",
             playerGame.Player.Id,
             hisGame,
             playerGame.Stats.Goals,
             playerGame.Stats.Assists,
             playerGame.Stats.PIM,
             playerGame.Stats.Shots,
             playerGame.Stats.PP,
             playerGame.Stats.SH,
             playerGame.Stats.GW,
             playerGame.Stats.TimeOnIce,
             playerGame.Stats.PlusMinus,
             playerGame.Stats.ENTimeOnIce,
             playerGame.Stats.PPTimeOnIce,
             playerGame.Stats.SHTimeOnIce,
             playerGame.Stats.Hits,
             playerGame.Stats.BlockedShots,
             playerGame.Stats.AttemptsBlocked,
             playerGame.Stats.ShotsMissed,
             playerGame.Stats.GiveAways,
             playerGame.Stats.TakeAways,
             playerGame.Stats.FaceOffsWon,
             playerGame.Stats.FaceOffsLost,
             playerGame.Stats.PenaltiesTaken,
             playerGame.Stats.PPAssists,
             playerGame.Stats.SHAssists,
             playerGame.Stats.GWAssists,
             playerGame.Stats.EmptyNet,
             playerGame.Stats.EmptyNetAssits
         );
     Scripts.ExecuteMySQLNonQuery(sqlToExecute);
 }
 public void Update(GameTime gameTime, PlayerGame playerGame)
 {
     _playerGame = playerGame;
 }
Example #34
0
 public void Update(GameTime gameTime, PlayerGame playerGame, Vector2 centerTile, BuildingPlacementInfo placementInfo)
 {
     _backColor = Color.LightGray;
     if (placementInfo == null)
     {
         if (centerTile == _location)
             _backColor = Color.LightBlue;
         if (HasHover)
             _backColor = Color.LightSalmon;
     } else
     {
         if (placementInfo.TopTilePlacementLocation.X <= X &&
             placementInfo.TopTilePlacementLocation.X + placementInfo.Height > X &&
             placementInfo.TopTilePlacementLocation.Y <= Y &&
             placementInfo.TopTilePlacementLocation.Y + placementInfo.Width > Y)
             _backColor = (placementInfo.CanPlace ? Color.Green : Color.Red);
         else
             _backColor = (IsBuildable ? Color.PaleGreen : Color.LightPink);
     }
 }
Example #35
0
        public void Update(GameTime gameTime, ref PlayerGame playerGame)
        {
            _playerGame = playerGame;
            List<ScreenItem> orderedScreenItems = controls.List.OrderByDescending<ScreenItem,
                int>(item => item.Layer).ToList<ScreenItem>();
            bool stillProcessingMouse = true;
            foreach (ScreenItem screenItem in orderedScreenItems)
            {
                if (screenItem == null)
                    continue;
                if (screenItem.Enabled && stillProcessingMouse)
                {
                    stillProcessingMouse = !screenItem.ProcessUpdateMouse();
                }
                screenItem.Update(gameTime);
            }
            MouseState mouseState = Mouse.GetState();
            controls.MoneyLabel.Text = ((int)Math.Floor(playerGame.Money)).ToString();
            controls.FoodLabel.Text = ((int)Math.Floor(playerGame.Food)).ToString();
            controls.OilLabel.Text = ((int)Math.Floor(playerGame.Oil)).ToString();

            List<ResearchProgress> currentResearchToBeUpdated = new List<ResearchProgress>();
            currentResearchToBeUpdated.AddRange(playerGame.CurrentResearch);
            foreach (ResearchProgress researchProgress in currentResearchToBeUpdated)
                researchProgress.Update(gameTime);

            Map loadedMap = null;
            switch (_currentMap)
            {
                case SimulationScreenMap.Urban: loadedMap = _playerGame.UrbanMap; break;
                case SimulationScreenMap.Country: loadedMap = _playerGame.CountryMap; break;
                case SimulationScreenMap.Ocean: loadedMap = _playerGame.OceanMap; break;
            }
            if (stillProcessingMouse && minimapVertices.PointInside(new Vector2(mouseState.X, mouseState.Y)))
            {
                loadedMap.ProcessMinimapMouse(new Vector2(minimapWindow.X - minimapWindow.Width / 2,
                    minimapWindow.Y - minimapWindow.Height / 2));
                stillProcessingMouse = false;
            }

            if (stillProcessingMouse)
                foreach (Rectangle interfaceRectangle in interfaceBlocks)
                {
                    if (mouseState.X >= interfaceRectangle.X && mouseState.Y >= interfaceRectangle.Y &&
                        mouseState.X <= interfaceRectangle.Right && mouseState.Y <= interfaceRectangle.Bottom)
                        stillProcessingMouse = false;
                }

            loadedMap.Update(gameTime, playerGame, mapWindow, stillProcessingMouse);
            outputText = loadedMap.output;
        }
 private void AddPlayerGame(PlayerGameHelper helper, PlayerGame playerGame)
 {
     helper.AddPlayerGameToMySQL(playerGame);
     InfoLabel.Text += String.Format("Adding player game for {0} on {1}. {2}", playerGame.Player.Id, playerGame.Game.Date, "<br />");
 }
Example #37
0
 public bool AreMet(PlayerGame playerGame)
 {
     return (playerGame.Money >= money && playerGame.Food >= food &&
         playerGame.Electricity - playerGame.ConsumedElectricity >= electricity &&
         playerGame.Oil >= oil);
 }
Example #38
0
        public void Initialize(Game game, ApplicationSkin applicationSkin, PlayerGame playerGame)
        {
            interfaceBlocks = new Rectangle[3];
            interfaceBlocks[0] = new Rectangle(0, 0, 144, 568);
            interfaceBlocks[1] = new Rectangle(0, 568, 1050, 133);
            interfaceBlocks[2] = new Rectangle(877, 376, 173, 192);

            _playerGame = playerGame;
            _playerGame.UrbanMap.TileClicked += new Map.TileClickedHandler(TileClicked);
            _playerGame.UrbanMap.BuildingPlacementBegan += new BuildingPlacementBeganHandler(BuildingPlacementBegins);
            _playerGame.UrbanMap.BuildingPlacementFinished += new BuildingPlacementFinishedHandler(BuildingPlacementEnds);
            _playerGame.UrbanMap.BuildingSelected += new BuildingSelectedHandler(BuildingSelected);
            _playerGame.CountryMap.TileClicked += new Map.TileClickedHandler(TileClicked);
            _playerGame.CountryMap.BuildingPlacementBegan += new BuildingPlacementBeganHandler(BuildingPlacementBegins);
            _playerGame.CountryMap.BuildingPlacementFinished += new BuildingPlacementFinishedHandler(BuildingPlacementEnds);
            _playerGame.CountryMap.BuildingSelected += new BuildingSelectedHandler(BuildingSelected);
            _playerGame.OceanMap.TileClicked += new Map.TileClickedHandler(TileClicked);
            _playerGame.OceanMap.BuildingPlacementBegan += new BuildingPlacementBeganHandler(BuildingPlacementBegins);
            _playerGame.OceanMap.BuildingPlacementFinished += new BuildingPlacementFinishedHandler(BuildingPlacementEnds);
            _playerGame.OceanMap.BuildingSelected += new BuildingSelectedHandler(BuildingSelected);

            _playerGame.ResearchCompleted += delegate(Research research) { _playerGame.ApplyBenefits(research.Benefits); };
            _playerGame.BuildingsMadeAvailable += delegate() { RefreshBuildingOpportunities(); };
            _playerGame.ResearchMadeAvailable += delegate() { RefreshResearchOpportunities(); };

            skin = applicationSkin;
            controls = new SimulationScreenControls(game, applicationSkin);
            controls.UrbanAreaSelection.Toggled += new EventHandler(areaSelectionToggled);
            controls.CountryAreaSelection.Toggled += new EventHandler(areaSelectionToggled);
            controls.OceanAreaSelection.Toggled += new EventHandler(areaSelectionToggled);

            controls.NewTechnologyNotice.MovingFinished += delegate() { controls.NewTechnologyNotice.Visible = false; };

            controls.BuildingListLeft.OnClick += delegate(ScreenItem item, MouseEventArgs args) { ShiftBuildingList(-1); };
            controls.BuildingListRight.OnClick += delegate(ScreenItem item, MouseEventArgs args) { ShiftBuildingList(1); };

            controls.BuildingListLeft.Enabled = false;
            controls.MoneyLabel.Text = playerGame.Money.ToString();
            controls.FoodLabel.Text = playerGame.Food.ToString();
            controls.OilLabel.Text = playerGame.Oil.ToString();

            controls.MinimapEast.OnClick += delegate(ScreenItem item, MouseEventArgs args) { ShiftViewport(new Vector2(0, 1)); };
            controls.MinimapNorth.OnClick += delegate(ScreenItem item, MouseEventArgs args) { ShiftViewport(new Vector2(-1, 0)); };
            controls.MinimapSouth.OnClick += delegate(ScreenItem item, MouseEventArgs args) { ShiftViewport(new Vector2(1, 0)); };
            controls.MinimapWest.OnClick += delegate(ScreenItem item, MouseEventArgs args) { ShiftViewport(new Vector2(0, -1)); };

            foreach (Research research in playerGame.AvailableResearches)
                controls.TechnologyList.Items.Add(new ScreenItemListItem(research.Name, research));
            controls.TechnologyList.ListItemSelected += new ScreenItemList.ListItemSelectedHandler(TechnologyListItemSelected);
            foreach (Building building in playerGame.AvailableBuildings)
                controls.BuildingDropdown.Items.Add(new ScreenItemListItem(building.Name, building));
            controls.BuildingDropdown.ListItemSelected += delegate(ScreenItemList list, ScreenItemListItem item)
            {
                OpenBuildingDialog((Building)item.AttachedInformation);
            };
            int buttonIdentity = 0;
            foreach (ScreenItemButton button in controls.BuildingListButtons)
            {
                button.AttachedInformation = buttonIdentity;
                buttonIdentity++;
                button.OnClick += delegate(ScreenItem item, MouseEventArgs args)
                {
                    OpenBuildingDialog(_playerGame.AvailableBuildings[availableBuildingListOffset +
                           (int)item.AttachedInformation]);
                };
            }

            int upperBounds = (playerGame.AvailableBuildings.Count > 6 ? 6 : playerGame.AvailableBuildings.Count);
            for (int index = 0; index < upperBounds; index++)
                controls.BuildingListButtons[index].Image = playerGame.AvailableBuildings[index].BuildingIcon;

            if (playerGame.AvailableBuildings.Count <= 6)
            {
                for (int index = playerGame.AvailableBuildings.Count; index < controls.BuildingListButtons.Count; index++)
                    controls.BuildingListButtons[index].Enabled = false;
                controls.BuildingListRight.Enabled = false;
            }

            mapWindow = new Rectangle(151, 0, game.GraphicsDevice.Viewport.Width - 151,
                game.GraphicsDevice.Viewport.Height - 133);
            minimapWindow = new Rectangle(955, 405, GlobalSettings.MinimapWidth, GlobalSettings.MinimapHeight);
            minimapVertices = new Vector2[4];
            minimapVertices[0] = Vector2.Zero;
            minimapVertices[1] = new Vector2(GlobalSettings.MinimapWidth, 0);
            minimapVertices[2] = new Vector2(GlobalSettings.MinimapWidth, GlobalSettings.MinimapHeight);
            minimapVertices[3] = new Vector2(0, GlobalSettings.MinimapHeight);
            for (int vertex = 0; vertex < 4; vertex++)
            {
                Vector2 originalVertice = minimapVertices[vertex];
                minimapVertices[vertex].X = (int)(originalVertice.X * Math.Cos(MathHelper.PiOver4) -
                    originalVertice.Y * Math.Sin(MathHelper.PiOver4)) + minimapWindow.X;
                minimapVertices[vertex].Y = (int)(originalVertice.X * Math.Sin(MathHelper.PiOver4) +
                    originalVertice.Y * Math.Cos(MathHelper.PiOver4)) + minimapWindow.Y;
            }

            controls.SelectedBuilding.OnClick += delegate(ScreenItem item, MouseEventArgs args)
            {
                if (((ScreenItemBuildingInformation)item).Building == null)
                    return;
                switch (_currentMap)
                {
                    case SimulationScreenMap.Urban: _playerGame.UrbanMap.CenterTile = ((ScreenItemBuildingInformation)item).Building.MapLocation; break;
                    case SimulationScreenMap.Country: _playerGame.CountryMap.CenterTile = ((ScreenItemBuildingInformation)item).Building.MapLocation; break;
                    case SimulationScreenMap.Ocean: _playerGame.OceanMap.CenterTile = ((ScreenItemBuildingInformation)item).Building.MapLocation; break;
                }
            };
        }
Example #39
0
        public void Update(GameTime gameTime, ref PlayerGame playerGame)
        {
            _playerGame = playerGame;
            List<ScreenItem> orderedScreenItems = _screenItems.Values.OrderByDescending<ScreenItem, int>(item => item.Layer).ToList<ScreenItem>();
            bool stillProcessingMouse = true;
            outputText = "";
            foreach (ScreenItem screenItem in orderedScreenItems)
            {
                if (screenItem.Enabled && stillProcessingMouse)// && screenItem.GetMouseOver())
                {
                    stillProcessingMouse = !screenItem.ProcessUpdateMouse();
                    if (!stillProcessingMouse)
                        outputText = screenItem.ToString();
                }
                screenItem.Update(gameTime);
                outputText += screenItem.ToString() + "\n";
            }

            Map loadedMap = null;
            switch (_currentMap)
            {
                case SimulationScreenMap.Urban: loadedMap = _playerGame.UrbanMap; break;
                case SimulationScreenMap.Country: loadedMap = _playerGame.CountryMap; break;
                case SimulationScreenMap.Ocean: loadedMap = _playerGame.OceanMap; break;
            }
            Microsoft.Xna.Framework.Input.KeyboardState _state = Microsoft.Xna.Framework.Input.Keyboard.GetState();
            if (_state.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Escape) && !_screenItems.ContainsKey("closeDialog"))
                openCloseDialog(_screenItems["windowButtons-Close"], new EventArgs());
            Vector2 centerTile = loadedMap.CenterTile;
            if (_state.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Left))
            {
                centerTile.X++;
                centerTile.Y--;
            }
            if (_state.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Right))
            {
                centerTile.X--;
                centerTile.Y++;
            }
            if (_state.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Up))
            {
                centerTile.X--;
                centerTile.Y--;
            }
            if (_state.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Down))
            {
                centerTile.X++;
                centerTile.Y++;
            }
            if (centerTile.X < 0)
                centerTile.X = 0;
            if (centerTile.X >= loadedMap.Width)
                centerTile.X = loadedMap.Width - 1;
            if (centerTile.Y < 0)
                centerTile.Y = 0;
            if (centerTile.Y >= loadedMap.Height)
                centerTile.Y = loadedMap.Height - 1;
            loadedMap.CenterTile = centerTile;
            loadedMap.Update(gameTime, playerGame, mapWindow);
        }