Пример #1
0
        public void Part1()
        {
            var lines  = Input.GetLines(2021, 4).ToList();
            var winner = new BingoGame(lines).Play();

            Console.WriteLine(winner.Score);
        }
Пример #2
0
        private static void StartBingoGame()
        {
            Clear();
            WriteLine("Starting a new game...");

            BingoGame game = new BingoGame(range, size);

            game.StartNewGame();

            PrintBoard(game.Board);

            while (!game.IsOver)
            {
                WriteLine("Press any key to draw a number...");
                ReadKey();
                Clear();

                int randNum = game.DrawNextNumber();
                WriteLine($"Drawn number is {randNum}");
                PrintBoard(game.Board);
            }

            WriteLine("Bingo! game is over...");
            CheckForRestart();
        }
Пример #3
0
        public void Part2()
        {
            var lines = Input.GetLines(2021, 4).ToList();
            var loser = new BingoGame(lines).PlayToTheEnd();

            Console.WriteLine(loser.Score);
        }
Пример #4
0
        static void Main(string[] args)
        {
            var rng        = new RandomNumberGenerator();
            var cardWidth  = 5;
            var cardLength = 5;
            var game       = new BingoGame(cardLength, cardWidth, rng, new BingoBankService(rng, cardLength * cardWidth), new BingoCardService(rng));

            game.NewGame();

            do
            {
                Console.WriteLine();
                Console.WriteLine("Pulling new number from bank...");
                game.NextRound();

                foreach (var row in game.GetCard())
                {
                    foreach (var number in row)
                    {
                        Console.Write(number.PadLeft(3));
                    }
                    Console.WriteLine();
                }
            } while (!game.IsBingo());
        }
        public void Setup()
        {
            A.CallTo(() => _cardService.GetGameCard(A <int> ._, A <int> ._))
            .Returns(new List <List <NumberCell> >());

            _game = new BingoGame(_gameRowSize, _gameColSize, _random, _bankService, _cardService);
            _successfullyCreatedNewGame = _game.NewGame();
        }
Пример #6
0
        private static async Task <AppResponse> Play(CloudTable table, string gameId, string move, string argument, string userName, string displayName, string channelName, ILogger log, CancellationToken token, Func <string, IEnumerable <BingoPlayer>, ILogger, CancellationToken, Task> postCards)
        {
            if (!Enum.TryParse <MoveType>(move, true, out var action))
            {
                return("Invalid move");
            }

            var row = await GetGame(table, gameId, token);

            var data = row?.Content;

            if (data == null && action != MoveType.Join)
            {
                return("A game has not yet been created.  Try `/bingo join` to start a new game");
            }
            if (data == null)
            {
                row = new TableRow <BingoData> {
                    Content = data = new BingoData {
                        ChannelName = channelName, SideSize = 5, Activities = new List <BingoActivity>(), Players = new List <BingoPlayer>()
                    }, PartitionKey = BingoPartition, RowKey = gameId
                }
            }
            ;

            try
            {
                var game = new BingoGame(data, userName, displayName);
                var(error, result) = await game.TryMove(action, argument, log, token);

                switch (action)
                {
                case MoveType.Join: return(error == null ? (true, $"{displayName} has joined the game." + (result == null ? "  You will receive a card once the game has been started with `/bingo start`." : "  The game has already started, so you can view your card with `/bingo card`")) : (false, error));

                case MoveType.Next: return(error == null ? (true, $"The next word is `{result}`") : (false, error));

                case MoveType.Leave: return(error == null ? (true, $"{displayName} has left the game") : (false, error));

                case MoveType.Bingo: return(error == null ? (true, $"{displayName} has won!") : (false, error));

                case MoveType.Start:
                    if (error != null)
                    {
                        return(error);
                    }

                    await postCards(gameId, data.Players, log, token);

                    return(true, $"The game has been started.  The first word is `{result}`");

                default: return(error ?? result);
                }
            }
            finally
            {
                await table.ExecuteAsync(TableOperation.InsertOrReplace(row));
            }
        }
Пример #7
0
        /// <summary>
        /// Parses the response received from the server.
        /// </summary>
        protected override void UnpackResponse()
        {
            base.UnpackResponse();

            // Create the streams we will be reading from.
            MemoryStream responseStream = new MemoryStream(m_responsePayload);
            BinaryReader responseReader = new BinaryReader(responseStream, Encoding.Unicode);

            // Try to unpack the data.
            try
            {
                // Seek past return code.
                responseReader.BaseStream.Seek(sizeof(int), SeekOrigin.Begin);

                // Get the count of games.
                ushort gameCount = responseReader.ReadUInt16();

                for (int i = 0; i < gameCount; i++)
                {
                    // Get the count of games.
                    int gameSequence = responseReader.ReadInt32();

                    // Get the count of games.
                    int displayGameNumber = responseReader.ReadInt32();

                    // Get the count of games.
                    int linearGameNumber = responseReader.ReadInt32();

                    // Get the count of games.
                    int continuationGameCount = responseReader.ReadInt32();

                    var bingoGame = new BingoGame()
                    {
                        LinearNumber          = gameSequence,
                        DisplayNumber         = displayGameNumber,
                        LinearDisplayNumber   = linearGameNumber,
                        ContinuationGameCount = continuationGameCount
                    };

                    m_linearGameList.Add(bingoGame);
                }
            }
            catch (EndOfStreamException e)
            {
                throw new MessageWrongSizeException("Get Session Linear Game Numbers", e);
            }
            catch (Exception e)
            {
                throw new ServerException("Get Session Linear Game Numbers", e);
            }

            // Close the streams.
            responseReader.Close();
        }
Пример #8
0
        public void Setup()
        {
            A.CallTo(() => _cardService.GetGameCard(A <int> ._, A <int> ._))
            .Returns(Data.GameCard);

            A.CallTo(() => _bankService.Pull())
            .Returns(1);

            _game = new BingoGame(_gameRowSize, _gameColSize, _random, _bankService, _cardService);
            _successfullyCreatedNewGame    = _game.NewGame();
            _successfullyGeneratedNewRound = _game.NextRound();
        }
Пример #9
0
        public IActionResult Index()
        {
            var game = new BingoGame
            {
                DateCreated = DateTime.Now
            };

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

            return(RedirectToAction("show", new { id = game.GameNumber }));
        }
Пример #10
0
        public BingoGame Start(String gameName = "square5")
        {
            var numbers = initNumbers(gameName);
            var game    = new BingoGame()
            {
                StartTime = new DateTime(),
                Numbers   = numbers
            };

            _context.BingoGames.Add(game);
            _context.SaveChanges();
            return(game);
        }
Пример #11
0
        private void button3_Click(object sender, EventArgs e)
        {
            // play cards vs db...

            BingoSession session = new BingoSession();
            Pattern      p       = new Pattern();

            p.algorithm     = OpenSkieScheduler3.PatternDescriptionTable.match_types.CrazyMark;
            p.repeat_count  = 24;
            p.crazy_hardway = true;

            BingoGame game;

            session.GameList.Add(game = new BingoGame(new BingoGameCore4.Pattern[] { p }));

            BingoGameGroup game_group = new BingoGameGroup(Guid.Empty);

            game_group.Add(game);

            BingoPacks packs = new BingoPacks(session.GameList, schedule, null);


            BingoGameCore4.CardMaster.CardReader card_file
                = new BingoGameCore4.CardMaster.CardReader("c:\\ftn3000\\data\\cards\\Random 360k (50s300w)(81_Full).20110225.dat");

            BingoDealer dealer = BingoDealers.GetDealer(card_file, 1, 1);

            packs.CreatePack(dealer, "Test Pack");
            BingoPack pack = packs.MakePack("Test Pack", card_file.Length);

            BingoSessionEvent session_evnet = new BingoSessionEvent(session, true);
            BingoPlayer       player;

            player = new BingoPlayer();

            PlayerTransaction transaction;

            player.transactions.Add(transaction = new PlayerTransaction(player, 12345689));
            player.PlayPack(transaction, pack);

            session_evnet.PlayerList.Add(player);
            BallDataExternal bde = new BallDataExternal();

            session_evnet.ball_data = bde;

            BingoGameState game_state = session_evnet.StepTo(0);

            bde.Balls = calls[0];
            session_evnet.Play(game_state);
        }
Пример #12
0
 private void InitializeCommands()
 {
     LaunchGameCommand = new RelayCommand <GameInfo>((x) =>
     {
         try
         {
             MessengerInstance.Send(new LaunchGameMessage(this, BingoGame.LoadGame(x.Language, x.Subject, x.Topic)));
         }
         catch (Exception e)
         {
             DialogManager.ShowDialog(new AlertDialog()
             {
                 AlertLevel = AlertLevel.Error,
                 Title      = Properties.Resources.GENERIC_Error,
                 Message    = Properties.Resources.START_GAME_ErrorStartingGame,
                 ShowCopyToClipboardButton = true,
                 Exception = e
             });
         }
     });
 }
Пример #13
0
        private void InitializeCommands()
        {
            GenerateCardsCommand = new RelayCommand <GameInfo>((x) =>
            {
                if (x == null || AmountOfCards == null || AmountOfQuestionsPerCard == null)
                {
                    DialogManager.ShowDialog(new AlertDialog()
                    {
                        AlertLevel = AlertLevel.Error,
                        Title      = Properties.Resources.GENERIC_Error,
                        Message    = Properties.Resources.GENERIC_FillNecessaryFields
                    });

                    return;
                }

                BingoGame game;

                try
                {
                    game = BingoGame.LoadGame(x.Language, x.Subject, x.Topic);
                }
                catch (Exception e)
                {
                    DialogManager.ShowDialog(new AlertDialog()
                    {
                        AlertLevel = AlertLevel.Error,
                        Title      = Properties.Resources.GENERIC_Error,
                        Message    = Properties.Resources.GENERATE_CARDS_ErrorLoadingGame,
                        Exception  = e,
                        ShowCopyToClipboardButton = true,
                    });

                    return;
                }

                AutoResetEvent autoReset      = new AutoResetEvent(false);
                IEnumerable <BingoCard> cards = null;

                SaveFileDialog saveDialog = new SaveFileDialog()
                {
                    Filter = "PDF (*.pdf)|*.pdf",
                };

                PdfDocument pdf = new PdfDocument();
                pdf.Info.Author = "VirtualBingo";
                pdf.Info.Title  = game.Topic;

                Thread thread = new Thread(() =>
                {
                    cards = game.DistributeQuestions(AmountOfCards.Value, AmountOfQuestionsPerCard.Value);

                    string tempImagePath = Path.GetTempFileName();

                    foreach (var card in cards)
                    {
                        PdfPage page = pdf.AddPage();

                        page.Orientation = PdfSharp.PageOrientation.Landscape;
                        page.Size        = PdfSharp.PageSize.A4;

                        CardDisplayer displayer = new CardDisplayer()
                        {
                            Card = card
                        };

                        RendererHelper.SaveImageOfRender(RendererHelper.Render(displayer, new Size(842, 595)), tempImagePath);

                        using (FileStream stream = File.Open(tempImagePath, FileMode.Open, FileAccess.Read, FileShare.Delete))
                        {
                            using (XGraphics gfx = XGraphics.FromPdfPage(page, XGraphicsUnit.Millimeter))
                            {
                                using (XImage xImage = XImage.FromStream(stream))
                                {
                                    gfx.DrawImage(xImage, 15, 15, 267, 180);
                                }
                            }
                        }
                    }
                });

                thread.SetApartmentState(ApartmentState.STA);
                thread.Start();

                if (saveDialog.ShowDialog() == true)
                {
                    thread.Join();

                    pdf.Save(saveDialog.FileName);

                    DialogManager.ShowDialog(new AlertDialog()
                    {
                        Title   = Properties.Resources.GENERIC_Success,
                        Message = Properties.Resources.GENERATE_CARDS_SuccessGenerating
                    });
                }
            });
        }
Пример #14
0
        /// <summary>
        /// Parses the response received from the server.
        /// </summary>
        protected override void UnpackResponse()
        {
            base.UnpackResponse();

            // Create the streams we will be reading from.
            MemoryStream responseStream = new MemoryStream(m_responsePayload);
            BinaryReader responseReader = new BinaryReader(responseStream, Encoding.Unicode);

            // Check the response length.
            if (responseStream.Length < MinResponseMessageLength)
            {
                throw new MessageWrongSizeException("Get Game Cards");
            }

            // Try to unpack the data.
            try
            {
                // Seek past return code.
                responseReader.BaseStream.Seek(sizeof(int), SeekOrigin.Begin);

                // Same Cards
                m_sameCards = responseReader.ReadBoolean();

                // Consecutive Cards
                m_consecutiveCards = responseReader.ReadBoolean();

                // Get the count of games.
                ushort gameCount = responseReader.ReadUInt16();

                // Clear any existing games.
                m_games.Clear();

                // Read all the game data.
                for (ushort currentGame = 0; currentGame < gameCount; currentGame++)
                {
                    BingoGame game = new BingoGame();

                    // Game Number
                    game.LinearNumber = responseReader.ReadInt32();

                    // Display Game Number
                    game.DisplayNumber = responseReader.ReadInt32();

                    // Game Type Id
                    game.Type = (GameType)responseReader.ReadInt32();

                    // Set whether this game has consecutive cards.
                    game.ConsecutiveCards = m_consecutiveCards;

                    // Get the count of card types.
                    ushort cardTypeCount = responseReader.ReadUInt16();

                    for (ushort currentType = 0; currentType < cardTypeCount; currentType++)
                    {
                        // Card Type Id
                        CardType cardType = (CardType)responseReader.ReadInt32();

                        // Rally DE2312 - Selling CBB cards returns an error.
                        CardMedia mediaType = (CardMedia)responseReader.ReadInt32();

                        // Get the count of levels.
                        ushort levelCount = responseReader.ReadUInt16();

                        for (ushort currentLevel = 0; currentLevel < levelCount; currentLevel++)
                        {
                            // Card Level Id
                            int cardLevelId = responseReader.ReadInt32();

                            // Rally US505
                            CardLevel level = null;

                            if (game.Type != GameType.CrystalBall && game.Type != GameType.PickYurPlatter) // Rally TA6385
                            {
                                // Try to find the level in the array we have.
                                if (m_levels == null || m_levels.Length == 0)
                                {
                                    throw new ModuleException(Resources.UnknownCardLevel);
                                }

                                foreach (CardLevel lvl in m_levels)
                                {
                                    if (lvl.Id == cardLevelId)
                                    {
                                        level = lvl;
                                        break;
                                    }
                                }

                                // Rally US229 & US505
                                if (level == null)
                                {
                                    throw new ModuleException(Resources.UnknownCardLevel);
                                }
                            }

                            // Get the count of cards.
                            ushort cardCount = responseReader.ReadUInt16();

                            for (ushort currentCard = 0; currentCard < cardCount; currentCard++)
                            {
                                BingoCard card = null;

                                // Rally TA5749
                                // First Card
                                bool firstCard = responseReader.ReadBoolean();

                                // Card Number
                                int cardNum = responseReader.ReadInt32();

                                // PDTS 1098
                                // Rally DE2312
                                // Create the card.
                                card                = BingoCardFactory.CreateBingoCard(game.Type, cardType, mediaType);
                                card.Number         = cardNum;
                                card.Level          = level;
                                card.IsStartingCard = firstCard;
                                // END: TA5749

                                // Rally US505
                                // Rally TA6385
                                if (m_getFaces || game.Type == GameType.CrystalBall || game.Type == GameType.PickYurPlatter)
                                {
                                    // Rally US498
                                    card.ParseFaceData(responseReader);
                                }

                                game.AddCard(card);
                            }
                        }
                    }

                    m_games.Add(game);
                }
            }
            catch (EndOfStreamException e)
            {
                throw new MessageWrongSizeException("Get Game Cards", e);
            }
            catch (Exception e)
            {
                throw new ServerException("Get Game Cards", e);
            }

            // Close the streams.
            responseReader.Close();
        }
Пример #15
0
        private void InitializeCommands()
        {
            SaveGameCommand = new RelayCommand(() =>
            {
                try
                {
                    BingoGame.CreateGameFile(GameSubject, GameTopic, GameLanguage, GameAuthor, AddedQuestions);
                }
                catch (Exception e)
                {
                    DialogManager.ShowDialog(new AlertDialog()
                    {
                        AlertLevel = AlertLevel.Error,
                        Title      = Properties.Resources.GENERIC_Error,
                        Message    = Properties.Resources.CREATE_GAME_ErrorCreatingGame,
                        ShowCopyToClipboardButton = true,
                        Exception = e
                    });
                }
            });

            AddQuestionCommand = new RelayCommand(() =>
            {
                if ((string.IsNullOrWhiteSpace(CurrentTitle) && string.IsNullOrWhiteSpace(CurrentTitleImagePath)) || (string.IsNullOrWhiteSpace(CurrentAnswer) && string.IsNullOrWhiteSpace(CurrentAnswerImagePath)))
                {
                    AddQuestionErrorMessage = Properties.Resources.CREATE_GAME_ErrorAddingQuestion;
                    return;
                }

                AddQuestionErrorMessage = null;

                AddedQuestions.Add(new BingoQuestion()
                {
                    Title  = CurrentTitle,
                    Answer = CurrentAnswer,

                    TitleImagePath          = CurrentTitleImagePath,
                    AlwaysDisplayTitleImage = CurrentIsImageNecessary,
                    AnswerImagePath         = CurrentAnswerImagePath
                });
            });

            RemoveQuestionCommand = new RelayCommand <BingoQuestion>((x) =>
            {
                AddedQuestions.Remove(x);
            });

            AddImageCommand = new RelayCommand <string>((x) =>
            {
                OpenFileDialog fileDialog = new OpenFileDialog()
                {
                    CheckPathExists = true,
                    CheckFileExists = true,
                    Filter          = "Image files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png",
                    Multiselect     = false
                };

                if (fileDialog.ShowDialog() == true)
                {
                    if (string.Compare(x, "Question", true) == 0)
                    {
                        CurrentTitleImagePath = fileDialog.FileName;
                    }
                    else if (string.Compare(x, "Answer", true) == 0)
                    {
                        CurrentAnswerImagePath = fileDialog.FileName;
                    }
                }
            });
        }
Пример #16
0
 public LaunchGameMessage(object sender, BingoGame game)
 {
     Game = game;
 }