This class stores settings related to the physics and gameplay in a game match.
This class includes the maximum number of players, constants for gravity and bullet speed, reload rate, maximum health, acceleration and rotation rate of ships and other constants that are set when the game initializes. In later revisions of the game, these constants could be made to change based upon the map file. Presently they are static values.
Esempio n. 1
0
 internal Client(INetworkClient client, MatchConfig config) : base(client, config)
 {
     CurrentInput = new MatchInput(config);
     InputContext = new MatchInputContext(CurrentInput);
     NetworkClient.OnRecievedInputs += OnRecievedInputs;
     NetworkClient.OnRecievedState  += OnRecievedState;
 }
Esempio n. 2
0
        public RegexConfiguration GetConfiguration(string path)
        {
            MatchConfig   matcher  = Matcher.GetConfiguration(path);
            ReplaceConfig replacer = Replacer.GetConfiguration(path);

            return(new RegexConfiguration(matcher, replacer));
        }
 public void StartMatch(MatchConfig config)
 {
     using (var rental = ObjectPool <MatchStartMessage> .Shared.Borrow()) {
         rental.RentedObject.MatchConfig = config;
         Connection.Send(MessageCodes.MatchStart, rental.RentedObject);
     }
 }
 public void SendConfig(MatchConfig config)
 {
     using (var rental = ObjectPool <ServerUpdateConfigMessage> .Shared.Borrow()) {
         rental.RentedObject.MatchConfig = config;
         Connection.Send(MessageCodes.UpdateConfig, rental.RentedObject);
     }
 }
        public void SetConfiguration(Configuration config)
        {
            Config = config;
            var newConfig = new MatchConfig();

            newConfig.FieldSize      = new Coordinates(Config.GetValue <int>("mbc_field_width"), Config.GetValue <int>("mbc_field_height"));
            newConfig.NumberOfRounds = Config.GetValue <int>("mbc_match_rounds");

            var initShips = new ShipList();

            foreach (var length in Config.GetList <int>("mbc_ship_sizes"))
            {
                initShips.Add(new Ship(length));
            }
            newConfig.StartingShips = initShips;

            newConfig.TimeLimit = Config.GetValue <int>("mbc_player_timeout");

            newConfig.GameMode = 0;
            foreach (var mode in Config.GetList <GameMode>("mbc_game_mode"))
            {
                newConfig.GameMode |= mode;
            }
            if (!newConfig.GameMode.HasFlag(GameMode.Classic))
            {
                throw new NotImplementedException("The " + newConfig.GameMode.ToString() + " game mode is not supported.");
            }
            newConfig.Random = new Random();
            ApplyEvent(new MatchConfigChangedEvent(newConfig));
        }
        public void PositionForCompetitor_StepForwardGivesExpectedLocations()
        {
            var config = new MatchConfig
            {
                InitialRange                 = 100,
                StepForwardProportion        = 0.5f,
                MaximumLocationRandomisation = 0,
                MinimumLocationRandomisation = 0
            };

            var steps = Enumerable.Range(-3, 3);

            var results = steps.Select(p => config.PositionForCompetitor(1, 1, p));

            var expectedXLocations = new float[]
            {
                config.InitialRange * 8,
                config.InitialRange * 4,
                config.InitialRange * 2,
                config.InitialRange,
                config.InitialRange / 2,
                config.InitialRange / 4,
                config.InitialRange / 8
            };

            var i = 0;

            foreach (var position in results)
            {
                Assert.AreEqual(expectedXLocations[i], position.magnitude);

                i++;
            }
        }
Esempio n. 7
0
        public void VerifyStart()
        {
            var matchConfig = new MatchConfig(501, 1, false, 3, true, "opponent", true, 0);
            var controller  = new MatchConfigController(this.switcher.Object, this.dataBase.Object);

            controller.Start(matchConfig);
            this.switcher.Verify(x => x.StartMatch(matchConfig), Times.Once, "StartMatch was not called");
        }
Esempio n. 8
0
 internal Server(INetworkServer server, MatchConfig config) : base(server, config)
 {
     // TODO(james7132): Run server simulation for momentary state syncs
     NetworkServer.ReceivedInputs += OnRecievedInputs;
     CurrentInput = new MatchInput(config);
     NextInput    = new MatchInput(config);
     InputBuffer  = new MatchInput[1];
 }
 /// <summary>
 /// Wraps a controller and sets up the thread aborter on the current thread.
 /// </summary>
 /// <param name="controllerWrap"></param>
 public TimedController(MatchConfig config, IController controllerWrap)
 {
     controller = controllerWrap;
     Match      = config;
     controller = controllerWrap;
     controller.ControllerMessageEvent += ReceiveMessage;
     aborter = new ThreadTimeoutAborter(Thread.CurrentThread, Match.TimeLimit);
 }
 public async Task Execute(MatchConfig config, bool loadStage = true)
 {
     if (!IsValidConfig(config))
     {
         throw new ArgumentException("Attempted to start game with invalid config");
     }
     await RunGame(config, loadStage);
 }
Esempio n. 11
0
 GameScene(MatchConfig config)
 {
     //IMPLEMENT INITIALIZATION LISTS
     this.objectsG = new List<GameObject>();
     this.objectsNG = new List<GameObject>();
     GameScene.scene = this;
     this.config = config;
 }
Esempio n. 12
0
 public TestInputSource(MatchConfig config)
 {
     input = new MatchInput(config);
     for (int i = 0; i < input.PlayerCount; i++)
     {
         input.PlayerInputs[i].IsValid = true;
     }
 }
Esempio n. 13
0
 internal Client(INetworkClient client, MatchConfig config) : base(client, config)
 {
     NetworkClient.OnRecievedState  += OnRecievedState;
     NetworkClient.OnRecievedInputs += OnRecievedInputs;
     InputContext   = new MatchInputContext(config);
     InputHistory   = new InputHistory <MatchInput>(new MatchInput(config));
     NetworkConfig  = Config.Get <NetworkConfig>();
     InputSendTimer = 0;
 }
        protected override async Task RunGame(MatchConfig config, bool loadStage = true)
        {
            var results = await CreateMatch(config).RunMatch(config, loadStage);

            await Config.Get <SceneConfig>().MatchEndScene.LoadAsync();

            var viewFactories = Object.FindObjectsOfType <ViewFactory <PlayerMatchStats, PlayerConfig> >();
            await Task.WhenAll(results.PlayerStats.Select(p => BuildResultViews(p, viewFactories)));
        }
Esempio n. 15
0
 internal static MatchConfigModel Map(MatchConfig matchConfig)
 {
     return(new MatchConfigModel()
     {
         Id = matchConfig.Id,
         End = matchConfig.End,
         Start = matchConfig.Start
     });
 }
Esempio n. 16
0
        public static IMatchController CreateHost(this INetworkStrategy strategy,
                                                  NetworkHost host,
                                                  MatchConfig config)
        {
            var server = strategy.CreateServer(host.Server, config);
            var client = strategy.CreateClient(host.Client, config);

            return(new NetworkHostController(client, server));
        }
Esempio n. 17
0
        private static void Main(string[] args)
        {
            // ////////////////////////////////////////////////////////////// //
            // Create an instance of our Ultron thinker via ThinkerPrototype. //
            // If we created directly with new, it would not be properly      //
            // configured.                                                    //
            // ////////////////////////////////////////////////////////////// //

            // Create a configuration for a default ColorShapeLinks match
            MatchConfig mc = new MatchConfig();

            // Get the fully qualified name of our basic Ultron thinker
            string ultronFullName = typeof(UltronThinker).FullName;

            // Create a prototype for our thinker
            ThinkerPrototype tp = new ThinkerPrototype(ultronFullName, "", mc);

            // Create an instance of our basic Ultron thinker
            IThinker ultronThinker = tp.Create();

            // //////////////////////////////////////////////////////// //
            // Create a board so we can test how our thinker will play. //
            // //////////////////////////////////////////////////////// //

            // A cancellation token, will be ignored
            CancellationToken ct = new CancellationToken();

            // Create a ColorShapeLinks board with default size
            Board board = new Board();

            // Show initial board
            Console.WriteLine("\n=== Initial board ===\n");
            ShowBoard(board);

            // Make some moves manually
            board.DoMove(PShape.Round, 0);  // White plays round piece in col 0
            board.DoMove(PShape.Square, 4); // Red plays square piece in col 4
            board.DoMove(PShape.Square, 5); // White plays round piece in col 5

            // Show board after our three manual moves
            Console.WriteLine("\n=== Board after three manual moves ===\n");
            ShowBoard(board);

            // What move would Ultron make at this moment?
            FutureMove ultronMove = ultronThinker.Think(board, ct);

            // Show move
            Console.WriteLine($"-> Ultron will play {ultronMove}");

            // Make the move selected by Ultron
            board.DoMove(ultronMove.shape, ultronMove.column);

            // Show board after Ultron made its move
            Console.WriteLine("\n=== Board after Ultron made move ===\n");
            ShowBoard(board);
        }
 internal Server(INetworkServer server, MatchConfig config) : base(server, config)
 {
     NetworkServer.ReceivedInputs += OnRecievedInputs;
     NetworkServer.PlayerRemoved  += OnRemovePlayer;
     InputContext    = new MatchInputContext(config);
     InputHistory    = new InputHistory <MatchInput>(new MatchInput(config));
     NetworkConfig   = Config.Get <NetworkConfig>();
     ClientTimesteps = new Dictionary <int, uint>();
     StateSendTimer  = 0;
 }
Esempio n. 19
0
 public TestInputSource(MatchConfig config)
 {
     input = new MatchInput(config);
     for (int i = 0; i < input.PlayerCount; i++)
     {
         var playerInput = input[i];
         playerInput.IsValid = true;
         input[i]            = playerInput;
     }
 }
Esempio n. 20
0
 internal Server(INetworkServer server, MatchConfig config) : base(server, config)
 {
     NetworkServer.ReceivedInputs += OnRecievedInputs;
     InputContext    = new MatchInputContext(config);
     LatestInput     = new MatchInput[1];
     LatestInput[0]  = new MatchInput(config);
     InputHistory    = new InputHistory <MatchInput>(LatestInput[0]);
     NetworkConfig   = Config.Get <NetworkConfig>();
     ClientTimesteps = new Dictionary <uint, uint>();
     StateSendTimer  = 0;
 }
    public void GetResolution_continues_game_with_remaining_time()
    {
        var timeMatchRule = new TimeMatchRule();
        var config        = new MatchConfig {
            Stocks = 5, PlayerConfigs = new PlayerConfig[4]
        };
        var state = new MatchState(config)
        {
            Time = 100
        };

        Assert.AreEqual(null, timeMatchRule.GetResolution(state));
    }
    public void GetResolution_zero_time_results_in_timeout()
    {
        var timeMatchRule = new TimeMatchRule();
        var config        = new MatchConfig {
            Stocks = 5, PlayerConfigs = new PlayerConfig[4]
        };
        var state = new MatchState(config)
        {
            Time = 0
        };

        Assert.AreEqual(MatchResolution.Tie, timeMatchRule.GetResolution(state));
    }
Esempio n. 23
0
    // [Server] Loads this MatchManager's config from the MatchSetupController's final config.
    private IEnumerator LoadMatchConfigCoroutine(MatchSetupController controller)
    {
        Debug.Log(debugTag + "Grabbing config from MatchSetupController...");

        while (!controller.Ready)
        {
            yield return(null);
        }

        this.config = controller.InitialConfig;
        Debug.Log(debugTag + "Config loaded! Sending to Broadcaster...");
        matchDataBroadcaster.MatchConfigStr = JsonUtility.ToJson(controller.InitialConfig);
    }
    public void Simulate_each_simulate_decreases_remaining_time()
    {
        var timeMatchRule = new TimeMatchRule();
        var config        = new MatchConfig {
            Stocks = 5, PlayerConfigs = new PlayerConfig[4]
        };
        var state = new MatchState(config)
        {
            Time = 100
        };
        var input        = new MatchInput(config);
        var inputContext = new MatchInputContext(input);

        Assert.AreEqual(99, timeMatchRule.Simulate(state, inputContext).Time);
    }
Esempio n. 25
0
 public InControlInputSource(MatchConfig config)
 {
     this.config       = config;
     controllerMapping = new PlayerControllerMapping();
     input             = new MatchInput(config);
     ValidMask         = 0;
     for (var i = 0; i < config.PlayerCount; i++)
     {
         if (!config.PlayerConfigs[i].IsLocal)
         {
             continue;
         }
         ValidMask |= (byte)(1 << i);
     }
     Debug.Log($"Valid Mask: {ValidMask}");
 }
Esempio n. 26
0
    // public void CalcBaseValue()
    // {
    //  // Calculates the value of the resources built-in to the card
    //  if (this.category == "Tile")
    //  {
    //      this.baseValue = 0;
    //      int retrievedPrice = 0;
    //      ResourceInfo.pricesMut.TryGetValue(this.resource, out retrievedPrice);
    //      this.baseValue = (retrievedPrice * this.quantity); //Could be 0, that's okay

    //      // Calculates the value of the resources on cards in the stack, if any
    //      for (int i = 0; i < this.cardStack.Count; i++)
    //      {
    //          retrievedPrice = 0;

    //          if (this.cardStack[i].Subtitle == "Resource")
    //          {
    //              ResourceInfo.pricesMut.TryGetValue(this.cardStack[i].Resource, out retrievedPrice);
    //              this.baseValue += (retrievedPrice * this.cardStack[i].FooterValue);
    //          }
    //          else if (this.cardStack[i].Subtitle == "Investment" && !this.cardStack[i].PercFlag)
    //          {
    //              this.baseValue += this.cardStack[i].FooterValue;
    //          }
    //          else if (this.cardStack[i].Subtitle == "Sabotage" && !this.cardStack[i].PercFlag)
    //          {
    //              this.baseValue -= this.cardStack[i].FooterValue;
    //          } // if
    //      } // for cardStack size
    //  }
    //  else if (this.card.Category == "Market")
    //  {
    //      // Base Value will not be used for Market Cards - Reference ResourceInfo instead.
    //      // ResourceInfo.prices.TryGetValue(this.resource, out this.baseValue);
    //      // Debug.Log(debug + "Base value for " + this.resource + " was found to be " + this.baseValue);
    //  }

    // } // CalcBaseValue()

    // Calculates the value of the resources on cards in the stack, if any
    // public void CalcValueMod()
    // {
    //  if (this.category == "Tile")
    //  {
    //      this.valueMod = 0;
    //      for (int i = 0; i < this.cardStack.Count; i++)
    //      {
    //          if (this.cardStack[i].Subtitle == "Investment" && this.cardStack[i].PercFlag)
    //          {
    //              this.valueMod += this.cardStack[i].FooterValue;
    //          }
    //          else if (this.cardStack[i].Subtitle == "Sabotage" && this.cardStack[i].PercFlag)
    //          {
    //              this.valueMod -= this.cardStack[i].FooterValue;
    //          } // if-else
    //      } // for cardStack size
    //  }
    //  else if (this.category == "Market")
    //  {
    //      // NOTE: Currently, this is the same code for Tile. This is here incase it needs to
    //      // to change at some point.
    //      this.valueMod = 0;
    //      // Debug.Log("Stack Size  :" + this.stackSize);
    //      // Debug.Log("Stack Count: " + this.cardStack.Count);

    //      for (int i = 0; i < this.cardStack.Count; i++)
    //      {
    //          if (this.cardStack[i].Subtitle == "Investment" && this.cardStack[i].PercFlag)
    //          {
    //              this.valueMod += this.cardStack[i].FooterValue;
    //              // Debug.Log("Should be working! " + this.cardStack[i].footerValue);
    //          }
    //          else if (this.cardStack[i].Subtitle == "Sabotage" && this.cardStack[i].PercFlag)
    //          {
    //              this.valueMod -= this.cardStack[i].FooterValue;
    //              // Debug.Log("Should be working! -" + this.cardStack[i].footerValue);
    //              // this.valueMod -= this.cardStack[i].footerValue; // NOTE: Only do locally!
    //          } // if-else
    //      } // for cardStack size
    //  } // if-else category
    // } // CalcValueMod()

    // Calculates the total value this card, and updates the
    //	totalValue field on this GridUnit object
    // public void CalcTotalValue()
    // {
    //  // Debug.Log(debug + "Category: " + this.category);
    //  // Reset all value data and recalculate
    //  if (this.category == "Tile")
    //  {
    //      this.totalValue = 0;
    //      this.CalcBaseValue();
    //      this.CalcValueMod();

    //      this.totalValue = (double)this.baseValue
    //          + ((double)this.baseValue * ((double)this.valueMod) / 100d);

    //      // Debug.Log(debug + "[GridUnit] Tile " + this.x + ", " + this.y + " base value:  " +
    //      //  this.baseValue);
    //      // Debug.Log(debug + "[GridUnit] Tile " + this.x + ", " + this.y + " total value: " +
    //      //  this.totalValue);

    //      if (this.totalValue < 0)
    //      {
    //          this.bankrupt = true;
    //          // GameManager.BankruptTile(this);
    //      } // bankrupt check
    //  }
    //  else if (this.category == "Market")
    //  {

    //      // Reset all value data and recalculate
    //      this.totalValue = 0;
    //      this.CalcBaseValue();
    //      this.CalcValueMod();

    //      // Debug.Log(debug + "Resource: " + this.resource + " ----------------------");
    //      // Debug.Log(debug + "Old PriceMut: " + ResourceInfo.pricesMut[this.resource]);
    //      // // ResourceInfo.prices.TryGetValue(this.resource, out this.baseValue);
    //      // Debug.Log(debug + "Base Value  : " + ResourceInfo.prices[this.resource]);
    //      // Debug.Log(debug + "Value Mod   : " + this.valueMod);
    //      // Debug.Log(debug + "Calculating...");

    //      this.totalValue = (double)ResourceInfo.prices[this.resource]
    //          + ((double)ResourceInfo.prices[this.resource] * ((double)this.valueMod) / 100d);

    //      // Debug.Log("Total Value: " + this.totalValue);

    //      ResourceInfo.pricesMut[this.resource] = (int)this.totalValue;
    //      // cardDis.UpdateFooter(this, ResourceInfo.pricesMut[this.resource]);
    //      // tileObj.GetComponent<CardState>().footerValue = ResourceInfo.pricesMut[this.resource];

    //      // Debug.Log(debug + "New PriceMut: " + ResourceInfo.pricesMut[this.resource]);
    //      // // ResourceInfo.prices.TryGetValue(this.resource, out this.baseValue);
    //      // Debug.Log(debug + "Base Value  : " + ResourceInfo.prices[this.resource]);
    //      // Debug.Log(debug + "Value Mod   : " + this.valueMod);
    //  } // if tile
    // } // CalcTotalValue()

    // COROUTINES ##################################################################################

    // [Client/Server] Parses the Match Config from MatchDataBroadcaster
    public IEnumerator ParseMatchConfigCoroutine()
    {
        yield return(StartCoroutine(GrabMatchDataBroadCasterCoroutine()));

        while (this.config == null)
        {
            Debug.Log(debugTag + "Parsing Config...");
            this.config = JsonUtility.FromJson <MatchConfig>(matchDataBroadcaster.MatchConfigStr);
            Debug.Log(debugTag + "Config parsed as: " + this.config);

            if (this.config == null)
            {
                yield return(null);
            }
        }
    }
Esempio n. 27
0
 public InControlInputSource(MatchConfig config)
 {
     input        = new MatchInput(config);
     ValidMask    = 0;
     playerInputs = new IInputSource <PlayerInput> [config.PlayerCount];
     for (var i = 0; i < config.PlayerCount; i++)
     {
         playerInputs[i] = new InControlPlayerInputSource(config.PlayerConfigs[i]);
         if (!config.PlayerConfigs[i].IsLocal)
         {
             continue;
         }
         ValidMask |= (byte)(1 << i);
     }
     Debug.Log($"Valid Mask: {ValidMask}");
 }
Esempio n. 28
0
    void Awake()
    {
        // Look for the MatchManager first ---------------------------------------------------------
        referenceObj = GameObject.Find("MatchManager(Clone)");

        // If found, swipe the config info to know how many Player objects to destroy --------------

        if (referenceObj != null)
        {
            MatchDataBroadcaster mdb    = referenceObj.GetComponent <MatchDataBroadcaster>();
            MatchConfig          config = JsonUtility.FromJson <MatchConfig>(mdb.MatchConfigStr);

            for (int i = 1; i <= config.MaxPlayerCount; i++)
            {
                string playerStr;
                playerStr    = "Player (" + i + ")";
                referenceObj = GameObject.Find(playerStr);
                SafeDestroy(referenceObj);
            }
        }

        // Attempt to stop hosting and destroy the NetworkManager ----------------------------------

        referenceObj = GameObject.Find("NetworkManager");

        if (referenceObj != null)
        {
            NetworkManager networkManager = referenceObj.GetComponent <NetworkManager>();

            if (networkManager != null)
            {
                networkManager.StopHost();
                // networkManager.StopClient();
            }

            SafeDestroy(referenceObj);
        }

        // Continue by destroying the MatchManager, as it's not needed anymore ---------------------

        referenceObj = GameObject.Find("MatchManager(Clone)");
        SafeDestroy(referenceObj);
    }
Esempio n. 29
0
        protected override async Task InitializeMatch(MatchManager manager, MatchConfig config)
        {
            if (NetworkManager.IsServer)
            {
                NetworkManager.Server.PlayerUpdated += ServerHandleClientReady;
                foreach (var client in NetworkManager.Server.Clients)
                {
                    Debug.Log($"Setting {client.PlayerID} not ready");
                    client.IsReady = false;
                }
            }
            if (NetworkManager.IsClient)
            {
                NetworkManager.Client.OnServerReady += ClientHandleServerReady;
            }
            await base.InitializeMatch(manager, config);

            // Wait for remote players to be ready
            var tasks = new List <Task>();

            if (NetworkManager.IsClient && !NetworkManager.Client.IsServerReady)
            {
                Debug.Log("Client: Set to Ready.");
                NetworkManager.Client.SetReady(true);
                tasks.Add(ClientReady.Task);
            }
            if (NetworkManager.IsServer && !AllClientsAreReady)
            {
                Debug.Log("Waiting on clients...");
                tasks.Add(ServerReady.Task);
            }
            await Task.WhenAll(tasks);

            if (NetworkManager.IsClient)
            {
                NetworkManager.Client.OnServerReady -= ClientHandleServerReady;
            }
            if (NetworkManager.IsServer)
            {
                NetworkManager.Server.PlayerUpdated -= ServerHandleClientReady;
            }
        }
Esempio n. 30
0
    void Start()
    {
        Debug.Log(debugTag + "Initializing...");

        // [Client/Server]
        if (!hasAuthority)
        {
            this.config = JsonUtility.FromJson <MatchConfig>(matchDataBroadcaster.MatchConfigStr);
            Debug.Log(debugTag + "Grabbed config for client: " + matchDataBroadcaster.MatchConfigStr);

            Debug.Log(debugTag + "Creating Decks...");
            masterDeck        = new MasterDeck(config.DeckFlavor);
            masterDeckMutable = new MasterDeck(config.DeckFlavor);

            return;
        }

        // [Server]
        InitializeMatch();
    }
Esempio n. 31
0
        public IMatchController CreateMatchController(MatchConfig config)
        {
            var strategy = GetNetworkStrategy();

            if (IsHost)
            {
                return(strategy.CreateHost(Host, config));
            }
            else if (IsClient)
            {
                return(strategy.CreateClient(Client, config));
            }
            else if (IsServer)
            {
                return(strategy.CreateServer(Server, config));
            }
            else
            {
                return(new MatchController(config));
            }
        }