private void OpenPlayerView(PlayerOption option)
		{
			statusLabel.Text = "Starting HTTP request";
			var playerViewController = new PlayerViewController (option, LetsStopTheWarUrl);
			playerViewController.ErrorOccurred += HandleError;
			NavigationController.PushViewController (playerViewController, true);
		}
        public void CheckPlayerSelection()
        {
            // R - Rock, P - Paper, S - Scissors, Q - Quit
            PlayerOption playerChoice = PlayerOption.Invalid;

            //declare string choice to check the player selection
            //compare the string choice base to PlayerOption enum model
            //using switch case
            string choice = "r";

            //use while loop
            //if the playerChoice will be equals to invalid continue loop
            //check the value of choice string by switch case and compare base on the case
            while (playerChoice == PlayerOption.Invalid)
            {
                switch (choice.ToLowerInvariant().Trim())
                {
                case "rock":
                case "r":
                    playerChoice = PlayerOption.Rock;
                    break;

                case "paper":
                case "p":
                    playerChoice = PlayerOption.Paper;
                    break;

                case "scissors":
                case "s":
                    playerChoice = PlayerOption.Scissors;
                    break;

                default:
                    //if the player choose selection it will loop unitl the player select the valid selection.
                    Console.WriteLine($"{choice} is not a valid. Please try again.\r\n");
                    break;
                }

                //call the CalculateWinner function
            }

            //Nested if for assert results
            if (playerChoice != PlayerOption.Invalid)
            {
                if (choice.Equals("r") || choice.Equals("rock"))
                {
                    Assert.AreEqual(playerChoice, PlayerOption.Rock);
                }

                if (choice.Equals("p") || choice.Equals("paper"))
                {
                    Assert.AreEqual(playerChoice, PlayerOption.Paper);
                }

                if (choice.Equals("s") || choice.Equals("scissors"))
                {
                    Assert.AreEqual(playerChoice, PlayerOption.Scissors);
                }
            }
        }
Example #3
0
        /// <summary>
        /// Gets the player selection
        /// </summary>
        /// <returns></returns>
        public PlayerOption GetPlayerSelection()
        {
            PlayerOption playerOption = PlayerOption.Invalid;

            while (playerOption == PlayerOption.Invalid)
            {
                Console.Write("Please choose. R/r - Rock, P/p - Paper, S/s - Scissors ");
                string choice = Console.ReadLine();
                switch (choice.ToLowerInvariant().Trim())
                {
                case "rock":
                case "r":
                    playerOption = PlayerOption.Rock;
                    break;

                case "paper":
                case "p":
                    playerOption = PlayerOption.Paper;
                    break;

                case "scissors":
                case "s":
                    playerOption = PlayerOption.Scissors;
                    break;

                default:
                    //if the player choose selection it will loop unitl the player select the valid selection.
                    Console.WriteLine($"{choice} is not a valid. Please try again.\r\n");
                    break;
                }
            }

            return(playerOption);
        }
Example #4
0
    /// <summary>
    /// Changes a keybind if the button being assigned isnt already assigned
    /// </summary>
    /// <param name="bind">The InputOption to bind</param>
    /// <param name="key">The key we want to assign to the InputOption</param>
    /// <returns></returns>
    public bool ChangeKeybind(PlayerOption pl, InputOption bind, KeyCode key)
    {
        List <KeyCode> allValues = new List <KeyCode>();

        allValues.AddRange(keybinds.player1.Keys);
        allValues.AddRange(keybinds.player2.Keys);

        foreach (KeyCode kc in allValues)
        {
            if (kc == key)
            {
                throw new ArgumentException("That key is already bound!");
            }
        }
        allValues = null;

        if (pl == PlayerOption.Player_1)
        {
            keybinds.player1[key] = bind;
        }
        else
        {
            keybinds.player2[key] = bind;
        }

        SaveKeybindsToFile();
        return(true);
    }
Example #5
0
        protected void UpdatePref(string key)
        {
            PlayerOption po = L.b.playerOptions[key];

            //remove old?
            string val = string.IsNullOrEmpty(po.Value())?"":po.Value().Replace(build.id + ";", "");

            val = build.id + ";" + val;

            //trim?
            int count = 0;

            foreach (char c in val)
            {
                if (c == ';')
                {
                    count++;
                }
            }

            if (count > 10)
            {
                val = val.Substring(0, val.LastIndexOf(';'));
            }

            po.SetValue(val);
        }
		void OpenPlayerView (PlayerOption option)
		{
			statusLabel.Text = "Starting HTTP request";
			var url = string.IsNullOrEmpty (urlTextbox.Text) ? LetsStopTheWarUrl : urlTextbox.Text;
			var playerViewController = new PlayerViewController (option, url);
			playerViewController.ErrorOccurred += HandleError;
			NavigationController.PushViewController (playerViewController, true);
		}
        private void OpenPlayerView(PlayerOption option)
        {
            statusLabel.Text = "Starting HTTP request";
            var playerViewController = new PlayerViewController(option, LetsStopTheWarUrl);

            playerViewController.ErrorOccurred += HandleError;
            NavigationController.PushViewController(playerViewController, true);
        }
Example #8
0
        void OpenPlayerView(PlayerOption option)
        {
            statusLabel.Text = "Starting HTTP request";
            var url = string.IsNullOrEmpty(urlTextbox.Text) ? LetsStopTheWarUrl : urlTextbox.Text;
            var playerViewController = new PlayerViewController(option, url);

            playerViewController.ErrorOccurred += HandleError;
            NavigationController.PushViewController(playerViewController, true);
        }
Example #9
0
    public Dictionary <KeyCode, InputOption> GetPlayerKeybinds(PlayerOption player)
    {
        if (player == PlayerOption.Player_1)
        {
            return(keybinds.player1);
        }
        else
        {
            return(keybinds.player2);
        }

        throw new ApplicationException("Unable to retrieve Keybinds");
    }
        public void PlayGame()
        {
            GameOptions gameOptions = new GameOptions();
            GameService gameService = new GameService();

            if (gameOptions.computerOnly)
            {
                //Calculate who will be the winner computer vs computer
                PlayerOption firstComputerChoice = GetComputerSelection();
                Console.WriteLine($"The Computer1 choosed: {firstComputerChoice}");

                PlayerOption secondComputerChoice = GetComputerSelection();
                Console.WriteLine($"The Computer2 choosed: {secondComputerChoice}");

                gameOptions = gameService.CalculateWinner(firstComputerChoice, secondComputerChoice, gameOptions);
                gameOptions.computerOnly = true;

                if (gameOptions.FirstComputerWins != 0)
                {
                    Assert.AreEqual(gameOptions.FirstComputerWins, 1);
                }
                if (gameOptions.SecondComputerWins != 0)
                {
                    Assert.AreEqual(gameOptions.SecondComputerWins, 1);
                }
            }
            else
            {
                //Calaculate who will be the winner player vs computer
                PlayerOption computerChoice = GetComputerSelection();
                PlayerOption playerChoice   = GetComputerSelection();

                //show the computer selected
                Console.WriteLine($"The computer choosed: {computerChoice}");
                //show the player selected
                Console.WriteLine($"You choosed: {playerChoice}");

                gameOptions = gameService.CalculateWinner(playerChoice, computerChoice, gameOptions);
                gameOptions.computerOnly = false;

                if (gameOptions.PlayerWins != 0)
                {
                    Assert.AreEqual(gameOptions.PlayerWins, 1);
                }
                if (gameOptions.ComputerWins != 0)
                {
                    Assert.AreEqual(gameOptions.ComputerWins, 1);
                }
            }
        }
        public PlayerViewController(PlayerOption playerOption, string sourceUrl) : base("PlayerViewController", null)
        {
            PlayerOption = playerOption;
            SourceUrl    = sourceUrl;
            AVAudioSession avSession = AVAudioSession.SharedInstance();

            avSession.SetCategory(AVAudioSessionCategory.Playback);

            NSError activationError = null;

            avSession.SetActive(true, out activationError);
            if (activationError != null)
            {
                Console.WriteLine("Could not activate audio session {0}", activationError.LocalizedDescription);
            }
        }
Example #12
0
        /// <summary>
        /// Gets the computer selection
        /// </summary>
        /// <returns></returns>
        public PlayerOption GetComputerSelection()
        {
            PlayerOption computerSelection = EnumHelper.Of <PlayerOption>();

            while (computerSelection == PlayerOption.Invalid)
            {
                if (computerSelection != PlayerOption.Invalid)
                {
                    break;
                }
                else
                {
                    computerSelection = EnumHelper.Of <PlayerOption>();
                }
            }

            return(computerSelection);
        }
        public PlayerOption GetComputerSelection()
        {
            PlayerOption computerSelection = EnumHelper.Of <PlayerOption>();

            while (computerSelection == PlayerOption.Invalid)
            {
                if (computerSelection != PlayerOption.Invalid)
                {
                    break;
                }
                else
                {
                    computerSelection = EnumHelper.Of <PlayerOption>();
                }
            }
            Console.WriteLine(computerSelection);
            Assert.AreNotEqual(computerSelection, PlayerOption.Invalid);

            return(computerSelection);
        }
Example #14
0
        CreateOptionsMonitor(ulong messageId, List <PlayerOption> options, MonitorType monitorType, int voteCount = 1)
        {
            return(async(Cacheable <IUserMessage, ulong> userMessageProvider, ISocketMessageChannel channel, SocketReaction reaction) =>
            {
                if (reaction.MessageId == messageId)
                {
                    IUserMessage message = await userMessageProvider.GetOrDownloadAsync();

                    int playerCount = voteCount + 1;
                    ReactionSummary reactionSummary = message.Reactions
                                                      .Select(r => new ReactionSummary(r.Key.Name, r.Value.ReactionCount))
                                                      .FirstOrDefault(r => r.Count == playerCount);

                    if (reactionSummary != null)
                    {
                        PlayerOption pickedOption = options.FirstOrDefault(o => o.Emote == reactionSummary.Name);
                        await CommandChannel.SendMessageAsync(CommandByMonitorType(pickedOption.Player.User, monitorType));
                    }
                }
            });
        }
Example #15
0
        /// <summary>
        /// Runs a player round
        /// </summary>
        /// <param name="roundNumber"></param>
        /// <returns></returns>
        public GameOptions PlayGame(GameOptions gameOptions)
        {
            DrawGameBoard(gameOptions);

            if (gameOptions.computerOnly)
            {
                //Calculate who will be the winner computer vs computer
                PlayerOption firstComputerChoice = GetComputerSelection();
                Console.WriteLine($"The Computer1 choosed: {firstComputerChoice}");

                PlayerOption secondComputerChoice = GetComputerSelection();
                Console.WriteLine($"The Computer2 choosed: {secondComputerChoice}");

                gameOptions = CalculateWinner(firstComputerChoice, secondComputerChoice, gameOptions);
                gameOptions.computerOnly = true;
            }
            else
            {
                //Calaculate who will be the winner player vs computer
                PlayerOption computerChoice = GetComputerSelection();
                PlayerOption playerChoice   = GetPlayerSelection();

                //show the computer selected
                Console.WriteLine($"The computer choosed: {computerChoice}");
                //show the player selected
                Console.WriteLine($"You choosed: {playerChoice}");

                gameOptions = CalculateWinner(playerChoice, computerChoice, gameOptions);
                gameOptions.computerOnly = false;
            }

            Console.Write("Press [Enter] to exit the game.");
            Console.ReadLine();

            return(gameOptions);
        }
Example #16
0
    public static void Launch_Movie(int select_item, int GetID, GUIAnimation m_SearchAnimation, PlayerOption playeroption)
    //-------------------------------------------------------------------------------------------
    // Play Movie
    //-------------------------------------------------------------------------------------------
    {
      LogMyFilms.Debug("Launch_Movie() select_item = '" + select_item + "' - GetID = '" + GetID + "' - m_SearchAnimation = '" + m_SearchAnimation + "', playeroption = '" + Enum.GetName(typeof(PlayerOption), playeroption) + "'");
      //enableNativeAutoplay(); // in case, other plugin disabled it - removed, as we now do start external player ourselves ...

      #region Version Select Dialog
      string filestorage = MyFilms.r[select_item][MyFilms.conf.StrStorage].ToString();
      if (Helper.FieldIsSet(MyFilms.conf.StrStorage))
      {
        Regex filmver = new Regex(@"\[\[([^\#]*)##([^\]]*)\]\]");
        MatchCollection filmverMatches = filmver.Matches(filestorage);
        if (filmverMatches.Count > 0)
        {
          GUIDialogMenu versionmenu =
            (GUIDialogMenu)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_MENU);
          versionmenu.Reset();
          versionmenu.SetHeading("Select Version");
          List<string> filestr = new List<string>();
          for (int i = 0; i < filmverMatches.Count; i++)
          {
            versionmenu.Add(filmverMatches[i].Groups[2].Value);
            filestr.Add(filmverMatches[i].Groups[1].Value);
          }
          versionmenu.DoModal(GetID);
          if (versionmenu.SelectedLabel == -1) return;
          filestorage = filestr[versionmenu.SelectedLabel];
        }
      }

      #endregion

      #region handle WOL
      // Guzzi: Added WOL to start remote host before playing the files
      // Wake up the TV server, if required
      // HandleWakeUpNas();
      // LogMyFilms.Info("Launched HandleWakeUpNas() to start movie'" + MyFilms.r[select_item][MyFilms.conf.StrSTitle.ToString()] + "'");

      if (MyFilms.conf.StrCheckWOLenable)
      {
        WakeOnLanManager wakeOnLanManager = new WakeOnLanManager();
        int wTimeout = MyFilms.conf.StrWOLtimeout;
        bool isActive;
        string UNCpath = filestorage;
        string NasServerName;
        string NasMACAddress;

        if (UNCpath.StartsWith("\\\\")) UNCpath = (UNCpath.Substring(2, UNCpath.Substring(2).IndexOf("\\") + 0)).ToLower();
        if ((UNCpath.Equals(MyFilms.conf.StrNasName1, StringComparison.InvariantCultureIgnoreCase)) ||
            (UNCpath.Equals(MyFilms.conf.StrNasName2, StringComparison.InvariantCultureIgnoreCase)) ||
            (UNCpath.Equals(MyFilms.conf.StrNasName3, StringComparison.InvariantCultureIgnoreCase)))
        {
          isActive = WakeOnLanManager.Ping(UNCpath, wTimeout);

          if (!isActive) // Only if NAS server is not yet already rzunning !
          {
            if (MyFilms.conf.StrCheckWOLuserdialog)
            {
              if (!(GUIUtils.ShowYesNoDialog(GUILocalizeStrings.Get(107986), "Film    : '" + MyFilms.r[select_item][MyFilms.conf.StrSTitle.ToString()] + "'" + "\n" + "Server  : '" + UNCpath + "'" + "\n" + "Status  : '" + GUILocalizeStrings.Get(10798742)))) // srv name + " - (offline) - start ?"
                return;
            }

            // Search the NAS where movie is located:
            if ((UNCpath.Equals(MyFilms.conf.StrNasName1, StringComparison.InvariantCultureIgnoreCase)) &&
                (MyFilms.conf.StrNasMAC1.Length > 1))
            {
              NasServerName = MyFilms.conf.StrNasName1;
              NasMACAddress = MyFilms.conf.StrNasMAC1;
            }
            else if ((UNCpath.Equals(MyFilms.conf.StrNasName2, StringComparison.InvariantCultureIgnoreCase)) &&
                     (MyFilms.conf.StrNasMAC2.Length > 1))
            {
              NasServerName = MyFilms.conf.StrNasName2;
              NasMACAddress = MyFilms.conf.StrNasMAC2;
            }
            else if ((UNCpath.Equals(MyFilms.conf.StrNasName3, StringComparison.InvariantCultureIgnoreCase)) &&
                     (MyFilms.conf.StrNasMAC3.Length > 1))
            {
              NasServerName = MyFilms.conf.StrNasName3;
              NasMACAddress = MyFilms.conf.StrNasMAC3;
            }
            else
            {
              NasServerName = String.Empty;
              NasMACAddress = String.Empty;
            }

            // Start NAS Server

            bool SuccessFulStart = wakeOnLanManager.WakeupSystem(wakeOnLanManager.GetHwAddrBytes(NasMACAddress), NasServerName, wTimeout);

            if (MyFilms.conf.StrCheckWOLuserdialog)
            {
              if (SuccessFulStart)
                GUIUtils.ShowNotifyDialog("'" + NasServerName + "' " + GUILocalizeStrings.Get(10798743)); //successfully started 
              else
                GUIUtils.ShowOKDialog("'" + NasServerName + "' " + GUILocalizeStrings.Get(10798744)); // could not be started 
            }
          }
        }
        else
        {
          GUIUtils.ShowOKDialog("", ("Server '" + UNCpath + "' " + GUILocalizeStrings.Get(10798746)), GUILocalizeStrings.Get(10798747), ""); // Automatic NAS start not possible ... 
          return;
        }
      }

      #endregion

      SetProcessAnimationStatus(true, m_SearchAnimation);
      #region Run externaly Program before Playing if defined in setup
      if (Helper.FieldIsSet(MyFilms.conf.CmdPar))
        RunProgram(MyFilms.conf.CmdExe, MyFilms.r[MyFilms.conf.StrIndex][MyFilms.conf.CmdPar].ToString());
      #endregion

      if (g_Player.Playing) g_Player.Stop();

      // search all files
      var newItems = new ArrayList();
      bool noResumeMovie = true;
      int movieIndex = 0;

      SearchAllFiles(MyFilms.r[select_item], false, ref noResumeMovie, ref newItems, ref movieIndex, false, filestorage);
      
      //  ToDo: add code to call population of trailers array and insert num of configured trailers into playlist
      // newItems.Insert(0, <trailers>);
      
      if (newItems.Count > 20) // Maximum 20 entries (limitation for MP dialogFileStacking)
      {
        GUIUtils.ShowOKDialog(MyFilms.r[select_item][MyFilms.conf.StrSTitle].ToString(), "maximum 20 entries for the playlist", "", "");
        LogMyFilms.Info("Too many entries found for movie '" + MyFilms.r[select_item][MyFilms.conf.StrSTitle] + "', number of entries found = " + newItems.Count);
        return;
      }
      SetProcessAnimationStatus(false, m_SearchAnimation);

      #region optional part selection dialog
      if (newItems.Count > 1)
      {
        if (noResumeMovie)
        {
          var dlg = (GUIDialogFileStacking)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_FILESTACKING);
          if (null != dlg)
          {
            dlg.SetNumberOfFiles(newItems.Count);
            dlg.DoModal(GUIWindowManager.ActiveWindow);
            int selectedFileIndex = dlg.SelectedFile;
            if (selectedFileIndex < 1) return;
            movieIndex = selectedFileIndex++;
          }
        }
      }
      #endregion

      if (newItems.Count > 0)
      {
        // Check, if the content returned is a BR playlist to supress internal player and dialogs
        bool isBRcontent = false;
        string mediapath = filestorage;
        if (newItems[0].ToString().ToLower().EndsWith("bdmv")) isBRcontent = true;
        bool isMpVideo = Utils.IsVideo(newItems[0].ToString());
        LogMyFilms.Info("Launch_Movie() - starting playback: isBRcontent = '" + isBRcontent + "', isMpVideo = '" + isMpVideo + "', #items = '" + newItems.Count + "', first item = '" + newItems[0] + "'), filestorage = '" + filestorage + "'");

        switch (playeroption)
        {
          case PlayerOption.External:
            try
            {
              LogMyFilms.Info("Launch_Movie() - start external player - path = '" + MyFilms.conf.ExternalPlayerPath + "', argument (filestorage) = '" + filestorage + "'");
              LaunchExternalPlayer(filestorage);
            } catch (Exception ex) { LogMyFilms.Info("Launch_Movie() - calling external player ended with exception: " + ex); }
            break;
          case PlayerOption.BluRayPlayerLauncher:
            LogMyFilms.Info("Launch_Movie() - activate blurayplayer plugin");
            GUIWindowManager.ActivateWindow((int)MyFilms.ExternalPluginWindows.BluRayPlayerLauncher);
            break;
          case PlayerOption.Internal:
            bool externalplayerextensiondetected = MyFilms.conf.ExternalPlayerExtensions.Split(new Char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Any(s => filestorage.ToLower().Contains(s.ToLower()));
            if (externalplayerextensiondetected && MyFilms.conf.ExternalPlayerPath.Length > 0) // check, if this is configured to use external player via extensions in setup
            {
              #region external player playback (myfilms)
              LogMyFilms.Info("Launch_Movie() - extension for external player detected! - start external player - path = '" + MyFilms.conf.ExternalPlayerPath + "', argument (filestorage) = '" + filestorage + "'");
              try
              {
                LaunchExternalPlayer(filestorage);
              } catch (Exception ex) { LogMyFilms.Info("Launch_Movie() - calling external player ended with exception: " + ex); }
              #endregion
            }
            else if (isMpVideo || (isBRcontent && Helper.IsBdHandlerAvailableAndEnabled)) // use internal playback, if suppoerted or BD handler is installed
            {
              #region internal playback
              LogMyFilms.Info("Launch_Movie() - start internal playback");
              playlistPlayer.Reset();
              playlistPlayer.CurrentPlaylistType = PlayListType.PLAYLIST_VIDEO_TEMP;
              PlayList playlist = playlistPlayer.GetPlaylist(PlayListType.PLAYLIST_VIDEO_TEMP);
              playlist.Clear();

              foreach (object t in newItems)
              {
                var movieFileName = (string)t;
                // ToDo: Check, if that is necessary - from MP1.3.x to get e.g. Mediainfo registered AddFileToDatabase(movieFileName);
                var newitem = new PlayListItem();
                newitem.FileName = movieFileName;
                newitem.Type = PlayListItem.PlayListItemType.Video;
                playlist.Add(newitem);
              }
              // ask for start movie Index

              MyFilms.conf.MyFilmsPlaybackActive = true; // Set Playbackhandler to active
              PlayMovieFromPlayList(noResumeMovie, movieIndex - 1); // play movie...
              #endregion
            }
            else if (isBRcontent && Helper.IsBluRayPlayerLauncherAvailableAndEnabled) // use BRplayerLauncher fir BR content, if installed
            {
              #region  BluRayPlayerLauncher playback
              LogMyFilms.Info("Launch_Movie() - activate blurayplayer plugin");
              GUIWindowManager.ActivateWindow((int)MyFilms.ExternalPluginWindows.BluRayPlayerLauncher);
              #endregion
            }
            else // playback not successful - notify user!
            {
              #region no playback option successful - notify user
              LogMyFilms.Info("Launch_Movie() - Internal Playback not successful - playback not started!");
              GUIUtils.ShowOKDialog("No playback possible, please check your setup. \nInstall BR Player Launcher, BDhandler or external player for unsupported media.");
              #endregion
            }
            break;
        }
      }
      else
      {
        //if (first)
        //// ask for mounting file first time
        //{
        var dlgYesNo = (GUIDialogYesNo)GUIWindowManager.GetWindow((int)GUIWindow.Window.WINDOW_DIALOG_YES_NO);
        dlgYesNo.SetHeading(GUILocalizeStrings.Get(107986)); //my films
        dlgYesNo.SetLine(1, GUILocalizeStrings.Get(219)); //no disc
        if (Helper.FieldIsSet(MyFilms.conf.StrIdentItem))
          if (MyFilms.conf.StrIdentLabel.Length > 0)
            dlgYesNo.SetLine(2, MyFilms.conf.StrIdentLabel + " = " + MyFilms.r[select_item][MyFilms.conf.StrIdentItem]); //Label Identification for Media
          else
            dlgYesNo.SetLine(2, "'" + MyFilms.conf.StrIdentItem + "' = " + MyFilms.r[select_item][MyFilms.conf.StrIdentItem]); //ANT Item Identification for Media
        else
          dlgYesNo.SetLine(2, "' disc n° = " + MyFilms.r[select_item]["Number"]); //ANT Number for Identification Media 
        dlgYesNo.DoModal(GetID);
        if (dlgYesNo.IsConfirmed) 
          Launch_Movie(select_item, GetID, m_SearchAnimation, playeroption);
        //}
        else
        {
          GUIUtils.ShowOKDialog("", GUILocalizeStrings.Get(1036), MyFilms.r[select_item][MyFilms.conf.StrSTitle].ToString(), ""); //no video found
          LogMyFilms.Info("File not found for movie '" + MyFilms.r[select_item][MyFilms.conf.StrSTitle] + "'");
        }
      }
    }
Example #17
0
        /// <summary>
        /// The player should now have the option of hitting, staying, splitting or doubling down.
        /// This function should run through the motions of the actual game of blackjack
        /// </summary>
        /// <param name="player"></param>
        private void PlayerPlay(Player player, Hand thisHand)
        {
            int total = thisHand.Total;

            thisHand.Status = HandStatus.InPlay;
            string option             = PlayerOption.begin.ToString();
            string probabilityOptions = "";
            string probOption         = "";

            while (total < 21 && (option.ToLower() == PlayerOption.hit.ToString() || option.ToLower() == PlayerOption.begin.ToString() || option.ToLower() == PlayerOption.prob.ToString()) && thisHand.Status != HandStatus.Bust)
            {
                if (probabilityOptions != "")
                {
                    show.ProbabilityOfCards(Deck.ProbabilityOfCard(probabilityOptions)); probabilityOptions = "";
                }
                UpdateTable(true, true);
                show.PlayerOptions(player.Name);
                option = player.GetPlayInput(thisHand, Dealer.Hands[0].Cards.First());
                if (option.IndexOf(' ') != -1)
                {
                    probOption = option; option = option.Substring(0, option.IndexOf(' '));
                }
                show.Clear();

                string lowerOption = option.ToLower();

                PlayerOption playerOption = GetIntOption(lowerOption);

                switch (playerOption)
                {
                case PlayerOption.hit:
                    Hit(thisHand);
                    break;

                case PlayerOption.dbl:
                    if (!Double(player, thisHand))
                    {
                        var message = "You do not have enough money to double";
                        show.AddToMessage(message);
                        option = PlayerOption.begin.ToString();
                    }
                    else if (thisHand.Status != HandStatus.Bust)
                    {
                        thisHand.Status = HandStatus.Played;
                    }
                    break;

                case PlayerOption.split:
                    if (thisHand.Cards[0].Name == thisHand.Cards[1].Name)
                    {
                        // We also need to verify that the player has enough money to split.
                        Split(ref player);
                        option          = PlayerOption.stand.ToString();
                        thisHand.Status = HandStatus.Played;
                    }
                    else
                    {
                        var message = "Split is not valid in this situation.";
                        show.AddToMessage(message);
                        option = PlayerOption.begin.ToString();
                    }
                    break;

                case PlayerOption.prob:
                    probabilityOptions = CheckProbability(probOption);
                    break;

                case PlayerOption.stand:
                default:
                    thisHand.Status = HandStatus.Played;
                    break;
                }
            }
        }
Example #18
0
        // ReSharper restore FunctionNeverReturns

        private static void PlayerThread(NetworkPlayer player)
        {
            NetworkStream clientStream;

            //make all the introductions. we do this before sending the world so the client doesn't see them as new connections
            foreach (var otherPlayer in Players.Values)
            {
                try
                {
                    new Connect(otherPlayer.Id, otherPlayer.UserName, otherPlayer.Coords)
                    {
                        ConnectedPlayer = player, Immediate = true
                    }.Send();
                }
                catch (Exception ex)
                {
                    WriteToServerConsoleLog(string.Format("{0} {1} caused an exception and was removed: {2}", player.UserName, player.IpAddress, ex.Message));
#if DEBUG
                    WriteToServerConsoleLog(ex.StackTrace);
#endif
                }

                new Connect(player.Id, player.UserName, player.Coords)
                {
                    ConnectedPlayer = otherPlayer
                }.Send();
            }

            try
            {
                Players.TryAdd(player.Id, player);                 //note: it is not possible for the add to fail on ConcurrentDictionary, see: http://www.albahari.com/threading/part5.aspx#_Concurrent_Collections
                UpdateServerConsolePlayerList();

                var getWorld = new GetWorld {
                    ConnectedPlayer = player
                };
                getWorld.Send();
                WriteToServerConsoleLog(String.Format("World send complete to {0} ({1} compressed, {2} uncompressed)", player.IpAddress, getWorld.DataLength, getWorld.UncompressedLength));

                //create a thread to handle communication with connected client
                player.TcpClient.NoDelay = true;
                clientStream             = player.TcpClient.GetStream();
            }
            catch (Exception ex)
            {
                HandleNetworkError(player, ex);
                return;
            }

            var actionTypebytes = new byte[sizeof(ushort)];
            try
            {
                if (!string.IsNullOrWhiteSpace(Config.MOTD))
                {
                    new ServerMsg(Config.MOTD, player).Send();
                }

                while (true)
                {
                    Thread.Sleep(10);                     //bm: polling is expensive. don't remove this or the server will pin your machine when only a couple users are online
                    GameAction gameAction;
                    while (player.SendQueue.Count > 0 && player.SendQueue.TryDequeue(out gameAction))
                    {
                        gameAction.Immediate = true;
                        gameAction.Send();
                    }

                    if (!clientStream.DataAvailable)
                    {
                        continue;
                    }
                    var bytesRead = 0;
                    while (bytesRead < actionTypebytes.Length)
                    {
                        bytesRead += clientStream.Read(actionTypebytes, bytesRead, actionTypebytes.Length - bytesRead);
                    }
                    var actionType = (ActionType)BitConverter.ToUInt16(actionTypebytes, 0);
                    switch (actionType)
                    {
                    case ActionType.AddBlock:
                        gameAction = new AddBlock();
                        break;

                    case ActionType.AddBlockItem:
                        gameAction = new AddBlockItem();
                        break;

                    case ActionType.AddBlockMulti:
                        gameAction = new AddBlockMulti();
                        break;

                    case ActionType.AddCuboid:
                        gameAction = new AddCuboid();
                        break;

                    case ActionType.AddProjectile:
                        gameAction = new AddProjectile();
                        break;

                    case ActionType.AddStaticItem:
                        gameAction = new AddStaticItem();
                        break;

                    case ActionType.AddStructure:
                        gameAction = new AddStructure();
                        break;

                    case ActionType.ChatMsg:
                        gameAction = new ChatMsg();
                        break;

                    case ActionType.Disconnect:
                        gameAction = new Disconnect();
                        break;

                    case ActionType.PickupBlockItem:
                        gameAction = new PickupBlockItem();
                        break;

                    case ActionType.PlayerInfo:
                        gameAction = new PlayerInfo();
                        break;

                    case ActionType.PlayerMove:
                        gameAction = new PlayerMove();
                        break;

                    case ActionType.PlayerOption:
                        gameAction = new PlayerOption();
                        break;

                    case ActionType.RemoveBlock:
                        gameAction = new RemoveBlock();
                        break;

                    case ActionType.RemoveBlockItem:
                        gameAction = new RemoveBlockItem();
                        break;

                    case ActionType.RemoveBlockMulti:
                        gameAction = new RemoveBlockMulti();
                        break;

                    case ActionType.ServerCommand:
                        gameAction = new ServerCommand();
                        break;

                    case ActionType.Connect:
                    case ActionType.ServerMsg:
                    case ActionType.ServerSync:
                    case ActionType.GetWorld:
                        throw new Exception(string.Format("Server should not receive action type: {0}", actionType));

                    case ActionType.Error:
                        var bytes = 0;
                        while (clientStream.ReadByte() != -1)
                        {
                            bytes++;
                        }
                        throw new Exception("GameAction 'Error' received. " + bytes + " byte(s) remained in the stream.");

                    default:
                        throw new Exception(string.Format("Unknown action type: {0}", actionType));
                    }
                    gameAction.ConnectedPlayer = player;
                    gameAction.Receive();
                    if (HasServerConsole && CaptureIncoming)                     //only stream messages if there is a console window and it has requested to display them
                    {
                        _serverConsole.UpdateStreamLogInvokable(gameAction, player, false);
                    }
                    if (actionType == ActionType.Disconnect)
                    {
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                HandleNetworkError(player, ex);
            }
        }
 public PlayerViewController(PlayerOption playerOption, string sourceUrl) : base("PlayerViewController", null)
 {
     PlayerOption = playerOption;
     SourceUrl    = sourceUrl;
 }
		public PlayerViewController (PlayerOption playerOption, string sourceUrl) : base ("PlayerViewController", null)
		{
			PlayerOption = playerOption;
			SourceUrl = sourceUrl;
		}
Example #21
0
        /// <summary>
        /// Calculates the winner
        /// </summary>
        /// <param name="playerOption"></param>
        /// <param name="computerOption"></param>
        /// <param name="gameOptions"></param>
        /// <returns></returns>
        public GameOptions CalculateWinner(PlayerOption playerOption, PlayerOption computerOption, GameOptions gameOptions)
        {
            /// <summary>
            /// Declare Dictionary for comparing of selection
            /// rock beats scissors
            /// scissors beats paper
            /// paper beats rock
            /// </summary>
            Dictionary <PlayerOption, PlayerOption> winners = new Dictionary <PlayerOption, PlayerOption>
            {
                { PlayerOption.Rock, PlayerOption.Scissors },
                { PlayerOption.Scissors, PlayerOption.Paper },
                { PlayerOption.Paper, PlayerOption.Rock }
            };

            //if true the game will play computer vs computer
            //if false the game will play player vs computer
            if (gameOptions.computerOnly)
            {
                //tie game
                if (playerOption == computerOption)
                {
                    Console.WriteLine($"The game is a tie.");
                    gameOptions.FirstComputerWins++;
                    gameOptions.SecondComputerWins++;
                }
                else
                {
                    //if the result equals the computers roll then the player wins
                    //otherwise the computer wins.
                    var result = winners[playerOption];
                    if (result == computerOption)
                    {
                        Console.WriteLine($"Computer1 wins {playerOption} beats {computerOption}.");
                        gameOptions.FirstComputerWins++;
                    }
                    else
                    {
                        Console.WriteLine($"Computer2 wins {computerOption} beats {playerOption}.");
                        gameOptions.SecondComputerWins++;
                    }
                }
            }
            else
            {
                //tie game
                if (playerOption == computerOption)
                {
                    Console.WriteLine($"The game is a tie.");
                    gameOptions.PlayerWins++;
                    gameOptions.ComputerWins++;
                }
                else
                {
                    //if the result equals the computers roll then the player wins
                    //otherwise the computer wins.
                    var result = winners[playerOption];
                    if (result == computerOption)
                    {
                        Console.WriteLine($"Congratulations you won. {playerOption} beats {computerOption}.");
                        gameOptions.PlayerWins++;
                    }
                    else
                    {
                        Console.WriteLine($"Computer Wins. {computerOption} beats {playerOption}.");
                        gameOptions.ComputerWins++;
                    }
                }
            }

            return(gameOptions);
        }
        public void CalculateWinner()
        {
            /// <summary>
            /// Declare Dictionary for comparing of selection
            /// </summary>
            Dictionary <PlayerOption, PlayerOption> winners = new Dictionary <PlayerOption, PlayerOption>
            {
                { PlayerOption.Rock, PlayerOption.Scissors },
                { PlayerOption.Scissors, PlayerOption.Paper },
                { PlayerOption.Paper, PlayerOption.Rock }
            };

            //Instantiate GameOptions
            GameOptions gameOptions = new GameOptions();

            //if true the game will play computer vs computer
            //if false the game will play player vs computer
            gameOptions.computerOnly = false;


            if (gameOptions.computerOnly)
            {
                PlayerOption firstComputerChoice = GetComputerSelection();
                Console.WriteLine($"The computer choosed: {firstComputerChoice}");

                PlayerOption secondComputerChoice = GetComputerSelection();
                Console.WriteLine($"The computer choosed: {secondComputerChoice}");


                //tie game
                if (firstComputerChoice == secondComputerChoice)
                {
                    gameOptions.FirstComputerWins++;
                    gameOptions.SecondComputerWins++;
                    Console.WriteLine($"The game is a tie.");
                    Assert.IsTrue(firstComputerChoice == secondComputerChoice);
                }
                else
                {
                    //if the result equals the computers roll then the player wins
                    //otherwise the computer wins.
                    var result = winners[firstComputerChoice];
                    if (result == secondComputerChoice)
                    {
                        gameOptions.FirstComputerWins++;
                        Console.WriteLine($"Computer1 wins {firstComputerChoice} beats {secondComputerChoice}.");
                        Assert.IsTrue(result == secondComputerChoice);
                    }
                    else
                    {
                        gameOptions.SecondComputerWins++;
                        Console.WriteLine($"Computer2 wins {secondComputerChoice} beats {firstComputerChoice}.");
                        Assert.IsTrue(result == secondComputerChoice);
                    }
                }
            }
            else
            {
                PlayerOption computerOption = EnumHelper.Of <PlayerOption>();
                PlayerOption playerOption   = EnumHelper.Of <PlayerOption>();

                //tie game
                if (playerOption == computerOption)
                {
                    gameOptions.PlayerWins++;
                    gameOptions.ComputerWins++;
                    Console.WriteLine($"The game is a tie.");
                    Assert.IsTrue(playerOption == computerOption);
                }
                else
                {
                    //if the result equals the computers roll then the player wins
                    //otherwise the computer wins.
                    var result = winners[playerOption];
                    if (result == computerOption)
                    {
                        gameOptions.PlayerWins++;
                        Console.WriteLine($"Congratulations you won. {playerOption} beats {computerOption}.");
                        Assert.IsTrue(result == computerOption);
                    }
                    else
                    {
                        gameOptions.ComputerWins++;
                        Console.WriteLine($"Computer Wins. {computerOption} beats {playerOption}.");
                        Assert.IsTrue(result != computerOption);
                    }
                }
            }
        }