Inheritance: Item
Esempio n. 1
0
 internal static Guess Create(Storage storage, Guess no, string question, Guess yes)
 {
     Guess guess = (Guess)storage.CreateClass(typeof(Guess));
     guess.Yes = yes;
     guess.Question = question;
     guess.No = no;
     return guess;
 }
Esempio n. 2
0
 public GuessForMarking(Guess guess)
 {
     this.ContributorName = guess.Contributor.UserName;
     this.Content = guess.Content;
     this.ContentType = guess.Type;
     this.GuessId = GuessId;
     this.AvailableMarks = new SelectList(new[] { 0, 1, 2, 3 });
 }
Esempio n. 3
0
File: Guess.cs Progetto: kjk/volante
 internal static Guess Create(IDatabase db, Guess no, string question, Guess yes)
 {
     Guess guess = (Guess)db.CreateClass(typeof(Guess));
     guess.Yes = yes;
     guess.Question = question;
     guess.No = no;
     return guess;
 }
Esempio n. 4
0
        public void Process(Guess guess)
        {
            _guessHistory.Add(guess);

            if (guess.Bulls == 0 && guess.Cows == 0)
            {
                AddInvalidDigits(guess.Value);
                ClearCombinationsWithInvalidNumbers();
            }
            else if ((guess.Bulls + guess.Cows == 4) && !_fourDigitsFound)
            {
                _fourDigitsFound = true;

                AddInvalidDigits(Source.Except(guess.Value));
                ClearCombinationsWithInvalidNumbers();
            }
            else
            {
                Func<IReadOnlyList<int>, bool> isMatch;
                if (guess.Cows == 0)
                {
                    var patterns = BuildPatternList(guess, guess.Bulls);

                    isMatch = code =>
                    {
                        return patterns.Any(p => p.IsMatch(code)) == false;
                    };

                    if (patterns.Any())
                        RemoveInvalidCode(isMatch);
                }
                else if (guess.Bulls == 0)
                {
                    var patterns = BuildPatternList(guess, guess.Cows);

                    isMatch = code =>
                    {
                        return patterns.Any(p => p.IsMatch(code));
                    };

                    if (patterns.Any())
                        RemoveInvalidCode(isMatch);
                }
                else
                {
                    var bullPatterns = BuildPatternList(guess, guess.Bulls);
                    var patterns = FillInPatterns(guess, bullPatterns);

                    isMatch = code =>
                    {
                        return patterns.Any(p => p.IsMatch(code)) == false;
                    };

                    if (patterns.Any())
                        RemoveInvalidCode(isMatch);
                }
            }
        }
Esempio n. 5
0
        private async void smgMain_OnGridClicked(Guess guess)
        {
            if (_currentGame == null)
                return;

            var response = await _currentGame.TakeGuess(guess);
            if (response.Status == "success")                 
                smgMain.UpdateMine(guess, response);
            else
                MessageBox.Show(response.Message);
        }
        public void Guess(Int32 value, string name)
        {
            Guess guess = new Guess(value, name);
            SendGuess(guess);

            if (player.Game.IsGuessCorrect(value))
            {
                SendGameOver();
            } else {
                SendHint(guess);
            }
        }
        /* public members */
        public static void MakeGuess(int userId, GuessModel guessModel)
        {
            ValidateUserNumber(guessModel.Number);
            var context = new BullsAndCowsEntities();
            using (context)
            {
                var user = GetUser(userId, context);
                var game = GetGame(guessModel.GameId, context);

                if (game.GameStatus != context.GameStatuses.First((st) => st.Status == GameStatusInProgress))
                {
                    throw new ServerErrorException("Game is not in progress", "INV_OP_GAME_STAT");
                }

                ValidateUserInGame(game, user);

                var guessNumber = guessModel.Number.ToString();
                string otherUserNumber = GetOtherUserNumber(game, user);

                int bullsCount, cowsCount;
                CountBullsAndCows(guessNumber, otherUserNumber, out bullsCount, out cowsCount);

                var guess = new Guess()
                {
                    Bulls = bullsCount,
                    Cows = cowsCount,
                    Game = game,
                    Number = guessModel.Number,
                    User = user
                };
                context.Guesses.Add(guess);

                var otherUser = (game.RedUser == user) ? game.BlueUser : game.RedUser;

                if (bullsCount == UserNumberLength)
                {
                    FinishGame(user, otherUser, game, context);
                }
                else
                {
                    game.UserInTurn = otherUser.Id;

                    MessageType guessMadeMessageType = context.MessageTypes.First(mt => mt.Type == MessageTypeGuessMade);
                    string messageText = string.Format(MessageTextGuessMade, user.Nickname, guessNumber, game.Title);
                    SendMessage(messageText, otherUser, game, guessMadeMessageType, context);
                }
                context.SaveChanges();
            }
        }
        public void SaveGuess(string userName, string name, bool correct)
        {
            var guess = new Guess();
            guess.Name = name;
            guess.Date = DateTime.Now;
            guess.Ip = IpAddress.Current;
            guess.Username = userName;
            guess.Correct = correct;

            if(name.StartsWith("Grímur"))
                guess.Correct = true;

            dbGuesses.Guesses.Add(guess);
            dbGuesses.SaveChanges();
        }
Esempio n. 9
0
 public void Guess(Player player, int value)
 {
     GuessTipp tipp;
     if(value < 0) throw new Exception("Die Zahl darf nicht kleiner als 0 sein!");
     if(value > 10) throw new Exception("Die Zahl darf nicht grösser als 10 sein!");
     if(value > number) tipp = GuessTipp.ToHeight;
     else if(value < number) tipp = GuessTipp.ToLow;
     else if(value == number) tipp = GuessTipp.Correct;
     else tipp = GuessTipp.Others;
     Guess g = new Guess(value, tipp, player.Name);
     guesses.Add(g);
     foreach (Player p in players)
         p.Client.PlayerGuess(g);
     if(tipp == GuessTipp.Correct)
         foreach(Player p in players)
             p.Client.GameOver(p==player, guesses);
 }
        internal Task NewGameAsync()
        {
            //this gets called later.
            var tempList = new CustomBasicList <Guess>();
            int guesses  = _global.HowManyGuess;

            guesses.Times(x =>
            {
                Guess thisGuess = new Guess();
                if (x == 1)
                {
                    thisGuess.GetNewBeads();
                }
                tempList.Add(thisGuess);
            });
            GuessList.ReplaceRange(tempList);
            return(_aggregator.ScrollToGuessAsync(GuessList.First()));
        }
Esempio n. 11
0
        ///// <summary>
        ///// 处理比分竞猜 庄家的押金投注
        ///// </summary>
        ///// <returns></returns>
        //private Response DealScoreDeclarerBet(Guess guess)
        //{
        //    Response rsp = ResultHelper.CreateResponse();

        //    if (guess.RowState == RowState.Added)//添加操作
        //    {
        //        //扣除庄家的投注
        //        rsp = SaveDeclarerBet(GuessDic.DeclarerScore, Convert.ToInt32(guess.ScoreDeclarerDeposit), guess);
        //        SystemHelper.CheckResponseIfError(rsp);
        //    }

        //    if (guess.RowState == RowState.Modified)////修改操作
        //    {
        //        var oldGuess = GuessHelper.Instance.GetGuess(guess.Id);

        //        //如果是从胜负竞猜切换到 比分竞猜,检查胜负竞猜那边有木有押金需要返回, 如果有就返还
        //        if ((oldGuess.GuessType == GuessDic.VictoryDefeat || oldGuess.GuessType == GuessDic.VictoryDefeatAndScore)
        //            && guess.GuessType == GuessDic.Score)
        //        {
        //            //返还之前的胜负投注
        //            UndoDeclarerBet(GuessDic.DeclarerVictoryDefeat, Convert.ToInt32(oldGuess.VictoryDefeatDeclarerDeposit), guess);
        //        }

        //        //先撤销之前的比分投注
        //        UndoDeclarerBet(GuessDic.DeclarerScore, Convert.ToInt32(oldGuess.ScoreDeclarerDeposit), guess);
        //        //再进行新的比分的投注
        //        SaveDeclarerBet(GuessDic.DeclarerScore, Convert.ToInt32(guess.ScoreDeclarerDeposit), guess);

        //    }


        //    return rsp;
        //}

        ///// <summary>
        ///// 处理胜负 庄家的押金投注
        ///// </summary>
        ///// <returns></returns>
        //private Response DeaVictoryDefeatDeclarerBet(Guess guess)
        //{
        //    Response rsp = ResultHelper.CreateResponse();

        //    if (guess.RowState == RowState.Added)//添加操作
        //    {
        //        //扣除庄家的投注
        //        rsp = SaveDeclarerBet(GuessDic.DeclarerVictoryDefeat, Convert.ToInt32(guess.VictoryDefeatDeclarerDeposit), guess);
        //        SystemHelper.CheckResponseIfError(rsp);
        //    }
        //    else if (guess.RowState == RowState.Modified)////修改操作
        //    {

        //        var oldGuess = GuessHelper.Instance.GetGuess(guess.Id);
        //        //如果是从比分竞猜切换到 胜负竞猜,检查比分竞猜那边有木有押金需要返回, 如果有就返还
        //        if ((oldGuess.GuessType == GuessDic.Score || oldGuess.GuessType == GuessDic.VictoryDefeatAndScore)
        //            && guess.GuessType == GuessDic.VictoryDefeat)
        //        {
        //            //返还之前的比分投注
        //            UndoDeclarerBet(GuessDic.DeclarerScore, Convert.ToInt32(oldGuess.ScoreDeclarerDeposit), guess);
        //        }


        //        //先撤销之前的胜负投注
        //        UndoDeclarerBet(GuessDic.DeclarerVictoryDefeat, Convert.ToInt32(oldGuess.VictoryDefeatDeclarerDeposit), guess);
        //        //再插入新的庄家胜负投注
        //        SaveDeclarerBet(GuessDic.DeclarerVictoryDefeat, Convert.ToInt32(guess.VictoryDefeatDeclarerDeposit), guess);

        //    }


        //    return rsp;
        //}


        public void AddDeclarerDeposit(Guess guess)
        {
            Response rsp = ResultHelper.CreateResponse();

            //比分竞猜的相关处理
            if (guess.GuessType == GuessDic.Score || guess.GuessType == GuessDic.VictoryDefeatAndScore)
            {
                //添加时扣除庄家的比分投注
                SaveDeclarerBet(GuessDic.DeclarerScore, Convert.ToInt32(guess.ScoreDeclarerDeposit), guess);
            }

            //胜负竞猜的相关处理
            if (guess.GuessType == GuessDic.VictoryDefeat || guess.GuessType == GuessDic.VictoryDefeatAndScore)
            {
                //添加时扣除庄家的胜负投注
                SaveDeclarerBet(GuessDic.DeclarerVictoryDefeat, Convert.ToInt32(guess.VictoryDefeatDeclarerDeposit), guess);
            }
        }
Esempio n. 12
0
        public void Game_Guess_ArgumentNotBetween1And6_ThrowsGameException()
        {
            // Arrange
            var gameExceptionMessage = string.Empty;

            // Act
            try
            {
                var guess = new Guess("1273", "1234");
            }
            catch (GameException exception)
            {
                gameExceptionMessage = exception.Message;
            }

            // Assert
            Assert.AreEqual("The digits must be between 1 and 6.", gameExceptionMessage);
        }
Esempio n. 13
0
            public void A_guess_piece_can_produce_Similar_and_Misplaced_feedbacks_simultaneously()
            {
                Puzzle puzzle = createPuzzle(new List <string> {
                    "One-Black",
                    "None-None" //null piece
                });
                Guess guess = createGuess(new List <string> {
                    "One-White",
                    "One-Black"
                });
                OverallFeedbackGenerator sut = new OverallFeedbackGenerator(puzzle);

                var actualFeedback = sut.Calculate(guess);

                Assert.AreEqual(0, actualFeedback.CorrectPieces);
                Assert.AreEqual(1, actualFeedback.MisplacedPieces);
                Assert.AreEqual(1, actualFeedback.SimilarPieces);
            }
Esempio n. 14
0
        public void Game_Guess_ArgumentNotDigit_ThrowsGameException()
        {
            // Arrange
            var gameExceptionMessage = string.Empty;

            // Act
            try
            {
                var guess = new Guess("a", "1234");
            }
            catch (GameException exception)
            {
                gameExceptionMessage = exception.Message;
            }

            // Assert
            Assert.AreEqual("You did not enter a number.", gameExceptionMessage);
        }
Esempio n. 15
0
        public void GuessedLetterMostRecentLetterIsAccurate()
        {
            // Arrange
            Guess        guess       = new Guess();
            WordToGuess  wordToGuess = new WordToGuess();
            const string THE_WORD    = "jellybean";

            wordToGuess.setWord(THE_WORD);
            const string GUESSED_LETTER = "a";

            guess.guessedLetter(GUESSED_LETTER, wordToGuess);

            // Act
            string actualMostRecentLetter = guess.getMostRecentGuess();

            // Assert
            Assert.AreEqual(GUESSED_LETTER, actualMostRecentLetter);
        }
Esempio n. 16
0
        public IHttpActionResult Create(int id, GuessDataModel model)
        {
            var userID = this.User.Identity.GetUserId();
            var guess = new Guess
            {
                Username = model.Username,
                GameID = id,
                Number = model.Number,
                DateMade = DateTime.Now,
                CowsCount = model.CowsCount,
                BullsCount = model.BullsCount
            };

            this.data.Guesses.Add(guess);
            this.data.SaveChanges();

            return Ok();
        }
Esempio n. 17
0
    /// <summary>
    /// Adds the (only possible) owned card to this players 'Does Have' list.
    /// </summary>
    /// <returns>The card added to 'Does Have'.</returns>
    public string AddOwnedCard(Guess G)
    {
        string HaveCard = "";

        for (int i = 0; i < 3; ++i)
        {
            if (!NotHave.Contains(G.Cards [i]))
            {
                HaveCard = G.Cards [i];
                DoesHave.Add(HaveCard);
                if (NotHave.Contains(HaveCard))
                {
                    Debug.Log("Broken: Contains a card that is in NotHave");
                }
            }
        }
        return(HaveCard);
    }
Esempio n. 18
0
        private async void smgMain_OnGridClicked(Guess guess)
        {
            if (_currentGame == null)
            {
                return;
            }

            var response = await _currentGame.TakeGuess(guess);

            if (response.Status == "success")
            {
                smgMain.UpdateMine(guess, response);
            }
            else
            {
                MessageBox.Show(response.Message);
            }
        }
Esempio n. 19
0
        public void Game_Guess_ArgumentMoreThan4Digits_ThrowsGameException()
        {
            // Arrange
            var gameExceptionMessage = string.Empty;

            // Act
            try
            {
                var guess = new Guess("12345", "1234");
            }
            catch (GameException exception)
            {
                gameExceptionMessage = exception.Message;
            }

            // Assert
            Assert.AreEqual("The number is not 4 digits.", gameExceptionMessage);
        }
Esempio n. 20
0
        public async Task <GuessResponse> TakeGuess(Guess guess)
        {
            var request = new HttpRequestMessage(HttpMethod.Post, "/action/checkboard.php")
            {
                Content = new FormUrlEncodedContent(new Dictionary <string, string>
                {
                    { "game_hash", GameResponse.GameHash },
                    { "guess", ((byte)guess).ToString(CultureInfo.InvariantCulture) },
                    { "v04", "1" }
                })
            };

            var response = await _client.SendAsync(request);

            var content = await response.Content.ReadAsStringAsync();

            return(JsonHelper.Deserialize <GuessResponse>(content));
        }
Esempio n. 21
0
        public void isWinCorrectForLoss()
        {
            // Arrange
            WordToGuess  wordToGuess = new WordToGuess();
            const string THE_WORD    = "jellybean";

            wordToGuess.setWord(THE_WORD);
            Guess  guess         = new Guess();
            string guessedLetter = "z";

            guess.guessedLetter(guessedLetter, wordToGuess);

            // Act
            bool actualIsWin = wordToGuess.isWin();

            // Assert
            Assert.IsFalse(actualIsWin);
        }
Esempio n. 22
0
 internal Guess dialog()
 {
     if (askQuestion("May be, " + question + " (y/n) ? "))
     {
         if (yes == null)
         {
             System.Console.WriteLine("It was very simple question for me...");
         }
         else
         {
             Guess clarify = yes.dialog();
             if (clarify != null)
             {
                 yes = clarify;
                 Store();
             }
         }
     }
     else
     {
         if (no == null)
         {
             if (yes == null)
             {
                 return(whoIsIt(this));
             }
             else
             {
                 no = whoIsIt(null);
                 Store();
             }
         }
         else
         {
             Guess clarify = no.dialog();
             if (clarify != null)
             {
                 no = clarify;
                 Store();
             }
         }
     }
     return(null);
 }
Esempio n. 23
0
 internal Guess dialog()
 {
     if (askQuestion("May be, " + question + " (y/n) ? "))
     {
         if (yes == null)
         {
             System.Console.WriteLine("It was very simple question for me...");
         }
         else
         {
             Guess clarify = yes.dialog();
             if (clarify != null)
             {
                 yes = clarify;
                 Store();
             }
         }
     }
     else
     {
         if (no == null)
         {
             if (yes == null)
             {
                 return whoIsIt(this);
             }
             else
             {
                 no = whoIsIt(null);
                 Store();
             }
         }
         else
         {
             Guess clarify = no.dialog();
             if (clarify != null)
             {
                 no = clarify;
                 Store();
             }
         }
     }
     return null;
 }
Esempio n. 24
0
        private void EnterGuess_Click(object sender, EventArgs e)
        {
            if (WorkflowInstanceId == Guid.Empty)
            {
                MessageBox.Show("Please select a workflow.");
                return;
            }

            int guess;

            if (!Int32.TryParse(Guess.Text, out guess))
            {
                MessageBox.Show("Please enter an integer.");
                Guess.SelectAll();
                Guess.Focus();
                return;
            }

            // >>>> RESUME A WORKFLOW <<<<
            WorkflowApplicationInstance instance = WorkflowApplication.GetInstance(WorkflowInstanceId, store);

            // Use the persisted WorkflowIdentity to retrieve the correct workflow
            // definition from the dictionary.
            Activity wf = WorkflowVersionMap.GetWorkflowDefinition(instance.DefinitionIdentity);

            // Associate the WorkflowApplication with the correct definition (a name & version)
            WorkflowApplication wfApp = new WorkflowApplication(wf, instance.DefinitionIdentity);


            // Configure the extensions and lifecycle handlers.
            // Do this before the instance is loaded. Once the instance is
            // loaded it is too late to add extensions.
            ConfigureWorkflowApplication(wfApp);

            // Load the workflow.
            wfApp.Load(instance); //takes a Guid InstanceId or WorkflowApplicationInstance instance from store

            // Resume the workflow.
            wfApp.ResumeBookmark("EnterGuess", guess);

            // Clear the Guess textbox.
            Guess.Clear();
            Guess.Focus();
        }
Esempio n. 25
0
        public Guess MakeGuess(int gameId, string number, string userId)
        {
            var game = this.games
                       .GetGameDetails(gameId)
                       .Select(g => new
            {
                g.Id,
                g.GameState,
                g.BlueUserNumber,
                g.RedUserNumber
            })
                       .FirstOrDefault();

            string correctNumber = null;

            if (game.GameState == GameState.BlueInTurn)
            {
                correctNumber = game.RedUserNumber;
            }
            else if (game.GameState == GameState.RedInTurn)
            {
                correctNumber = game.BlueUserNumber;
            }

            var cows  = this.GetCows(number, correctNumber);
            var bulls = this.GetBulls(number, correctNumber);

            var newGuess = new Guess
            {
                GameId     = gameId,
                Number     = number,
                UserId     = userId,
                DateMade   = DateTime.UtcNow,
                BullsCount = bulls,
                CowsCount  = cows
            };

            this.guesses.Add(newGuess);
            this.guesses.SaveChanges();

            this.games.ChangeGameState(gameId, bulls == GameConstants.GuessNumberLength);

            return(newGuess);
        }
Esempio n. 26
0
        public void isWinCorrectForWin()
        {
            // Arrange
            WordToGuess  wordToGuess = new WordToGuess();
            const string THE_WORD    = "jellybean";

            wordToGuess.setWord(THE_WORD);
            Guess  guess         = new Guess();
            string guessedLetter = "j";

            guess.guessedLetter(guessedLetter, wordToGuess);
            string ignore = wordToGuess.getGuessesSoFar(guessedLetter);

            guessedLetter = "e";
            guess.guessedLetter(guessedLetter, wordToGuess);
            ignore        = wordToGuess.getGuessesSoFar(guessedLetter);
            guessedLetter = "l";
            guess.guessedLetter(guessedLetter, wordToGuess);
            ignore        = wordToGuess.getGuessesSoFar(guessedLetter);
            guessedLetter = "l";
            guess.guessedLetter(guessedLetter, wordToGuess);
            ignore        = wordToGuess.getGuessesSoFar(guessedLetter);
            guessedLetter = "y";
            guess.guessedLetter(guessedLetter, wordToGuess);
            ignore        = wordToGuess.getGuessesSoFar(guessedLetter);
            guessedLetter = "b";
            guess.guessedLetter(guessedLetter, wordToGuess);
            ignore        = wordToGuess.getGuessesSoFar(guessedLetter);
            guessedLetter = "e";
            guess.guessedLetter(guessedLetter, wordToGuess);
            ignore        = wordToGuess.getGuessesSoFar(guessedLetter);
            guessedLetter = "a";
            guess.guessedLetter(guessedLetter, wordToGuess);
            ignore        = wordToGuess.getGuessesSoFar(guessedLetter);
            guessedLetter = "n";
            guess.guessedLetter(guessedLetter, wordToGuess);
            ignore = wordToGuess.getGuessesSoFar(guessedLetter);

            // Act
            bool actualIsWin = wordToGuess.isWin();

            // Assert
            Assert.IsTrue(actualIsWin);
        }
Esempio n. 27
0
        public void GetUserGuessResult(List <string> i_UserGuess, int i_RowNumber)
        {
            Guess result = new Guess(i_UserGuess);

            char[] guessResult = result.m_Match;

            createResultPicture(guessResult, i_RowNumber);
            if (new string(guessResult).Equals("VVVV"))
            {
                winLoseMode(true);
            }
            else
            {
                if (i_RowNumber == m_Rows.Length - 1)
                {
                    winLoseMode(false);
                }
            }
        }
Esempio n. 28
0
 //处理竞猜状态
 public void DealState(Guess guess)
 {
     //只要没结算就 计算出竞猜的状态, 如果结算了就不处理竞猜状态
     if (guess.State != GuessDic.AlreadySettlement)
     {
         if (DateTime.Now < guess.BeginTime)
         {
             guess.State = GuessDic.NotPublish;
         }
         else if (DateTime.Now < guess.EndTime && DateTime.Now > guess.BeginTime)
         {
             guess.State = GuessDic.Processing;
         }
         else if (DateTime.Now > guess.EndTime)
         {
             guess.State = GuessDic.Finished;
         }
     }
 }
Esempio n. 29
0
        private void checkResultButton_Click(object i_Sender, EventArgs i_E)
        {
            int   bullsHitscounter = 0;
            Guess guessResult      = r_GameLogic.CheckGuess(getCurrentLineGuessButtonsColors());

            while (bullsHitscounter < guessResult.Bulls)
            {
                m_RowsOfGuesses[m_CurrentLine].PaintResultButtons(Color.Black, bullsHitscounter);
                bullsHitscounter++;
            }

            while (bullsHitscounter < guessResult.Hits + guessResult.Bulls)
            {
                m_RowsOfGuesses[m_CurrentLine].PaintResultButtons(Color.Yellow, bullsHitscounter);
                bullsHitscounter++;
            }

            nextGuessHandler(guessResult.Bulls == r_NumberOfDifferentColorsInGuess);
        }
Esempio n. 30
0
 private void NewGameButton_Click(object sender, RoutedEventArgs e)
 {
     TipsRichTextBox.Document.Blocks.Clear();
     guess     = new Guess(Number);
     Count     = 0;
     UserInput = "";
     State     = true;
     TipsRichTextBox.AppendText("Game Start!\r");
     ButtonOne.IsEnabled   = true;
     ButtonTwo.IsEnabled   = true;
     ButtonThree.IsEnabled = true;
     ButtonFour.IsEnabled  = true;
     ButtonFive.IsEnabled  = true;
     ButtonSix.IsEnabled   = true;
     ButtonSeven.IsEnabled = true;
     ButtonEight.IsEnabled = true;
     ButtonNine.IsEnabled  = true;
     ButtonZero.IsEnabled  = true;
 }
    static public void  Main(string[] args)
    {
        Storage db = StorageFactory.Instance.CreateStorage();

        bool multiclient = args.Length > 0 && args[0].StartsWith("multi");

        if (multiclient)
        {
            db.SetProperty("perst.multiclient.support", true);
        }

        db.Open("guess.dbs", 4 * 1024 * 1024, "GUESS");

        while (askQuestion("Think of an animal. Ready (y/n) ? "))
        {
            if (multiclient)
            {
                db.BeginThreadTransaction(TransactionMode.ReadWrite);
            }
            Guess root = (Guess)db.Root;
            if (root == null)
            {
                root    = whoIsIt(null);
                db.Root = root;
            }
            else
            {
                root.dialog();
            }
            if (multiclient)
            {
                db.EndThreadTransaction();
            }
            else
            {
                db.Commit();
            }
        }

        Console.WriteLine("End of the game");
        db.Close();
    }
Esempio n. 32
0
        /// <summary>
        /// 设置已结算金额
        /// </summary>
        /// <param name="guess"></param>
        public void SetSettlement(Guess guess)
        {
            //胜负竞猜
            if (guess.GuessType == GuessDic.VictoryDefeat)
            {
                SetVictoryDefeatSettlement(guess);
            }
            //比分竞猜
            if (guess.GuessType == GuessDic.Score)
            {
                SetScoreSettlement(guess);
            }

            //胜负比分竞猜
            if (guess.GuessType == GuessDic.VictoryDefeatAndScore)
            {
                SetVictoryDefeatSettlement(guess);
                SetScoreSettlement(guess);
            }
        }
Esempio n. 33
0
        public void getGuessedSoFarCorrect()
        {
            // Arrange
            WordToGuess  wordToGuess = new WordToGuess();
            const string THE_WORD    = "jellybean";

            wordToGuess.setWord(THE_WORD);
            Guess        guess          = new Guess();
            const string GUESSED_LETTER = "a";

            guess.guessedLetter(GUESSED_LETTER, wordToGuess);

            // Act
            string actualGuessSoFar = wordToGuess.getGuessesSoFar(GUESSED_LETTER);

            // Assert
            const string EXPECTED_GUESSED_SO_FAR = "_ _ _ _ _ _ _ a _ ";

            Assert.AreEqual(EXPECTED_GUESSED_SO_FAR, actualGuessSoFar);
        }
Esempio n. 34
0
        private void GetGuessScoreList(Guess obj)
        {
            var sql = @"

 SELECT * 
 FROM dbo.GuessScore 
 WHERE GuessId=@GuessId
 ORDER BY LeftScore DESC ,RightScore ASC

";
            var cmd = CommandHelper.CreateText <GuessScore>(FetchType.Fetch, sql);

            cmd.Params.Add("@GuessId", obj.Id);
            var result = DbContext.GetInstance().Execute(cmd);

            if (result.Entities.Count > 0)
            {
                obj.ScoreList.AddRange(result.Entities.ToList <EntityBase, GuessScore>());
            }
        }
Esempio n. 35
0
        private List <GuessBet> GetGuessScoreBetList(Guess guess)
        {
            var sql = @"

SELECT * 
FROM dbo.GuessBet 
WHERE  
      GuessId=@GuessId
	  AND LeftScore=@LeftScore
	  AND RightScore=@RightScore
";
            var cmd = CommandHelper.CreateText <GuessBet>(FetchType.Fetch, sql);

            cmd.Params.Add("@GuessId", guess.Id);
            cmd.Params.Add("@LeftScore", guess.BingoLeftScore);
            cmd.Params.Add("@RightScore", guess.BingoRightScore);
            var result = DbContext.GetInstance().Execute(cmd);

            return(result.Entities.ToList <EntityBase, GuessBet>());
        }
Esempio n. 36
0
        public void GuessedLetterCorrectLetterIsAccurate()
        {
            // Arrange
            Guess        guess       = new Guess();
            WordToGuess  wordToGuess = new WordToGuess();
            const string THE_WORD    = "jellybean";

            wordToGuess.setWord(THE_WORD);
            const string CORRECT_LETTER = "a";

            guess.guessedLetter(CORRECT_LETTER, wordToGuess);

            // Act
            int actualWrongGuessCount = guess.getWrongGuesses();

            // Assert
            const int EXPECTED_WRONG_GUESS_COUNT = 0;

            Assert.AreEqual(EXPECTED_WRONG_GUESS_COUNT, actualWrongGuessCount);
        }
        private void EnterGuess_Click(object sender, EventArgs e)
        {
            if (WorkflowInstanceId == Guid.Empty)
            {
                MessageBox.Show("Please select a workflow.");
                return;
            }

            int guess;

            if (!Int32.TryParse(Guess.Text, out guess))
            {
                MessageBox.Show("Please enter an integer.");
                Guess.SelectAll();
                Guess.Focus();
                return;
            }

            WorkflowApplicationInstance instance =
                WorkflowApplication.GetInstance(WorkflowInstanceId, store);

            // Use the persisted WorkflowIdentity to retrieve the correct workflow
            // definition from the dictionary.
            Activity wf =
                WorkflowVersionMap.GetWorkflowDefinition(instance.DefinitionIdentity);

            // Associate the WorkflowApplication with the correct definition
            WorkflowApplication wfApp =
                new WorkflowApplication(wf, instance.DefinitionIdentity);

            ConfigureWorkflowApplication(wfApp);

            // Load the workflow.
            wfApp.Load(instance);

            // Resume the workflow.
            wfApp.ResumeBookmark("EnterGuess", guess);

            Guess.Clear();
            Guess.Focus();
        }
Esempio n. 38
0
 internal Guess dialog()
 {
     if (askQuestion("May be, " + Question + " (y/n) ? "))
     {
         if (Yes == null)
         {
             Console.WriteLine("It was very simple question for me...");
         }
         else
         {
             Guess clarify = Yes.dialog();
             if (clarify != null)
             {
                 Yes = clarify;
             }
         }
     }
     else
     {
         if (No == null)
         {
             if (Yes == null)
             {
                 return(whoIsIt(Database, this));
             }
             else
             {
                 No = whoIsIt(Database, null);
             }
         }
         else
         {
             Guess clarify = No.dialog();
             if (clarify != null)
             {
                 No = clarify;
             }
         }
     }
     return(null);
 }
Esempio n. 39
0
        /// <summary>
        /// 设置猜中的比分和赔率到Guess实体上
        /// </summary>
        /// <param name="guess"></param>
        /// <param name="obj"></param>
        public void SetBingoScoreAndOdds(Guess guess, GuessVS obj)
        {
            var sql = @"
 SELECT * 
 FROM dbo.GuessScore
 WHERE GuessId=@GuessId
	AND  LeftScore=@LeftScore
	AND RightScore=@RightScore
";
            var cmd = CommandHelper.CreateText <GuessScore>(FetchType.Fetch, sql);

            cmd.Params.Add("@GuessId", guess.Id);
            cmd.Params.Add("@LeftScore", obj.LeftScore);
            cmd.Params.Add("@RightScore", obj.RightScore);
            var result     = DbContext.GetInstance().Execute(cmd);
            var guessScore = result.FirstEntity <GuessScore>();

            guess.BingoLeftScore  = guessScore.LeftScore;
            guess.BingoRightScore = guessScore.RightScore;
            guess.BingoScoreOdds  = guessScore.Odds;
        }
Esempio n. 40
0
        public void GetProbability_ExcludeAllRedTwoCards_ReturnsZeroForRedTwoCard()
        {
            FakeGameProvider gameProvider = GameProviderFabric.Create(Color.Red);

            Guess guess = new Guess(gameProvider,
                                    CreateCardInHand(gameProvider, new Card(Color.Red, Rank.Three)));

            List <Card> excludedCards = new List <Card>
            {
                new Card(Color.Red, Rank.Two),
                new Card(Color.Red, Rank.Two),
            };

            List <Card> cardsToSearch = new List <Card> {
                new Card(Color.Red, Rank.Two)
            };

            Probability result = guess.GetProbability(cardsToSearch, excludedCards);

            Assert.AreEqual(0, result.Value);
        }
Esempio n. 41
0
        private void paintFeedbackButtons(List <GameButton> i_GuessButtons, List <GameButton> i_FeedbackButtons)
        {
            Guess guessedletters = new Guess(0, r_OptionalColors.CreateUserGuess(i_GuessButtons));

            int[] feedbackArray        = guessedletters.GetFeedback(r_GameGuess.SequenceOfRandomLetters);
            int   numOfYellowsFeedback = feedbackArray[1];
            int   numOfBlacksFeedback  = feedbackArray[0];

            for (int i = 0; i < numOfBlacksFeedback; i++)
            {
                i_FeedbackButtons[i].BackColor = Color.Black;
            }
            for (int i = 0; i < numOfYellowsFeedback; i++)
            {
                i_FeedbackButtons[i + numOfBlacksFeedback].BackColor = Color.Yellow;
            }
            if (numOfBlacksFeedback == k_NumberOfColorsToGuess)
            {
                r_GameGuess.UserWin = true;
            }
        }
Esempio n. 42
0
 internal static Guess whoIsIt(Storage storage, Guess parent)
 {
     System.String animal = input("What is it ? ");
     System.String difference = input("What is a difference from other ? ");
     return Create(storage, parent, difference, Create(storage, null, animal, null));
 }
        private Game[] GenerateValidTestGames(int count)
        {
            Game[] games = new Game[count];
            var guess = new Guess
            {
                ID = 1,
                Username = "******"
            };

            for (int i = 0; i < count; i++)
            {
                games[i] = new Game
                {
                    ID = i,
                    Name = "Title #" + i,
                    DateCreated = DateTime.Now,
                    BlueUser = new User()
                };
            }

            return games;
        }
Esempio n. 44
0
        private Guess GetGuess(string modelGuess)
        {
            var guess = this.data.Guesses.All().FirstOrDefault(c => c.Username == modelGuess);
            if (guess == null)
            {
                guess = new Guess { Username = modelGuess };
                this.data.Guesses.Add(guess);
            }

            return guess;
        }
        public IHttpActionResult Play(PlayRequestDataModel request)
        {
            var currentUserId = this.userIdProvider.GetUserId();

            if (request == null || !ModelState.IsValid)
            {
                return this.BadRequest(this.ModelState);
            }

            var gameId = request.GameId;

            var game = this.Data.Games.SearchFor(g => g.Id == gameId).FirstOrDefault();

            if (game == null)
            {
                return this.BadRequest("Invalid game id!");
            }

            if (game.FirstPlayerId != currentUserId &&
                game.SecondPlayerId != currentUserId)
            {
                return this.BadRequest("This is not your game!");
            }

            if (game.State != GameState.FirstPlayerTurn &&
                game.State != GameState.SecondPlayerTurn)
            {
                return this.BadRequest("Invalid game state!");
            }

            if ((game.State == GameState.FirstPlayerTurn &&
                game.FirstPlayerId != currentUserId)
                ||
                (game.State == GameState.SecondPlayerTurn &&
                game.SecondPlayerId != currentUserId))
            {
                return this.BadRequest("It's not your turn!");
            }

            // Update games state and adding new guess number
            var guessNumber = request.GuessNumber;

            var newGuessNumber = new GuessNumber
            {
                Number = guessNumber,
                GameId = gameId,
                PlayerId = currentUserId
            };

            this.Data.GuessNumbers.Add(newGuessNumber);

            game.State = game.State == GameState.FirstPlayerTurn ?
                GameState.SecondPlayerTurn : GameState.FirstPlayerTurn;

            this.Data.SaveChanges();
            var guess = new Guess
            {
                GuessingUserId = currentUserId,
                GuessNumber = guessNumber.ToString()
            };
            var guessResult = this.gameValidator.GetResult(guess, Data);

            switch (guessResult.GameResult)
            {
                case GameResult.NotFinished:
                    break;
                case GameResult.WonByFirstPlayer:
                    game.State = GameState.WonByFirstPlayer;
                    game.GameEnd = DateTime.Now;
                    this.Data.SaveChanges();
                    break;
                case GameResult.WonBySecondPlayer:
                    game.State = GameState.WonBySecondPlayer;
                    game.GameEnd = DateTime.Now;
                    this.Data.SaveChanges();
                    break;
                default:
                    break;
            }

            return this.Ok(guessResult);
        }
Esempio n. 46
0
        private void drawSingleUserFeedback(Guess guess, SpriteBatch spriteBatch, Vector2 offset)
        {
            int feedBackOffset = 0;

            // Exact feedback markers
            for (int i = 0; i < guess.numExact; i++)
            {
                drawFeedbackPeg(spriteBatch, offset, feedBackOffset, COLOR_EXACT);
                feedBackOffset += feedbackImgSize;
            }
            // Almost feedback markers
            for (int i = 0; i < guess.numAlmost; i++)
            {
                drawFeedbackPeg(spriteBatch, offset, feedBackOffset, COLOR_ALMOST);
                feedBackOffset += feedbackImgSize;
            }
        }
Esempio n. 47
0
        override public void Update(KeyboardState keyboard, KeyboardState oldKeyboard)
        {
            if (currPlayer == PlayerTurn.Computer)
            {
                Guess currentGuess = new Guess();
                currentGuess.code = new int[playerGuess.Length];
                playerGuess.CopyTo(currentGuess.code, 0);
                

                // Calculate number of exact
                for (int i = 0; i < CODE_LENGTH; i++)
                {
                    // Same color in same spot
                    if (code[i] == playerGuess[i])
                        numExact++;

                }
                // Calculate number of almost
                numAlmost -= numExact; // Corrects for exact values double counted as "almosts"
                for (int i = 0; i < playerGuessColorCounts.Length; i++)
                {
                    numAlmost += Math.Min(playerGuessColorCounts[i], codeColorCounts[i]);
                }

                currentGuess.numExact = numExact;
                currentGuess.numAlmost = numAlmost;
                guesses.Add(currentGuess);

                if (numExact == CODE_LENGTH)
                    isCodeCracked = true;


                printAnalysis(); // For debugging

                resetPlayerGuess();
                currPlayer = PlayerTurn.User;
            }
            else
            {
                // All slots filled
                if (playerGuess.Count<int>(count => count == -1) == 0)
                {
                    foreach (int color in playerGuess)
                    {
                        playerGuessColorCounts[color]++;
                    }
                    numTurns++;
                    numExact = 0;
                    numAlmost = 0;
                    currPlayer = PlayerTurn.Computer;
                }
                else
                {
                    // First unfilled one
                    int nextIndex = Array.IndexOf(playerGuess, -1);

                    // NEEDSWORK: This will eventually be done with a mouse / clicking. Even so,
                    // the logic should be changed so that a color isn't accepted / added to the
                    // code until the user approves it. Leaving it this way for now.
                    
                    foreach (Keys key in codeKeysMap.Keys)
                    {
                        if (wasKeyPressed(key, keyboard, oldKeyboard))
                        {
                            playerGuess[nextIndex] = codeKeysMap[key];
                            break;
                        }
                    }
                }
            }
        }
Esempio n. 48
0
 private void drawSingleUserGuess(Guess guess, SpriteBatch spriteBatch, Vector2 offset)
 {
     // User's guess
     for (int i = 0; i < guess.code.Length; i++)
     {
         if (guess.code[i] == -1)
             continue;
         drawCodeLight(spriteBatch, offset, i, codeColors[guess.code[i]]);
     }
 }
Esempio n. 49
0
        private void drawCurrGuess(SpriteBatch spriteBatch, Vector2 offset)
        {
            Guess g = new Guess();
            g.code = new int[playerGuess.Length];
            g.code = playerGuess;
            g.numAlmost = numAlmost;
            g.numExact = numExact;

            drawSingleUserGuess(g, spriteBatch, offset + new Vector2(150, 0));
        }
Esempio n. 50
0
        /// <summary>
        ///  更新一条数据
        /// </summary>
        public SqlParameter[] SetParameter(Guess.Model.T_Game model)
        {
            SqlParameter[] parameters = {

                    new SqlParameter("@F_Phases", SqlDbType.Int,4),
                    new SqlParameter("@F_Type", SqlDbType.Int,4),
                    new SqlParameter("@F_NumOne", SqlDbType.Int,4),
                    new SqlParameter("@F_NumTwo", SqlDbType.Int,4),
                    new SqlParameter("@F_NumThree", SqlDbType.Int,4),
                    new SqlParameter("@F_NumFour", SqlDbType.Int,4),
                    new SqlParameter("@F_NumFive", SqlDbType.Int,4),
                    new SqlParameter("@F_Bonus", SqlDbType.Int,4),
                    new SqlParameter("@F_InvolvedNum", SqlDbType.Int,4),
                    new SqlParameter("@F_WinningNum", SqlDbType.Int,4),
                    new SqlParameter("@F_Lottery", SqlDbType.Bit,1),
                    new SqlParameter("@F_Id", SqlDbType.Int,4)};

            parameters[0].Value = model.F_Phases;
            parameters[1].Value = model.F_Type;
            parameters[2].Value = model.F_NumOne;
            parameters[3].Value = model.F_NumTwo;
            parameters[4].Value = model.F_NumThree;
            parameters[5].Value = model.F_NumFour;
            parameters[6].Value = model.F_NumFive;
            parameters[7].Value = model.F_Bonus;
            parameters[8].Value = model.F_InvolvedNum;
            parameters[9].Value = model.F_WinningNum;
            parameters[10].Value = model.F_Lottery;
            parameters[11].Value = model.F_Id;

            return parameters;
        }
Esempio n. 51
0
        public int Update(Guess.Model.T_Game t_m)
        {
            string sql = string.Format("update T_Game set {0}=@{0},{1}=@{1},{2}=@{2},{3}=@{3},{4}=@{4},{5}=@{5},{6}=@{6},{7}=@{7},{8}=@{8},{9}=@{9},{10}=@{10} where {11}=@{11}",
                "F_Phases",
                "F_Type",
                "F_NumOne",
                "F_NumTwo",
                "F_NumThree",
                "F_NumFour",
                "F_NumFive",
                "F_Bonus",
                "F_InvolvedNum",
                "F_WinningNum",
                "F_Lottery",
                "F_Id"
                );

            return DBHelper.NonQuery(sql,SetParameter(t_m));
        }
Esempio n. 52
0
 public Guess(Guess no, System.String question, Guess yes)
 {
     this.yes = yes;
     this.question = question;
     this.no = no;
 }
Esempio n. 53
0
        private List<CodePattern> BuildPatternList(Guess guess, int lowerIndex)
        {
            var patterns = new List<CodePattern>();
            var basePattern = new List<int?>() { guess[0], guess[1], guess[2], guess[3] };
            var positions = Enumerable.Range(0, guess.Value.Count).ToList();

            var variations = new Combinations<int>(positions, lowerIndex, GenerateOption.WithoutRepetition);

            foreach (var variation in variations)
            {
                var basePatternCopy = new List<int?>(basePattern);

                for (var i = 0; i < basePatternCopy.Count; i++)
                {
                    if (variation.Contains(i) == false)
                    {
                        basePatternCopy[i] = null;
                    }
                }

                patterns.Add(new CodePattern(basePatternCopy));
            }

            return patterns;
        }
Esempio n. 54
0
		static void Main(string[] args) {
			string[,] initial ={{"3","1","3","3","3","2","2","3"},
							    {"2","3","2","2","2","2","2","2"},
							    {"2","2","2","2","2","2","2","2"},
							    {"3","2","2","3","3","2","2","3"},
							    {"3","2","2","3","3","2","2","3"},
							    {"2","2","2","2","2","2","2","2"},
								{"2","2","2","2","2","2","2","2"},
								{"3","2","2","3","3","2","2","3"},};
			initial = extend(initial);
			size = initial.GetLength(0);
			convert = size + 1;
			set = new Blocks(convert);
			board = new Board(size);
			entryNum(initial);
			currentGuess = board.boardProperty;
			/****************************************
			 * 終わるまでループ
			 ****************************************/
			while(true) {
				if(!currentGuess.Check) {
					currentGuess.Check = true;
					guess();
				}
				if(board.complete()) {
					board.debugWrite();
				}
				nextGuess();
				if(currentGuess == null) {
					System.Console.WriteLine("以上");
					break;
				}
			}
			/****************************************
			 * 盤面の表示やデバック関係
			 ****************************************/
			System.Console.WriteLine("\n==========以下入力関係==========");
			for(int i = 1; i < size - 1; i++) {
				for(int j = 1; j < size - 1; j++) {
					System.Console.Write("{0, 2}", initial[i, j]);
				}
				System.Console.WriteLine();
			}
			System.Console.Write("Enterで終了");
			System.Console.ReadLine();
		}
Esempio n. 55
0
        private List<CodePattern> FillInPatterns(Guess guess, List<CodePattern> bullPatterns)
        {
            var patterns = new List<CodePattern>();

            foreach (var bullPattern in bullPatterns)
            {
                var potentialCows = new List<DigitWithPosition>();

                for (var i = 0; i < bullPattern.Pattern.Count; i++)
                {
                    if (bullPattern[i].HasValue == false)
                    {
                        potentialCows.Add(new DigitWithPosition(guess[i], i));
                    }
                }

                var cowCombinations = CreateCowCombinations(guess, potentialCows);

                var appliedPatterns = ApplyCowCombinations(bullPattern, cowCombinations);
                patterns.AddRange(appliedPatterns);
            }

            return patterns;
        }
Esempio n. 56
0
		public static void nextGuess() {
			currentGuess = currentGuess.next();
			if(currentGuess != null) {
				board.boardProperty = currentGuess;
			}
		}
Esempio n. 57
0
        private List<IList<DigitWithPosition>> CreateCowCombinations(Guess guess, List<DigitWithPosition> potentialCows)
        {
            var cows = new List<DigitWithPosition>();

            foreach (var potentialCow in potentialCows)
            {
                var otherPositions = potentialCows
                    .Where(c => c.Digit != potentialCow.Digit)
                    .Select(c => c.Position);

                cows.AddRange(otherPositions.Select(p => new DigitWithPosition(potentialCow.Digit, p)));
            }

            var cowCombinations =new Combinations<DigitWithPosition>(cows, guess.Cows, GenerateOption.WithoutRepetition).ToList();
            StripOutInvalidCowCombinations(cowCombinations);
            return cowCombinations;
        }
Esempio n. 58
0
File: Guess.cs Progetto: kjk/volante
 internal static Guess whoIsIt(IDatabase db, Guess parent)
 {
     System.String animal = input("What is it ? ");
     System.String difference = input("What is a difference from other ? ");
     return Create(db, parent, difference, Create(db, null, animal, null));
 }
Esempio n. 59
0
 internal static Guess whoIsIt(Guess parent)
 {
     System.String animal = input("What is it ? ");
     System.String difference = input("What is a difference from other ? ");
     return new Guess(parent, difference, new Guess(null, animal, null));
 }
Esempio n. 60
0
File: Guess.cs Progetto: kjk/volante
 internal Guess dialog()
 {
     if (askQuestion("May be, " + Question + " (y/n) ? "))
     {
         if (Yes == null)
         {
             Console.WriteLine("It was very simple question for me...");
         }
         else
         {
             Guess clarify = Yes.dialog();
             if (clarify != null)
             {
                 Yes = clarify;
             }
         }
     }
     else
     {
         if (No == null)
         {
             if (Yes == null)
             {
                 return whoIsIt(Database, this);
             }
             else
             {
                 No = whoIsIt(Database, null);
             }
         }
         else
         {
             Guess clarify = No.dialog();
             if (clarify != null)
             {
                 No = clarify;
             }
         }
     }
     return null;
 }