Ejemplo n.º 1
0
        public PlayWindow(bool islocal = false)
            : base()
        {
            //GameLogWindow.Show();
            //GameLogWindow.Visibility = Visibility.Hidden;
            Program.Dispatcher = Dispatcher;
            DataContext        = Program.GameEngine;
            InitializeComponent();
            _isLocal = islocal;
            //Application.Current.MainWindow = this;
            Version oversion = Assembly.GetExecutingAssembly().GetName().Version;

            Title = "Octgn  version : " + oversion + " : " + Program.GameEngine.Definition.Name;
            Program.GameEngine.ComposeParts(this);
            this.Loaded                += OnLoaded;
            this.chat.MouseEnter       += ChatOnMouseEnter;
            this.chat.MouseLeave       += ChatOnMouseLeave;
            this.playerTabs.MouseEnter += PlayerTabsOnMouseEnter;
            this.playerTabs.MouseLeave += PlayerTabsOnMouseLeave;
            SubscriptionModule.Get().IsSubbedChanged += OnIsSubbedChanged;
            this.ContentRendered += OnContentRendered;
        }
Ejemplo n.º 2
0
        private void Program_OnOptionsChanged()
        {
            if (Dispatcher.CheckAccess())
            {
                Task.Factory.StartNew(Program_OnOptionsChanged);
                return;
            }
            var isSubbed = SubscriptionModule.Get().IsSubscribed ?? false;

            Dispatcher.Invoke(new Action(() =>
            {
                ImageBrush ib;
                if (isSubbed && !string.IsNullOrWhiteSpace(Prefs.WindowSkin))
                {
                    var bimage = new BitmapImage(new Uri(Prefs.WindowSkin));

                    ib = new ImageBrush(bimage);
                    if (Prefs.TileWindowSkin)
                    {
                        ib.Stretch       = Stretch.None;
                        ib.TileMode      = TileMode.Tile;
                        ib.ViewportUnits = BrushMappingMode.Absolute;
                        ib.Viewport      = new Rect(0, 0, bimage.PixelWidth, bimage.PixelHeight);
                    }
                    else
                    {
                        ib.Stretch = Stretch.Fill;
                    }
                }
                else
                {
                    ib = new ImageBrush(new BitmapImage(new Uri("pack://application:,,,/Resources/background.png")))
                    {
                        Stretch = Stretch.Fill
                    };
                }
                MainContainer.Background = ib;
            }));
        }
Ejemplo n.º 3
0
        public static void PlayGameSound(GameSound sound)
        {
            var isSubscribed = SubscriptionModule.Get().IsSubscribed ?? false;

            if (isSubscribed && Prefs.EnableGameSound)
            {
                Task.Factory.StartNew(() =>
                {
                    try
                    {
                        if (sound.Src.ToLowerInvariant().EndsWith(".mp3"))
                        {
                            using (var mp3Reader = new Mp3FileReader(sound.Src))
                                using (var stream = new WaveChannel32(mp3Reader))
                                    using (var wo = new WaveOut())
                                    {
                                        wo.Init(stream);
                                        wo.Play();
                                        while (wo.PlaybackState == PlaybackState.Playing)
                                        {
                                            Thread.Sleep(1);
                                        }
                                    }
                        }
                        else
                        {
                            using (var player = new SoundPlayer(sound.Src))
                            {
                                player.PlaySync();
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Log.Warn("PlayGameSound Error", e);
                    }
                });
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// The lobby client on on login complete.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="results">
        /// The results.
        /// </param>
        private void LobbyClientOnOnLoginComplete(object sender, LoginResults results)
        {
            this.Dispatcher.BeginInvoke(new Action(() => ConnectBox.Visibility = Visibility.Hidden));
            switch (results)
            {
            case LoginResults.Success:
                this.SetStateOnline();
                this.Dispatcher.BeginInvoke(new Action(() =>
                {
                    if (GameManager.Get().GameCount == 0)
                    {
                        TabCustomGames.Focus();
                    }
                    else
                    {
                        TabCommunityChat.Focus();
                    }
                })).Completed += (o, args) => Task.Factory.StartNew(() =>
                {
                    Thread.Sleep(15000);
                    this.Dispatcher.Invoke(new Action(()
                                                      =>
                    {
                        var s =
                            SubscriptionModule.Get
                                ().IsSubscribed;
                        if (s != null && s == false)
                        {
                            ShowSubMessage();
                        }
                    }));
                });
                break;

            default:
                this.SetStateOffline();
                break;
            }
        }
Ejemplo n.º 5
0
 public static void PlaySound(Stream sound, bool subRequired = true)
 {
     if (subRequired && SubscriptionModule.Get().IsSubscribed == false)
     {
         return;
     }
     Task.Factory.StartNew(() =>
     {
         try
         {
             using (sound)
                 using (var player = new SoundPlayer(sound))
                 {
                     player.PlaySync();
                 }
         }
         catch (Exception e)
         {
             Log.Warn("Play Sound Error", e);
         }
     });
 }
Ejemplo n.º 6
0
        private void ProgramOnOnOptionsChanged()
        {
            if (!this.Dispatcher.CheckAccess())
            {
                Dispatcher.Invoke(new Action(this.ProgramOnOnOptionsChanged));
                return;
            }
            var issub = SubscriptionModule.Get().IsSubscribed ?? false;

            if (issub && !String.IsNullOrWhiteSpace(Prefs.WindowSkin))
            {
                var bimage = new BitmapImage(new Uri(Prefs.WindowSkin));

                var ib = new ImageBrush(bimage);
                if (Prefs.TileWindowSkin)
                {
                    ib.Stretch       = Stretch.None;
                    ib.TileMode      = TileMode.Tile;
                    ib.ViewportUnits = BrushMappingMode.Absolute;
                    ib.Viewport      = new Rect(0, 0, bimage.PixelWidth, bimage.PixelHeight);
                }
                else
                {
                    ib.Stretch = Stretch.Fill;
                }
                this.MainBorder.Background = ib;
            }
            else
            {
                var bimage = new BitmapImage(new Uri("pack://application:,,,/Resources/background.png"));

                var ib = new ImageBrush(bimage);
                ib.Stretch = Stretch.Fill;
                this.MainBorder.Background = ib;
                //this.MainBorder.SetResourceReference(Border.BackgroundProperty, "ControlBackgroundBrush");
            }
        }
Ejemplo n.º 7
0
 public HostGameSettings()
 {
     InitializeComponent();
     Games = new ObservableCollection <DataGameViewModel>();
     Program.LobbyClient.OnDataReceived  += LobbyClientOnDataReceviedCaller;
     Program.LobbyClient.OnLoginComplete += LobbyClientOnLoginComplete;
     Program.LobbyClient.OnDisconnect    += LobbyClientOnDisconnect;
     TextBoxGameName.Text          = Prefs.LastRoomName ?? Skylabs.Lobby.Randomness.RandomRoomName();
     CheckBoxIsLocalGame.IsChecked = !Program.LobbyClient.IsConnected;
     CheckBoxIsLocalGame.IsEnabled = Program.LobbyClient.IsConnected;
     lastHostedGameType            = Prefs.LastHostedGameType;
     TextBoxUserName.Text          = (Program.LobbyClient.IsConnected == false ||
                                      Program.LobbyClient.Me == null ||
                                      Program.LobbyClient.Me.UserName == null) ? Prefs.Nickname : Program.LobbyClient.Me.UserName;
     TextBoxUserName.IsEnabled = !Program.LobbyClient.IsConnected;
     if (Program.LobbyClient.IsConnected)
     {
         PasswordGame.IsEnabled = SubscriptionModule.Get().IsSubscribed ?? false;
     }
     else
     {
         PasswordGame.IsEnabled = true;
     }
 }
Ejemplo n.º 8
0
 private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
 {
     this.Loaded -= OnLoaded;
     SubscriptionModule.Get().IsSubbedChanged += Main_IsSubbedChanged;
     UpdateManager.Instance.Start();
 }
Ejemplo n.º 9
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.º 10
0
        private void ChangeIconClick(object sender, RoutedEventArgs e)
        {
            if ((SubscriptionModule.Get().IsSubscribed ?? false) == false)
            {
                TopMostMessageBox.Show(
                    "You must be subscribed to set your icon", "Error", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }
            var fd = new OpenFileDialog();

            fd.Filter =
                "All Images|*.BMP;*.JPG;*.JPEG;*.PNG|BMP Files: (*.BMP)|*.BMP|JPEG Files: (*.JPG;*.JPEG)|*.JPG;*.JPEG|PNG Files: (*.PNG)|*.PNG";
            fd.CheckFileExists = true;
            if (!(bool)fd.ShowDialog())
            {
                return;
            }
            if (!File.Exists(fd.FileName))
            {
                return;
            }
            var finfo = new FileInfo(fd.FileName);

            try
            {
                var img = System.Drawing.Image.FromFile(fd.FileName);
                if (img.Width != 16 || img.Height != 16)
                {
                    img = ResizeImage(img, new System.Drawing.Size(16, 16));
                    //throw new UserMessageException("Image must be exactly 16x16 in size.");
                }
                using (var imgStream = new MemoryStream())
                {
                    img.Save(imgStream, ImageFormat.Png);
                    imgStream.Seek(0, SeekOrigin.Begin);
                    var client = new Octgn.Site.Api.ApiClient();
                    var res    = client.SetUserIcon(
                        Program.LobbyClient.Username,
                        Program.LobbyClient.Password,
                        "png",
                        imgStream);

                    switch (res)
                    {
                    case UserIconSetResult.Ok:
                        Task.Factory.StartNew(() =>
                        {
                            Thread.Sleep(5000);
                            this.OnLoaded(null, null);
                        });

                        TopMostMessageBox.Show(
                            "Your icon has been changed. It can take a few minutes for the change to take place.",
                            "Change Icon",
                            MessageBoxButton.OK,
                            MessageBoxImage.Information);
                        break;

                    case UserIconSetResult.ImageSizeBad:
                        throw new UserMessageException("Image must be exactly 16x16 in size.");

                    case UserIconSetResult.NotSubscribed:
                        throw new UserMessageException("You must be subscribed to do that.");

                    case UserIconSetResult.CredentialsError:
                        throw new UserMessageException(
                                  "Incorrect username/password. try exiting OCTGN and reloading it.");

                    default:
                        throw new UserMessageException(
                                  "There was an error uploading your icon. Please try again later.");
                    }
                }
            }
            catch (UserMessageException ex)
            {
                TopMostMessageBox.Show(ex.Message, "Change Icon Error", MessageBoxButton.OK, MessageBoxImage.Warning);
                Log.Warn("ChangeIconClick(UserMessageException)", ex);
            }
            catch (Exception ex)
            {
                TopMostMessageBox.Show(
                    "There was an unknown error. Please try a different image.",
                    "Change Icon Error",
                    MessageBoxButton.OK,
                    MessageBoxImage.Warning);
                Log.Warn("ChangeIconClick", ex);
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="OctgnChrome"/> class.
        /// </summary>
        public OctgnChrome()
        {
            this.WindowStyle        = WindowStyle.None;
            this.ResizeMode         = ResizeMode.CanResize;
            this.CanResize          = true;
            this.MainBorder         = new Border();
            this.SourceInitialized += new EventHandler(win_SourceInitialized);
            if (!this.IsInDesignMode())
            {
                if (Prefs.UseWindowTransparency)
                {
                    this.AllowsTransparency = true;
                    base.Background         = Brushes.Transparent;
                    this.MainBorder.SetResourceReference(Border.BackgroundProperty, "ControlBackgroundBrush");
                    this.MainBorder.BorderThickness = new Thickness(2);
                    this.MainBorder.CornerRadius    = new CornerRadius(5);
                    this.MainBorder.BorderBrush     = new LinearGradientBrush(
                        Color.FromArgb(150, 30, 30, 30), Color.FromArgb(150, 200, 200, 200), 45);
                }
                else
                {
                    this.AllowsTransparency = false;
                    base.Background         = Brushes.DimGray;
                }
            }

            Program.OnOptionsChanged += ProgramOnOnOptionsChanged;
            SubscriptionModule.Get().IsSubbedChanged += OnIsSubbedChanged;

            var issub = SubscriptionModule.Get().IsSubscribed ?? false;

            if (issub && !String.IsNullOrWhiteSpace(Prefs.WindowSkin))
            {
                var bimage = new BitmapImage(new Uri(Prefs.WindowSkin));

                var ib = new ImageBrush(bimage);
                if (Prefs.TileWindowSkin)
                {
                    ib.Stretch       = Stretch.None;
                    ib.TileMode      = TileMode.Tile;
                    ib.ViewportUnits = BrushMappingMode.Absolute;
                    ib.Viewport      = new Rect(0, 0, bimage.PixelWidth, bimage.PixelHeight);
                }
                else
                {
                    ib.Stretch = Stretch.Fill;
                }
                this.MainBorder.Background = ib;
            }
            base.Content = this.MainBorder;

            this.MakeDrag();


            this.MainGrid = new Grid();
            this.TitleRow = new RowDefinition {
                Height = new GridLength(35)
            };
            this.MainGrid.RowDefinitions.Add(this.TitleRow);
            this.MainGrid.RowDefinitions.Add(new RowDefinition {
                Height = new GridLength(100, GridUnitType.Star)
            });
            this.MainGrid.ColumnDefinitions.Add(new ColumnDefinition {
                Width = new GridLength(50)
            });
            this.MainGrid.ColumnDefinitions.Add(new ColumnDefinition {
                Width = new GridLength(100, GridUnitType.Star)
            });
            this.MainGrid.ColumnDefinitions.Add(new ColumnDefinition {
                Width = new GridLength(120)
            });
            this.DragGrid.Children.Add(this.MainGrid);
            Grid.SetColumn(this.MainGrid, 1);
            Grid.SetRow(this.MainGrid, 1);

            // IconImage = new Image{Source = new BitmapImage(new Uri("pack://application:,,,/OCTGN;component/Resources/Icon.ico")) };
            this.IconImage                     = new Image();
            this.IconImage.Stretch             = Stretch.Uniform;
            this.IconImage.Source              = this.Icon;
            this.IconImage.VerticalAlignment   = VerticalAlignment.Center;
            this.IconImage.HorizontalAlignment = HorizontalAlignment.Center;
            this.MainGrid.Children.Add(this.IconImage);

            // Setup content area
            this.ContentArea = new Border();
            this.MainGrid.Children.Add(this.ContentArea);
            Grid.SetRow(this.ContentArea, 1);
            Grid.SetColumnSpan(this.ContentArea, 3);

            // Add label
            this.LabelTitle             = new TextBlock();
            this.LabelTitle.FontFamily  = new FontFamily("Euphemia");
            this.LabelTitle.FontSize    = 22;
            this.LabelTitle.Foreground  = Brushes.DarkGray;
            this.LabelTitle.FontWeight  = FontWeights.Bold;
            this.LabelTitle.FontStyle   = FontStyles.Italic;
            this.LabelTitle.DataContext = this;
            this.LabelTitle.SetBinding(TextBlock.TextProperty, new Binding("Title")
            {
                UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
            });
            this.LabelTitle.MouseDown += this.BorderMouseDown1;
            this.MainGrid.Children.Add(this.LabelTitle);
            Grid.SetColumn(this.LabelTitle, 1);

            // Add window controls
            this.WcGrid = new Grid();
            this.WcGrid.ColumnDefinitions.Add(new ColumnDefinition {
                Width = new GridLength(40)
            });
            this.WcGrid.ColumnDefinitions.Add(new ColumnDefinition {
                Width = new GridLength(40)
            });
            this.WcGrid.ColumnDefinitions.Add(new ColumnDefinition {
                Width = new GridLength(40)
            });
            this.MainGrid.Children.Add(this.WcGrid);
            Grid.SetColumn(this.WcGrid, 2);

            this.WindowMinimizeButton             = new Border();
            this.WindowMinimizeButton.MouseEnter += this.WindowControlMouseEnter;
            this.WindowMinimizeButton.MouseLeave += this.WindowControlMouseLeave;
            this.WindowMinimizeButton.Focusable   = true;
            this.WindowMinimizeButton.PreviewMouseLeftButtonUp += (sender, args) =>
            {
                WindowState  = WindowState.Minimized;
                args.Handled = true;
            };
            this.WindowMinimizeButton.Child = new Image()
            {
                Stretch = Stretch.None, Source = new BitmapImage(new Uri("pack://application:,,,/OCTGN;component/Resources/minimize.png"))
            };
            this.WcGrid.Children.Add(this.WindowMinimizeButton);
            Grid.SetColumn(this.WindowMinimizeButton, 0);

            this.WindowResizeButton             = new Border();
            this.WindowResizeButton.MouseEnter += this.WindowControlMouseEnter;
            this.WindowResizeButton.MouseLeave += this.WindowControlMouseLeave;
            this.WindowResizeButton.Focusable   = true;
            this.WindowResizeButton.PreviewMouseLeftButtonUp += (sender, args) =>
            {
                WindowState = (WindowState == WindowState.Maximized)
                                                                                     ? WindowState.Normal
                                                                                     : WindowState.Maximized;
                args.Handled = true;
            };
            this.WindowResizeButton.Child = new Image()
            {
                Stretch = Stretch.None, Source = new BitmapImage(new Uri("pack://application:,,,/OCTGN;component/Resources/minmax.png"))
            };
            this.WcGrid.Children.Add(this.WindowResizeButton);
            Grid.SetColumn(this.WindowResizeButton, 1);

            this.WindowCloseButton             = new Border();
            this.WindowCloseButton.MouseEnter += this.WindowControlMouseEnter;
            this.WindowCloseButton.MouseLeave += this.WindowControlMouseLeave;
            this.WindowCloseButton.Focusable   = true;
            this.WindowCloseButton.PreviewMouseLeftButtonUp += (sender, args) =>
            {
                Close();
                args.Handled = true;
            };
            this.WindowCloseButton.Child = new Image()
            {
                Stretch = Stretch.None, Source = new BitmapImage(new Uri("pack://application:,,,/OCTGN;component/Resources/closewindow.png"))
            };
            this.WcGrid.Children.Add(this.WindowCloseButton);
            Grid.SetColumn(this.WindowCloseButton, 2);

            this.Loaded          += OnLoaded;
            this.LocationChanged += OnLocationChanged;
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="OctgnChrome"/> class.
        /// </summary>
        public OctgnChrome()
        {
            this.WindowStyle        = WindowStyle.None;
            this.ResizeMode         = ResizeMode.CanResize;
            this.CanResize          = true;
            this.MainBorder         = new Border();
            this.SourceInitialized += new EventHandler(win_SourceInitialized);
            if (!this.IsInDesignMode())
            {
                if (Prefs.UseWindowTransparency)
                {
                    this.AllowsTransparency    = true;
                    base.Background            = Brushes.Transparent;
                    this.MainBorder.Background = new SolidColorBrush(Color.FromRgb(64, 64, 64));
                    //this.MainBorder.SetResourceReference(Border.BackgroundProperty, "ControlBackgroundBrush");
                    this.MainBorder.BorderThickness = new Thickness(2);
                    this.MainBorder.CornerRadius    = new CornerRadius(5);
                    this.MainBorder.BorderBrush     = new LinearGradientBrush(
                        Color.FromArgb(40, 30, 30, 30), Color.FromArgb(150, 200, 200, 200), 45);
                }
                else
                {
                    this.AllowsTransparency = false;
                    base.Background         = new SolidColorBrush(Color.FromRgb(64, 64, 64));
                }
                Program.OnOptionsChanged += ProgramOnOnOptionsChanged;
                SubscriptionModule.Get().IsSubbedChanged += OnIsSubbedChanged;
            }

            this.WindowStartupLocation = WindowStartupLocation.CenterScreen;

            var mainWindow = WindowManager.Main ?? System.Windows.Application.Current.MainWindow;

            if (mainWindow != null && mainWindow.Owner == null && !Equals(mainWindow, this) && mainWindow.IsVisible)
            {
                this.WindowStartupLocation = WindowStartupLocation.Manual;
                this.Left = mainWindow.Left + 10;
                this.Top  = mainWindow.Top + 10;
            }

            base.Content = this.MainBorder;

            this.MakeDrag();


            this.MainGrid = new Grid();
            this.TitleRow = new RowDefinition {
                Height = new GridLength(35)
            };
            this.MainGrid.RowDefinitions.Add(this.TitleRow);
            this.MainGrid.RowDefinitions.Add(new RowDefinition {
                Height = new GridLength(100, GridUnitType.Star)
            });
            this.MainGrid.ColumnDefinitions.Add(new ColumnDefinition {
                Width = new GridLength(50)
            });
            this.MainGrid.ColumnDefinitions.Add(new ColumnDefinition {
                Width = new GridLength(100, GridUnitType.Star)
            });
            this.MainGrid.ColumnDefinitions.Add(new ColumnDefinition {
                Width = new GridLength(0, GridUnitType.Auto)
            });
            this.DragGrid.Children.Add(this.MainGrid);
            Grid.SetColumn(this.MainGrid, 1);
            Grid.SetRow(this.MainGrid, 1);


            IconBorder                     = new Border();
            IconBorder.Background          = new SolidColorBrush(Color.FromArgb(100, 255, 255, 255));
            IconBorder.CornerRadius        = new CornerRadius(5, 0, 0, 0);
            IconBorder.Padding             = new Thickness(5, 2, 5, 2);
            IconBorder.HorizontalAlignment = HorizontalAlignment.Stretch;
            this.IconBorder.MouseDown     += this.BorderMouseDown1;
            this.MainGrid.Children.Add(IconBorder);
            Grid.SetColumnSpan(IconBorder, 2);

            var iconsp = new StackPanel();

            iconsp.Orientation         = Orientation.Horizontal;
            iconsp.HorizontalAlignment = HorizontalAlignment.Stretch;
            IconBorder.Child           = iconsp;



            // IconImage = new Image{Source = new BitmapImage(new Uri("pack://application:,,,/OCTGN;component/Resources/Icon.ico")) };
            this.IconImage                     = new Image();
            this.IconImage.Stretch             = Stretch.Uniform;
            this.IconImage.Source              = this.Icon;
            this.IconImage.VerticalAlignment   = VerticalAlignment.Center;
            this.IconImage.HorizontalAlignment = HorizontalAlignment.Center;
            //this.MainGrid.Children.Add(this.IconImage);
            iconsp.Children.Add(this.IconImage);
            iconsp.Children.Add(new Border {
                Width = 20
            });


            // Add label
            this.LabelTitle = new TextBlock();
            //this.LabelTitle.FontFamily = new FontFamily("Euphemia");
            this.LabelTitle.FontSize          = 20;
            this.LabelTitle.VerticalAlignment = VerticalAlignment.Center;
            this.LabelTitle.Foreground        = new SolidColorBrush(Color.FromRgb(248, 248, 248));
            this.LabelTitle.FontWeight        = FontWeights.Bold;
            this.LabelTitle.Effect            = new DropShadowEffect()
            {
                BlurRadius = 5,
                Color      = Color.FromRgb(64, 64, 64),
                //Color = Colors.DodgerBlue,
                Direction = 0,
                Opacity   = .9, ShadowDepth = 0, RenderingBias = RenderingBias.Performance
            };
            //this.LabelTitle.FontStyle = FontStyles.Italic;
            this.LabelTitle.DataContext = this;
            this.LabelTitle.SetBinding(TextBlock.TextProperty, new Binding("Title")
            {
                UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
            });
            //this.MainGrid.Children.Add(this.LabelTitle);
            //Grid.SetColumn(this.LabelTitle, 1);
            iconsp.Children.Add(this.LabelTitle);

            // Setup content area
            this.ContentArea = new Border();
            this.MainGrid.Children.Add(this.ContentArea);
            Grid.SetRow(this.ContentArea, 1);
            Grid.SetColumnSpan(this.ContentArea, 3);

            // Add window controls
            var wcborder = new Border();

            wcborder.Background   = new SolidColorBrush(Color.FromArgb(200, 64, 64, 64));
            wcborder.CornerRadius = new CornerRadius(0, 5, 0, 0);
            //wcborder.Padding = new Thickness(5, 2, 5, 2);
            wcborder.HorizontalAlignment = HorizontalAlignment.Stretch;
            this.MainGrid.Children.Add(wcborder);
            Grid.SetColumn(wcborder, 2);

            this.WcGrid             = new StackPanel();
            this.WcGrid.Orientation = Orientation.Horizontal;
            //this.WcGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(0,GridUnitType.Auto) });
            //this.WcGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(0,GridUnitType.Auto) });
            //this.WcGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(le.NaN,GridUnitType.Auto) });
            //this.MainGrid.Children.Add(this.WcGrid);
            //Grid.SetColumn(this.WcGrid, 2);
            wcborder.Child = this.WcGrid;

            this.WindowMinimizeButton = new Border();
            this.WindowMinimizeButton.CornerRadius              = new CornerRadius(0, 5, 0, 0);
            this.WindowMinimizeButton.MouseEnter               += this.WindowControlMouseEnter;
            this.WindowMinimizeButton.MouseLeave               += this.WindowControlMouseLeave;
            this.WindowMinimizeButton.Focusable                 = true;
            this.WindowMinimizeButton.Cursor                    = Cursors.Hand;
            this.WindowMinimizeButton.Width                     = 40;
            this.WindowMinimizeButton.PreviewMouseLeftButtonUp += (sender, args) =>
            {
                WindowState  = WindowState.Minimized;
                args.Handled = true;
            };
            this.WindowMinimizeButton.Child = new Image()
            {
                Stretch = Stretch.None, Source = new BitmapImage(new Uri("pack://application:,,,/OCTGN;component/Resources/minimize.png"))
            };
            this.WcGrid.Children.Add(this.WindowMinimizeButton);
            Grid.SetColumn(this.WindowMinimizeButton, 0);

            this.WindowResizeButton = new Border();
            this.WindowResizeButton.CornerRadius              = new CornerRadius(0, 5, 0, 0);
            this.WindowResizeButton.MouseEnter               += this.WindowControlMouseEnter;
            this.WindowResizeButton.MouseLeave               += this.WindowControlMouseLeave;
            this.WindowResizeButton.Focusable                 = true;
            this.WindowResizeButton.Cursor                    = Cursors.Hand;
            this.WindowResizeButton.Width                     = 40;
            this.WindowResizeButton.PreviewMouseLeftButtonUp += (sender, args) =>
            {
                WindowState = (WindowState == WindowState.Maximized)
                                                                                     ? WindowState.Normal
                                                                                     : WindowState.Maximized;
                args.Handled = true;
            };
            this.WindowResizeButton.Child = new Image()
            {
                Stretch = Stretch.None, Source = new BitmapImage(new Uri("pack://application:,,,/OCTGN;component/Resources/minmax.png"))
            };
            this.WcGrid.Children.Add(this.WindowResizeButton);
            Grid.SetColumn(this.WindowResizeButton, 1);

            this.WindowCloseButton = new Border();
            this.WindowCloseButton.CornerRadius              = new CornerRadius(0, 5, 0, 0);
            this.WindowCloseButton.MouseEnter               += this.WindowControlMouseEnter;
            this.WindowCloseButton.MouseLeave               += this.WindowControlMouseLeave;
            this.WindowCloseButton.Focusable                 = true;
            this.WindowCloseButton.Cursor                    = Cursors.Hand;
            this.WindowCloseButton.Width                     = 40;
            this.WindowCloseButton.PreviewMouseLeftButtonUp += (sender, args) =>
            {
                Close();
                args.Handled = true;
            };
            this.WindowCloseButton.Child = new Image()
            {
                Stretch = Stretch.None, Source = new BitmapImage(new Uri("pack://application:,,,/OCTGN;component/Resources/closewindow.png"))
            };
            this.WcGrid.Children.Add(this.WindowCloseButton);
            Grid.SetColumn(this.WindowCloseButton, 2);

            this.Loaded          += OnLoaded;
            this.LocationChanged += OnLocationChanged;
        }
Ejemplo n.º 13
0
        private void SubscribeClick(object sender, MouseButtonEventArgs e)
        {
            var url = SubscriptionModule.Get().GetSubscribeUrl(new SubType());

            Program.LaunchUrl(url);
        }
Ejemplo n.º 14
0
        public TableControl()
        {
            InitializeComponent();
            if (DesignerProperties.GetIsInDesignMode(this))
            {
                return;
            }
            var tableDef = Program.GameEngine.Definition.Table;
            var subbed   = SubscriptionModule.Get().IsSubscribed ?? false;

            if (subbed && String.IsNullOrWhiteSpace(Prefs.DefaultGameBack) && File.Exists(Prefs.DefaultGameBack))
            {
                SetBackground(Prefs.DefaultGameBack, "uniformToFill");
            }
            else
            {
                if (tableDef.Background != null)
                {
                    SetBackground(tableDef);
                }
            }
            Program.GameEngine.BoardImage = tableDef.Board;
            //if (!Program.GameSettings.HideBoard)
            //    if (tableDef.Board != null)
            //        SetBoard(tableDef);

            if (!Program.GameSettings.UseTwoSidedTable)
            {
                middleLine.Visibility = Visibility.Collapsed;
            }

            if (Player.LocalPlayer.InvertedTable)
            {
                transforms.Children.Insert(0, new ScaleTransform(-1, -1));
            }

            _defaultWidth  = Program.GameEngine.Definition.CardWidth;
            _defaultHeight = Program.GameEngine.Definition.CardHeight;
            SizeChanged   += delegate
            {
                IsCardSizeValid = false;
                AspectRatioChanged();
            };
            MoveCard.Done   += CardMoved;
            CreateCard.Done += CardCreated;
            Unloaded        += delegate
            {
                MoveCard.Done   -= CardMoved;
                CreateCard.Done -= CardCreated;
            };
            Loaded += delegate { CenterView(); };
            Program.GameEngine.PropertyChanged += GameOnPropertyChanged;
            if (Player.LocalPlayer.InvertedTable)
            {
                var rotateAnimation = new DoubleAnimation(0, 180, TimeSpan.FromMilliseconds(1));
                var rt = (RotateTransform)NoteCanvas.RenderTransform;
                rt.BeginAnimation(RotateTransform.AngleProperty, rotateAnimation);
            }
            //this.IsManipulationEnabled = true;
            //this.ManipulationDelta += OnManipulationDelta;

            Player.LocalPlayer.PropertyChanged += LocalPlayerOnPropertyChanged;
        }
Ejemplo n.º 15
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.º 16
0
        private void OnLoaded(object sen, RoutedEventArgs routedEventArgs)
        {
            this.OnIsSubbedChanged(SubscriptionModule.Get().IsSubscribed ?? false);
            this.Loaded -= OnLoaded;
            _fadeIn      = (Storyboard)Resources["ImageFadeIn"];
            _fadeOut     = (Storyboard)Resources["ImageFadeOut"];

            cardViewer.Source = StringExtensionMethods.BitmapFromUri(new Uri(Program.GameEngine.Definition.CardBack));
            if (Program.GameEngine.Definition.CardCornerRadius > 0)
            {
                cardViewer.Clip = new RectangleGeometry();
            }
            AddHandler(CardControl.CardHoveredEvent, new CardEventHandler(CardHovered));
            AddHandler(CardRun.ViewCardModelEvent, new EventHandler <CardModelEventArgs>(ViewCardModel));

            Loaded += (sender, args) => Keyboard.Focus(table);
            // Solve various issues, like disabled menus or non-available keyboard shortcuts

            GroupControl.groupFont    = new FontFamily("Segoe UI");
            GroupControl.fontsize     = 12;
            chat.output.FontFamily    = new FontFamily("Segoe UI");
            chat.output.FontSize      = 12;
            chat.watermark.FontFamily = new FontFamily("Segoe UI");
            MenuConsole.Visibility    = Visibility.Visible;
            Log.Info(string.Format("Found #{0} amount of fonts", Program.GameEngine.Definition.Fonts.Count));
            if (Program.GameEngine.Definition.Fonts.Count > 0)
            {
                UpdateFont();
            }

            Log.Info(string.Format("Checking if the loaded game has boosters for limited play."));
            int setsWithBoosterCount = Program.GameEngine.Definition.Sets().Where(x => x.Packs.Count() > 0).Count();

            Log.Info(string.Format("Found #{0} sets with boosters.", setsWithBoosterCount));
            if (setsWithBoosterCount == 0)
            {
                LimitedGameMenuItem.Visibility = Visibility.Collapsed;
                Log.Info("Hiding limited play in the menu.");
            }
            if ((SubscriptionModule.Get().IsSubscribed ?? false) == false)
            {
                if (Program.GameEngine.Definition.Id != Guid.Parse("844d5fe3-bdb5-4ad2-ba83-88c2c2db6d88"))
                {
                    SubMessage.Visibility = Visibility.Visible;
                }
            }
            //SubTimer.Start();

#if (!DEBUG)
            // Show the Scripting console in dev only
            if (Application.Current.Properties["ArbitraryArgName"] == null)
            {
                return;
            }
            string fname = Application.Current.Properties["ArbitraryArgName"].ToString();
            if (fname != "/developer")
            {
                return;
            }
#endif
        }
Ejemplo n.º 17
0
        private void LoadSearchClick(object sender, RoutedEventArgs e)
        {
            if ((SubscriptionModule.Get().IsSubscribed ?? false) == false)
            {
                var res =
                    TopMostMessageBox.Show(
                        "This feature is only for subscribers. Please visit http://www.octgn.net for subscription information."
                        + Environment.NewLine + "Would you like to go there now?",
                        "Oh No!",
                        MessageBoxButton.YesNo,
                        MessageBoxImage.Exclamation);
                if (res == MessageBoxResult.Yes)
                {
                    var url = SubscriptionModule.Get().GetSubscribeUrl(new SubType()
                    {
                        Description = "", Name = ""
                    });
                    if (url != null)
                    {
                        Program.LaunchUrl(url);
                    }
                }
                return;
            }
            if (!IsGameLoaded)
            {
                return;
            }
            var save = SearchSave.Load();

            if (save == null)
            {
                return;
            }

            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);
                return;
            }
            else if (Game.Id != save.GameId)
            {
                TopMostMessageBox.Show(
                    "This search is for the game " + game.Name + ". You currently have the game " + Game.Name
                    + " loaded so you can not load this search.", "Oh No", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            var ctrl = new SearchControl(Game, save)
            {
                SearchIndex = Searches.Count == 0 ? 1 : Searches.Max(x => x.SearchIndex) + 1
            };

            ctrl.CardAdded    += AddResultCard;
            ctrl.CardRemoved  += RemoveResultCard;
            ctrl.CardSelected += CardSelected;
            LoadFonts(ctrl.resultsGrid);
            Searches.Add(ctrl);
            searchTabs.SelectedIndex = Searches.Count - 1;
        }
Ejemplo n.º 18
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
            };

            HostedGame result = null;

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

            Program.CurrentHostedGame = result ?? throw new InvalidOperationException("HostGame returned a null");
            Program.GameEngine        = new GameEngine(game, Program.LobbyClient.User.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.º 19
0
 private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
 {
     this.Loaded -= OnLoaded;
     SubscriptionModule.Get().IsSubbedChanged += Main_IsSubbedChanged;
 }
Ejemplo n.º 20
0
 private void CheckBoxIsLocalGame_OnUnchecked(object sender, RoutedEventArgs e)
 {
     PasswordGame.IsEnabled = SubscriptionModule.Get().IsSubscribed ?? false;
 }
Ejemplo n.º 21
0
        public TableControl()
        {
            InitializeComponent();
            if (DesignerProperties.GetIsInDesignMode(this))
            {
                return;
            }
            var tableDef = Program.GameEngine.Definition.Table;
            var subbed   = SubscriptionModule.Get().IsSubscribed ?? false;

            if (subbed && !String.IsNullOrWhiteSpace(Prefs.DefaultGameBack) && File.Exists(Prefs.DefaultGameBack))
            {
                SetBackground(Prefs.DefaultGameBack, "uniformToFill");
            }
            else
            {
                if (tableDef.Background != null)
                {
                    SetBackground(tableDef);
                }
            }
            Program.GameEngine.BoardImage = Program.GameEngine.GameBoard.Source;
            //if (!Program.GameSettings.HideBoard)
            //    if (tableDef.Board != null)
            //        SetBoard(tableDef);

            if (!Program.GameSettings.UseTwoSidedTable)
            {
                middleLine.Visibility = Visibility.Collapsed;
            }

            if (Player.LocalPlayer.InvertedTable)
            {
                transforms.Children.Insert(0, new ScaleTransform(-1, -1));
            }

            _defaultWidth  = Program.GameEngine.Definition.CardSize.Width;
            _defaultHeight = Program.GameEngine.Definition.CardSize.Height;
            SizeChanged   += delegate
            {
                IsCardSizeValid = false;
                AspectRatioChanged();
            };
            MoveCards.Done  += CardMoved;
            CreateCard.Done += CardCreated;
            Unloaded        += delegate
            {
                MoveCards.Done  -= CardMoved;
                CreateCard.Done -= CardCreated;
            };
            Loaded += delegate { CenterView(); };
            //var didIt = false;
            //Loaded += delegate
            //{
            //if (didIt) return;
            //didIt = true;
            //foreach (var p in Player.AllExceptGlobal.GroupBy(x => x.InvertedTable))
            //{
            //    var sx = Program.GameEngine.BoardMargin.Left;
            //    var sy = Program.GameEngine.BoardMargin.Bottom;
            //    if (p.Key == true)
            //    {
            //        sy = Program.GameEngine.BoardMargin.Top;
            //        sx = Program.GameEngine.BoardMargin.Right;
            //    }
            //    foreach (var player in p)
            //    {
            //        foreach (var tgroup in player.TableGroups)
            //        {
            //            var pile = new AdhocPileControl();
            //            pile.DataContext = tgroup;
            //            PlayerCanvas.Children.Add(pile);
            //            Canvas.SetLeft(pile, sx);
            //            Canvas.SetTop(pile, sy);
            //            if (p.Key)
            //                sx -= Program.GameEngine.Definition.CardWidth * 2;
            //            else
            //                sx += Program.GameEngine.Definition.CardWidth * 2;
            //        }
            //        if (p.Key)
            //            sx -= Program.GameEngine.Definition.CardWidth * 4;
            //        else
            //            sx += Program.GameEngine.Definition.CardWidth * 4;
            //    }
            //}
            //};
            Program.GameEngine.PropertyChanged += GameOnPropertyChanged;
            if (Player.LocalPlayer.InvertedTable)
            {
                var rotateAnimation = new DoubleAnimation(0, 180, TimeSpan.FromMilliseconds(1));
                var rt = (RotateTransform)NoteCanvas.RenderTransform;
                rt.BeginAnimation(RotateTransform.AngleProperty, rotateAnimation);
            }

            Player.LocalPlayer.PropertyChanged += LocalPlayerOnPropertyChanged;
        }