Exemplo n.º 1
0
        public ActionResult Detail(int Id)
        {
            Game       game   = _session.Get <Game>(Id);
            GameDetail detail = Mapper.Map <GameDetail>(game);

            return(View(detail));
        }
Exemplo n.º 2
0
        /// <summary>
        /// 获取游戏详情
        /// </summary>
        /// <param name="contentId"></param>
        /// <returns></returns>
        public async Task <GameDetail> GetGameDetail(string contentId)
        {
            GameDetail gameDetail = new GameDetail();
            string     fileName   = "GameDetail_" + contentId + ".json";

            if (!ConnectionHelper.IsInternetAvailable)
            {
                gameDetail = await FileHelper.Current.ReadObjectAsync <GameDetail>(fileName);
            }
            else
            {
                PostDataTemplate <GameDetailRequest> postData = new PostDataTemplate <GameDetailRequest>
                {
                    request = new GameDetailRequest()
                    {
                        contentId = contentId
                    }
                };

                var gameDetailResult = await PostJson <PostDataTemplate <GameDetailRequest>, ResultDataTemplate <GameDetail> >(ServiceUri.GameDetail, postData);

                gameDetail = gameDetailResult?.Result;
            }
            return(gameDetail);
        }
Exemplo n.º 3
0
        //public List<GameImageListItems> ConvertDataEntitiesToImageViewModel(List<GameImage> images)
        //{
        //    // instantiate a new List<ReviewListItem>**
        //    List<GameImageListItems> returnList = new List<GameImageListItems>();
        //    // foreach through my entity.AllReviews
        //    foreach (var image in images)
        //    {
        //        //create a new ReviewListItem
        //        var gameImageListItem = new GameImageListItems();
        //        // assign it the values from the entity.AllReviews[i],
        //        gameImageListItem.GameImageId = image.GameImageID;
        //        gameImageListItem.FileContent = image.FileContent;
        //        gameImageListItem.FileName = image.FileName;
        //        gameImageListItem.FileType = image.FileType;
        //        gameImageListItem.FileSize = image.FileSize;

        //        // add ReviewListItem to my List<ReviewListItem>**
        //        returnList.Add(gameImageListItem);
        //    }
        //    //  return that List<ReviewListItem>**
        //    return returnList;
        //}
        public GameDetail GetGameById(int id)
        {
            ReviewService reviewService = new ReviewService();

            using (var ctx = new ApplicationDbContext())
            {
                var entity =
                    ctx
                    .Games
                    .SingleOrDefault(e => e.GameId == id);
                var detail = new GameDetail
                {
                    //AllGameImages = ConvertDataEntitiesToImageViewModel(entity.AllGameImages.ToList()),
                    GameId      = entity.GameId,
                    Title       = entity.Title,
                    Description = entity.Description,
                    PlatformID  = entity.PlatformId,
                    PlatTitle   = entity.Platform.Title,
                    Developer   = entity.Developer,
                    ESRB        = (Models.GameModels.ESRB)entity.ESRB,
                    ReleaseDate = entity.ReleaseDate,
                    //AverageStarRating = entity.AverageStarRating,
                    AllGameReviews = ConvertDataEntitiesToViewModel(entity.AllGameReviews.ToList())
                };
                return(detail);
            }
        }
Exemplo n.º 4
0
        private GameDetail GetDetailFromGame(Game game, IEnumerable <Score> allScores)
        {
            var awayScore = allScores
                            .Where(x => x.TeamId == game.AwayTeamId)
                            .Sum(x => x.Points);

            var homeScore = allScores
                            .Where(x => x.TeamId == game.HomeTeamId)
                            .Sum(x => x.Points);

            var gameClock = _gameEngineListener.GetGameClockById(game.Id);

            if (gameClock.IsNull())
            {
                gameClock = new GameClock();
            }

            var gameDetail = new GameDetail
            {
                Id         = game.Id,
                Name       = game.Name,
                Quarter    = gameClock.Quarter,
                GameClock  = gameClock.Time.ToCustomString("mm:ss.f"), // Render as a game clock,
                AwayTeamId = game.AwayTeamId,
                AwayScore  = awayScore,
                HomeTeamId = game.HomeTeamId,
                HomeScore  = homeScore
            };

            return(gameDetail);
        }
Exemplo n.º 5
0
 public void SetUp()
 {
     gameDetail = new GameDetail();
     context    = new ValidationContext(gameDetail, null, null);
     results    = new List <ValidationResult>();
     TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(typeof(GameDetail), typeof(GameDetailMetadata)), typeof(GameDetail));
 }
Exemplo n.º 6
0
    public IEnumerator SetGameDetail()
    {
        WWW wwwGetGameDetail = new WWW("http://103.239.222.212/ALIVE2Service/api/game/AllGameDetail");

        yield return(wwwGetGameDetail);

        Debug.Log(wwwGetGameDetail.text);
        Debug.Log(wwwGetGameDetail.error);
        Debug.Log(wwwGetGameDetail.url);

        File.WriteAllText(Application.persistentDataPath + "/AllGameDetail.json", wwwGetGameDetail.text);
        Debug.Log("AllGameDetail written");

        string jsonString = File.ReadAllText(Application.persistentDataPath + "/AllGameDetail.json");

        GameDetailRoot gameDetailRoot = new GameDetailRoot();

        gameDetailRoot = JsonUtility.FromJson <GameDetailRoot>("{\"gameDetails\":" + jsonString + "}");

        string fileName = "";

        foreach (GameDetail gameDetail in gameDetailRoot.gameDetails)
        {
            Debug.Log(gameDetail.gameDetailName);
            fileName = gameDetail.gameDetailName;
            GameDetail detail = new GameDetail();
            detail.gameDetailID          = gameDetail.gameDetailID;
            detail.gameDetailName        = gameDetail.gameDetailName;
            detail.gameDetailValue       = gameDetail.gameDetailValue;
            detail.gameDetailDescription = gameDetail.gameDetailDescription;
            string gameDetailJson = JsonUtility.ToJson(detail);
            File.WriteAllText(Application.persistentDataPath + "/" + fileName + ".json", gameDetailJson);
        }
    }
Exemplo n.º 7
0
        public async Task <IHttpActionResult> PutGameDetail(int id, GameDetail gameDetail)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != gameDetail.Id)
            {
                return(BadRequest());
            }

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

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

            return(StatusCode(HttpStatusCode.NoContent));
        }
Exemplo n.º 8
0
    public void addCard(DbCowsCard c)
    {
        if (c == null)
        {
            return;
        }

        m_cardType = c.cardsType;
        m_cards    = new List <CardInfo>();

        CardInfo info = GameDetail.createCardInfo(c.cards0);

        m_cards.Add(info);

        info = GameDetail.createCardInfo(c.cards1);
        m_cards.Add(info);

        info = GameDetail.createCardInfo(c.cards2);
        m_cards.Add(info);

        info = GameDetail.createCardInfo(c.cards3);
        m_cards.Add(info);

        info = GameDetail.createCardInfo(c.cards4);
        m_cards.Add(info);
    }
 void OnGetGameDetails(string errorString, GameDetail result, params object[] userParam)
 {
     if (string.IsNullOrEmpty(errorString) && result != null)
     {
         AdminPercentMessage.text = "(Tournament creator gets " + result.LeaderboardAdminSharePercent.ToString() + "% of total points collected in the tournament)";
     }
 }
Exemplo n.º 10
0
        // GET: Games/Delete/5
        public ActionResult Delete(int?id)
        {
            Account account = Session["account"] as Account;

            if (account == null)
            {
                TempData["infoMsg"] = "You must be logged in.";
                return(RedirectToAction("", "Login"));
            }
            if (account.roleCode != "employee")
            {
                throw new HttpException(403, "Access denied");
            }
            if (id == null)
            {
                throw new HttpException(400, "Bad request");
            }
            Game       game       = db.GameDetails.Find(id).Game;
            GameDetail gameDetail = db.GameDetails.Find(id);

            if (game == null)
            {
                throw new HttpException(404, "Not found");
            }
            if (gameDetail == null)
            {
                throw new HttpException(404, "Not found");
            }
            return(View(game));
        }
Exemplo n.º 11
0
        public ActionResult Delete(int?id)
        {
            GameService service = new GameService();
            GameDetail  game    = service.GetGameById(id);

            return(View(game));
        }
Exemplo n.º 12
0
        private void BindGameDetail()
        {
            int gameDetailId = Request.QueryString["GameDetailId"].ToInt();

            if (gameDetailId > 0)
            {
                GameDetail gameDetailLookup = GameDetailDAL.GetItem(gameDetailId);

                if (gameDetailLookup != null)
                {
                    lblGameDetailId.Text = gameDetailLookup.GameDetailId.ToString();
                    lblGameId.Text       = gameDetailLookup.GameId.ToString();
                    lblMatch.Text        = gameDetailLookup.Match;
                    lblOdds.Text         = gameDetailLookup.Odds;
                    lblPrize.Text        = gameDetailLookup.Prize;
                }

                else
                {
                    lblMessage.Text = "Game could not be found.";
                }
            }
            else
            {
                lblMessage.Text = "Invalid ID. Game record could not be found.";
            }
        }
Exemplo n.º 13
0
        public static GameDetail GetItem(int gameDetailId)
        {
            GameDetail tempItem = null;

            using (SqlConnection myConnection = new SqlConnection(AppConfiguration.ConnectionString))
            {
                using (SqlCommand myCommand = new SqlCommand("usp_GetGameDetail", myConnection))
                {
                    myCommand.CommandType = CommandType.StoredProcedure;

                    myCommand.Parameters.AddWithValue("@QueryId", SelectTypeEnum.GetItem);
                    myCommand.Parameters.AddWithValue("@GameDetailId", gameDetailId);

                    myConnection.Open();
                    using (SqlDataReader myReader = myCommand.ExecuteReader())
                    {
                        if (myReader.Read())
                        {
                            tempItem = FillDataRecord(myReader);
                        }
                        myReader.Close();
                    }
                }
            }
            return(tempItem);
        }
Exemplo n.º 14
0
        private static GameDetail FillDataRecord(IDataRecord myDataRecord)
        {
            GameDetail myObject = new GameDetail();

            myObject.GameDetailId = myDataRecord.GetInt32(myDataRecord.GetOrdinal("GameDetailId"));

            if (!myDataRecord.IsDBNull(myDataRecord.GetOrdinal("GameId")))
            {
                myObject.GameId = myDataRecord.GetInt32(myDataRecord.GetOrdinal("GameId"));
            }

            if (!myDataRecord.IsDBNull(myDataRecord.GetOrdinal("Match")))
            {
                myObject.Match = myDataRecord.GetString(myDataRecord.GetOrdinal("Match"));
            }

            if (!myDataRecord.IsDBNull(myDataRecord.GetOrdinal("Odds")))
            {
                myObject.Odds = myDataRecord.GetString(myDataRecord.GetOrdinal("Odds"));
            }

            if (!myDataRecord.IsDBNull(myDataRecord.GetOrdinal("Prize")))
            {
                myObject.Prize = myDataRecord.GetString(myDataRecord.GetOrdinal("Prize"));
            }

            return(myObject);
        }
 public ActionResult AddGames(GameDetail gameDetails)
 {
     if (ModelState.IsValid)
     {
         try
         {
             string fileName       = Path.GetFileNameWithoutExtension(gameDetails.ImageFile.FileName);
             string imageExtension = Path.GetExtension(gameDetails.ImageFile.FileName);
             fileName = fileName + DateTime.Now.ToString("yymmssfff") + imageExtension;
             gameDetails.GameImagePath = "~/Images/" + fileName;
             fileName = Path.Combine(Server.MapPath("~/Images/"), fileName);
             gameDetails.ImageFile.SaveAs(fileName);
             gamexContext.GameDetails.Add(gameDetails);
             gamexContext.SaveChanges();
             var gameDetailsToSet = gamexContext.GameDetails.Single(game => game.GameId == gameDetails.GameId);
             gameDetailsToSet.GamePurchaseCount = 0;
             gamexContext.SaveChanges();
             ViewBag.Message = "Game Added Successfully";
         }
         catch (Exception e)
         {
             ViewBag.Message = e.Message;
         }
     }
     return(View());
 }
Exemplo n.º 16
0
 private void lvServerListing_SelectionChanged(object sender, SelectionChangedEventArgs e)
 {
     if (e.AddedItems.Count > 0)
     {
         GSSelection = (GameDetail)e.AddedItems[0];
         UpdateServerDetailsView(GSSelection);
     }
 }
Exemplo n.º 17
0
        public async Task <int> AddGame(Model.ViewModel.Game game)
        {
            await GameDetail.AddAsync(mapper.Map <Model.DTO.Game>(game));

            var entity = await GameDetail.GetItemsAsync(a => a.GameName == game.GameName);

            return(entity.FirstOrDefault().Id);
        }
Exemplo n.º 18
0
        public GameDetail getDetail(string id)
        {
            string url = string.Format("http://www.giantbomb.com/api/game/3030-{0}/?api_key={1}&format=json&field_list=deck,genres,id,image,images,name,original_game_rating,original_release_date,similar_games,site_detail_url,themes,videos,platforms", id, apikey);

            GameDetail temp = new GameDetail();

            temp = JsonConvert.DeserializeObject <GameDetail>(ApiCall.ApiGET(url));
            return(temp);
        }
Exemplo n.º 19
0
        private GameListing GSListing;  // The Stores the Game server list used by list view
        //////////////////////////////////////////////////

        ///// STRUCTORS //////////////////////////////////
        public WindowPortal(App app)
        {
            InitializeComponent();
            Parent      = app;
            GSSelection = null;
            GSListing   = null;

            this.btnJoinServer.IsEnabled = false;
        }
Exemplo n.º 20
0
 private static void WriteHeader(IWriterRow csvWriter, int gameNum, GameDetail gameDetail)
 {
     csvWriter.WriteField($"Game {gameNum}");
     csvWriter.WriteField("Match Replay Url");
     csvWriter.WriteField("Team on Blue Side");
     csvWriter.WriteField("Winner");
     csvWriter.WriteField("ProDraft Spectate Link");
     csvWriter.WriteField("Post Game Screenshot");
 }
Exemplo n.º 21
0
        public async Task <IHttpActionResult> GetGameDetail(int id)
        {
            GameDetail gameDetail = await db.GameDetails.FindAsync(id);

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

            return(Ok(gameDetail));
        }
Exemplo n.º 22
0
        public void CollectMatchMvpData(SimplifiedMatchSubmissionView view,
                                        Dictionary <string, SummonerInfoEntity> registeredPlayers,
                                        GameDetail gameInfo, Dictionary <int, MatchMvpEntity> mvpDetails, List <MatchMvpEntity> updateMvpDetails,
                                        List <MatchMvpEntity> insertMvpDetails, SummonerInfoEntity userPlayer)
        {
            registeredPlayers.TryGetValue(gameInfo.BlueMvp.ToLowerInvariant(), out var blueMvp);
            registeredPlayers.TryGetValue(gameInfo.RedMvp.ToLowerInvariant(), out var redMvp);
            registeredPlayers.TryGetValue(gameInfo.HonoraryBlueOppMvp.ToLowerInvariant(), out var honoraryBlueOppMvp);
            registeredPlayers.TryGetValue(gameInfo.HonoraryRedOppMvp.ToLowerInvariant(), out var honoraryRedOppMvp);

            if (mvpDetails.TryGetValue(gameInfo.GameNum, out var mvpEntity))
            {
                if (!string.IsNullOrEmpty(gameInfo.BlueMvp) && blueMvp != null && blueMvp.Id != mvpEntity.BlueMvp)
                {
                    mvpEntity.BlueMvp = blueMvp.Id;
                }

                if (!string.IsNullOrEmpty(gameInfo.RedMvp) && redMvp != null && redMvp.Id != mvpEntity.RedMvp)
                {
                    mvpEntity.RedMvp = redMvp.Id;
                }
                if (!string.IsNullOrEmpty(gameInfo.HonoraryBlueOppMvp) && honoraryBlueOppMvp != null &&
                    honoraryBlueOppMvp.Id != mvpEntity.HonoraryBlueOppMvp)
                {
                    mvpEntity.HonoraryBlueOppMvp = honoraryBlueOppMvp.Id;
                }

                if (!string.IsNullOrEmpty(gameInfo.HonoraryRedOppMvp) && honoraryRedOppMvp != null &&
                    honoraryRedOppMvp.Id != mvpEntity.HonoraryRedOppMvp)
                {
                    mvpEntity.HonoraryRedOppMvp = honoraryRedOppMvp.Id;
                }

                mvpEntity.UpdatedBy = userPlayer.SummonerName;
                mvpEntity.UpdatedOn = DateTime.Now;
                updateMvpDetails.Add(mvpEntity);
            }
            else
            {
                mvpEntity = new MatchMvpEntity
                {
                    Id                 = Guid.NewGuid(),
                    BlueMvp            = blueMvp?.Id,
                    RedMvp             = redMvp?.Id,
                    HonoraryBlueOppMvp = honoraryBlueOppMvp?.Id,
                    HonoraryRedOppMvp  = honoraryRedOppMvp?.Id,
                    Game               = gameInfo.GameNum,
                    TeamScheduleId     = view.ScheduleId,
                    CreatedBy          = userPlayer.SummonerName,
                    CreatedOn          = DateTime.Now
                };
                insertMvpDetails.Add(mvpEntity);
            }
        }
Exemplo n.º 23
0
        public async Task <IHttpActionResult> PostGameDetail(GameDetail gameDetail)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            db.GameDetails.Add(gameDetail);
            await db.SaveChangesAsync();

            return(CreatedAtRoute("DefaultApi", new { id = gameDetail.Id }, gameDetail));
        }
Exemplo n.º 24
0
        // GET: Game Details
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            GameService service = new GameService();
            GameDetail  game    = service.GetGameById(id);

            return(View(game));
        }
Exemplo n.º 25
0
        // GET: Reports/Game
        public ActionResult Game(int?gameId)
        {
            Account account = Session["account"] as Account;

            if (account == null)
            {
                TempData["infoMsg"] = "You must be logged in.";
                return(RedirectToAction("", "Login"));
            }
            if (account.roleCode != "employee")
            {
                throw new HttpException(403, "Access denied");
            }
            if (gameId == null)
            {
                throw new HttpException(400, "Bad request");
            }
            Game game = db.Games.Find(gameId);

            if (game == null)
            {
                throw new HttpException(404, "Not found");
            }
            GameAndGameDetails gameAndGameDetails = new GameAndGameDetails();

            gameAndGameDetails.gameId    = game.gameId;
            gameAndGameDetails.title     = game.title;
            gameAndGameDetails.publisher = game.publisher;
            gameAndGameDetails.relDate   = game.relDate;
            gameAndGameDetails.rateAVG   = game.rateAVG;
            GameDetail         physical     = game.GameDetails.Where(g => g.phyCopy).SingleOrDefault();
            GameDetail         downloadable = game.GameDetails.Where(g => !g.phyCopy).SingleOrDefault();
            List <OrderDetail> orders;

            if (physical != null)
            {
                ViewBag.phyPrice       = physical.price;
                gameAndGameDetails.qoh = physical.qoh;
                orders       = db.OrderDetails.Where(o => o.gameDetailId == physical.gameDetailId).ToList();
                ViewBag.buys = orders != null ? orders.Count : 0;
            }
            if (downloadable != null)
            {
                ViewBag.downPrice = downloadable.price;
                orders            = db.OrderDetails.Where(o => o.gameDetailId == downloadable.gameDetailId).ToList();
                ViewBag.downloads = orders != null ? orders.Count : 0;
            }
            gameAndGameDetails.genreCode = game.GameGenres.First().genreCode;
            return(View(gameAndGameDetails));
        }
Exemplo n.º 26
0
        public async Task <IHttpActionResult> DeleteGameDetail(int id)
        {
            GameDetail gameDetail = await db.GameDetails.FindAsync(id);

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

            db.GameDetails.Remove(gameDetail);
            await db.SaveChangesAsync();

            return(Ok(gameDetail));
        }
Exemplo n.º 27
0
        public ActionResult Edit([Bind(Include = "gameDetailId,gameId,title,platformCode,publisher,price,qoh,relDate,genreCode,desc")] GameAndGameDetails gameAndGameDetails)
        {
            Account account = Session["account"] as Account;

            if (account == null)
            {
                TempData["infoMsg"] = "You must be logged in.";
                return(RedirectToAction("", "Login"));
            }
            if (account.roleCode != "employee")
            {
                throw new HttpException(403, "Access denied");
            }
            if (gameAndGameDetails.relDate > DateTime.Today)
            {
                ModelState.AddModelError("relDate", "Release date cannot be later than today.");
            }
            if (ModelState.IsValid)
            {
                try
                {
                    Game game = db.Games.Find(gameAndGameDetails.gameId);
                    game.title           = gameAndGameDetails.title;
                    game.relDate         = gameAndGameDetails.relDate;
                    game.desc            = gameAndGameDetails.desc;
                    game.publisher       = gameAndGameDetails.publisher;
                    db.Entry(game).State = EntityState.Modified;
                    GameDetail gameDetail = db.GameDetails.Find(gameAndGameDetails.gameDetailId);
                    gameDetail.price           = (decimal)gameAndGameDetails.price;
                    gameDetail.qoh             = gameAndGameDetails.phyCopy ? gameAndGameDetails.qoh : null;
                    db.Entry(gameDetail).State = EntityState.Modified;
                    GamePlatform gamePlatform = db.GamePlatforms.Where(gp => gp.gameId == gameAndGameDetails.gameId).SingleOrDefault();
                    gamePlatform.platformCode = gameAndGameDetails.platformCode;
                    GameGenre gameGenre = db.GameGenres.Where(gg => gg.gameId == gameAndGameDetails.gameId).SingleOrDefault();
                    gameGenre.genreCode          = gameAndGameDetails.genreCode;
                    db.Entry(gamePlatform).State = EntityState.Modified;
                    db.Entry(gameGenre).State    = EntityState.Modified;
                    db.SaveChanges();
                    return(RedirectToAction("Index"));
                }
                catch (Exception)
                {
                    TempData["errMsg"] = "An unexpected error has occurred. Please try again later.";
                }
            }
            ViewBag.genres     = new SelectList(db.Genres, "genreCode", "genreCode", gameAndGameDetails.genreCode);
            ViewBag.platforms  = new SelectList(db.Platforms, "platformCode", "platformCode", gameAndGameDetails.platformCode);
            ViewBag.publishers = new SelectList(Enum.GetValues(typeof(GameEnums.Publisher)), gameAndGameDetails.publisher);
            return(View(gameAndGameDetails));
        }
Exemplo n.º 28
0
        private void UpdateServerDetailsView(GameDetail gsd)
        {
            if (gsd != null)
            {
                bool     serverStatus = TestGameServerStatus(gsd.ServerName);
                string[] friendslist  = GetFriendsFromPlayerList(gsd.PlayerList).ToArray();

                this.lbDetail_ServerName.Content         = gsd.ServerName;
                this.lbDetail_ServerStatus.Content       = serverStatus.ToString();
                this.lbDetail_JoinedFriends.Content      = friendslist.Length;
                this.ltbDetail_ListedFriends.ItemsSource = friendslist;
                this.btnJoinServer.IsEnabled             = serverStatus;
            }
        }
Exemplo n.º 29
0
        public void GetLiveGameDetailTestBasic()
        {
            NHLApiClient api = new NHLApiClient();

            // Load Expected result from file
            var testResponse = File.ReadAllText(@"../../../TestAPIResponses/GetLiveGameDetailResult.json");
            var jobj         = JObject.Parse(testResponse);
            var expected     = JsonConvert.DeserializeObject <GameDetail>(jobj.ToString());

            // Make API web call
            GameDetail actual = api.GetLiveGameDetail(2017030325); //Jets vs Vegas WCF Game 5 2018

            //Assert
            Assert.AreEqual(expected, actual);
        }
Exemplo n.º 30
0
        public static GameDetail ToGameDetail(this List <Attribute> attributes)
        {
            var retval             = new GameDetail();
            var gameDetailPropInfo = retval.GetType();

            foreach (var anAttribuite in attributes)
            {
                var prop = gameDetailPropInfo.GetProperty(anAttribuite.Name);

                //do the conversion and set it
                prop.SetValue(retval, System.Convert.ChangeType(anAttribuite.Value, prop.PropertyType), null);
            }

            return(retval);
        }
Exemplo n.º 31
0
        public async Task <GameDetail> GetGameDetails(string ID)
        {
            HttpResponseMessage response = await client.GetAsync($"games/{ID}?key={api}");

            if (response.IsSuccessStatusCode)
            {
                string content = await response.Content.ReadAsStringAsync();

                GameDetail game = JsonConvert.DeserializeObject <GameDetail>(content);
                if (game != null)
                {
                    return(game);
                }
            }
            return(null);
        }
Exemplo n.º 32
0
        public static String getMove(GameDetail game)
        {
            //Find the closest coin
            int currentLoc = game.thisPlayer.x * 10 + game.thisPlayer.y;
            int minLoc = currentLoc;
            int minsDist = 100;
            foreach (dynamic coin in game.coins)
            {
                int dist = getPath(game, currentLoc, coin.x * 10 + coin.y).Count;
                if (dist < minsDist)
                {
                    minLoc = coin.x * 10 + coin.y;
                    minsDist = dist;
                }
            }

            foreach (dynamic lifePack in game.lifePacks)
            {
                int dist = getPath(game, currentLoc, lifePack.x * 10 + lifePack.y).Count;
                if (dist < minsDist)
                {
                    minLoc = lifePack.x * 10 + lifePack.y;
                    minsDist = dist;
                }
            }

            if (minsDist == 100) return Constant.SHOOT;

            int from = game.thisPlayer.x * 10 + game.thisPlayer.y;
            int to = minLoc;

            List<int> path = getPath(game, from, to);

            if (path == null || path.Count == 0)
            {
                Console.WriteLine("Error:" + from + " " + to);
                return Constant.SHOOT;
            }

            Console.WriteLine(path[0]);

            if (path[0] - from == 10) return Constant.RIGHT;
            if (path[0] - from == -10) return Constant.LEFT;
            if (path[0] - from == 1) return Constant.DOWN;
            else  return Constant.UP;
        }
Exemplo n.º 33
0
        public static List<int> getPath(GameDetail game,int from, int to)
        {
            List<int> path = new List<int>();

            //Mark cells unvisited | when we visit them, mark with parent cell's id
            int[] parents = new int[100];
            for (int i = 0; i < 100; i++)
                parents[i] = -1;

            //Queue to enque tmperol cells
            Queue<int> queue = new Queue<int>();
            queue.Enqueue(from);

            while(queue.Count>0)
            {
                int block = queue.Dequeue();
                int i = block / 10, j = block % 10;

                if (game.blocks[i, j].GetType() != typeof(EmptyBlock))
                {
                    parents[block] = -2;
                    continue;//do no add childs if it is a blocked cell
                }

                if(i>0)
                {
                    int tmp = (i - 1) * 10 + j;
                    if (parents[tmp] == -1)
                    {
                        parents[tmp] = block;
                        queue.Enqueue(tmp);
                    }
                }
                if (j > 0)
                {
                    int tmp = (i) * 10 + j-1;
                    if (parents[tmp] == -1)
                    {
                        parents[tmp] = block;
                        queue.Enqueue(tmp);
                    }
                }
                if (i <9)
                {
                    int tmp = (i + 1) * 10 + j;
                    if (parents[tmp] == -1)
                    {
                        parents[tmp] = block;
                        queue.Enqueue(tmp);
                    }
                }
                if (j < 9)
                {
                    int tmp = (i) * 10 + j+1;
                    if (parents[tmp] == -1)
                    {
                        parents[tmp] = block;
                        queue.Enqueue(tmp);
                    }
                }
            }

            //Return null if we can't find a possible path
            if (parents[to] <0) return path;

            //Find the path
            int movingCell = to;
            while(movingCell!=from)
            {
                path.Add(movingCell);
                movingCell = parents[movingCell];
            }
            path.Reverse();
            return path;
        }
Exemplo n.º 34
0
        public static String getMoveNew(GameDetail game, TimeSpan time)
        {
            List<int[]> items = new List<int[]>();
            if(game.thisPlayer.health>50 || game.coins.Count==0)
                foreach(LifePack l in game.lifePacks)
                {
                    items.Add(new int[] { l.x, l.y, 5000,  ((time - l.arrivedTime).Seconds)   });
                }

            foreach (Coin c in game.coins)
            {
                items.Add(new int[] { c.x, c.y, c.value, ((time - c.arrivedTime).Seconds) });
            }

            //List<int[]> playerDistances = new List<int[]>();
            int[] moves = new int[items.Count];

                int[,,] grid = new int[10, 10, 4];

                int[] start = new int[] { game.thisPlayer.x, game.thisPlayer.y, game.thisPlayer.direction };

                Queue<int[]> queue = new Queue<int[]>();
                queue.Enqueue(start);
                grid[start[0], start[1], start[2]] = 1;

                while (queue.Count > 0)
                {
                    int[] current = queue.Dequeue();
                    int currentDistance = grid[current[0], current[1], current[2]];

                    for (int i = 0; i < 4; i++)
                    {
                        int[] loc;
                        if (i != current[2])
                        {
                            if (grid[current[0], current[1], i] != 0) continue;

                            loc = new int[] { current[0], current[1], i };
                            queue.Enqueue(loc);
                            grid[loc[0], loc[1], loc[2]] = currentDistance + 1;

                            if (currentDistance == 1) grid[loc[0], loc[1], loc[2]] += 10000 * i;
                        }
                        else {
                            loc = null;
                            //up
                            if (i == 0 && current[1] > 0)
                                loc = new int[] { current[0], current[1] - 1, i };
                            //Down
                            else if (i == 2 && current[1] < 9)
                                loc = new int[] { current[0], current[1] + 1, i };
                            //Right
                            else if (i == 1 && current[0] < 9)
                                loc = new int[] { current[0] + 1, current[1], i };
                            //Left
                            else if (i == 3 && current[0] > 0)
                                loc = new int[] { current[0] - 1, current[1], i };

                            if (loc != null && grid[loc[0], loc[1], loc[2]] == 0 && game.blocks[loc[0], loc[1]].GetType() == typeof(EmptyBlock))
                            {
                                queue.Enqueue(loc);
                                grid[loc[0], loc[1], loc[2]] = currentDistance + 1;
                                if (currentDistance == 1) grid[loc[0], loc[1], loc[2]] += 10000 * i;
                            }
                        }
                    }
                }

                int[] distances = new int[items.Count];

                for(int i=0; i<items.Count; i++)
                {
                    int x = items[i][0], y = items[i][1];
                    // int x = 1, y = 1;
                    int min = 9000;
                    int move = 5;
                    for (int j = 0; j < 4; j++)
                    {
                        if (min > (grid[x, y, j] % 10000))
                        {
                            min = grid[x, y, j] % 10000;
                            move = grid[x, y, j] / 10000;
                        }
                    }
                    distances[i] = min;
                    moves[i] = move;

                }

            if (items.Count == 0)
            {
                if (game.thisPlayer.direction == 0 && game.thisPlayer.y == 0)
                    return Constant.DOWN;
                if (game.thisPlayer.direction == 1 && game.thisPlayer.x == 9)
                    return Constant.LEFT;
                if (game.thisPlayer.direction == 2 && game.thisPlayer.y == 9)
                    return Constant.UP;
                if (game.thisPlayer.direction == 3 && game.thisPlayer.x == 0)
                    return Constant.RIGHT;
                return Constant.SHOOT;

            }

            int maxItemValue = 0, itemIndex = 0, minSteps = 9000; ;

            for(int i=0; i< items.Count; i++)
            {
                //if (items[i][3] > playerDistances[thisPlayerId][i]) minByOthers[i] = 0;
                    if(minSteps> distances[i])
                    {
                        minSteps = distances[i];
                        itemIndex = i;
                    }
            }
            //If line of sight shoot
            int locx = game.thisPlayer.x, locy = game.thisPlayer.y;

            while (game.blocks[locx, locy].GetType() == typeof(EmptyBlock) || game.blocks[locx, locy].GetType() == typeof(Water))
            {
                if (game.thisPlayer.direction == 0 && locy > 0) locy--;

                else if (game.thisPlayer.direction == 1 && locx < 9) locx++;

                else if (game.thisPlayer.direction == 2 && locy < 9) locy++;

                else if (game.thisPlayer.direction == 3 && locx > 0) locx--;
                else
                    break;

                foreach (Player p in game.players)
                    if (p.x == locx && p.y == locy && p.health > 0 && p.name != game.thisPlayer.name && p.name != null && p.name[0] == 'P') return Constant.SHOOT;
               // Console.WriteLine(locx + " " + locy);
            }

            int finalMove = moves[itemIndex];
            if (finalMove == 0) return Constant.UP;
            else if (finalMove == 1) return Constant.RIGHT;
            else if (finalMove == 2) return Constant.DOWN;
            else if (finalMove == 3) return Constant.LEFT;
            else return "LOL";
        }
        public ActionResult ManageResults( int seasonid, int id, DateTime date, int? gameid )
        {
            var season = new Season();
            var games = new List<GameSchedule>();
            var game = new GameSchedule();
            var homeTeam = new Team();
            var awayTeam = new Team();
            var awayTeamPlayers = new List<Player>();
            var homeTeamPlayers = new List<Player>();
            var homeGoalies = new List<Player>();
            var awayGoalies = new List<Player>();
            var playerScoring = new List<GameScoring>();
            var awayGoalieScoring = new GameGoaltending();
            var homeGoalieScoring = new GameGoaltending();
            var gameDetails = new GameDetail();
            var selectedHomeGoalie = 0;
            var selectedAwayGoalie = 0;

            if ( seasonid > 0 )
            {
                season = ( from s in db.Seasons
                           where s.Id == seasonid
                           select s ).SingleOrDefault<Season>();

                games = ( from g in db.GameSchedules
                          where g.SeasonId == season.Id &&
                          g.GameDate == date
                          orderby g.GameTime ascending
                          select g ).ToList<GameSchedule>();

                if ( games.Count == 0 )
                    Response.Redirect( "/LeagueManager/" + season.Id.ToString() + "/Result?error=nogames" );

                if ( gameid == null || gameid <= 0 )
                    gameid = games.First().Id;

                game = ( from g in db.GameSchedules
                         where g.Id == gameid
                         select g ).SingleOrDefault<GameSchedule>();

                homeTeam = ( from t in db.Teams
                             where t.Id == game.HomeTeamId
                             select t ).SingleOrDefault<Team>();

                awayTeam = ( from t in db.Teams
                             where t.Id == game.AwayTeamId
                             select t ).SingleOrDefault<Team>();

                awayTeamPlayers = ( from tp in db.TeamPlayers
                                    from p in db.Players
                                    where tp.PlayerId == p.Id &&
                                    tp.TeamId == awayTeam.Id &&
                                    p.Position1 != "Goalie" &&
                                    tp.SeasonId == seasonid
                                    orderby p.LastName ascending, p.FirstName ascending
                                    select p ).ToList<Player>();
                awayTeamPlayers.Add( GetPlayerSub() );

                homeTeamPlayers = ( from tp in db.TeamPlayers
                                    from p in db.Players
                                    where tp.PlayerId == p.Id &&
                                    tp.TeamId == homeTeam.Id &&
                                    p.Position1 != "Goalie" &&
                                    tp.SeasonId == seasonid
                                    orderby p.LastName ascending, p.FirstName ascending
                                    select p ).ToList<Player>();
                homeTeamPlayers.Add( GetPlayerSub() );

                awayGoalies = ( from tp in db.TeamPlayers
                                from p in db.Players
                                where tp.TeamId == awayTeam.Id &&
                                p.Id == tp.PlayerId &&
                                tp.IsGoalie == true &&
                                tp.SeasonId == seasonid
                                orderby p.LastName ascending
                                select p ).ToList<Player>();

                if ( awayGoalies.Count == 1 )
                    selectedAwayGoalie = awayGoalies.First().Id;

                awayGoalies.Add( GetGoalieSub() );

                homeGoalies = ( from tp in db.TeamPlayers
                                from p in db.Players
                                where tp.TeamId == homeTeam.Id &&
                                p.Id == tp.PlayerId &&
                                tp.IsGoalie == true &&
                                tp.SeasonId == seasonid
                                orderby p.LastName ascending
                                select p ).ToList<Player>();

                if ( homeGoalies.Count == 1 )
                    selectedHomeGoalie = homeGoalies.First().Id;

                homeGoalies.Add( GetGoalieSub() );

                playerScoring = ( from gs in db.GameScorings
                                  where gs.GameScheduleId == game.Id
                                  select gs ).ToList<GameScoring>();

                homeGoalieScoring = ( from gt2 in db.GameGoaltendings
                                      from p in db.Players
                                      where gt2.GameScheduleId == game.Id &&
                                      gt2.TeamId == homeTeam.Id &&
                                      ( p.Id == gt2.PlayerId )
                                      select gt2 ).SingleOrDefault<GameGoaltending>();

                awayGoalieScoring = ( from gt3 in db.GameGoaltendings
                                      from p in db.Players
                                      where gt3.GameScheduleId == game.Id &&
                                      gt3.TeamId == awayTeam.Id &&
                                      ( p.Id == gt3.PlayerId )
                                      select gt3 ).SingleOrDefault<GameGoaltending>();

                gameDetails = ( from gd in db.GameDetails
                                where gd.GameScheduleId == game.Id
                                select gd ).SingleOrDefault<GameDetail>();
            }
            else
                throw new Exception( "SeasonId value is invalid: 0" );

            return View( "ManageGameResult", new GameResultModel
                                                 {
                                                     Season = season,
                                                     Date = date,
                                                     SelectedGame = ( gameid > 0 ) ? game : games.First(),
                                                     Games = new SelectList( games, "Id", "GameTime", ( game.Id > 0 ) ? game.Id : games.First().Id ),
                                                     AwayTeam = awayTeam,
                                                     HomeTeam = homeTeam,
                                                     AwayTeamPlayers = awayTeamPlayers,
                                                     AwayTeamGoalies = new SelectList( awayGoalies, "Id", "LastName", ( awayGoalieScoring != null ) ? awayGoalieScoring.PlayerId : selectedAwayGoalie ),
                                                     HomeTeamPlayers = homeTeamPlayers,
                                                     HomeTeamGoalies = new SelectList( homeGoalies, "Id", "LastName", ( homeGoalieScoring != null ) ? homeGoalieScoring.PlayerId : selectedHomeGoalie ),
                                                     PlayerScoring = playerScoring,
                                                     HomeGoalieScoring = homeGoalieScoring,
                                                     AwayGoalieScoring = awayGoalieScoring,
                                                     GameDetails = gameDetails,
                                                     Ref1 = new SelectList( GetRefs(), "Id", "LastName", ( gameDetails != null ) ? gameDetails.Referee1 : 0 ),
                                                     Ref2 = new SelectList( GetRefs(), "Id", "LastName", ( gameDetails != null ) ? gameDetails.Referee2 : 0 )
                                                 } );
        }
Exemplo n.º 36
0
    GameDetail ToGameDetail(XmlNode node, ref string errorString)
    {
        try
        {
            GameDetail game = null;
            if (node != null && !string.IsNullOrEmpty(node.InnerXml))
            {
                game = new GameDetail();
                game.Id = node["Id"].InnerText;
                game.Name = node["Name"].InnerText;
                game.Comment = node["Comment"].InnerText;
                bool boolVal = false;
                if (bool.TryParse(node["Active"].InnerText, out boolVal))
                {
                    game.Active = boolVal;
                }

                game.CreatedDate = node["CreatedDate"].InnerText;

                if (bool.TryParse(node["IsAvailableForSponsorship"].InnerText, out boolVal))
                {
                    game.IsAvailableForSponsorship = boolVal;
                }
                float floatVal = 0;

                if (float.TryParse(node["RewardPercentage"].InnerText, out floatVal))
                {
                    game.RewardPercentage = floatVal;
                }

                if (float.TryParse(node["TopWinnersPercentage"].InnerText, out floatVal))
                {
                    game.TopWinnersPercentage = floatVal;
                }

                if (float.TryParse(node["DeveloperPercentage"].InnerText, out floatVal))
                {
                    game.DeveloperPercentage = floatVal;
                }

                game.Extras = node["Extras"].InnerText;
                game.FullDescription = node["FullDescription"].InnerText;

                long longVal = 0;
                if (long.TryParse(node["TotalPlayersParticipated"].InnerText, out longVal))
                {
                    game.TotalPlayersParticipated = longVal;
                }

                List<string> urls = new List<string>();
                XmlNodeList urlNodes = node["DistributionUrls"].ChildNodes;

                foreach (XmlNode urlNode in urlNodes)
                {
                    urls.Add(urlNode.InnerText);
                }
                game.DistributionUrls = urls.ToArray();
                game.GameLogoUrl = node["GameLogoUrl"].InnerText;

                longVal = 0;
                if (long.TryParse(node["LeaderboardAdminSharePercent"].InnerText, out longVal))
                {
                    game.LeaderboardAdminSharePercent = longVal;
                }

                longVal = 0;
                if (long.TryParse(node["LeaderboardPlayershare"].InnerText, out longVal))
                {
                    game.LeaderboardPlayershare = longVal;
                }
                game.GameDescriptionLink = node["GameDescriptionLink"].InnerText;
                return game;
            }
        }
        catch (Exception ex)
        {
            errorString = ex.Message;
        }
        return null;
    }