コード例 #1
0
            public async Task DeleteGameAsync(string name)
            {
                Data.Game game = DatabaseHandler.GetFromDb(new Data.Game {
                    Name = name
                });

                if (game is null)
                {
                    await ReplyAsync(Message.Error.GameNotFound(game));
                }
                else
                {
                    switch (DatabaseHandler.RemoveFromDb(game))
                    {
                    case DatabaseHandler.Result.Failed:
                        await ReplyAsync(Message.Error.Generic);

                        break;

                    case DatabaseHandler.Result.Successful:
                        await ReplyAsync(Message.Info.SuccessfullyRemoved(game));

                        break;
                    }
                }
            }
コード例 #2
0
ファイル: GameListItem.xaml.cs プロジェクト: IanWhalen/OCTGN
 public GameListItem()
 {
     InitializeComponent();
     _game = new Data.Game();
     DataContext = this;
     LIBorder.DataContext = this;
 }
コード例 #3
0
ファイル: SetModule.cs プロジェクト: hsaddouki/Inquisition
            public async Task SetGameVersionAsync(string name, string version)
            {
                if (name is null || version is null)
                {
                    await ReplyAsync("Incorrect command structure, use: db port \"[Game]\" \"[NewVersion]\"");

                    return;
                }

                Data.Game game = db.Games.Where(x => x.Name == name).FirstOrDefault();
                if (game is null)
                {
                    await ReplyAsync($"Sorry, {name} not found in the database");

                    return;
                }
                else
                {
                    try
                    {
                        game.Version = version;
                        await db.SaveChangesAsync();
                        await ReplyAsync($"Changed {game.Name}'s version to {version} successfully");
                    }
                    catch (Exception ex)
                    {
                        await ReplyAsync($"Nope, something went wrong. " +
                                         $"Please let the knobhead who programmed this know about it, thanks");

                        Console.WriteLine(ex.Message);
                        throw;
                    }
                }
            }
コード例 #4
0
        // TO DO: return warnings and errors
        // handling exceptions
        public void SaveNewGame(string title, string sourceCode, string description, string icon, int userID)
        {
            var gameNote = new Data.Game()
            {
                Title          = title,
                Description    = description,
                SourceCode     = sourceCode,
                UrlIcon        = icon,
                UserId         = userID,
                PointDialogues = new List <Data.GameData.PointDialog>(),
                Transitions    = new List <Data.GameData.Transition>(),
                Rating         = 0,
            };

            SaveGameComponents(sourceCode, gameNote);

            try
            {
                dataBase.Add(gameNote);

                dataBase.SaveChanges();
            }
            catch (Exception e)
            {
                throw e;
            }
        }
コード例 #5
0
        protected void InstallGame(object sender, RoutedEventArgs e)
        {
            if (!Settings.Default.DontShowInstallNotice)
            new InstallNoticeDialog { Owner = Application.Current.MainWindow }.ShowDialog();

            // Get the definition file
            Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
            ofd.Filter = "Game definition files (*.o8g)|*.o8g";
            if (ofd.ShowDialog() != true) return;

            // Open the archive
            Definitions.GameDef game = Definitions.GameDef.FromO8G(ofd.FileName);
            if (!game.CheckVersion()) return;

            // Check if the game already exists
            if (Program.GamesRepository.Games.Any(g => g.Id == game.Id))
                if (MessageBox.Show("This game already exists.\r\nDo you want to overwrite it?", "Confirmation", MessageBoxButton.YesNo, MessageBoxImage.Exclamation) != MessageBoxResult.Yes)
                    return;

            var gameData = new Data.Game()
            {
                Id = game.Id, Name = game.Name,
            Filename = ofd.FileName, Version = game.Version,
                CardWidth = game.CardDefinition.Width, CardHeight = game.CardDefinition.Height,
                CardBack = game.CardDefinition.back,
                DeckSections = game.DeckDefinition.Sections.Keys,
            SharedDeckSections = game.SharedDeckDefinition == null ? null : game.SharedDeckDefinition.Sections.Keys
            };
            Program.GamesRepository.InstallGame(gameData, game.CardDefinition.Properties.Values);
        }
コード例 #6
0
ファイル: GameService.cs プロジェクト: cmu-sei/gameboard
        public async Task <SessionForecast[]> SessionForecast(string id)
        {
            Data.Game entity = await Store.Retrieve(id);

            var ts   = DateTimeOffset.UtcNow;
            var step = ts;

            var expirations = await Store.DbContext.Players
                              .Where(p => p.GameId == id && p.Role == PlayerRole.Manager && p.SessionEnd.CompareTo(ts) > 0)
                              .Select(p => p.SessionEnd)
                              .ToArrayAsync();

            // foreach half hour, get count of available seats
            List <SessionForecast> result = new();

            for (int i = 0; i < 480; i += 30)
            {
                step = ts.AddMinutes(i);
                int reserved = expirations.Count(d => step.CompareTo(d) < 0);
                result.Add(new SessionForecast
                {
                    Time      = step,
                    Reserved  = reserved,
                    Available = entity.SessionLimit - reserved
                });
            }

            return(result.ToArray());
        }
コード例 #7
0
ファイル: Games.cs プロジェクト: WalterSharpJr/ping-pong
        /// <summary>
        /// Creates a new game entity in the database
        /// </summary>
        /// <param name="game"></param>
        /// <returns></returns>
        public Models.RequestResult Create(Data.Game game)
        {
            try
            {
                if (game.IsValid() == true)
                {
                    game.Id = Guid.NewGuid();
                    game.WinningPlayerId = (game.Player1Score > game.Player2Score ? game.Player1Id : game.Player2Id);
                    game.PlayedOn        = DateTime.Now;

                    Context.Games.Add(game);
                    Context.SaveChanges();

                    return(Models.RequestResult.GetSuccess());
                }

                return(Models.RequestResult.GetFail(StatusCodes.Status400BadRequest));
            }
            catch (Microsoft.EntityFrameworkCore.DbUpdateException)
            {
                return(Models.RequestResult.GetFail(StatusCodes.Status400BadRequest));
            }
            catch (Exception)
            {
                return(Models.RequestResult.GetFail(StatusCodes.Status500InternalServerError));
            }
        }
コード例 #8
0
ファイル: GameService.cs プロジェクト: cmu-sei/gameboard
        public async Task <string> Export(GameSpecExport model)
        {
            var yaml = new SerializerBuilder()
                       .WithNamingConvention(CamelCaseNamingConvention.Instance)
                       .Build();

            var entity = await Store.Retrieve(model.Id, q => q.Include(g => g.Specs));

            if (entity is Data.Game)
            {
                return(yaml.Serialize(entity));
            }

            entity = new Data.Game
            {
                Id = Guid.NewGuid().ToString("n")
            };

            for (int i = 0; i < model.GenerateSpecCount; i++)
            {
                entity.Specs.Add(new Data.ChallengeSpec
                {
                    Id     = Guid.NewGuid().ToString("n"),
                    GameId = entity.Id
                });
            }

            return(model.Format == ExportFormat.Yaml
                ? yaml.Serialize(entity)
                : JsonSerializer.Serialize(entity, JsonOptions)
                   );
        }
コード例 #9
0
ファイル: GameListItem.xaml.cs プロジェクト: clavalle/OCTGN
 public GameListItem()
 {
     InitializeComponent();
     _game                = new Data.Game();
     DataContext          = this;
     LIBorder.DataContext = this;
 }
コード例 #10
0
        void StartLocalGame(Data.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 + "@" + Program.ChatServerPath), 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.GameSettings.UseTwoSidedTable     = true;
            Program.Game   = new Game(GameDef.FromO8G(game.FullPath), Username, true);
            Program.IsHost = true;

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

            Program.Client = new Client(ip, hostport);
            Program.Client.Connect();
            SuccessfulHost = true;
        }
コード例 #11
0
        private void CreateTeamsAndGame(GamePoolContext context, string bowlName, string teamA, string teamB, string network, string gameDateTime)
        {
            Team t1 = new Data.Team()
            {
                Id          = Guid.NewGuid().ToString(),
                Description = (string.IsNullOrEmpty(teamA)) ? $"{bowlName} Home" : teamA
            };
            Team t2 = new Data.Team()
            {
                Id          = Guid.NewGuid().ToString(),
                Description = (string.IsNullOrEmpty(teamB)) ? $"{bowlName} Home" : teamB
            };
            Game g1 = new Data.Game()
            {
                HomeTeamId   = t1.Id,
                AwayTeamId   = t2.Id,
                Description  = bowlName,
                Network      = network,
                GameDateTime = gameDateTime,
                Id           = Guid.NewGuid().ToString(),
                AwayScore    = 0,
                HomeScore    = 0
            };

            context.Teams.Add(t1);
            context.Teams.Add(t2);
            context.Games.Add(g1);
        }
コード例 #12
0
ファイル: GhostCommands.cs プロジェクト: davewiebe/GameBot
        private async Task CheckGhostAttempts(Data.Game game)
        {
            var ghosts = _perudoGameService.GetGamePlayers(game)
                         .Where(x => x.NumberOfDice == 0)
                         .Where(x => x.GhostAttemptsLeft > 0).ToList();

            foreach (var ghost in ghosts)
            {
                if (ghost.GhostAttemptPips == 0 || ghost.GhostAttemptQuantity == 0)
                {
                    ghost.GhostAttemptsLeft   -= 1;
                    ghost.GhostAttemptQuantity = 0;
                    ghost.GhostAttemptPips     = 0;
                    ghost.Dice = "";
                    _db.SaveChanges();

                    if (ghost.GhostAttemptsLeft > 0)
                    {
                        await SendMessageAsync($":hourglass: {ghost.Player.Nickname} has {ghost.GhostAttemptsLeft} attempt left.");
                    }
                    else
                    {
                        await SendMessageAsync($":runner: {ghost.Player.Nickname} fled.");
                    }

                    continue;
                }

                var quantity = GetNumberOfDiceMatchingBid(game, ghost.GhostAttemptPips);

                if (quantity == ghost.GhostAttemptQuantity)
                {
                    ghost.GhostAttemptsLeft    = -1;
                    ghost.NumberOfDice         = 1;
                    ghost.GhostAttemptQuantity = 0;
                    ghost.GhostAttemptPips     = 0;
                    ghost.Dice = "";
                    _db.SaveChanges();

                    await SendMessageAsync($":boom: A wild {ghost.Player.Nickname} appeared!");
                }
                else if (ghost.GhostAttemptQuantity > 0)
                {
                    ghost.GhostAttemptsLeft   -= 1;
                    ghost.GhostAttemptQuantity = 0;
                    ghost.GhostAttemptPips     = 0;
                    _db.SaveChanges();

                    if (ghost.GhostAttemptsLeft > 0)
                    {
                        await SendMessageAsync($":hourglass: {ghost.Player.Nickname} has {ghost.GhostAttemptsLeft} attempt left.");
                    }
                    else
                    {
                        await SendMessageAsync($":runner: {ghost.Player.Nickname} fled.");
                    }
                }
            }
        }
コード例 #13
0
        private void GOnOnGameClick(object sender, EventArgs eventArgs)
        {
            var hg = sender as Octgn.Data.Game;

            if (hg == null || Program.PlayWindow != null)
            {
                Program.LauncherWindow.Navigate(new Login());
                return;
            }
            var hostport = 5000;

            while (!Skylabs.Lobby.Networking.IsPortAvailable(hostport))
            {
                hostport++;
            }
            var hs = new HostedGame(hostport, hg.Id, hg.Version, "LocalGame", "", null, true);

            hs.HostedGameDone += hs_HostedGameDone;
            if (!hs.StartProcess())
            {
                hs.HostedGameDone -= hs_HostedGameDone;
                Program.LauncherWindow.Navigate(new Login());
                return;
            }

            Program.IsHost = true;
            Data.Game theGame =
                Program.GamesRepository.Games.FirstOrDefault(g => g.Id == hg.Id);
            if (theGame == null)
            {
                return;
            }
            Program.Game = new Game(GameDef.FromO8G(theGame.FullPath), true);

            var       ad = new IPAddress[1];
            IPAddress ip = IPAddress.Parse("127.0.0.1");

            if (ad.Length <= 0)
            {
                return;
            }
            try
            {
                Program.Client = new Client(ip, hostport);
                Program.Client.Connect();
                Dispatcher.Invoke(new Action(() => Program.LauncherWindow.NavigationService.Navigate(new StartGame(true)
                {
                    Width = 400
                })));
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }
            }
        }
コード例 #14
0
        private void LoadDeck(Data.Game game)
        {
            if (_unsaved)
            {
                MessageBoxResult result = MessageBox.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 != null) && Prefs.LastFolder == "")
                                      ? game.DefaultDecksPath
                                      : Prefs.LastFolder
            };

            if (ofd.ShowDialog() != true)
            {
                return;
            }
            Prefs.LastFolder = Path.GetDirectoryName(ofd.FileName);

            // Try to load the file contents
            Deck newDeck;

            try
            {
                newDeck = Deck.Load(ofd.FileName, Program.GamesRepository);
            }
            catch (DeckException ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            catch (Exception ex)
            {
                MessageBox.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();
        }
コード例 #15
0
        public async Task <Dto.Game?> UpdateAsync(int id, Dto.GameInput input)
        {
            Game entity = _mapper.Map <Dto.GameInput, Game>(input);
            Game?result = await _gameRepository.UpdateAsync(id, entity);

            return(result is null
            ? null
            :_mapper.Map <Game, Dto.Game>(result));
        }
コード例 #16
0
 public DataGameViewModel(Data.Game game)
 {
     Id          = game.Id;
     Name        = game.Name;
     Version     = game.Version;
     CardBackUri = game.GetCardBackUri();
     FullPath    = game.FullPath;
     IsSelected  = false;
 }
コード例 #17
0
            public async Task GamePortAsync(string name)
            {
                Data.Game game = db.Games.Where(x => x.Name == name).FirstOrDefault();
                if (game is null)
                {
                    await ReplyAsync($"Sorry, {name} not found in the database");

                    return;
                }

                await ReplyAsync($"{game.Name}'s port is {game.Port}");
            }
コード例 #18
0
 public SearchControl(Data.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.SelectCards(null).DefaultView);
 }//Why are we populating the list on load? I'd rather wait until the search is run with no parameters (V)_V
コード例 #19
0
        private void hgl_OnGameClick(object sender, EventArgs e)
        {
            if (Program.PlayWindow != null)
            {
                return;
            }
            var hg = sender as HostedGameData;

            Data.Game theGame =
                Program.GamesRepository.AllGames.FirstOrDefault(g => hg != null && g.Id == hg.GameGuid);
            if (theGame == null)
            {
                return;
            }
            if (_joiningGame)
            {
                return;
            }
            _joiningGame   = true;
            Program.IsHost = false;
            Program.Game   = new Game(GameDef.FromO8G(theGame.FullPath));

            var       ad = Dns.GetHostAddresses(Skylabs.Lobby.Client.Host);
            IPAddress ip = ad[0];

            if (ad.Length <= 0)
            {
                return;
            }
            try
            {
                if (hg != null)
                {
                    Program.Client = new Client(ip, hg.Port);
                }
                Program.Client.Connect();
                Dispatcher.Invoke(new Action(() => frame1.Navigate(new StartGame())));
                _joiningGame = false;
            }
            catch (Exception ex)
            {
                _joiningGame = false;
                Debug.WriteLine(ex);
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }
            }
        }
コード例 #20
0
 private void GenerateColumns(Data.Game game)
 {
     foreach (PropertyDef prop in game.CustomProperties)
     {
         resultsGrid.Columns.Add(new DataGridTextColumn
         {
             Binding = new Binding
             {
                 Path = new PropertyPath(prop.Name),
                 Mode = BindingMode.OneTime
             },
             Header = prop.Name
         });
     }
 }
コード例 #21
0
 private void UpdateGenrePickerItems(Data.Game game = null)
 {
     GenrePicker.ItemsSource = (from i in Global.DB.Genres
                                select new InteractiveListItem
     {
         Text = i.GenreName, Item = i
     }).ToList();
     if (game != null)
     {
         foreach (InteractiveListItem i in GenrePicker.Items)
         {
             i.IsTicked = game.Genres
                          .FirstOrDefault(g => g.GenreName == i.Text) is Data.Genre;
         }
     }
 }
コード例 #22
0
        public async Task GamePortAsync(string name)
        {
            Data.Game game = DatabaseHandler.GetFromDb(new Data.Game {
                Name = name
            });
            if (game is null)
            {
                await ReplyAsync(Message.Error.GameNotFound(new Data.Game {
                    Name = name
                }));

                return;
            }

            await ReplyAsync($"{game.Name}'s port is {game.Port}");
        }
コード例 #23
0
        private async Task <bool> IsUnlocked(Data.Player player, Data.Game game, string specId)
        {
            bool result = true;

            foreach (var prereq in game.Prerequisites.Where(p => p.TargetId == specId))
            {
                var condition = await Store.DbSet.AnyAsync(c =>
                                                           c.TeamId == player.TeamId &&
                                                           c.SpecId == prereq.RequiredId &&
                                                           c.Score >= prereq.RequiredScore
                                                           );

                result &= condition;
            }

            return(result);
        }
コード例 #24
0
        public async Task StartGameAsync(string name)
        {
            Data.Game game = DatabaseHandler.GetFromDb(new Data.Game {
                Name = name
            });
            string Path = ProcessDictionary.Path;

            if (game is null)
            {
                await ReplyAsync(Message.Error.GameNotFound(game));

                return;
            }

            try
            {
                if (ProcessDictionary.Instance.TryGetValue(game.Name, out Process temp))
                {
                    await ReplyAsync(Message.Error.GameAlreadyRunning(game));

                    return;
                }

                Process p = new Process();
                p.StartInfo.FileName  = $"C:\\Windows\\system32\\notepad.exe";
                p.StartInfo.Arguments = game.LaunchArgs;
                p.Start();

                ProcessDictionary.Instance.Add(game.Name, p);

                game.IsOnline = true;
                DatabaseHandler.UpdateInDb(game);

                await ReplyAsync(Message.Info.GameStartingUp(game));
            }
            catch (Exception ex)
            {
                await ReplyAsync(Message.Error.UnableToStartGameServer(game));

                Console.WriteLine(ex.Message);
            }
        }
コード例 #25
0
        private void GOoffConnOnGameClick(object sender, EventArgs eventArgs)
        {
            var hg = sender as Octgn.Data.Game;

            if (hg == null || Program.PlayWindow != null)
            {
                Program.LauncherWindow.NavigationService.Navigate(new Login());
                return;
            }
            Program.IsHost = false;
            Data.Game theGame =
                Program.GamesRepository.Games.FirstOrDefault(g => g.Id == hg.Id);
            if (theGame == null)
            {
                Program.LauncherWindow.Navigate(new Login());
                return;
            }
            Program.Game = new Game(GameDef.FromO8G(theGame.FullPath), true);
            Program.LauncherWindow.Navigate(new ConnectLocalGame());
        }
コード例 #26
0
        private void UpdateSubsInfo(Data.Game game = null)
        {
            int    numberOfSubs   = (game is null ? 0 : game.Subscriptions.Count);
            int    numberOfRrates = 0;
            double avgRate        = 0;

            if (game != null && game.Subscriptions.Count > 0)
            {
                var rates = game.Subscriptions.Where(s => s.Rate != null);
                numberOfSubs = rates.Count();
                if (numberOfRrates > 0)
                {
                    avgRate = rates.Average(s => (double)s.Rate);
                }
            }
            SubsInfoText.Text = AppResources.Lang.SubsRatesAndAvg
                                .Replace("{subs}", numberOfSubs.ToString())
                                .Replace("{rates}", numberOfRrates.ToString())
                                .Replace("{avg}", avgRate.ToString());
        }
コード例 #27
0
        // finds game with the id
        // clear all dialog points and transitions in this game
        // updates fields in game table
        // saves points and transitions
        public void UpdateGame(int gameID, string title, string sourceCode, string description, string icon)
        {
            dataBase.Transitions.RemoveRange(dataBase.Transitions.Where(c => c.GameId == gameID));

            dataBase.PointDialogs.RemoveRange(dataBase.PointDialogs.Where(c => c.GameId == gameID));

            Data.Game gameNote = null;

            try
            {
                gameNote = dataBase.Games.Single(c => c.Id == gameID);
            }
            catch (Exception e)
            {
                //...
            }

            {
                gameNote.Title = title;

                gameNote.SourceCode = sourceCode;

                gameNote.Description = description;

                gameNote.UrlIcon = icon;
            }

            SaveGameComponents(sourceCode, gameNote);

            try
            {
                dataBase.Update(gameNote);

                dataBase.SaveChanges();
            }
            catch (Exception e)
            {
                //...
            }
        }
コード例 #28
0
        public async Task StatusAsync(string name)
        {
            Data.Game game = DatabaseHandler.GetFromDb(new Data.Game {
                Name = name
            });
            if (game is null)
            {
                await ReplyAsync(Message.Error.GameNotFound(new Data.Game {
                    Name = name
                }));

                return;
            }

            bool ProcessRunning   = ProcessDictionary.Instance.TryGetValue(game.Name, out Process p);
            bool GameMarkedOnline = game.IsOnline;

            if (!ProcessRunning && !GameMarkedOnline)
            {
                await ReplyAsync($"{game.Name} server is offline. If you wish to start it up use: game start \"{game.Name}\"");

                return;
            }
            else if (ProcessRunning && !GameMarkedOnline)
            {
                await ReplyAsync($"{game.Name} has a process running, but is marked as offline in the database, " +
                                 $"please let the knobhead who programmed this know abut this error, thanks");

                return;
            }
            else if (!ProcessRunning && GameMarkedOnline)
            {
                await ReplyAsync($"{game.Name} server is not running, but is marked as online in the database, " +
                                 $"please let the knobhead who programmed this know abut this error, thanks");

                return;
            }

            await ReplyAsync($"{game.Name} server is online, version {game.Version} on port {game.Port}");
        }
コード例 #29
0
ファイル: StartModule.cs プロジェクト: hsaddouki/Inquisition
        public async Task StartGameAsync(string name)
        {
            Data.Game game = db.Games.Where(x => x.Name == name).FirstOrDefault();
            if (game is null)
            {
                await ReplyAsync(ErrorMessage.GameNotFound(game.Name));

                return;
            }

            try
            {
                if (ProcessDictionary.Instance.TryGetValue(game.Name, out Process temp))
                {
                    await ReplyAsync(ErrorMessage.GameAlreadyRunning(Context.User.Mention, game.Name, game.Version, game.Port));

                    return;
                }

                Process p = new Process();
                p.StartInfo.FileName  = Path + game.ExeDir;
                p.StartInfo.Arguments = game.Args;
                p.Start();

                ProcessDictionary.Instance.Add(game.Name, p);

                game.IsOnline = true;
                await db.SaveChangesAsync();

                await ReplyAsync(InfoMessage.GameStartingUp(Context.User.Mention, game.Name, game.Version, game.Port));
            }
            catch (Exception ex)
            {
                await ReplyAsync(ErrorMessage.UnableToStartGameServer(game.Name));

                Console.WriteLine(ex.Message);
                throw;
            }
        }
コード例 #30
0
ファイル: CustomGames.xaml.cs プロジェクト: clavalle/OCTGN
        private void StartJoinGame(HostedGameViewModel hostedGame, Data.Game game)
        {
            Program.IsHost = false;
            Program.Game   = new Game(GameDef.FromO8G(game.FullPath), Program.LobbyClient.Me.UserName);
            Program.CurrentOnlineGameName = hostedGame.Name;
            IPAddress hostAddress = Dns.GetHostAddresses(Program.GameServerPath).FirstOrDefault();

            if (hostAddress == null)
            {
                throw new UserMessageException("There was a problem with your DNS. Please try again.");
            }

            try
            {
                Program.Client = new Client(hostAddress, hostedGame.Port);
                Program.Client.Connect();
            }
            catch (Exception)
            {
                throw new UserMessageException("Could not connect. Please try again.");
            }
        }
コード例 #31
0
 private void AddGame()
 {
     if (string.IsNullOrWhiteSpace(GameNameText.Text))
     {
         return;
     }
     Data.Game game = new Data.Game
     {
         GameName       = GameNameText.Text,
         Developer      = AddGetDeveloper(DeveloperText.Text),
         GameExePath    = PathText.Text,
         Image          = AddGetImage(ImageNameText.Text),
         IsSingleplayer = SPToggle.IsChecked,
         IsMultiplayer  = MPToggle.IsChecked,
         Genres         = GetTickedGenres()
     };
     Global.DB.Games.Add(game);
     Global.DB.SaveChanges();
     UpdateGameItems();
     ClearFields();
     Voice.Say(AppResources.Lang.GameAddedToDB);
 }
コード例 #32
0
        public async Task DeleteGameAsync(string name)
        {
            Data.Game game = db.Games.Where(x => x.Name == name).FirstOrDefault();
            if (game is null)
            {
                await ReplyAsync(ErrorMessage.GameNotFound(game.Name));

                return;
            }
            try
            {
                db.Remove(game);
                await db.SaveChangesAsync();
                await ReplyAsync(InfoMessage.SuccessfullyRemoved(game));
            }
            catch (Exception ex)
            {
                await ReplyAsync(ErrorMessage.DatabaseAccess());

                Console.WriteLine(ex.Message);
                throw;
            }
        }
コード例 #33
0
        protected override void OnClosing(CancelEventArgs e)
        {
            base.OnClosing(e);

            if (_unsaved)
            {
                MessageBoxResult result = MessageBox.Show("This deck contains unsaved modifications. Save?", "Warning",
                                                          MessageBoxButton.YesNoCancel, MessageBoxImage.Warning);
                switch (result)
                {
                    case MessageBoxResult.Yes:
                        Save();
                        break;
                    case MessageBoxResult.No:
                        break;
                    default:
                        e.Cancel = true;
                        return;
                }
            }

            Game = null; // Close DB if required
        }
コード例 #34
0
ファイル: SetList.xaml.cs プロジェクト: IanWhalen/OCTGN
 public void Set(Data.Game game)
 {
     SelectedGame = game;
     RefreshList();
 }
コード例 #35
0
ファイル: GameList.xaml.cs プロジェクト: YoshiEnVerde/OCTGN
        public void Install_Game()
        {
            Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
            ofd.Filter = "Game definition files (*.o8g)|*.o8g";
            if (ofd.ShowDialog() != true) return;

            //Fix def filename
            String newFilename = Uri.UnescapeDataString(ofd.FileName);
            if (!newFilename.ToLower().Equals(ofd.FileName.ToLower()))
            {
                try
                {
                    File.Move(ofd.FileName, newFilename);
                }
                catch (Exception)
                {
                    MessageBox.Show("This file is currently in use. Please close whatever application is using it and try again.");
                    return;
                }

            }

            try
            {
                //Move the definition file to a new location, so that the old one can be deleted
                string path = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Octgn", "Defs");
                if(!Directory.Exists(path))
                    Directory.CreateDirectory(path);
                FileInfo fi = new FileInfo(newFilename);
                string copyto = System.IO.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;
                }
                newFilename = copyto;
                // Open the archive
                Definitions.GameDef game = Definitions.GameDef.FromO8G(newFilename);
                if (!game.CheckVersion()) return;

                // Check if the game already exists
                if (Program.GamesRepository.Games.Any(g => g.Id == game.Id))
                    if (MessageBox.Show("This game already exists.\r\nDo you want to overwrite it?", "Confirmation", MessageBoxButton.YesNo, MessageBoxImage.Exclamation) != MessageBoxResult.Yes)
                        return;

                var gameData = new Data.Game()
                {
                    Id = game.Id,
                    Name = game.Name,
                    Filename = newFilename,
                    Version = game.Version,
                    CardWidth = game.CardDefinition.Width,
                    CardHeight = game.CardDefinition.Height,
                    CardBack = game.CardDefinition.back,
                    DeckSections = game.DeckDefinition.Sections.Keys,
                    SharedDeckSections = game.SharedDeckDefinition == null ? null : game.SharedDeckDefinition.Sections.Keys
                };
                Program.GamesRepository.InstallGame(gameData, game.CardDefinition.Properties.Values);
            }
            catch (System.IO.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);
            }
        }
コード例 #36
0
 public HostGameSettings(Data.Game game)
 {
     InitializeComponent();
     _game = game;
 }
コード例 #37
0
ファイル: GameDef.cs プロジェクト: 0M3G4/OCTGN
        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 (Program.GamesRepository.Games.Any(g => g.Id == game.Id))
                    if (
                        MessageBox.Show("This game already exists.\r\nDo you want to overwrite it?", "Confirmation",
                                        MessageBoxButton.YesNo, MessageBoxImage.Exclamation) != MessageBoxResult.Yes)
                        return false;

                var gameData = new Data.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,
                                       SharedDeckSections =
                                           game.SharedDeckDefinition == null
                                               ? null
                                               : game.SharedDeckDefinition.Sections.Keys,
                                       Repository = Program.GamesRepository,
                                       FileHash = game.FileHash
                                   };
                Program.GamesRepository.InstallGame(gameData, game.CardDefinition.Properties.Values);
                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;
            }
        }
コード例 #38
0
        protected void InstallGame(object sender, RoutedEventArgs e)
        {
            if(!Settings.Default.DontShowInstallNotice)
                new InstallNoticeDialog { Owner = Program.ClientWindow }.ShowDialog();

            // Get the definition file
            Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
            ofd.Filter = "Game definition files (*.o8g)|*.o8g";
            if(ofd.ShowDialog() != true) return;

            //Fix def filename
            String newFilename = Uri.UnescapeDataString(ofd.FileName);
            if(!newFilename.ToLower().Equals(ofd.FileName.ToLower()))
            {
                File.Move(ofd.FileName, newFilename);
            }

            try
            {
                // Open the archive
                Definitions.GameDef game = Definitions.GameDef.FromO8G(newFilename);
                if(!game.CheckVersion()) return;

                // Check if the game already exists
                if(Program.GamesRepository.Games.Any(g => g.Id == game.Id))
                    if(MessageBox.Show("This game already exists.\r\nDo you want to overwrite it?", "Confirmation", MessageBoxButton.YesNo, MessageBoxImage.Exclamation) != MessageBoxResult.Yes)
                        return;

                var gameData = new Data.Game()
                {
                    Id = game.Id,
                    Name = game.Name,
                    Filename = newFilename,
                    Version = game.Version,
                    CardWidth = game.CardDefinition.Width,
                    CardHeight = game.CardDefinition.Height,
                    CardBack = game.CardDefinition.back,
                    DeckSections = game.DeckDefinition.Sections.Keys,
                    SharedDeckSections = game.SharedDeckDefinition == null ? null : game.SharedDeckDefinition.Sections.Keys
                };
                Program.GamesRepository.InstallGame(gameData, game.CardDefinition.Properties.Values);
            }
            catch(System.IO.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);
            }
        }
コード例 #39
0
 public HostGameSettings(Octgn.Data.Game game)
 {
     InitializeComponent();
     Game = game;
 }
コード例 #40
0
 private void NewClicked(object sender, RoutedEventArgs e)
 {
     Game = (Data.Game)((MenuItem)e.OriginalSource).DataContext;
     CommandManager.InvalidateRequerySuggested();
     Deck = new Deck(Game);
     deckFilename = null;
 }
コード例 #41
0
        private void LoadDeck(Data.Game game)
        {
            if (_unsaved)
            {
                MessageBoxResult result = MessageBox.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 != null) && (SimpleConfig.ReadValue("lastFolder")) == "")
                                      ? game.DefaultDecksPath
                                      : SimpleConfig.ReadValue("lastFolder")
                          };
            if (ofd.ShowDialog() != true) return;
            SimpleConfig.WriteValue("lastFolder", Path.GetDirectoryName(ofd.FileName));

            // Try to load the file contents
            Deck newDeck;
            try
            {
                newDeck = Deck.Load(ofd.FileName, Program.GamesRepository);
            }
            catch (DeckException ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            catch (Exception ex)
            {
                MessageBox.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();
        }
コード例 #42
0
 private void NewDeckCommand(object sender, ExecutedRoutedEventArgs e)
 {
     e.Handled = true;
     if (Game == null)
     {
         if (Program.GamesRepository.Games.Count == 1)
             Game = Program.GamesRepository.Games[0];
         else
         {
             MessageBox.Show("You have to select a game before you can use this command.", "Error",
                             MessageBoxButton.OK);
             return;
         }
     }
     Deck = new Deck(Game);
     _deckFilename = null;
 }
コード例 #43
0
 private void NewClicked(object sender, RoutedEventArgs e)
 {
     if (_unsaved)
     {
         MessageBoxResult result = MessageBox.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;
         }
     }
     Game = (Data.Game) ((MenuItem) e.OriginalSource).DataContext;
     CommandManager.InvalidateRequerySuggested();
     Deck = new Deck(Game);
     _deckFilename = null;
 }
コード例 #44
0
 public HostGameSettings(Data.Game game)
 {
     InitializeComponent();
     _game = game;
     textBox1.Text = Prefs.LastRoomName;
 }
コード例 #45
0
ファイル: SetList.xaml.cs プロジェクト: YoshiEnVerde/OCTGN
 public SetList(Octgn.Data.Game selectedGame)
 {
     InitializeComponent();
     SelectedGame = selectedGame;
 }
コード例 #46
0
        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            base.OnClosing(e);

            if (unsaved)
            {
                var result = MessageBox.Show("This deck contains unsaved modifications. Save?", "Warning", MessageBoxButton.YesNoCancel, MessageBoxImage.Warning);
                switch (result)
                {
                    case MessageBoxResult.Yes:
                        Save();
                        break;
                    case MessageBoxResult.No:
                        break;
                    default:
                        e.Cancel = true;
                        return;
                }
            }

            Game = null;	// Close DB if required
            Program.lwMainWindow.Show();
            if ((Program.lwMainWindow.Content as Launcher.MainMenu) == null)
                Program.lwMainWindow.Navigate(new Launcher.MainMenu());
            Application.Current.MainWindow = Program.lwMainWindow;
        }
コード例 #47
0
ファイル: GameListItem.xaml.cs プロジェクト: 0M3G4/OCTGN
 public GameListItem()
 {
     InitializeComponent();
     _game = new Data.Game();
 }
コード例 #48
0
        private void LoadDeck(Data.Game game)
        {
            if (unsaved)
            {
                var result = MessageBox.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
            Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog()
            {
                Filter = "OCTGN deck files (*.o8d) | *.o8d",
                InitialDirectory = game != null ? game.DefaultDecksPath : null
            };
            if (ofd.ShowDialog() != true) return;
            // Try to load the file contents
            Deck newDeck;
            try
            {
                newDeck = Deck.Load(ofd.FileName, Program.GamesRepository);
            }
            catch (DeckException ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            catch (Exception ex)
            {
                MessageBox.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();
        }