Exemplo n.º 1
0
        public void Show()
        {
            var form    = new Form();
            var painter = new MapPainter();
            var map     = MapLoader.LoadMap(
                Path.Combine(TestContext.CurrentContext.TestDirectory, @"..\..\..\..\maps\sample.json"));

            var ai        = new GreedyAi();
            var simulator = new GameSimulator(map.Map, new Settings());

            simulator.StartGame(new List <IAi> {
                ai
            });

            while (true)
            {
                var gameState = simulator.NextMove();
                painter.Map = gameState.CurrentMap;

                var panel = new ScaledViewPanel(painter)
                {
                    Dock = DockStyle.Fill
                };
                form.Controls.Add(panel);
                form.ShowDialog();
            }
        }
Exemplo n.º 2
0
 public FootballPlayer(Vector2Int Position, Team Team, int JerseyNumber, GameSimulator GameSimulator)
 {
     this.Position      = Position;
     this.Team          = Team;
     this.JerseyNumber  = JerseyNumber;
     this.GameSimulator = GameSimulator;
 }
Exemplo n.º 3
0
        private void RunSimulation(GameSimulator simulator)
        {
            simulator.GameStarted += state =>
            {
                Console.WriteLine("Started game");
                Console.Write(state);
            };
            simulator.GameEnded += stats =>
            {
                if (stats.WasWon)
                {
                    Console.WriteLine("Game won");
                }
                else
                {
                    Console.WriteLine("Game lost");
                }

                Console.WriteLine(stats.FinalState);
                Console.WriteLine();
            };

            var finalStats = simulator.Run();

            Console.WriteLine($"Games played\t\t\t: {finalStats.GamesPlayed}");
            Console.WriteLine($"Games won\t\t\t: {finalStats.Wins}");
            Console.WriteLine($"Total duration\t\t\t: {finalStats.TotalDurationMinutes} min");
            Console.WriteLine($"Average turns taken\t\t: {finalStats.AverageTurnsTaken}");
            Console.WriteLine($"Average game duration\t\t: {finalStats.AverageGameDurationMinutes} min");
            Console.WriteLine($"Average turn duration\t\t: {finalStats.AverageTurnDurationSeconds} sec");
            Console.WriteLine($"Most common number reached\t: {finalStats.MostCommonNumberReached}");
        }
Exemplo n.º 4
0
 private void StartNewGame()
 {
     State      = GameSimulator.RandomInitialState();
     TurnsTaken = 0;
     UpdateDisplay();
     ClearLabels();
 }
Exemplo n.º 5
0
    // Use this for initialization
    void Start()
    {
        GameSimulator simulator = new GameSimulator();

        simulator.Play();



        //Debug.Log(msg);
        List <Player> recentPlayers = PlayerManager.GetRecentPlayers(5);

        Debug.Log("These are recent 5 players logged in:");
        foreach (Player p in recentPlayers)
        {
            Debug.Log(p.Name + " logged in on:" + p.LastLogin.ToShortDateString());
        }

        string name          = simulator.GetRandomPlayerName();
        Player currentPlayer = PlayerManager.LoadPlayer(name);

        Debug.Log("Current player is:" + currentPlayer.Name);

        int bestScore = KicksManager.GetBestScore(currentPlayer.Name);

        Debug.Log("Best score for player:" + currentPlayer.Name + " is:" + bestScore.ToString());

        BallKick bestScoreOfAll = KicksManager.GetHighestScore();

        Debug.Log("Best score ever is:" + bestScoreOfAll.Score + " obtained by:" + bestScoreOfAll.PlayerName + " on date:" + bestScoreOfAll.DateRegistered.ToShortDateString());
    }
Exemplo n.º 6
0
    private void Awake()
    {
        var formation = GenerateFormation();

        GameSimulator = new GameSimulator(5, 10, ViewController);
        ViewController.Init(Dimensions.x, Dimensions.y, formation, GameSimulator);
    }
Exemplo n.º 7
0
        static void Main(string[] args)
        {
            GameMaster master = new GameMaster("Master");

            master.OutputActionEvent += OutputAction;

            var p1 = new Player("Kondo");

            p1.OutputActionEvent += OutputAction;
            master.AddPlayer(p1);

            var p2 = new Player("Ookura");

            p2.OutputActionEvent += OutputAction;
            master.AddPlayer(p2);

            var p3 = new Player("Yamazaki");

            p3.OutputActionEvent += OutputAction;
            master.AddPlayer(p3);

            var p4 = new Player("Nakazawa");

            p4.OutputActionEvent += OutputAction;
            master.AddPlayer(p4);

            var sim = new GameSimulator(master);

            sim.RunSimSync();

            Console.ReadLine();
        }
Exemplo n.º 8
0
        public void simulateImprovedFindingSecretNumber()
        {
            GameSimulator gs = new GameSimulator(setSize, secretNumber);

            gs.ImprovedFindSecretNumber();
            Assert.IsTrue(gs.Game.SecretNumberFound());
            Assert.AreEqual("Number found after 8 guess/es", gs.Game.ShowStatus());
        }
Exemplo n.º 9
0
        static void Main(string[] args)
        {
            var testFile  = File.ReadAllText(args[0]);
            var maps      = JsonConvert.DeserializeObject <List <string> >(testFile);
            var simulator = new GameSimulator();

            simulator.SimulateAllGames(maps);
        }
Exemplo n.º 10
0
        public void Initialize(String XMLFile)
        {
            CommandRequester c = new CommandRequester();
            GameSimulator s = new GameSimulator();
            replayer = new ReplayReader(XMLFile);

            GameController.Initialize(XMLFile, false, _frame, null, s, null, c);
            GameController.connectAsInputSource(replayer);
        }
Exemplo n.º 11
0
 public Example(IProjectionContext projectionContext, EventReader eventReader, GameSimulator simulator, IConsole console, GameOverToPlayerDistributorProjection distributorProjection, IrresponsibleGamblingDetectorProjection detectorProjection, IrresponsibleGamblerAlarmPublisher irresponsibleGamblerAlarmPublisher)
 {
     _projectionContext     = projectionContext;
     _eventReader           = eventReader;
     _simulator             = simulator;
     _console               = console;
     _distributorProjection = distributorProjection;
     _detectorProjection    = detectorProjection;
     _irresponsibleGamblerAlarmPublisher = irresponsibleGamblerAlarmPublisher;
 }
Exemplo n.º 12
0
 private void StartGame()
 {
     Grid = new Grid();
     foreach (var player in Players)
     {
         CommandHandler.QueueCommand(TCmdEnterGame.Construct(), player);
     }
     Simulator = new GameSimulator(this, 25);
     Logger.Log($"Game:{GameIndex} has started");
 }
Exemplo n.º 13
0
        public void TestValidTeamNames()
        {
            GameSimulator sut = new GameSimulator(new NCAA(), "Kansas State", "Oklahoma");

            Game simulatedGame = sut.SimulateGame();

            Assert.NotNull(simulatedGame);
            Assert.AreEqual(simulatedGame.GetHomeTeam().GetTeamName(), "Kansas State");
            Assert.AreEqual(simulatedGame.GetAwayTeam().GetTeamName(), "Oklahoma");
        }
Exemplo n.º 14
0
        public void Initialize(String XMLFile)
        {
            Monirator        m = new Monirator();
            CommandRequester c = new CommandRequester();
            NetworkManager   n = new NetworkManager();
            GameSimulator    s = new GameSimulator();

            GameController.Initialize(XMLFile, false, _frame, m, s, n, c);
            GameController.connectAsInputSource(n);
        }
Exemplo n.º 15
0
 private int Simulate(MCTSTree node)
 {
     GameSimulator.ResetSimulation(node.gameState);
     while (!GameSimulator.IsSimulationFinished())
     {
         List <CharacterActionType> actions        = GameSimulator.GetNextPossibleActions(node);
         CharacterActionType        selectedAction = GameSimulator.GetRandomAction(actions);
         GameSimulator.PlayAction(selectedAction);
     }
     return(GameSimulator.GetResult(id));
 }
Exemplo n.º 16
0
        public void IsActionLegal_WithNoAction_ReturnsFalse()
        {
            // Arrange
            var state = GameSimulator.RandomInitialState();

            // Act
            bool result = state.IsActionLegal(Player.Model.Action.NoAction);

            // Assert
            Assert.IsFalse(result);
        }
Exemplo n.º 17
0
        public void canCountWins()
        {
            //arrange
            var gameSimulator = new GameSimulator();

            //act

            var counterResult = gameSimulator.SimulateGame();

            //assert
        }
Exemplo n.º 18
0
        public void ApplyAction_WithNoAction_StateIsUnchanged()
        {
            // Arrange
            var state = GameSimulator.RandomInitialState();
            var copy  = new GameState(state);

            // Act
            state.ApplyAction(Player.Model.Action.NoAction);

            // Assert
            Assert.AreEqual(copy, state);
        }
Exemplo n.º 19
0
    public void Init(int height, int width, Formation formation, GameSimulator simulator)
    {
        GameSimulator = simulator;
        if (grid != null)
        {
            return;
        }

        this.height = height;
        this.width  = width;

        SetupGameBoard();
        SetupPlayers(formation);
    }
Exemplo n.º 20
0
        public async Task <GameDataModel> SimulateAsync(string gameId, TankModel tank1, TankModel tank2, GameMapModel map)
        {
            var gameData = await _resultsApiClient.GetScoreAsync(gameId);

            GameSimulator simulator = new GameSimulator(gameData.Id, Environment.GetEnvironmentVariable("WEATHER_API_URL"), map);

            simulator.GameFinished += OnGameFinished;

            gameData.Status = GameStatus.InProgress;
            await _resultsApiClient.UpdateAsync(gameData);

            simulator.Start(tank1, tank2);

            return(gameData);
        }
Exemplo n.º 21
0
        private void uxPredict_Click(object sender, EventArgs e)
        {
            GameSimulator gameSimulator = new GameSimulator(ncaa, uxHomeTeam.Text, uxAwayTeam.Text);
            Game          simulatedGame = gameSimulator.SimulateGame();

            if (simulatedGame == null)
            {
                MessageBox.Show(Messages.INVALID_TEAM_NAME_MESSAGE);
            }
            else
            {
                DisplayScore(simulatedGame);
                simulatedGame.GetHomeTeam().ClearProjectedPoints();
                simulatedGame.GetAwayTeam().ClearProjectedPoints();
            }
        }
        public static void Main()
        {
            var summary        = new SimulationSummary();
            var successfulRuns = 0;

            Console.WriteLine($"Simulating {SimulationConstants.SimulationsToRun} games");

            for (var i = 1; i <= SimulationConstants.SimulationsToRun; i++)
            {
                var players = new List <Player>()
                {
                    new Player("Player 1", new StrengthStrategy()),
                    new Player("Player 2", new HealerStrategy()),
                    new Player("Player 3", new PrimitiveStrategy())
                };
                var gameSummary = GameSimulator.SimulateGame(players, players[0]);

                if (gameSummary == null)
                {
                    continue;
                }

                summary.TotalRounds += gameSummary.RoundsInGame;
                if (gameSummary.WinningPlayer != null)
                {
                    summary.TotalHealth       += gameSummary.WinningPlayer.Health;
                    summary.TotalStrength     += gameSummary.WinningPlayer.Strength;
                    summary.TotalAgility      += gameSummary.WinningPlayer.Agility;
                    summary.TotalPerception   += gameSummary.WinningPlayer.Perception;
                    summary.TotalWeaponDamage += gameSummary.WinningPlayer.Weapon != null ? gameSummary.WinningPlayer.Weapon.Damage : 0;
                    TrackStringOccurence(summary.StrategiesUsed, gameSummary.WinningPlayer.Strategy.ToString());
                    TrackStringOccurence(summary.PlayerWinsByName, gameSummary.WinningPlayer.Name);
                    successfulRuns++;
                }

                if (i % (SimulationConstants.SimulationsToRun / 10) == 0)
                {
                    Console.WriteLine($"- {i}/{successfulRuns}");
                }
            }

            Console.WriteLine($"Number of Failed Simulations: {SimulationConstants.SimulationsToRun - successfulRuns}");

            summary.NumberOfSimulations = successfulRuns;
            PrintSimulationSummary(summary);
            Console.ReadLine();
        }
Exemplo n.º 23
0
 private void reset(bool playerStarts)
 {
     foreach (var btn in buttons)
     {
         btn.Enabled = true;
         btn.Text    = "";
     }
     if (playerStarts)
     {
         game = new GameSimulator();
     }
     else
     {
         game = new GameSimulator(BoardState.Cell.X);
         machineMoves();
     }
 }
Exemplo n.º 24
0
        public void Initialize(String XMLFile, bool isHost, Frame_Game frame, Monirator m, GameSimulator s, NetworkManager n, CommandRequester r)
        {
            TileMap  map      = new TileMap();
            RuleBook rulebook = new RuleBook();

            rulebook.LoadXMLData(XMLFile);

            monirator         = m;
            simulator         = s;
            NetworkController = n;
            CmdRequester      = r;

            simulator.Initialize(map);
            monirator.Initialize(map, rulebook);
            HostSession = isHost;

            frame.AddUnitEvent += new EventHandler(CmdRequester.AddButtonHandler);
        }
Exemplo n.º 25
0
        private void DoAction(Model.Action action)
        {
            bool wasActionTaken = false;

            if (_Mode == Mode.Play)
            {
                wasActionTaken = GameSimulator.TakeAction(State, action);
            }
            else if (_Mode == Mode.Guide && State.IsActionLegal(action))
            {
                State.ApplyAction(action);
            }

            if (wasActionTaken)
            {
                ++TurnsTaken;
                UpdateDisplay();
                DisplayEndOfGameIfNeeded();
            }
        }
Exemplo n.º 26
0
 public Form1()
 {
     InitializeComponent();
     game         = new GameSimulator();
     this.buttons = new Button[] {
         button1,
         button2,
         button3,
         button4,
         button5,
         button6,
         button7,
         button8,
         button9,
     };
     foreach (var button in buttons)
     {
         button.Click += buttonClick;
     }
     this.ActiveControl = null;
 }
Exemplo n.º 27
0
        static void Main(string[] args)
        {
            var userInputs = UserInputs.GenerateUserInput(args);

            var gameRules = new List <IRule>
            {
                new OverPopulation(),
                new Reproduction(),
                new UnderPopulation()
            };

            var randomCellPositions = NumberGenerator.Random(userInputs);

            Board board = new Board(userInputs);

            board.Initialize(randomCellPositions);

            Game game = new Game(board, gameRules);

            GameSimulator.Play(game);
        }
Exemplo n.º 28
0
        private void radioButton3_CheckedChanged(object sender, EventArgs e)
        {
            if ((sender as RadioButton).Checked)
            {
                ChangeMode(Mode.Simulate);
                ClearLabels();

                Simulator              = new GameSimulator(1, State, Player);
                Simulator.ActionTaken += SimulatorTookAction;
                Simulator.GameEnded   += SimulatedGameEnded;

                Task.Run(() =>
                {
                    Simulator.Run(() => _Mode != Mode.Simulate);
                });
            }
            else
            {
                Simulator.ActionTaken -= SimulatorTookAction;
                Simulator.GameEnded   -= SimulatedGameEnded;
            }
        }
Exemplo n.º 29
0
        /// <summary>
        /// ゲーム開始
        /// </summary>
        private void StartGame()
        {
            if (!CanStartGame())
            {
                return;
            }

            GameHistory.Clear();

            var master = new GameMaster(MasterName);

            master.OutputActionEvent += OutputParsonAction;

            foreach (var name in PlayerList)
            {
                var player = new Player(name);

                player.OutputActionEvent += OutputParsonAction;

                master.AddPlayer(player);
            }

            Sim = new GameSimulator(master, () =>
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    IsGamePlaying = false;
                    Sim           = null;
                    RaiseCommandCanExecute();
                });
            });

            Sim.RunSimAsync();
            IsGamePlaying = true;
            RaiseCommandCanExecute();
        }
Exemplo n.º 30
0
    /**
     * Responsible for drawing the settings window.
     */
    private void settingsWindow(int _windowID)
    {
        GUILayout.Label("Rows");
        grid_rows_ = GUILayout.TextField(grid_rows_);
        GUILayout.Label("Columns");
        grid_columns_ = GUILayout.TextField(grid_columns_);

        // Rebuilds the grid.
        if (GUILayout.Button("Rebuild"))
        {
            buildGrid();

            if (game_simulator_ != null)
            {
                game_simulator_.Dispose();
            }

            // By setting the game simulator to null I can ensure that no simulation is running whenever the "Start" button is clicked afterwards.
            game_simulator_ = null;

            b_is_simulation_running_ = false;
        }

        // Starts the simulation.
        if (GUILayout.Button("Start"))
        {
            b_is_simulation_running_ = true;

            // If the game simulator is set to null it means that we need a new game simulator object to run the simulation since we've most likely rebuilt the grid.
            if (game_simulator_ == null)
            {
                game_simulator_ = new GameSimulator(game_grid_, b_use_multithreading_, true);
            }
            else
            {
                game_simulator_.IsSimulationRunning = true;
                // I need to reset the threading environment since it might have changed if the user clicked on the "Step" button
                game_simulator_.UseThreading = b_use_multithreading_;
            }
        }

        // Stops the simulation
        if (GUILayout.Button("Stop"))
        {
            b_is_simulation_running_            = false;
            game_simulator_.IsSimulationRunning = false;
        }

        // Runs one step of the simulation
        if (GUILayout.Button("Step (Disables Multithreading)"))
        {
            b_is_simulation_running_ = false;
            b_use_multithreading_    = false;

            // I can only run valid simulations. If no simulations are found I start a new one without multithreading and ticking.
            if (game_simulator_ == null)
            {
                game_simulator_ = new GameSimulator(game_grid_, false, false);
            }
            else
            {
                game_simulator_.IsSimulationRunning = false;
                game_simulator_.UseThreading        = false;
            }

            GameSimulator.SimulationStep temp_simulation_step = game_simulator_.Simulate();
            game_grid_ = temp_simulation_step.cell_grid;
            last_simulation_duration_ = temp_simulation_step.time_to_simulate;

            updateGridGraphics();
        }

        if (GUILayout.Toggle(b_use_multithreading_, "Multithreading") != b_use_multithreading_)
        {
            b_use_multithreading_ = !b_use_multithreading_;

            // If we still have not created a simulation create a non ticking, single threaded one
            // Threading environment will be set immediately after and ticking should only start with the appropriate button
            if (game_simulator_ == null)
            {
                game_simulator_ = new GameSimulator(game_grid_, false, false);
            }

            game_simulator_.UseThreading = b_use_multithreading_;
        }

        GUILayout.Label("Last simulation time: " + last_simulation_duration_ + "ms");

        GUI.DragWindow();
    }