Ejemplo n.º 1
0
        async Task StartOnlineGame(DataNew.Entities.Game game, string name, string password)
        {
            var client = new Octgn.Site.Api.ApiClient();

            if (!client.IsGameServerRunning(Program.LobbyClient.Username, Program.LobbyClient.Password))
            {
                throw new UserMessageException("The game server is currently down. Please try again later.");
            }
            Program.CurrentOnlineGameName = name;
            // TODO: Replace this with a server-side check
            password = SubscriptionModule.Get().IsSubscribed == true ? password : String.Empty;
            var result = await Program.LobbyClient.HostGame(game, name, password, game.Name, game.IconUrl,
                                                            typeof(Octgn.Server.Server).Assembly.GetName().Version, Specators);

            if (result == null)
            {
                throw new InvalidOperationException("HostGame returned a null");
            }

            Program.LobbyClient.CurrentHostedGamePort = (int)result.Port;
            //Program.GameSettings.UseTwoSidedTable = true;
            Program.GameEngine = new GameEngine(game, Program.LobbyClient.Me.UserName, false, this.Password);
            Program.IsHost     = true;

            var hostAddress = Dns.GetHostAddresses(AppConfig.GameServerPath).First();

            // Should use gameData.IpAddress sometime.
            Program.Client = new ClientSocket(hostAddress, (int)result.Port);
            Program.Client.Connect();
            SuccessfulHost = true;
        }
Ejemplo n.º 2
0
 public GameListItem()
 {
     InitializeComponent();
     _game = new DataNew.Entities.Game();
     DataContext = this;
     LIBorder.DataContext = this;
 }
Ejemplo n.º 3
0
        private void StartJoinGame(HostedGameViewModel hostedGame, DataNew.Entities.Game game)
        {
            Log.InfoFormat("Starting to join a game {0} {1}", hostedGame.GameId, hostedGame.Name);
            Program.IsHost                = false;
            Program.GameEngine            = new GameEngine(game, Program.LobbyClient.Me.UserName);
            Program.CurrentOnlineGameName = hostedGame.Name;
            IPAddress hostAddress = Dns.GetHostAddresses(AppConfig.GameServerPath).FirstOrDefault();

            if (hostAddress == null)
            {
                Log.WarnFormat("Dns Error, couldn't resolve {0}", AppConfig.GameServerPath);
                throw new UserMessageException("There was a problem with your DNS. Please try again.");
            }

            try
            {
                Log.InfoFormat("Creating client for {0}:{1}", hostAddress, hostedGame.Port);
                Program.Client = new Client(hostAddress, hostedGame.Port);
                Log.InfoFormat("Connecting client for {0}:{1}", hostAddress, hostedGame.Port);
                Program.Client.Connect();
            }
            catch (Exception e)
            {
                Log.Warn("Start join game error ", e);
                throw new UserMessageException("Could not connect. Please try again.");
            }
        }
Ejemplo n.º 4
0
        void StartLocalGame(DataNew.Entities.Game game, string name, string password)
        {
            var hs = new HostedGame(HostPort, game.Id, game.Version, game.Name, name, null, new User(Prefs.Nickname + "@" + AppConfig.ChatServerPath), true);

            if (!hs.StartProcess())
            {
                throw new UserMessageException("Cannot start local game. You may be missing a file.");
            }
            Program.LobbyClient.CurrentHostedGamePort = HostPort;
            Program.GameSettings.UseTwoSidedTable     = true;
            Program.GameEngine = new GameEngine(game, Prefs.Nickname, true);
            Program.IsHost     = true;

            var ip = IPAddress.Parse("127.0.0.1");

            for (var i = 0; i < 5; i++)
            {
                try
                {
                    Program.Client = new Octgn.Networking.Client(ip, HostPort);
                    Program.Client.Connect();
                    return;
                }
                catch (Exception e)
                {
                    Log.Warn("Start local game error", e);
                    if (i == 4)
                    {
                        throw;
                    }
                }
                Thread.Sleep(2000);
            }
            throw new UserMessageException("Cannot start local game. You may be missing a file.");
        }
Ejemplo n.º 5
0
 public GameListItem()
 {
     InitializeComponent();
     _game                = new DataNew.Entities.Game();
     DataContext          = this;
     LIBorder.DataContext = this;
 }
Ejemplo n.º 6
0
        Task <bool> StartLocalGame(DataNew.Entities.Game game, string name, string password)
        {
            var octgnVersion = typeof(Server.Server).Assembly.GetName().Version;

            var user = Program.LobbyClient?.User
                       ?? new User(Guid.NewGuid().ToString(), Username);

            var username = user.DisplayName;

            var hg = new HostedGame()
            {
                Id           = Guid.NewGuid(),
                Name         = name,
                HostUser     = user,
                GameName     = game.Name,
                GameId       = game.Id,
                GameVersion  = game.Version.ToString(),
                HostAddress  = $"0.0.0.0:{Prefs.LastLocalHostedGamePort}",
                Password     = password,
                OctgnVersion = octgnVersion.ToString(),
                GameIconUrl  = game.IconUrl,
                Spectators   = true,
                DateCreated  = DateTimeOffset.Now
            };

            if (Program.LobbyClient?.User != null)
            {
                hg.HostUserIconUrl = ApiUserCache.Instance.ApiUser(Program.LobbyClient.User)?.IconUrl;
            }

            return(Program.JodsEngine.HostGame(hg, HostedGameSource.Lan, username, password));
        }
Ejemplo n.º 7
0
 public DataGameViewModel(DataNew.Entities.Game game)
 {
     Id          = game.Id;
     Name        = game.Name;
     Version     = game.Version;
     CardBackUri = new Uri(game.CardSize.Back);
     //FullPath = game.FullPath;
     IsSelected = false;
 }
Ejemplo n.º 8
0
        public void CheckXml(DataNew.Entities.Game game)
        {
            XmlSetParser xmls = xml_set;

            if (game.Id.ToString() != xmls.game())
            {
                throw new Exception("Error! Wrong game specified in xml");
            }
            xmls.check();
        }
Ejemplo n.º 9
0
        private void LoadDeck(DataNew.Entities.Game game)
        {
            if (_unsaved)
            {
                MessageBoxResult result = TopMostMessageBox.Show("This deck contains unsaved modifications. Save?", "Warning",
                                                                 MessageBoxButton.YesNoCancel, MessageBoxImage.Warning);
                switch (result)
                {
                case MessageBoxResult.Yes:
                    Save();
                    break;

                case MessageBoxResult.No:
                    break;

                default:
                    return;
                }
            }
            // Show the dialog to choose the file
            var ofd = new OpenFileDialog
            {
                Filter           = "Octgn deck files (*.o8d) | *.o8d",
                InitialDirectory = game.GetDefaultDeckPath()
            };

            if (ofd.ShowDialog() != true)
            {
                return;
            }

            // Try to load the file contents
            ObservableDeck newDeck;

            try
            {
                newDeck = new Deck().Load(game, ofd.FileName).AsObservable();
                Game    = GameManager.Get().Games.First(x => x.Id == newDeck.GameId);
            }
            catch (UserMessageException ex)
            {
                TopMostMessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            catch (Exception ex)
            {
                TopMostMessageBox.Show("Octgn couldn't load the deck.\r\nDetails:\r\n\r\n" + ex.Message, "Error",
                                       MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            //Game = Program.GamesRepository.Games.First(g => g.Id == newDeck.GameId);
            Deck          = newDeck;
            _deckFilename = ofd.FileName;
            CommandManager.InvalidateRequerySuggested();
        }
Ejemplo n.º 10
0
        public void CheckXml(Windows.ChangeSetsProgressDialog wnd, int max, DataNew.Entities.Game game)
        {
            XmlSetParser xmls = xml_set;

            if (game.Id.ToString() != xmls.game())
            {
                wnd.UpdateProgress(max, max, string.Format("Error! Wrong game specified in xml"), false);
                return;
            }
            xmls.check();
        }
Ejemplo n.º 11
0
        async Task StartOnlineGame(DataNew.Entities.Game game, string name, string password)
        {
            var client = new Octgn.Site.Api.ApiClient();

            if (!await client.IsGameServerRunning(Prefs.Username, Prefs.Password.Decrypt()))
            {
                throw new UserMessageException("The game server is currently down. Please try again later.");
            }
            Program.CurrentOnlineGameName = name;
            // TODO: Replace this with a server-side check
            password = SubscriptionModule.Get().IsSubscribed == true ? password : String.Empty;

            var octgnVersion = typeof(Server.Server).Assembly.GetName().Version;

            var req = new HostedGame {
                GameId       = game.Id,
                GameVersion  = game.Version.ToString(),
                Name         = name,
                GameName     = game.Name,
                GameIconUrl  = game.IconUrl,
                Password     = password,
                HasPassword  = !string.IsNullOrWhiteSpace(password),
                OctgnVersion = octgnVersion.ToString(),
                Spectators   = Specators
            };

            var result = await Program.LobbyClient.HostGame(req);

            Program.CurrentHostedGame = result ?? throw new InvalidOperationException("HostGame returned a null");
            Program.GameEngine        = new GameEngine(game, Program.LobbyClient.Me.DisplayName, false, this.Password);
            Program.IsHost            = true;

            foreach (var address in Dns.GetHostAddresses(AppConfig.GameServerPath))
            {
                try {
                    if (address == IPAddress.IPv6Loopback)
                    {
                        continue;
                    }

                    // Should use gameData.IpAddress sometime.
                    Log.Info($"{nameof(StartOnlineGame)}: Trying to connect to {address}:{result.Port}");

                    Program.Client = new ClientSocket(address, result.Port);
                    await Program.Client.Connect();

                    SuccessfulHost = true;
                    return;
                } catch (Exception ex) {
                    Log.Error($"{nameof(StartOnlineGame)}: Couldn't connect to address {address}:{result.Port}", ex);
                }
            }
            throw new InvalidOperationException($"Unable to connect to {AppConfig.GameServerPath}.{result.Port}");
        }
Ejemplo n.º 12
0
        void StartOnlineGame(DataNew.Entities.Game game, string name, string password)
        {
            var client = new Octgn.Site.Api.ApiClient();

            if (!client.IsGameServerRunning(Program.LobbyClient.Username, Program.LobbyClient.Password))
            {
                throw new UserMessageException("The game server is currently down. Please try again later.");
            }
            Program.CurrentOnlineGameName = name;
            Program.LobbyClient.BeginHostGame(game, name, password, game.Name);
        }
Ejemplo n.º 13
0
        private void GameSelector_GameChanged(object sender, DataNew.Entities.Game e)
        {
            var gameIndex = Games.FindIndex(g => g.Id == e?.Id);

            if (gameIndex == -1)
            {
                gameIndex = 0;
            }

            ComboBoxGame.SelectedIndex = gameIndex;
        }
Ejemplo n.º 14
0
 public SearchControl(DataNew.Entities.Game game)
 {
     Game = game;
     InitializeComponent();
     filtersList.ItemsSource =
         Enumerable.Repeat <object>("First", 1).Union(
             Enumerable.Repeat <object>(new SetPropertyDef(Game.Sets()), 1).Union(
                 game.AllProperties().Where(p => !p.Hidden)));
     GenerateColumns(game);
     //resultsGrid.ItemsSource = game.SelectCards(null).DefaultView;
     UpdateDataGrid(game.AllCards().ToDataTable(Game).DefaultView);
 }//Why are we populating the list on load? I'd rather wait until the search is run with no parameters (V)_V
Ejemplo n.º 15
0
        async Task StartLocalGame(DataNew.Entities.Game game, string name, string password)
        {
            var hg = new HostedGame()
            {
                Id          = Guid.NewGuid(),
                Name        = name,
                HostUser    = Program.LobbyClient?.Me,
                GameName    = game.Name,
                GameId      = game.Id,
                GameVersion = game.Version.ToString(),
                HostAddress = $"0.0.0.0:{HostPort}",
                Password    = password,
                GameIconUrl = game.IconUrl,
                Spectators  = true,
            };

            if (Program.LobbyClient?.Me != null)
            {
                hg.HostUserIconUrl = ApiUserCache.Instance.ApiUser(Program.LobbyClient.Me).IconUrl;
            }
            // We don't use a userid here becuase we're doing a local game.
            var hs = new HostedGameProcess(hg, X.Instance.Debug, true);

            hs.Start();

            Program.GameSettings.UseTwoSidedTable = HostGame.UseTwoSidedTable;
            Program.IsHost     = true;
            Program.GameEngine = new GameEngine(game, Prefs.Nickname, false, password, true);

            var ip = IPAddress.Parse("127.0.0.1");

            for (var i = 0; i < 5; i++)
            {
                try
                {
                    Program.Client = new Octgn.Networking.ClientSocket(ip, HostPort);
                    await Program.Client.Connect();

                    return;
                }
                catch (Exception e)
                {
                    Log.Warn("Start local game error", e);
                    if (i == 4)
                    {
                        throw;
                    }
                }
                Thread.Sleep(2000);
            }
            throw new UserMessageException("Cannot start local game. You may be missing a file.");
        }
Ejemplo n.º 16
0
 // C'tor
 internal Player(DataNew.Entities.Game g, string name, byte id, ulong pkey)
 {
     State = PlayerState.Connected;
     // Init fields
     _name     = name;
     Id        = id;
     PublicKey = pkey;
     // Register the lPlayer
     Application.Current.Dispatcher.Invoke(new Action(() => all.Add(this)));
     //Create the color brushes
     SetPlayerColor(id);
     // Create counters
     _counters = new Counter[0];
     if (g.Player.Counters != null)
     {
         _counters = g.Player.Counters.Select(x => new Counter(this, x)).ToArray();
     }
     // Create variables
     Variables = new Dictionary <string, int>();
     foreach (var varDef in g.Variables.Where(v => !v.Global))
     {
         Variables.Add(varDef.Name, varDef.Default);
     }
     // Create global variables
     GlobalVariables = new Dictionary <string, string>();
     foreach (var varD in g.Player.GlobalVariables)
     {
         GlobalVariables.Add(varD.Name, varD.Value);
     }
     // Create a hand, if any
     if (g.Player.Hand != null)
     {
         _hand = new Hand(this, g.Player.Hand);
     }
     // Create groups
     _groups = new Group[0];
     if (g.Player.Groups != null)
     {
         var tempGroups = g.Player.Groups.ToArray();
         _groups    = new Group[tempGroups.Length + 1];
         _groups[0] = _hand;
         for (int i = 1; i < IndexedGroups.Length; i++)
         {
             _groups[i] = new Pile(this, tempGroups[i - 1]);
         }
     }
     // Raise the event
     if (PlayerAdded != null)
     {
         PlayerAdded(null, new PlayerEventArgs(this));
     }
 }
Ejemplo n.º 17
0
        // C'tor for global items
        internal Player(DataNew.Entities.Game g)
        {
            all.CollectionChanged += (sender, args) =>
            {
                allExceptGlobal.Clear();
                foreach (var p in all.ToArray().Where(x => x != Player.GlobalPlayer))
                {
                    allExceptGlobal.Add(p);
                }
            };
            State = PlayerState.Connected;
            var globalDef = g.GlobalPlayer;

            // Register the lPlayer
            lock (all)
                all.Add(this);
            // Init fields
            _name     = "Global";
            Id        = 0;
            PublicKey = 0;
            if (GlobalVariables == null)
            {
                // Create global variables
                GlobalVariables = new Dictionary <string, string>();
                foreach (var varD in g.Player.GlobalVariables)
                {
                    GlobalVariables.Add(varD.Name, varD.Value);
                }
            }
            // Create counters
            _counters = new Counter[0];
            if (globalDef.Counters != null)
            {
                _counters = globalDef.Counters.Select(x => new Counter(this, x)).ToArray();
            }
            // Create global's lPlayer groups
            // TODO: This could fail with a run-time exception on write, make it safe
            // I don't know if the above todo is still relevent - Kelly Elton - 3/18/2013
            if (globalDef.Groups != null)
            {
                var tempGroups = globalDef.Groups.ToArray();
                _groups    = new Group[tempGroups.Length + 1];
                _groups[0] = _hand;
                for (int i = 1; i < IndexedGroups.Length; i++)
                {
                    _groups[i] = new Pile(this, tempGroups[i - 1]);
                }
            }
            OnPropertyChanged("All");
            OnPropertyChanged("AllExceptGlobal");
            OnPropertyChanged("Count");
        }
Ejemplo n.º 18
0
        void StartOnlineGame(DataNew.Entities.Game game, string name, string password)
        {
            var client = new Octgn.Site.Api.ApiClient();

            if (!client.IsGameServerRunning(Program.LobbyClient.Username, Program.LobbyClient.Password))
            {
                throw new UserMessageException("The game server is currently down. Please try again later.");
            }
            Program.CurrentOnlineGameName = name;
            // TODO: Replace this with a server-side check
            password = SubscriptionModule.Get().IsSubscribed == true ? password : String.Empty;
            Program.LobbyClient.BeginHostGame(game, name, password, game.Name,
                                              typeof(Octgn.Server.Server).Assembly.GetName().Version, Specators);
        }
Ejemplo n.º 19
0
        private void StartJoinGame(HostedGameViewModel hostedGame, DataNew.Entities.Game game, bool spectate)
        {
            if (hostedGame.GameSource == "Online")
            {
                var client = new Octgn.Site.Api.ApiClient();
                if (!client.IsGameServerRunning(Program.LobbyClient.Username, Program.LobbyClient.Password))
                {
                    throw new UserMessageException("The game server is currently down. Please try again later.");
                }
            }
            Log.InfoFormat("Starting to join a game {0} {1}", hostedGame.GameId, hostedGame.Name);
            Program.IsHost        = false;
            Program.IsMatchmaking = false;
            var password = "";

            if (hostedGame.HasPassword)
            {
                Dispatcher.Invoke(new Action(() =>
                {
                    var dlg  = new InputDlg("Password", "Please enter this games password", "");
                    password = dlg.GetString();
                }));
            }
            var username = (Program.LobbyClient.IsConnected == false ||
                            Program.LobbyClient.Me == null ||
                            Program.LobbyClient.Me.UserName == null) ? Prefs.Nickname : Program.LobbyClient.Me.UserName;

            Program.GameEngine            = new GameEngine(game, username, spectate, password);
            Program.CurrentOnlineGameName = hostedGame.Name;
            IPAddress hostAddress = hostedGame.IPAddress;

            if (hostAddress == null)
            {
                Log.WarnFormat("Dns Error, couldn't resolve {0}", AppConfig.GameServerPath);
                throw new UserMessageException("There was a problem with your DNS. Please try again.");
            }

            try
            {
                Log.InfoFormat("Creating client for {0}:{1}", hostAddress, hostedGame.Port);
                Program.Client = new ClientSocket(hostAddress, hostedGame.Port);
                Log.InfoFormat("Connecting client for {0}:{1}", hostAddress, hostedGame.Port);
                Program.Client.Connect();
            }
            catch (Exception e)
            {
                Log.Warn("Start join game error ", e);
                throw new UserMessageException("Could not connect. Please try again.");
            }
        }
Ejemplo n.º 20
0
        private void GenerateColumns(DataNew.Entities.Game game)
        {
            foreach (DataNew.Entities.PropertyDef prop in game.CustomProperties)
            {
                if (prop.Name == "Name" || prop.Hidden)
                {
                    continue;
                }
                if (prop.Type == DataNew.Entities.PropertyType.RichText)
                {
                    var binding = new Binding
                    {
                        Path               = new PropertyPath(prop.Name),
                        Mode               = BindingMode.OneTime,
                        Converter          = new RichTextConverter(),
                        ConverterParameter = game
                    };

                    var factory = new FrameworkElementFactory(typeof(RichTextBlock));
                    factory.SetValue(TextBlock.TextWrappingProperty, TextWrapping.Wrap);
                    factory.SetBinding(RichTextBlock.InlineProperty, binding);

                    var template = new DataTemplate()
                    {
                        VisualTree = factory
                    };
                    var textColumn = new DataGridTemplateColumn()
                    {
                        SortMemberPath = prop.Name,
                        CanUserSort    = true,
                        Header         = prop.Name,
                        CellTemplate   = template,
                    };
                    resultsGrid.Columns.Add(textColumn);
                }
                else
                {
                    resultsGrid.Columns.Add(new DataGridTextColumn
                    {
                        Binding = new Binding
                        {
                            Path = new PropertyPath(prop.Name),
                            Mode = BindingMode.OneTime
                        },
                        Header = prop.Name
                    });
                }
            }
        }
Ejemplo n.º 21
0
        async Task <bool> StartOnlineGame(DataNew.Entities.Game game, string name, string password)
        {
            var client = new Octgn.Site.Api.ApiClient();

            if (!await client.IsGameServerRunning(Prefs.Username, Prefs.Password.Decrypt()))
            {
                throw new UserMessageException("The game server is currently down. Please try again later.");
            }
            Program.CurrentOnlineGameName = name;
            // TODO: Replace this with a server-side check
            password = SubscriptionModule.Get().IsSubscribed == true ? password : String.Empty;

            var octgnVersion = typeof(Server.Server).Assembly.GetName().Version;

            var req = new HostedGame {
                GameId       = game.Id,
                GameVersion  = game.Version.ToString(),
                Name         = name,
                GameName     = game.Name,
                GameIconUrl  = game.IconUrl,
                Password     = password,
                HasPassword  = !string.IsNullOrWhiteSpace(password),
                OctgnVersion = octgnVersion.ToString(),
                Spectators   = Specators
            };

            var lobbyClient = Program.LobbyClient ?? throw new InvalidOperationException("lobby client null");

            HostedGame result = null;

            try {
                result = await lobbyClient.HostGame(req);
            } catch (ErrorResponseException ex) {
                if (ex.Code != ErrorResponseCodes.UserOffline)
                {
                    throw;
                }
                throw new UserMessageException("The Game Service is currently offline. Please try again.");
            }

            var launchedEngine = await Program.JodsEngine.HostGame(
                result,
                HostedGameSource.Online,
                lobbyClient.User.DisplayName,
                Password
                );

            return(launchedEngine);
        }
Ejemplo n.º 22
0
        void StartLocalGame(DataNew.Entities.Game game, string name, string password)
        {
            var hostport = new Random().Next(5000, 6000);

            while (!Networking.IsPortAvailable(hostport))
            {
                hostport++;
            }
            var hs = new HostedGame(hostport, game.Id, game.Version, game.Name, name
                                    , Password, new User(Username + "@" + AppConfig.ChatServerPath), Specators, true);

            if (!hs.StartProcess())
            {
                throw new UserMessageException("Cannot start local game. You may be missing a file.");
            }
            Prefs.Nickname = Username;
            Program.LobbyClient.CurrentHostedGamePort = hostport;
            Program.GameEngine = new GameEngine(game, Username, false, password, true);
//            Program.GameSettings.UseTwoSidedTable = true;
            Program.CurrentOnlineGameName = name;
            Program.IsHost        = true;
            Program.IsMatchmaking = false;

            var ip = IPAddress.Parse("127.0.0.1");

            for (var i = 0; i < 5; i++)
            {
                try
                {
                    Program.Client = new ClientSocket(ip, hostport);
                    Program.Client.Connect();
                    SuccessfulHost = true;
                    return;
                }
                catch (Exception e)
                {
                    Log.Warn("Start local game error", e);
                    if (i == 4)
                    {
                        throw;
                    }
                }
                Thread.Sleep(2000);
            }
        }
Ejemplo n.º 23
0
        public static void SetGameSetting <T>(DataNew.Entities.Game game, string propName, T val)
        {
            var defSettings = new Hashtable();

            defSettings["name"] = game.Name;
            var settings = Config.Instance.ReadValue("GameSettings_" + game.Id.ToString(), defSettings);

            if (!settings.ContainsKey(propName))
            {
                settings.Add(propName, val);
            }
            else
            {
                settings[propName] = val;
            }

            Config.Instance.WriteValue("GameSettings_" + game.Id.ToString(), settings);
        }
Ejemplo n.º 24
0
        public SearchControl(DataNew.Entities.Game game, DeckBuilderWindow deckWindow)
        {
            _deckWindow = deckWindow;
            NumMod      = "";
            Game        = game;
            InitializeComponent();
            var source =
                Enumerable.Repeat <object>("First", 1)
                .Union(Enumerable.Repeat <object>(new SetPropertyDef(Game.Sets().Where(x => x.Hidden == false)), 1))
                .Union(game.AllProperties().Where(p => !p.Hidden));

            filtersList.ItemsSource = source;
            GenerateColumns(game);
            //resultsGrid.ItemsSource = game.SelectCards(null).DefaultView;
            UpdateDataGrid(game.AllCards(true).ToDataTable(Game).DefaultView);
            FileName = "";
            UpdateCount();
        }
Ejemplo n.º 25
0
 public void SetFromSave(DataNew.Entities.Game loadedGame, SearchFilterItem search)
 {
     comparisonText.Text = search.CompareValue;
     if (search.IsSetProperty)
     {
         comparisonList.SelectedItem =
             comparisonList.Items.OfType <DataNew.Entities.Set>()
             .FirstOrDefault(x => x.Id == Guid.Parse(search.SelectedComparison));
     }
     else
     {
         comparisonList.SelectedItem =
             comparisonList.Items.OfType <SqlComparison>()
             .FirstOrDefault(
                 x =>
                 x.Name.Equals(search.SelectedComparison, StringComparison.InvariantCultureIgnoreCase));
     }
     //}
 }
Ejemplo n.º 26
0
 private void GenerateColumns(DataNew.Entities.Game game)
 {
     foreach (DataNew.Entities.PropertyDef prop in game.CustomProperties)
     {
         if (prop.Name == "Name")
         {
             continue;
         }
         resultsGrid.Columns.Add(new DataGridTextColumn
         {
             Binding = new Binding
             {
                 Path = new PropertyPath(prop.Name),
                 Mode = BindingMode.OneTime
             },
             Header = prop.Name
         });
     }
 }
Ejemplo n.º 27
0
        public void CheckVerboseXml(Windows.ChangeSetsProgressDialog wnd, int max, DataNew.Entities.Game game)
        {
            XmlSetParser xmls = xml_set;

            wnd.UpdateProgress(1, max, "Parsing retrieved xml...", false);
            xmls.check();
            if (game.Id.ToString() != xmls.game())
            {
                wnd.UpdateProgress(10, 10, string.Format("Error! Wrong game specified in xml"), false);
                return;
            }
            wnd.UpdateProgress(2, max, "Name: " + xmls.name(), false);
            wnd.UpdateProgress(3, max, "Game: " + xmls.game(), false);
            wnd.UpdateProgress(4, max, "UUID: " + xmls.uuid(), false);
            wnd.UpdateProgress(5, max, "Version: " + xmls.version(), false);
            wnd.UpdateProgress(6, max, "Date: " + xmls.date(), false);
            wnd.UpdateProgress(7, max, "Link: " + xmls.link(), false);
            wnd.UpdateProgress(8, max, "Login: "******"Password: "******"Xml seems ok"), false);
        }
Ejemplo n.º 28
0
        async Task StartLocalGame(DataNew.Entities.Game game, string name, string password)
        {
            var hostport = new Random().Next(5000, 6000);

            while (!NetworkHelper.IsPortAvailable(hostport))
            {
                hostport++;
            }

            var hg = new HostedGame()
            {
                Id          = Guid.NewGuid(),
                Name        = name,
                HostUser    = Program.LobbyClient?.User ?? new User(hostport.ToString(), Username),
                GameName    = game.Name,
                GameId      = game.Id,
                GameVersion = game.Version.ToString(),
                HostAddress = $"0.0.0.0:{hostport}",
                Password    = password,
                GameIconUrl = game.IconUrl,
                Spectators  = true,
            };

            if (Program.LobbyClient?.User != null)
            {
                hg.HostUserIconUrl = ApiUserCache.Instance.ApiUser(Program.LobbyClient.User)?.IconUrl;
            }

            // Since it's a local game, we want to use the username instead of a userid, since that won't exist.
            var hs = new HostedGameProcess(hg, X.Instance.Debug, true);

            hs.Start();

            Prefs.Nickname                = hg.HostUser.DisplayName;
            Program.GameEngine            = new GameEngine(game, Username, false, password, true);
            Program.CurrentOnlineGameName = name;
            Program.IsHost                = true;

            var ip = IPAddress.Parse("127.0.0.1");

            for (var i = 0; i < 5; i++)
            {
                try
                {
                    Program.Client = new ClientSocket(ip, hostport);
                    await Program.Client.Connect();

                    SuccessfulHost = true;
                    return;
                }
                catch (Exception e)
                {
                    Log.Warn("Start local game error", e);
                    if (i == 4)
                    {
                        throw;
                    }
                }
                Thread.Sleep(2000);
            }
        }
Ejemplo n.º 29
0
        // C'tor
        internal Player(DataNew.Entities.Game g, string name, string userId, byte id, ulong pkey, bool spectator, bool local)
        {
            // Cannot access Program.GameEngine here, it's null.

            Id    = id;
            _name = name;

            if (!string.IsNullOrWhiteSpace(userId))
            {
                UserId = userId;

                if (!userId.StartsWith("##LOCAL##"))
                {
                    Task.Factory.StartNew(async() => {
                        try {
                            var c = new ApiClient();

                            var apiUser = await c.UserFromUserId(userId);
                            if (apiUser != null)
                            {
                                this.DisconnectPercent = apiUser.DisconnectPercent;
                                this.UserIcon          = apiUser.IconUrl;
                            }
                        } catch (Exception e) {
                            Log.Warn("Player() Error getting api stuff", e);
                        }
                    });
                }
            }
            else
            {
                UserId = $"##LOCAL##{name}:{id}";
            }
            _spectator = spectator;
            SetupPlayer(Spectator);
            PublicKey = pkey;
            if (Spectator == false)
            {
                all.Add(this);
            }
            else
            {
                spectators.Add(this);
            }
            // Assign subscriber status
            _subscriber = SubscriptionModule.Get().IsSubscribed ?? false;
            //Create the color brushes
            SetPlayerColor(id);
            // Create counters
            _counters = new Counter[0];
            if (g.Player.Counters != null)
            {
                _counters = g.Player.Counters.Select(x => new Counter(this, x)).ToArray();
            }
            // Create global variables
            GlobalVariables = new Dictionary <string, string>();
            foreach (var varD in g.Player.GlobalVariables)
            {
                GlobalVariables.Add(varD.Name, varD.Value);
            }
            // Create a hand, if any
            if (g.Player.Hand != null)
            {
                _hand = new Hand(this, g.Player.Hand);
            }
            // Create groups
            _groups = new Group[0];
            if (g.Player.Groups != null)
            {
                var tempGroups = g.Player.Groups.ToArray();
                _groups    = new Group[tempGroups.Length + 1];
                _groups[0] = _hand;
                for (int i = 1; i < IndexedGroups.Length; i++)
                {
                    _groups[i] = new Pile(this, tempGroups[i - 1]);
                }
            }
            minHandSize = 250;
            if (Spectator == false)
            {
                // Raise the event
                if (PlayerAdded != null)
                {
                    PlayerAdded(null, new PlayerEventArgs(this));
                }
                Ready = false;
                OnPropertyChanged("All");
                OnPropertyChanged("AllExceptGlobal");
                OnPropertyChanged("Count");
            }
            else
            {
                OnPropertyChanged("Spectators");
                Ready = true;
            }
            CanKick = local == false && Program.IsHost;
        }
Ejemplo n.º 30
0
        public bool Install()
        {
            //Fix def filename
            String newFilename = Uri.UnescapeDataString(FileName);
            if (!newFilename.ToLower().Equals(FileName.ToLower()))
            {
                try
                {
                    File.Move(FileName, newFilename);
                }
                catch (Exception)
                {
                    MessageBox.Show(
                        "This file is currently in use. Please close whatever application is using it and try again.");
                    return false;
                }
            }

            try
            {
                GameDef game = GameDef.FromO8G(newFilename);
                //Move the definition file to a new location, so that the old one can be deleted
                string path = Path.Combine(Prefs.DataDirectory,"Games", game.Id.ToString(), "Defs");
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);
                var fi = new FileInfo(newFilename);
                string copyto = Path.Combine(path, fi.Name);
                try
                {
                    if (newFilename.ToLower() != copyto.ToLower())
                        File.Copy(newFilename, copyto, true);
                }
                catch (Exception)
                {
                    MessageBox.Show(
                        "File in use. You shouldn't install games or sets when in the deck editor or when playing a game.");
                    return false;
                }
                newFilename = copyto;
                // Open the archive
                game = GameDef.FromO8G(newFilename);
                if (!game.CheckVersion()) return false;

                //Check game scripts
                if (!Windows.UpdateChecker.CheckGameDef(game))
                    return false;

                // Check if the game already exists
                if (GameManager.Get().GetById(game.Id) != null)
                    if (
                        MessageBox.Show("This game already exists.\r\nDo you want to overwrite it?", "Confirmation",
                                        MessageBoxButton.YesNo, MessageBoxImage.Exclamation) != MessageBoxResult.Yes)
                        return false;

                if (Fonts.Count > 0)
                {
                    InstallFonts();
                }

                var gameData = new DataNew.Entities.Game
                                   {
                                       Id = game.Id,
                                       Name = game.Name,
                                       Filename = new FileInfo(newFilename).Name,
                                       Version = game.Version,
                                       CardWidth = game.CardDefinition.Width,
                                       CardHeight = game.CardDefinition.Height,
                                       CardBack = game.CardDefinition.Back,
                                       DeckSections = game.DeckDefinition.Sections.Keys.ToList(),
                                       SharedDeckSections =
                                           game.SharedDeckDefinition == null
                                               ? null
                                               : game.SharedDeckDefinition.Sections.Keys.ToList(),
                                       FileHash = game.FileHash
                                   };
                var rootDir = Path.Combine(Prefs.DataDirectory, "Games", game.Id.ToString()) + "\\";
                using (Package package = Package.Open(copyto, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    foreach (var p in package.GetParts())
                    {
                        this.ExtractPart(p,rootDir);
                    }
                }

                gameData.CustomProperties = game.CardDefinition.Properties.Select(x => x.Value).ToList();

                GameManager.Get().InstallGame(gameData);
                return true;
            }
            catch (FileFormatException)
            {
                //Removed ex.Message. The user doesn't need to see the exception
                MessageBox.Show("Your game definition file is corrupt. Please redownload it.", "Error",
                                MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }
        }
Ejemplo n.º 31
0
        public SearchControl(DataNew.Entities.Game loadedGame, SearchSave save)
        {
            NumMod = "";
            var game = GameManager.Get().GetById(save.GameId);

            if (game == null)
            {
                TopMostMessageBox.Show("You don't have the game for this search installed", "Oh No", MessageBoxButton.OK, MessageBoxImage.Error);
                save = null;
            }
            else if (loadedGame.Id != save.GameId)
            {
                TopMostMessageBox.Show(
                    "This search is for the game " + game.Name + ". You currently have the game " + loadedGame.Name
                    + " loaded so you can not load this search.", "Oh No", MessageBoxButton.OK, MessageBoxImage.Error);
                save = null;
            }
            Game = loadedGame;
            InitializeComponent();
            filtersList.ItemsSource =
                Enumerable.Repeat <object>("First", 1)
                .Union(Enumerable.Repeat <object>(new SetPropertyDef(Game.Sets()), 1))
                .Union(game.AllProperties().Where(p => !p.Hidden));
            this.GenerateColumns(game);
            FileName = "";
            if (save != null)
            {
                this.SearchName = save.Name;
                this.FileName   = save.FileName;
                // Load filters
                foreach (var filter in save.Filters)
                {
                    DataNew.Entities.PropertyDef prop;
                    if (filter.IsSetProperty)
                    {
                        prop = filtersList.Items.OfType <SetPropertyDef>().First();
                    }
                    else
                    {
                        prop = loadedGame.AllProperties().FirstOrDefault(
                            x => x.Name.Equals(filter.PropertyName, StringComparison.InvariantCultureIgnoreCase));
                    }
                    if (prop == null)
                    {
                        continue;
                    }

                    filterList.Items.Add(prop);
                }

                RoutedEventHandler loadedEvent = null;

                loadedEvent = (sender, args) => {
                    this.Loaded -= loadedEvent;

                    var generator = filterList.ItemContainerGenerator;
                    for (int i = 0; i < filterList.Items.Count; i++)
                    {
                        DependencyObject container = generator.ContainerFromIndex(i);
                        var filterCtrl             = (FilterControl)VisualTreeHelper.GetChild(container, 0);
                        var filter = save.Filters[i];
                        filterCtrl.SetFromSave(Game, filter);
                    }
                    this.RefreshSearch(SearchButton, null);
                };

                this.Loaded += loadedEvent;
            }
            this.UpdateDataGrid(game.AllCards(true).ToDataTable(Game).DefaultView);
            UpdateCount();
        }
Ejemplo n.º 32
0
        // C'tor
        internal Player(DataNew.Entities.Game g, string name, byte id, ulong pkey, bool spectator, bool local)
        {
            // Cannot access Program.GameEngine here, it's null.

            Task.Factory.StartNew(() =>
            {
                try
                {
                    var c    = new ApiClient();
                    var list = c.UsersFromUsername(new String[] { name });
                    var item = list.FirstOrDefault();
                    if (item != null)
                    {
                        this.DisconnectPercent = item.DisconnectPercent;
                        this.UserIcon          = item.IconUrl;
                    }
                }
                catch (Exception e)
                {
                    Log.Warn("Player() Error getting api stuff", e);
                }
            });
            _spectator = spectator;
            SetupPlayer(Spectator);
            // Init fields
            _name     = name;
            Id        = id;
            PublicKey = pkey;
            if (Spectator == false)
            {
                all.Add(this);
            }
            else
            {
                spectators.Add(this);
            }
            // Assign subscriber status
            _subscriber = SubscriptionModule.Get().IsSubscribed ?? false;
            //Create the color brushes
            SetPlayerColor(id);
            // Create counters
            _counters = new Counter[0];
            if (g.Player.Counters != null)
            {
                _counters = g.Player.Counters.Select(x => new Counter(this, x)).ToArray();
            }
            // Create variables
            Variables = new Dictionary <string, int>();
            foreach (var varDef in g.Variables.Where(v => !v.Global))
            {
                Variables.Add(varDef.Name, varDef.Default);
            }
            // Create global variables
            GlobalVariables = new Dictionary <string, string>();
            foreach (var varD in g.Player.GlobalVariables)
            {
                GlobalVariables.Add(varD.Name, varD.Value);
            }
            // Create a hand, if any
            if (g.Player.Hand != null)
            {
                _hand = new Hand(this, g.Player.Hand);
            }
            // Create groups
            _groups = new Group[0];
            if (g.Player.Groups != null)
            {
                var tempGroups = g.Player.Groups.ToArray();
                _groups    = new Group[tempGroups.Length + 1];
                _groups[0] = _hand;
                for (int i = 1; i < IndexedGroups.Length; i++)
                {
                    _groups[i] = new Pile(this, tempGroups[i - 1]);
                }
            }
            minHandSize = 250;
            if (Spectator == false)
            {
                // Raise the event
                if (PlayerAdded != null)
                {
                    PlayerAdded(null, new PlayerEventArgs(this));
                }
                Ready = false;
                OnPropertyChanged("All");
                OnPropertyChanged("AllExceptGlobal");
                OnPropertyChanged("Count");
            }
            else
            {
                OnPropertyChanged("Spectators");
                Ready = true;
            }
            CanKick = local == false && Program.IsHost;
        }
Ejemplo n.º 33
0
 public void Set(DataNew.Entities.Game game)
 {
     SelectedGame = game;
     RefreshList();
 }
Ejemplo n.º 34
0
 public static void Open(GameDef game, bool readOnly)
 {
     OpenedGame = GameManager.Get().GetById(game.Id);
     //OpenedGame = Program.GamesRepository.Games.First(g => g.Id == game.Id);
 }