public void CanCreateGameOfSize3()
 {
     var game = new Game(3);
     AssertThat.AreEqual(@"...
                           ...
                           ...", game);
 }
        public void CanCreateGame()
        {
            var game = new Game(2);

            var expected = new[,] {{false, false}, {false, false}};
            CollectionAssert.AreEqual(expected, game.Cells);
        }
Exemple #3
0
        public void GameSave(GameBoard gameBoard, string gameName)
        {
            var save = new Domain.Game()
            {
                GameName  = gameName,
                TimeSaved = DateTime.UtcNow,
                FirstMove = gameBoard.FirstMove,
                Width     = gameBoard.Width,
                Height    = gameBoard.Height,
                Moves     = gameBoard.PlayedColumns.Select(col => new Move()
                {
                    Column = col,
                }).ToList()
            };

            _savedGames.Add(save);

            var json = JsonSerializer.Serialize(_savedGames, new JsonSerializerOptions()
            {
                AllowTrailingCommas = true,
                WriteIndented       = true
            });

            File.WriteAllText("/home/pearu/Desktop/games.db", json);
        }
            public static void AreEqual(string expectedGameRepresentation, Game game)
            {
                var row = 0;
                var lines = expectedGameRepresentation.Split(new[] {Environment.NewLine, "\n"}, StringSplitOptions.RemoveEmptyEntries).ToList().ConvertAll(_ => _.Trim());
                var errors = expectedGameRepresentation.Split(new[] {Environment.NewLine, "\n"}, StringSplitOptions.RemoveEmptyEntries).ToList().ConvertAll(_ => _.Trim().ToCharArray());
                var hasErrors = false;

                foreach (var line in lines) {
                    var column = 0;
                    foreach (var code in line) {
                        switch (code) {
                            case '.':
                                if (game[row, column].IsAlive) {
                                    hasErrors = true;
                                    errors[row][column] = '*';
                                }
                                break;
                            case 'x':
                            case 'X':
                                if (game[row, column].IsDead) {
                                    hasErrors = true;
                                    errors[row][column] = '*';
                                }
                                break;
                        }
                        column++;
                    }
                    row++;
                }
                if (hasErrors) {
                    Assert.Fail("Games doesn't match:" + Environment.NewLine + ConvertToString(errors));
                }
            }
 public void CanSetAliveCells()
 {
     var game = new Game(2);
     game.GiveBirth(0, 0);
     game.GiveBirth(0, 1);
     AssertThat.AreEqual(@"xx
                           ..", game);
 }
 public Game Reconstitute(DataObjects.Game doGame)
 {
     var game = new Game(doGame.Size, doGame.Name);
     foreach (var cell in doGame.Cells) {
         game.GiveBirth(cell.Y, cell.X);
     }
     return game;
 }
 public void Save(Game game)
 {
     var session = database.OpenSession();
     var doGame = session.Query<DataObjects.Game>().SingleOrDefault(_ => _.Name == game.Name)
                  ?? new DataObjects.Game();
     new GameTranslator().Persist(game, doGame);
     session.SaveOrUpdate(doGame);
     session.Flush();
 }
 private static string CreateDescription(Game game)
 {
     return string.Format("{0}, {1} - {2}-{3} - {4} - {5}",
                          game.Slot.StartDateTime.DayOfWeek,
                          game.Slot.StartDateTime.ToShortDateString(),
                          game.Slot.StartDateTime.ToShortTimeString(),
                          game.Slot.EndDateTime.ToShortTimeString(),
                          game.Slot.Field.Size,
                          game.Slot.Field.Description);
 }
 private void PersistCells(Game game, DataObjects.Game doGame)
 {
     doGame.Cells.Clear();
     for (var row = 0; row < game.Size; row++) {
         for (var column = 0; column < game.Size; column++) {
             if (game[row, column].IsAlive) {
                 doGame.Cells.Add(new Cell {X = column, Y = row});
             }
         }
     }
 }
        public void AnyLiveCellWithZeroNeighborsDies()
        {
            var game = new Game(3);
            game.GiveBirth(1, 1);

            game.Step();

            AssertThat.AreEqual(@"...
                                  ...
                                  ...", game);
        }
        public static GameEditViewModel Load(Game game)
        {
            var vm = new GameEditViewModel
                         {
                             Description = CreateDescription(game),
                             Team1 = game.Team1.Id,
                             Team2 = game.Team2.Id
                         };

            return vm;
        }
        public void TestWithTwoNeighbors()
        {
            var game = new Game(3);
            game.GiveBirth(0, 0);
            game.GiveBirth(0, 1);
            game.GiveBirth(1, 1);

            game.Step();

            Assert.IsTrue(game.Cells[1, 1]);
        }
        public void AnyLiveCellWithThreeNeighborsLives()
        {
            var game = new Game(3);
            game.GiveBirth(0, 0);
            game.GiveBirth(0, 2);
            game.GiveBirth(2, 0);
            game.GiveBirth(1, 1);

            game.Step();

            Assert.IsTrue(game[1, 1].IsAlive);
        }
 public static Game AsGame(this string gameRepresentation, string name = "")
 {
     var lines = gameRepresentation.Split(new[] {Environment.NewLine, "\n"}, StringSplitOptions.RemoveEmptyEntries).ToList().ConvertAll(_ => _.Trim().ToCharArray());
     var game = new Game(lines.Count, name);
     for (var row = 0; row < lines.Count; row++) {
         var line = lines[row];
         for (var column = 0; column < line.Count(); column++) {
             if (line[column] == 'x' || line[column] == 'X') {
                 game.GiveBirth(row, column);
             }
         }
     }
     return game;
 }
        public void CanCreateGameAnySize()
        {
            var game = new Game(3);

            Assert.IsFalse(game.Cells[0, 0]);
            Assert.IsFalse(game.Cells[0, 1]);
            Assert.IsFalse(game.Cells[0, 2]);
            Assert.IsFalse(game.Cells[1, 0]);
            Assert.IsFalse(game.Cells[1, 1]);
            Assert.IsFalse(game.Cells[1, 2]);
            Assert.IsFalse(game.Cells[2, 0]);
            Assert.IsFalse(game.Cells[2, 1]);
            Assert.IsFalse(game.Cells[2, 1]);
        }
Exemple #16
0
        public async Task GetMatchData(Guid host)
        {
            Domain.Game g   = Handler.TryGetWaitingGame(host);
            string      msg = "";

            if (g == null)
            {
                msg = "Match not found! (Try refreshing)";
            }
            else if (g.Player2 != null)
            {
                msg = "This match already has a second player.";
            }

            await Clients.Caller.SendAsync("MatchData", msg, g);
        }
        public void TestAllCellsWithThreeNeighbors()
        {
            var game = new Game(3);
            game.GiveBirth(0, 0);
            game.GiveBirth(2, 0);
            game.GiveBirth(0, 2);

            game.Step();

            var expected = new[,] {
                {false, false, false},
                {false, true, false},
                {false, false, false}
            };
            CollectionAssert.AreEqual(expected, game.Cells);
        }
        public static void AddWaiting(IClientProxy client, string connectionId, Domain.Game game)
        {
            var    owner = game.Player1.Guid;
            string key   = GetKey(owner);

            _waiting[key] = new Waiting()
            {
                Game      = game,
                MatchInfo = new Domain.Matchmaking.MatchInfo()
                {
                    Name = game.GameName, OwnerId = owner, MatchId = game.GameGuid
                },
                Client = client,
            };
            _connectionToUserMap[connectionId] = key;
            _userToConnectionMap[key]          = connectionId;
        }
        public void GameIsSaved()
        {
            var database = new InMemoryDatabase();
            var game = new Game(2, "Test game");
            game.GiveBirth(0, 0);
            game.GiveBirth(0, 1);

            new GameService().Save(game, database);

            var session = database.OpenSession();
            var gameFromDb = session.Query<Infrastructure.DataObjects.Game>().Single(_ => _.Name == "Test game");
            Assert.AreEqual(2, gameFromDb.Cells.Count());

            Assert.AreEqual(0, gameFromDb.Cells.First().X);
            Assert.AreEqual(0, gameFromDb.Cells.First().Y);

            Assert.AreEqual(1, gameFromDb.Cells.Last().X);
            Assert.AreEqual(0, gameFromDb.Cells.Last().Y);
        }
Exemple #20
0
        public void GameSaveToDb(GameBoard board, string name)
        {
            var moveList = board.PlayedColumns.Select((col, i) => new Move()
            {
                Column = col
            }).ToList();

            var game = new Domain.Game()
            {
                GameName       = name,
                TimeSaved      = DateTime.Now,
                Moves          = moveList,
                FirstMove      = board.FirstMove,
                Height         = board.Height,
                SelectedColumn = board.SelectedColumn,
                Width          = board.Width
            };

            using (var ctx = new AppDbContext())
            {
                ctx.Games.Add(game);
                ctx.SaveChanges();
            }
        }
        public int[] GetBestPrizeNumber(Game[] games)
        {
            int[] result = {1,1,1};

            if (games.Count(p => p.Id % 9 == 0) == 0)
            {
                for (int i = 0; i < 3; i++)
                {
                    double[] prizes = { 0, 0, 0 };
                    string[] winners = games[i].Winner1.Split(',');
                    SetPossiblePrizesList(i, winners, ref prizes);

                    for (int j = 2; j <= 4; j++)
                    {
                        double[] testPrizes = { 0, 0, 0 };
                        switch (j)
                        {
                            case 2: winners = games[i].Winner2 != null ? games[i].Winner2.Split(',') : null; break;
                            case 3: winners = games[i].Winner3 != null ? games[i].Winner3.Split(',') : null; break;
                            case 4: winners = games[i].Winner4 != null ? games[i].Winner4.Split(',') : null; break;
                        }
                        if (winners != null)
                        {
                            SetPossiblePrizesList(i, winners, ref testPrizes);
                            if (testPrizes[i] < prizes[i])
                            {
                                prizes[i] = testPrizes[i];
                                result[i] = j;
                            }
                        }
                    }
                }
            }

            return result;
        }
Exemple #22
0
        // Save when starting game.
        public static void InitialSave(GameState gameState)
        {
            Console.Clear();
            Console.Write("Saving...");
            using var dbCtx = GetConnection();
            dbCtx.Database.Migrate();

            var playerOne = gameState.PlayerAState;
            var playerTwo = gameState.PlayerBState;

            var playerA = new Domain.Player
            {
                Name       = playerOne.GetName(),
                PlayerType = playerOne.GetPlayerType(),
                GameShips  = new List <GameShip>(),
            };
            var playerB = new Domain.Player
            {
                Name       = playerTwo.GetName(),
                PlayerType = playerTwo.GetPlayerType(),
                GameShips  = new List <GameShip>(),
            };

            var playerAShips = playerOne.GetShips()
                               .Select(ship => new GameShip()
            {
                ECellState = ship.CellState,
                Hits       = ship.Hits,
                IsSunk     = ship.IsSunk,
                Width      = ship.Width,
                Name       = ship.Name,
                Player     = playerA
            })
                               .ToList();

            var playerBShips = playerTwo.GetShips()
                               .Select(ship => new GameShip()
            {
                ECellState = ship.CellState,
                Hits       = ship.Hits,
                IsSunk     = ship.IsSunk,
                Width      = ship.Width,
                Name       = ship.Name,
                Player     = playerB
            })
                               .ToList();

            playerA.GameShips = playerAShips;
            playerB.GameShips = playerBShips;

            var gameOptions = new GameOption
            {
                Name             = DateTime.Now.ToString(CultureInfo.CurrentCulture),
                BoardWidth       = gameState.BoardWidthState,
                BoardHeight      = gameState.BoardHeightState,
                EShipsCanTouch   = gameState.ShipsCanTouchState,
                NextMoveAfterHit = gameState.GameOptions.GetNextMoveAfterHit(),
                NumberOfShips    = playerAShips.Count
            };

            var newGame = new Domain.Game
            {
                Description = $"{playerA.Name}&{playerB.Name}@{DateTime.Now}".Replace(" ", "_"),
                GameOption  = gameOptions,
                PlayerA     = playerA,
                PlayerB     = playerB,
                GameStates  = new List <Domain.GameState>()
            };

            var state = new Domain.GameState
            {
                PlayerABoardState = playerOne.GetSerializedGameBoardState(),
                PlayerBBoardState = playerTwo.GetSerializedGameBoardState(),
                NextMoveByPlayerA = true
            };

            newGame.GameStates.Add(state);
            dbCtx.Games.Add(newGame);
            dbCtx.SaveChanges();
        }
 public void Save(Game game, IDatabase database)
 {
     new GameRepository(database).Save(game);
 }
 public void Persist(Game game, DataObjects.Game doGame)
 {
     doGame.Size = game.Size;
     doGame.Name = game.Name;
     PersistCells(game, doGame);
 }
Exemple #25
0
 public async Task StartMatchmaking(Guid host, Domain.Game game) => Handler.AddWaiting(Clients.Caller, Context.ConnectionId, game);
 public static GameViewModel Load(Game game)
 {
     return Mapper.Map<Game, GameViewModel>(game);
 }
        private List<JObject> CreateRidJson(Game[] games, int state)
        {
            List<JObject> rids = new List<JObject>();

            foreach(Game game in games)
            {
                string[] coefficients = new string[game.NumberOfPlayers];
                switch (state)
                {
                    case 0:
                        {
                            coefficients = game.CoefficientsStep1.Split(','); break;
                        }
                    case 1:
                        {
                            coefficients = game.CoefficientsStep2.Split(','); break;
                        }
                    case 2:
                        {
                            coefficients = game.CoefficientsStep3.Split(','); break;
                        }
                    case 3:
                        {
                            var winners = game.Winner1.Split(',');
                            for (int i = 0; i < game.NumberOfPlayers; i++)
                            {
                                coefficients[i] = winners.Contains((i + 1).ToString()) ? "0.97" : "0";
                            }
                            break;
                        }

                }

            var table = TableNumber[game.NumberOfPlayers];

            for (int i = 0; i < game.NumberOfPlayers; i++)
                {
                    rids.Add(new JObject(
                        new JProperty("id","18291417"),
                        new JProperty("RID","117464212"),
                        new JProperty("ridName","Игрок " + table + i.ToString()),
                        new JProperty("odd0",coefficients[i]),
                        new JProperty("active","1")
                        ));
                }
            }

            return rids;
        }
 public void Load(string gameName)
 {
     CurrentGame = service.Load(gameName);
 }
        private string GetDesk(Game game, int state,int gameNumber,bool isStatic)
        {
            var desk = String.Empty;

            switch (state)
            {
                case 3:
                    {
                        desk = " " + GetCardById(Convert.ToInt16(GetFinalInfo(gameNumber, "river", game, isStatic ? new int[] { 1, 1, 1 } : riverNumber)));
                        goto case 2;
                    }
                case 2:
                    {
                        desk = " " + GetCardById(game.Turn) + desk;
                        goto case 1;
                    }
                case 1:
                    {
                        desk = GetCardById(game.Flop1) + " " + GetCardById(game.Flop2) + " " + GetCardById(game.Flop3) + desk;
                        break;
                    }
                default:
                    break;
            }

            return desk;
        }
        public int? ChangeGameState(int? round)
        {
            var current = ctx.GameStates.FirstOrDefault();
            Game[] games = null;
            int state = 0;

            if (current == null)
            {
                games = GetNextGames();
                //games = GetNextGames(); //for random
                SetState(new GameState()
                {
                    Table4PlayerId = games[0].Id,
                    Table6PlayerId = games[1].Id,
                    Table8PlayerId = games[2].Id,
                    State = 0,
                    StartTime = DateTime.Now,
                    Round = round.Value
                });
            }
            else
            {
                if (current.State != 3 && !round.HasValue)
                {
                    current.StartTime = DateTime.Now;
                    current.State++;
                    games = new Game[] { current.Table4Player, current.Table6Player, current.Table8Player };
                    state = current.State;
                }
                else
                {
                    //games = ctx.Games.Where(m => m.Id > current.Table8PlayerId).Take(3).ToArray().OrderBy(m => m.NumberOfPlayers).ToArray();
                    games = GetNextGames();
                    SetState(new GameState()
                    {
                        Table4PlayerId = games[0].Id,
                        Table6PlayerId = games[1].Id,
                        Table8PlayerId = games[2].Id,
                        State = 0,
                        StartTime = DateTime.Now,
                        Round = round ?? current.Round+1
                    });
                    ctx.Entry(current).State = EntityState.Deleted;
                }
            }

            try
            {
                ctx.SaveChanges();
                return state;
            }
            catch (Exception)
            {
                return null;
            }
        }
        private JProperty CreateGameJSON(Game game, int state,int gameNumber,bool isStatic,ref string finalWinners)
        {
            string[] coefficients = new string[game.NumberOfPlayers];
            switch (state)
            {
                case 0:
                    {
                        coefficients = game.CoefficientsStep1.Split(',');
                        break;
                    }
                case 1:
                    {
                        coefficients = game.CoefficientsStep2.Split(',');
                        break;
                    }
                case 2:
                    {
                        coefficients = game.CoefficientsStep3.Split(',');
                        break;
                    }
                case 3:
                    {
                        if (isStatic == false)
                        {
                            var winners = GetFinalInfo(gameNumber, "winner", game, isStatic ? new int[] { 1, 1, 1 } : riverNumber).Split(',');
                            for (int i = 0; i < game.NumberOfPlayers; i++)
                            {
                                coefficients[i] = winners.Contains((i + 1).ToString()) ? "0.97" : "0";
                                if (winners.Contains((i + 1).ToString()))
                                {
                                    finalWinners += (gameNumber + 1).ToString() + i.ToString() + ",";

                                }
                            }
                        }
                        break;
                    }

            }
            var table = TableNumber[game.NumberOfPlayers];

            var players = new JObject();

            if (state != 3)
            {
                for (int i = 0; i < game.NumberOfPlayers; i++)
                {
                    players.Add(CreatePlayerJSON(table, i, coefficients[i], (short)game.GetType().GetProperty("Player" + (i + 1).ToString() + "Card1").GetValue(game, null),
                        (short)game.GetType().GetProperty("Player" + (i + 1).ToString() + "Card2").GetValue(game, null), "0.000"));
                }
            }
            else
            {
                var winners = GetFinalInfo(gameNumber, "winner", game, isStatic ? new int[] { 1, 1, 1 } : riverNumber).Split(',');
                for (int i = 0; i < game.NumberOfPlayers; i++)
                {
                    players.Add(CreatePlayerJSON(table, i, (winners.Contains((i + 1).ToString())) ? "0.97" : "0", (short)game.GetType().GetProperty("Player" + (i + 1).ToString() + "Card1").GetValue(game, null),
                        (short)game.GetType().GetProperty("Player" + (i + 1).ToString() + "Card2").GetValue(game, null), (winners.Contains((i+1).ToString())) ? "1.000" : "0.000"));
                }
            }

            var gameJobject = new JObject(
                new JProperty("playersNo", game.NumberOfPlayers.ToString()),
                new JProperty("deskCards", GetDesk(game, state,gameNumber,isStatic)),
                new JProperty("players", players)
            );

            if (state == 3)
                gameJobject.Add(new JProperty("BH", GetFinalInfo(gameNumber, "winning", game, isStatic ? new int[] { 1, 1, 1 } : riverNumber)));

            var gamejson =
            new JProperty(table, gameJobject);

            return gamejson;
        }
        //public Game[] GetTable(out short state)
        //{
        //    state = 0;
        //    var current = ctx.GameStates.FirstOrDefault();
        //    Game[] games = null;
        //    if (current == null)
        //    {
        //        games = ctx.Games.Take(3).ToArray().OrderBy(m => m.NumberOfPlayers).ToArray();
        //        SetState(new GameState()
        //        {
        //            Table4PlayerId = games[0].Id,
        //            Table6PlayerId = games[1].Id,
        //            Table8PlayerId = games[2].Id,
        //            State = 0,
        //            StartTime = DateTime.Now
        //        });
        //    }
        //    else
        //    {
        //        if (true)
        //        {
        //            games = new Game[] { current.Table4Player, current.Table6Player, current.Table8Player };
        //            state = current.State;
        //        }
        //        else
        //        {
        //            if (current.State != 3)
        //            {
        //                state = ++current.State;
        //                current.StartTime = DateTime.Now;
        //                games = new Game[] { current.Table4Player, current.Table6Player, current.Table8Player };
        //            }
        //            else
        //            {
        //                games = ctx.Games.Where(m => m.Id > current.Table8PlayerId).Take(3).ToArray().OrderBy(m => m.NumberOfPlayers).ToArray();
        //                SetState(new GameState()
        //                {
        //                    Table4PlayerId = games[0].Id,
        //                    Table6PlayerId = games[1].Id,
        //                    Table8PlayerId = games[2].Id,
        //                    State = 0,
        //                    StartTime = DateTime.Now
        //                });
        //                ctx.Entry(current).State = EntityState.Deleted;
        //            }
        //        }
        //    }
        //    try
        //    {
        //        ctx.SaveChanges();
        //    }
        //    catch (Exception)
        //    {
        //        throw;
        //    }
        //    return games;
        //}
        public Game[] GetTable(out short state)
        {
            state = 0;
            var current = ctx.GameStates.FirstOrDefault();
            Game[] games = new Game[] { current.Table4Player, current.Table6Player, current.Table8Player };
            state = current!=null ? current.State : Convert.ToInt16(0);

            return games;
        }
 private string GetFinalInfo(int gameNumber, string info,Game game,int[] riverNumber)
 {
     switch (info)
     {
         case "winner":
             {
                 switch (riverNumber[gameNumber])
                 {
                     case 1: return game.Winner1;
                     case 2: return game.Winner2;
                     case 3: return game.Winner3;
                     case 4: return game.Winner4;
                 }
                 break;
             }
         case "winning":
             {
                 switch (riverNumber[gameNumber])
                 {
                     case 1: return game.Winning1_base.Name;
                     case 2: return game.Winning2_base.Name;
                     case 3: return game.Winning3_base.Name;
                     case 4: return game.Winning4_base.Name;
                 }
                 break;
             }
         case "river":
             {
                 switch (riverNumber[gameNumber])
                 {
                     case 1: return game.River1.ToString();
                     case 2: return game.River2.ToString();
                     case 3: return game.River3.ToString();
                     case 4: return game.River4.ToString();
                 }
                 break;
             }
     }
     return "";
 }
        public Game[] GetTable()
        {
            var current = ctx.GameStates.FirstOrDefault();
            Game[] games = new Game[] { current.Table4Player, current.Table6Player, current.Table8Player };

            return games;
        }