Ejemplo n.º 1
0
        /// <summary>
        /// Home page. If data is provided, it means user has played words and pressed Submit.
        /// In that case, returns an updated game object. Otherwise returns a currently existing one.
        /// </summary>
        /// <returns></returns>
        public IActionResult Index()
        {
            Game game = _scrabbleContext.Games.Single(g => g.ID == 1);

            foreach (var p in game.Players)
            {
                p.Rack.RefillRackFromPouch();
            }
            if (TempData["FlipBoard"] != null)
            {
                ViewBag.FlipBoard = TempData["FlipBoard"].ToString();
            }
            List <KeyValuePair <string, StringValues> > data = null;

            try
            {
                data = Request.Form.ToList();
            }
            catch (Exception e)
            {
                //return StatusCode(400, e.Message);
            }
            if (data == null)
            {
                //return StatusCode(400, "No data entered.");
            }
            else
            {
                var playedWords     = Helper.GetPlayedWords(data);
                var playedRackTiles = Helper.GetPlayedRackTiles(data);
                var boardArray      = game.Board.ConvertTo2DArray();
                if (playedRackTiles.Length == 0)
                {
                    return(StatusCode(400, "You have not played a tile."));
                }
                //if (!game.Board.CheckIfAnchorIsUsed(playedRackTiles, boardArray))
                //{
                //    return StatusCode(400, "Anchor is not used.");
                //}
                //if (!Helpers.Helper.ValidateStart(boardArray, playedRackTiles))
                //{
                //    return StatusCode(400, "Invalid start.");
                //}
                //if (!Helpers.Helper.IsRackPlayConnected(boardArray, playedRackTiles))
                //{
                //    return StatusCode(400, "Play is not connected.");
                //}

                var result = Helper.GetWordScores(game, data);
                if (result.StatusCode != 200)
                {
                    return(StatusCode(result.StatusCode, result.StatusDescription));
                }
                game.SwitchToNextPlayer();
            }
            _scrabbleContext.SaveChanges();
            return(View(game));
        }
Ejemplo n.º 2
0
        static void Main(string[] args)
        {
            var config = new ConfigurationBuilder()
                         .SetBasePath(System.IO.Directory.GetCurrentDirectory())
                         .AddJsonFile("appsettings.json", true, true)
                         .AddJsonFile("appsettings.local.json", true, true)
                         .AddEnvironmentVariables()
                         .AddCommandLine(args ?? new string[] { })
                         .Build();

            // create db context
            var connectionString = config.GetConnectionString("Scrabble");
            var dbContextOptions = new DbContextOptionsBuilder <ScrabbleContext>()
                                   .UseNpgsql(connectionString)
                                   .Options;
            var dbContext = new ScrabbleContext(dbContextOptions);

            var players       = dbContext.Players.ToList();
            var existingGames = dbContext.Games.ToList();

            // load file data
            var filename = args[0];
            var filetext = System.IO.File.ReadAllText(filename);
            var filedata = JObject.Parse(filetext);

            var rowdata = filedata["sheets"][0]["data"][0]["rowData"];

            Console.WriteLine($"{filedata["sheets"] == null}");
            Console.WriteLine($"{filedata["sheets"][0] == null}");
            Console.WriteLine($"{filedata["sheets"][0]["data"][0]["rowData"] == null}");

            var currentGame = null as Game;

            foreach (var(col, columnIndex) in rowdata[0]["values"].Enumerate())
            {
                var dateStr = col["formattedValue"]?.ToString();
                if (dateStr != null)
                {
                    var date = DateTimeOffset.ParseExact(dateStr, "d.MM.yyyy", System.Globalization.CultureInfo.CurrentCulture);
                    Console.WriteLine(date);
                    var existingGame = existingGames.Any(g => g.Start.Date == date);
                    if (existingGame)
                    {
                        Console.WriteLine("Game already imported, skipping");
                        currentGame = null;
                    }
                    else
                    {
                        dbContext.SaveChanges();
                        currentGame = new Game()
                        {
                            Start       = date,
                            End         = date,
                            GamePlayers = new List <GamePlayer>(),
                            Rounds      = new List <Round>(),
                        };
                        dbContext.Games.Add(currentGame);
                    }
                }

                if (currentGame != null)
                {
                    var playerName = rowdata[1]["values"][columnIndex]["formattedValue"].ToString();
                    Console.WriteLine($"  Player {playerName}");

                    var player = players.FirstOrDefault(p => string.Equals(p.Name, playerName, StringComparison.CurrentCultureIgnoreCase));
                    if (player == null)
                    {
                        player = new Player()
                        {
                            Name = playerName,
                        };
                        players.Add(player);
                    }
                    currentGame.GamePlayers.Add(new GamePlayer
                    {
                        Player = player,
                        Order  = currentGame.GamePlayers.Count(),
                    });

                    for (var rowIndex = 3; rowIndex < 30; rowIndex++)
                    {
                        var scoreStr = rowdata[rowIndex]["values"][columnIndex]?["formattedValue"]?.Value <string>();
                        if (scoreStr == null)
                        {
                            break;
                        }

                        if (!int.TryParse(scoreStr, out var score))
                        {
                            Console.WriteLine($"Parse error in score: {scoreStr}");
                            break;
                        }

                        var roundNumber = rowIndex - 2;
                        var round       = currentGame.Rounds.FirstOrDefault(r => r.RoundNumber == roundNumber);
                        if (round == null)
                        {
                            round = new Round
                            {
                                RoundNumber  = roundNumber,
                                PlayerRounds = new List <PlayerRound>(),
                            };
                            currentGame.Rounds.Add(round);
                        }

                        round.PlayerRounds.Add(new PlayerRound {
                            Player = player,
                            Score  = score,
                        });

                        Console.WriteLine($"    {score}");
                    }
                }
            }

            dbContext.SaveChanges();
        }