Exemplo n.º 1
0
        public static void EndGame(Constants.GameEndReason reason)
        {
            SidebarController.ToggleMenu(true);

            if (reason != Constants.GameEndReason.Forced)
            {
                var players = Game.Current.Players.OrderByDescending(p => p.Score).ToList();

                using var dbConnection = new SqliteConnection("Data Source=" + Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), "Game.db"));
                dbConnection.Open();

                var command = dbConnection.CreateCommand();
                command.CommandText = "CREATE TABLE IF NOT EXISTS Scores(Player TEXT NOT NULL, Score INTEGER NOT NULL, Timestamp TEXT NOT NULL)";
                command.ExecuteNonQuery();

                command.CommandText = "BEGIN";
                command.ExecuteNonQuery();

                foreach (var player in players)
                {
                    var insertCommand = dbConnection.CreateCommand();
                    insertCommand.CommandText = "INSERT INTO Scores(Player, Score, Timestamp) VALUES(@Player, @Score, @Timestamp)";
                    insertCommand.Parameters.AddWithValue("@Player", player.Name);
                    insertCommand.Parameters.AddWithValue("@Score", player.Score);
                    insertCommand.Parameters.AddWithValue("@Timestamp", DateTime.Now.ToString(Constants.DatabaseDateTimeFormat));
                    insertCommand.ExecuteNonQuery();
                }

                command.CommandText = "END";
                command.ExecuteNonQuery();
                dbConnection.Close();

                SidebarController.RenderHighscores();

                var winners = players.Where(p => p.Score == players[0].Score).ToList();

                var winText = winners.Count switch
                {
                    1 => $"{winners[0].Name} печели!",
                    2 => $"Равенство между {winners[0].Name} и {winners[1].Name}!",
                    _ => $"Равенство: {string.Join(", ", winners.Select(w => w.Name))}!"
                };

                string message = $"{reason.GetDescription()}\n" +
                                 $"{winText}";
                MessageBox.Show(message, "Край на играта");
            }
        }
    }