/// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used such as when the application is launched to open a specific file.
        /// </summary>
        /// <param name="e">Details about the launch request and process.</param>
        protected override void OnLaunched(LaunchActivatedEventArgs args)
        {
            _model = new ReversiGameModel(new ReversiFileDataAccess(_supportedGameTableSizesArray), _tableSizeDefaultSetting); // létrehozzuk a modellt perzisztanciával
            _model.SetGameEnded += new EventHandler <ReversiSetGameEndedEventArgs>(Model_SetGameEnded);

            _viewModel            = new ReversiViewModel(_model);         // létrehozzuk a nézetmodellt
            _viewModel.NewGame   += ViewModel_NewGame;
            _viewModel.LoadGame  += new EventHandler(ViewModel_LoadGame); // kezeljük a nézetmodell eseményeit
            _viewModel.SaveGame  += new EventHandler(ViewModel_SaveGame);
            _viewModel.ReadRules += new EventHandler(ViewModel_ReadRules);
            _viewModel.ReadAbout += new EventHandler(ViewModel_ReadAbout);
            // a kilépést most nem kell

            Frame rootFrame = new Frame();      // létrehozzuk az ablakkeretet

            rootFrame.DataContext = _viewModel; // erre állítjuk be a nézetmodellt

            Window.Current.Content = rootFrame; // a keretet állítjuk be tartalomnak

            // amennyiben nem a felhasználó zárta be az alkalmazást, be kell töltenünk a korábbi állapotot
            if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
            {
                LoadAppState();
            }

            if (!rootFrame.Navigate(typeof(MainPage), args.Arguments)) // beállítjuk a nyitóképernyőt
            {
                throw new Exception("Failed to create initial page");
            }

            // amennyiben a rendszer fel akarja venni a saját parancsainkat
            SettingsPane.GetForCurrentView().CommandsRequested += new TypedEventHandler <SettingsPane, SettingsPaneCommandsRequestedEventArgs>(SettingsPane_CommandsRequested);

            Window.Current.Activate(); // aktiváljuk az ablakot
        }
        public void ReversiGameModelNewGameInitializeTooSmallTest()
        {
            Int32[] wrongGameTableSizesArray = new Int32[] { 10, 2, 20 }; // <- 2

            _dataAccess = new ReversiFileDataAccess(wrongGameTableSizesArray);
            Assert.ThrowsException <ReversiModelException>(() => _model = new ReversiGameModel(_dataAccess, _tableSizeDefaultSetting));
        }
        public void Initialize()
        {
            _dataAccess = new ReversiFileDataAccess(_supportedGameTableSizesArray);

            _model = new ReversiGameModel(_dataAccess, _tableSizeDefaultSetting);

            _model.UpdateTable      += new EventHandler <ReversiUpdateTableEventArgs>(model_UpdateTable);
            _model.SetGameEnded     += new EventHandler <ReversiSetGameEndedEventArgs>(model_SetGameEnded);
            _model.UpdatePlayerTime += new EventHandler <ReversiUpdatePlayerTimeEventArgs>(model_UpdatePlayerTime);
        }
        /// <summary>
        /// Sends the current game state to all current players...
        /// </summary>
        /// <param name="game"></param>
        private static void SendGameToAll(ReversiGameModel game)
        {
            Console.WriteLine("Sending game matchup to players");
            // Send the game object to each of the clients.
            foreach (KeyValuePair <int, ClientModel> item in game.CurrentPlayersList)
            {
                // Send the game data to each of the players

                DataTransmission.SerializeData <ReversiGameModel>(game, item.Value.ConnectionSocket);
            }
        }
Exemple #5
0
        /// <summary>
        /// Creaeting the reversi ViewModel.
        /// </summary>
        /// <param name="model">The Model type, which it will use.</param>
        public ReversiViewModel(ReversiGameModel model)
        {
            // Initialize what we have to.
            _model = model;
            _model.SetGameEnded     += new EventHandler <ReversiSetGameEndedEventArgs>(Model_SetGameEnded);
            _model.UpdatePlayerTime += new EventHandler <ReversiUpdatePlayerTimeEventArgs>(Model_UpdatePlayerTime);
            _model.UpdateTable      += new EventHandler <ReversiUpdateTableEventArgs>(Model_UpdateTable);

            NewGameCommand         = new DelegateCommand(param => { OnNewGame(); });
            LoadGameCommand        = new DelegateCommand(param => { OnLoadGame(); });
            SaveGameCommand        = new DelegateCommand(param => OnSaveGame());
            ExitApplicationCommand = new DelegateCommand(param => OnExitApplication());

            RulesCommand = new DelegateCommand(param => OnReadRules());
            AboutCommand = new DelegateCommand(param => OnReadAbout());

            PassCommand  = new DelegateCommand(param => OnPass());
            PauseCommand = new DelegateCommand(param => OnPause());

            Cells = new ObservableCollection <ReversiCell>();

            _saved = true;

            _saveMenuItemEnabled = false;
            OnPropertyChanged("SaveMenuItemEnabled");

            _passButtonEnabled = false;
            OnPropertyChanged("PassButtonEnabled");
            _pauseButtonEnabled = false;
            OnPropertyChanged("PauseButtonEnabled");

            _pauseText = "Pause";
            OnPropertyChanged("PauseText");

            _player1Time = 0;
            OnPropertyChanged("Player1Time");
            _player2Time = 0;
            OnPropertyChanged("Player2Time");

            _player1Points = 0;
            OnPropertyChanged("Player1Points");
            _player2Points = 0;
            OnPropertyChanged("Player2Points");

            dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
        }
        ///// <summary>
        ///// Removes a player from the staging area to the gameroom.
        ///// </summary>
        //private static void RemovePlayersFromStaging()
        //{
        //    for (int i = ReversiSettings.ReversiPlayersPerGame - 1; i >= 0; i--)
        //    {
        //        StagingArea.RemoveAt(i);
        //    }
        //}



        /// <summary>
        /// The main thread routine for each game
        /// </summary>
        /// <param name="data">The game staging area list of client models</param>
        private void InitializeMatchup(object data)
        {
            List <ReversiClientModel> clientModels = (List <ReversiClientModel>)data;

            //// Create the game instance which moves the players to the game room
            ReversiGameModel game = new ReversiGameModel(clientModels);

            RunningGames.Add(game.GameId, game);  // add the game to the dictionary of running games

            Console.WriteLine("... GameServer: Matchup pairing complete. Game " + game.GameId.ToString() + " is ready to start.");
            Console.WriteLine(game.DisplayGameInfoComplete());

            // Send the game object to each of the clients.
            foreach (KeyValuePair <int, ClientModel> item in game.CurrentPlayersList)
            {
                ReversiClientModel client = (ReversiClientModel)item.Value;

                // Send the game data to each of the players
                Console.WriteLine("Sending initial game matchup to players");
                DataTransmission.SerializeData <ReversiGameModel>(game, client.ConnectionSocket);

                // And remove the players from the Staging area.
                StagingArea.Remove(client);
            }

            //// The main game loop. Process individual moves here
            List <TcpClient> sockets = game.GetPlayersSocketList();

            while (!game.GameIsOver)
            {
                // If the game is paused ignore the user input
                if (game.GameIsPaused == true)
                {
                    continue;
                }

                if (game.GameOverCheckRequired)
                {
                    if (game.CheckGameOver(game.CurrentPlayer) == true)
                    {
                        Console.WriteLine("No available moves for " + game.CurrentPlayer);
                        game.GameIsOver = true;
                        break;
                    }

                    Console.WriteLine("Valid moves available for " + game.CurrentPlayer);
                    game.AvailableMovesList.ForEach(Console.WriteLine);
                    game.GameOverCheckRequired = false;
                }

                // If the current turn is valid and complete, switch to the next player
                if (game.TurnComplete)
                {
                    Console.WriteLine(game.Gameboard.DrawGameboardString());
                    game.NextPlayer();
                    game.TurnComplete          = false;
                    game.GameOverCheckRequired = true;

                    // Update the game model for all players...
                    SendGameToAll(game);
                }

                List <ClientModel> disconnectList = new List <ClientModel>();
                foreach (KeyValuePair <int, ClientModel> item in game.CurrentPlayersList)
                {
                    ClientModel client = item.Value;
                    Socket      s      = client.ConnectionSocket.Client;

                    // Check for disconnected sockets
                    if (!SocketConnected(s))
                    {
                        Console.WriteLine("GameServer: (GameID #" + game.GameId + ")");

                        disconnectList.Add(client);
                    }
                }

                // Remove any disconnected players from the game...
                foreach (ClientModel disconnectClient in disconnectList)
                {
                    ClientDisconnectedEventArgs args = new ClientDisconnectedEventArgs
                    {
                        client           = disconnectClient,
                        TimeOfDisconnect = DateTime.Now
                    };
                    game.GameIsPaused = true;
                    OnClientDisconnected(args);

                    game.RemovePlayerFromGame(((ClientModel)disconnectClient));
                    try
                    {
                        disconnectClient.ConnectionSocket.Close();
                    }
                    catch
                    {
                        // Do nothing
                    }
                }

                // Now proceed through the current player list, looking for moves sent by the clients
                foreach (KeyValuePair <int, ClientModel> item in game.CurrentPlayersList)
                {
                    NetworkStream stream;
                    try
                    {
                        stream = item.Value.ConnectionSocket.GetStream();
                    }
                    catch (ObjectDisposedException e)
                    {
                        // Catches a disposed socket possibility here in case it hasn't been fully disposed yet.
                        continue;
                    }

                    if (stream.DataAvailable)
                    {
                        GameMoveModel move = DataTransmission.DeserializeData <GameMoveModel>(item.Value.ConnectionSocket);
                        Console.WriteLine("GameServer: (GameID #" + game.GameId + ")" + move.ByPlayer + " move request received");

                        if (move.ByPlayer == game.CurrentPlayer)
                        {
                            game.CurrentMoveIndex = move.MoveIndex;

                            // Check that the move was valid.
                            if (game.PlayTurn())
                            {
                                Console.WriteLine("GameServer: (GameID #" + game.GameId + ")" + move.ByPlayer + " submitted a valid move");
                                game.TurnComplete     = true;
                                game.CurrentMoveIndex = move.MoveIndex;
                            }
                        }
                        else
                        {
                            Console.WriteLine("GameServer: (GameID #" + game.GameId + ") Move received by opponent.  Ignoring...");
                        }
                    }
                }
            }

            // At this point the game is over.
            Console.WriteLine("The game is over...");
        }