示例#1
1
        /// <summary>
        /// Initializes the underlying <see cref="MatchInfo"/> with values provided by a <see cref="Configuration"/>
        /// and associates the <see cref="MatchInfo"/> with the given <see cref="ControllerInformation"/>.
        /// </summary>
        /// <param name="config">The <see cref="Configuration"/> to load settings from.</param>
        /// <param name="controllerInfos">A variable number of <see cref="ControllerInformation"/>
        /// to associate with.</param>
        /// <exception cref="ControllerIncompatibleException">A controller is not designed for the
        /// configured <see cref="GameMode"/>.</exception>
        public CMatchInfo(Configuration config, params ControllerInformation[] controllerInfos)
        {
            //Get the game mode from the Configuration.
            DetermineGameMode(config);

            //Make sure all of the controllers are compatible with the given game mode.
            foreach (var controllerInfo in controllerInfos)
            {
                if (!controllerInfo.Capabilities.CompatibleWith(gameMode))
                {
                    throw new ControllerIncompatibleException(controllerInfo, gameMode);
                }
            }

            this.controllerNames = new List<string>();
            foreach (var controllerInfo in controllerInfos)
            {
                this.controllerNames.Add(controllerInfo.ToString());
            }

            //Configuration setting for a list of ships that the controllers start with.
            initShips = new ShipList(config.GetList<int>("mbc_ship_sizes").ToArray());

            //Configuration setting for the size of the field.
            fieldSize = new Coordinates(
                config.GetValue<int>("mbc_field_width"),
                config.GetValue<int>("mbc_field_height"));

            //Configuration setting for the amount of time a controller is allowed per method invoke.
            methodTimeLimit = config.GetValue<int>("mbc_timeout");
        }
        public async Task <IHttpActionResult> PutShipList(int id, ShipList shipList)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != shipList.Id)
            {
                return(BadRequest());
            }

            db.Entry(shipList).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ShipListExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
        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));
        }
示例#4
0
        public static void Main(string[] args)
        {
            var bot = new Bot();

            Console.WriteLine(@"
           ▄████████  ▄████████     ███      ▄█     ▄████████ 
          ███    ███ ███    ███ ▀█████████▄ ███    ███    ███ 
          ███    ███ ███    █▀     ▀███▀▀██ ███▌   ███    █▀  
          ███    ███ ███            ███   ▀ ███▌   ███        
         ▀███████████ ███            ███     ███▌ ▀███████████ 
          ███    ███ ███    █▄      ███     ███           ███ 
          ███    ███ ███    ███     ███     ███     ▄█    ███ 
          ███    █▀  ████████▀     ▄████▀   █▀    ▄████████▀  
                                                      "); //ЧСВ

            ReloadSettings();                             // Загрузим настройки

            ShipList.ReadFromXML(BotSettings.ShipXML);
            DonatorList.ReadFromXML(BotSettings.DonatorXML);
            UserList.ReadFromXML(BotSettings.WarningsXML);

            DonatorList.SaveToXML(BotSettings.DonatorXML); // Если вдруг формат был изменен, перезапишем XML-файлы.
            UserList.SaveToXML(BotSettings.WarningsXML);

            bot.RunBotAsync().GetAwaiter().GetResult();
        }
        protected internal override void PerformOperation()
        {
            IEnumerable <Coordinates> locations = ShipList.GetAllLocations(Position, Orientation, Ship.Length);

            foreach (Coordinates coords in locations)
            {
                if (coords.X < 0 || coords.Y < 0 || coords.X >= Ship.Owner.Match.FieldSize.X || coords.Y >= Ship.Owner.Match.FieldSize.Y)
                {
                    throw new InvalidEventException(this, String.Format("The ship {0} was placed out of bounds.", Ship));
                }
                foreach (Ship otherShip in Ship.Owner.Ships)
                {
                    if (otherShip.IsPlaced && otherShip.IsAt(coords))
                    {
                        throw new InvalidEventException(this, String.Format("The ship {0} conflicts with ship {1}.", Ship, otherShip));
                    }
                }
            }
            Ship.Location           = Position;
            Ship.Orientation        = Orientation;
            Ship.Locations          = new HashSet <Coordinates>(locations);
            Ship.RemainingLocations = new HashSet <Coordinates>(Ship.Locations);
            Ship.IsPlaced           = true;
            Ship.Active             = true;
        }
示例#6
0
    IEnumerator LoadShipAsync(string ship, int index)
    {
        ShipsJsonFactory shipFactory = new ShipsJsonFactory(this);
        string           baseUrl     = "https://api.spacexdata.com/v3/ships/";
        ShipList         shipList    = listParent.shipList;

        shipList.listItems = new List <ShipListItem>();
        shipFactory.FetchJson(baseUrl + ship);
        yield return(new WaitUntil(() => shipFactory.IsDone));

        if (!shipFactory.IsError)
        {
            Ships        shipsRoot = shipFactory.GetRootObject();
            ShipListItem item      = new ShipListItem();
            item.homePort    = shipsRoot.ship.home_port;
            item.imageUrl    = shipsRoot.ship.image;
            item.numMissions = shipsRoot.ship.missions.Length;
            item.shipName    = shipsRoot.ship.ship_name;
            item.shipType    = shipsRoot.ship.ship_type;
            shipList.listItems.Add(item);
        }
        shipList.SpawnList();
        if (index > 0 && index < coroutines.Count)
        {
            activeCoroutines.RemoveAll(value => value == coroutines[index]);
        }
    }
示例#7
0
 public FieldInfo()
 {
     Ships = new ShipList();
     Shots = new ShotList();
     ShipsLeft = new ShipList();
     ShotsAgainst = new ShotList();
 }
 private void PlaceShips(Event ev)
 {
     while (!ShipList.AreShipsPlaced(Player.Ships))
     {
         ShipList.PlaceShip(Player.Ships, RandomCoordinates(), RandomShipOrientation());
     }
 }
示例#9
0
        // Updates the list of ships to give orders to and targets when the system changes
        public void RefreshShips(int a, int b)
        {
            if (SelectedSystem == null || _starSystems.SelectedIndex == -1)
            {
                return;
            }

            _shipList.Clear();
            foreach (Entity ship in SelectedSystem.SystemManager.GetAllEntitiesWithDataBlob <ShipInfoDB>(_gameVM.CurrentAuthToken))
            {
                if (ship.HasDataBlob <PropulsionDB>())
                {
                    ShipList.Add(ship, ship.GetDataBlob <NameDB>().GetName(_gameVM.CurrentFaction));
                }
            }

            _shipList.SelectedIndex = 0;

            //RefreshTarget(0, 0);

            OnPropertyChanged(nameof(ShipList));
            OnPropertyChanged(nameof(MoveTargetList));

            OnPropertyChanged(nameof(SelectedShip));
            OnPropertyChanged(nameof(SelectedMoveTarget));

            return;
        }
        public async Task Leave(CommandContext ctx, [Description("Корабль")][RemainingText]
                                string name)
        {
            if (!ShipList.Ships[name].Members.ContainsKey(ctx.Member.Id))
            {
                await ctx.RespondAsync($"{Bot.BotSettings.ErrorEmoji} Вы не являетесь членом этого корабля!");

                return;
            }

            if (ShipList.Ships[name].Members[ctx.Member.Id].Type == MemberType.Owner)
            {
                await ctx.RespondAsync($"{Bot.BotSettings.ErrorEmoji} Вы должны передать права владельца корабля прежде чем покинуть его!");

                return;
            }

            if (!ShipList.Ships[name].Members[ctx.Member.Id].Status)
            {
                await ctx.RespondAsync($"{Bot.BotSettings.ErrorEmoji} Чтобы отклонить приглашение используйте команду `!no`!");

                return;
            }

            ShipList.Ships[name].RemoveMember(ctx.Member.Id);
            ShipList.SaveToXML(Bot.BotSettings.ShipXML);

            await ctx.Member.RevokeRoleAsync(ctx.Guild.GetRole(ShipList.Ships[name].Role));

            await ctx.RespondAsync($"{Bot.BotSettings.OkEmoji} Вы покинули корабль **{name}**!");
        }
        public async Task New(CommandContext ctx, [Description("Уникальное имя корабля")][RemainingText]
                              string name)
        {
            var doc = XDocument.Load("actions.xml");

            foreach (var action in doc.Element("actions").Elements("action"))
            {
                if (Convert.ToUInt64(action.Value) == ctx.Member.Id)
                {
                    await ctx.RespondAsync($"{Bot.BotSettings.ErrorEmoji} Вы не можете снова создать корабль!");

                    return;
                }
            }

            var ship = Ship.Create(name, 0, 0);

            ship.AddMember(ctx.Member.Id, MemberType.Owner);

            ShipList.SaveToXML(Bot.BotSettings.ShipXML);

            doc.Element("actions").Add(new XElement("action", ctx.Member.Id, new XAttribute("type", "ship")));
            doc.Save("actions.xml");

            await ctx.Guild.GetChannel(Bot.BotSettings.PrivateRequestsChannel)
            .SendMessageAsync($"**Запрос на создание корабля**\n\n" +
                              $"**От:** {ctx.Member.Mention} ({ctx.Member.Id})\n" +
                              $"**Название:** {name}\n" +
                              $"**Время:** {DateTime.Now.ToUniversalTime()}\n\n" +
                              $"Отправьте `{Bot.BotSettings.Prefix}confirm {name}` для подтверждения, или " +
                              $"`{Bot.BotSettings.Prefix}decline {name}` для отказа.");

            await ctx.RespondAsync(
                $"{Bot.BotSettings.OkEmoji} Успешно отправлен запрос на создание корабля **{name}**!");
        }
        public async Task Invite(CommandContext ctx, [Description("Участник")] DiscordMember member)
        {
            var ship = ShipList.GetOwnedShip(ctx.Member.Id);

            if (ship == null)
            {
                await ctx.RespondAsync($"{Bot.BotSettings.ErrorEmoji} Вы не являетесь владельцем корабля!");

                return;
            }

            if (ctx.Member == member)
            {
                await ctx.RespondAsync($"{Bot.BotSettings.ErrorEmoji} Нельзя пригласить самого себя!");

                return;
            }

            ship.AddMember(member.Id);
            ShipList.SaveToXML(Bot.BotSettings.ShipXML);

            await member.SendMessageAsync(
                $"Вы были приглашены на корабль **{ship.Name}** участником **{ctx.Member.Username}**! Отправьте " +
                $"`{Bot.BotSettings.Prefix}yes {ship.Name}` для принятия приглашения, или `{Bot.BotSettings.Prefix}no {ship.Name}` для отказа.");

            await ctx.RespondAsync(
                $"{Bot.BotSettings.OkEmoji} Успешно отправлено приглашение участнику {member.Username}!");
        }
 /// <summary>
 /// Checks if a player's ship are placed, and are valid within the parameters of the match.
 /// </summary>
 /// <param name="player"></param>
 /// <returns></returns>
 public bool ShipsValid(Player player)
 {
     return(player.Ships != null &&
            ShipList.AreEquivalentLengths(player.Ships, StartingShips) &&
            ShipList.AreShipsValid(player.Ships, FieldSize) &&
            ShipList.GetConflictingShips(player.Ships).Count() == 0);
 }
示例#14
0
        /// <summary>
        /// Initializes the underlying <see cref="MatchInfo"/> with values provided by a <see cref="Configuration"/>
        /// and associates the <see cref="MatchInfo"/> with the given <see cref="ControllerInformation"/>.
        /// </summary>
        /// <param name="config">The <see cref="Configuration"/> to load settings from.</param>
        /// <param name="controllerInfos">A variable number of <see cref="ControllerInformation"/>
        /// to associate with.</param>
        /// <exception cref="ControllerIncompatibleException">A controller is not designed for the
        /// configured <see cref="GameMode"/>.</exception>
        public CMatchInfo(Configuration config, params ControllerInformation[] controllerInfos)
        {
            //Get the game mode from the Configuration.
            DetermineGameMode(config);

            //Make sure all of the controllers are compatible with the given game mode.
            foreach (var controllerInfo in controllerInfos)
            {
                if (!controllerInfo.Capabilities.CompatibleWith(gameMode))
                {
                    throw new ControllerIncompatibleException(controllerInfo, gameMode);
                }
            }

            this.controllerNames = new List <string>();
            foreach (var controllerInfo in controllerInfos)
            {
                this.controllerNames.Add(controllerInfo.ToString());
            }

            //Configuration setting for a list of ships that the controllers start with.
            initShips = new ShipList(config.GetList <int>("mbc_ship_sizes").ToArray());

            //Configuration setting for the size of the field.
            fieldSize = new Coordinates(
                config.GetValue <int>("mbc_field_width"),
                config.GetValue <int>("mbc_field_height"));

            //Configuration setting for the amount of time a controller is allowed per method invoke.
            methodTimeLimit = config.GetValue <int>("mbc_timeout");
        }
示例#15
0
 public void AddMatchMakerShips(ShipList sl)
 {
     sl.ships.ForEach(delegate(string uuid, Ship ship)
     {
         GameObject matchShip = Instantiate(Resources.Load <GameObject>("MatchShip"), new Vector3(0, 0, 0), Quaternion.identity);
         matchShip.GetComponent <SB_MatchShip>().SetShip(ship);
         matchShip.transform.SetParent(m_MatchMakerShipContainer.transform);
     });
 }
示例#16
0
    public void LoadShipList()
    {
        var ships = Load <ShipList> (ShipListPath);

        if (ships != null)
        {
            shipList = ships;
        }
    }
示例#17
0
    private void OnMyShipClic()
    {
        ShipList view = Instantiate <ShipList>(pref.prefabShipListView);

        Window w = sys.NewWindow("myShipList", view.gameObject);

        w.Title = "Vaisseaux";
        w.Show();
    }
示例#18
0
    public async void OnShipBuilderMessage(object msg)
    {
        if (msg is Statistics)
        {
            Statistics stats = msg as Statistics;
            RoomManager.HandleStats(stats);
        }
        else if (msg is UnlockMessage)
        {
            Debug.Log("Unlock message received.");
            UnlockMessage unlocks = msg as UnlockMessage;
            PlayerData.SetUnlocks(unlocks);
        }
        else if (msg is ShipList)
        {
            Debug.Log("ShipList message received.");
            ShipList sl = msg as ShipList;
            PlayerData.myShips = sl.ships;
            RoomManager.HandleShipListUpdated();
        }
        else if (msg is ErrorMessage)
        {
            ErrorMessage er = msg as ErrorMessage;
            RoomManager.HandleErrorMessage(er.message);
        }
        else
        {
            IndexedDictionary <string, object> message = (IndexedDictionary <string, object>)msg;

            string action = message["action"].ToString();

            if (action == "message")
            {
                RoomManager.HandleMessage((string)message["message"]);
            }

            if (action == "ship_upgrade_success")
            {
                PlayerData.ResetUpgrades();
                RoomManager.HandleUpgradeSuccess();
            }

            if (action == "enter_match_making")
            {
                await shipBuilderRoom.Leave();

                shipBuilderRoom = null;

                Dictionary <string, object> options = new Dictionary <string, object>()
                {
                    { "token", PlayerPrefs.GetString("token") },
                    { "rank", PlayerData.CurrentShip().rank }
                };
                RoomManager.HandleEnterMatchMaking(options);
            }
        }
    }
示例#19
0
 /// <summary>
 ///     Place ships in specific locations
 /// </summary>
 private void placeShips()
 {
     // Smallest to largest
     ShipList.PlaceShip(Player.Ships, new Coordinates(9, 8), ShipOrientation.Vertical);   // 2 length
     ShipList.PlaceShip(Player.Ships, new Coordinates(0, 7), ShipOrientation.Horizontal); // 3 length
     ShipList.PlaceShip(Player.Ships, new Coordinates(7, 1), ShipOrientation.Vertical);   // 3 length
     ShipList.PlaceShip(Player.Ships, new Coordinates(1, 9), ShipOrientation.Horizontal); // 4 length
     ShipList.PlaceShip(Player.Ships, new Coordinates(2, 4), ShipOrientation.Horizontal); // 5 length
 }
示例#20
0
 public MatchConfig(MatchConfig copy)
 {
     StartingShips = new ShipList(copy.StartingShips);
     NumberOfRounds = copy.NumberOfRounds;
     FieldSize = copy.FieldSize;
     TimeLimit = copy.TimeLimit;
     GameMode = copy.GameMode;
     Random = copy.Random;
 }
示例#21
0
 public FieldInfo(FieldInfo copy)
 {
     if (copy != null)
     {
         Ships = new ShipList(copy.Ships);
         Shots = new ShotList(copy.Shots);
         ShipsLeft = new ShipList(copy.ShipsLeft);
         ShotsAgainst = new ShotList(copy.ShotsAgainst);
     }
 }
        /// <summary>
        /// Applies a configuration to the match.
        /// </summary>
        /// <param name="conf"></param>
        private void ApplyParameters(Configuration conf)
        {
            fieldSize      = new Coordinates(conf.GetValue <int>("mbc_field_width"), conf.GetValue <int>("mbc_field_height"));
            numberOfRounds = conf.GetValue <int>("mbc_match_rounds");

            startingShips = ShipList.ShipsFromLengths(conf.GetList <int>("mbc_ship_sizes"));
            timeLimit     = conf.GetValue <int>("mbc_player_timeout");

            gameModes = conf.GetList <GameMode>("mbc_game_mode");
        }
示例#23
0
    void InitializePlanet(SunBehaviour sun, Vector3 axis, float radius)
    {
        transform.localScale = Vector3.one * radius;
        this.radius          = radius;

        AddMyComponent <SatelliteBehaviour>()
        .SetSun(sun.transform, sun.radius, axis);

        ships = new ShipList(this, axis, .05f);
    }
示例#24
0
 public Register(Register copy)
     : base(copy)
 {
     if (copy != null)
     {
         Ships = new ShipList(copy.Ships);
         ShipsLeft = new ShipList(copy.ShipsLeft);
         Shots = new ShotList(copy.Shots);
         ShotsAgainst = new ShotList(copy.ShotsAgainst);
     }
 }
        public async Task <IHttpActionResult> GetShipList(int id)
        {
            ShipList shipList = await db.ShipLists.FindAsync(id);

            if (shipList == null)
            {
                return(NotFound());
            }

            return(Ok(shipList));
        }
示例#26
0
    public void ClearCoroutines()
    {
        ShipList shipList = listParent.shipList;

        shipList.RefreshList();
        for (int i = 0; i < activeCoroutines.Count; i++)
        {
            StopCoroutine(activeCoroutines[i]);
        }
        coroutines.Clear();
    }
        public async Task <IHttpActionResult> PostShipList(ShipList shipList)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            db.ShipLists.Add(shipList);
            await db.SaveChangesAsync();

            return(CreatedAtRoute("DefaultApi", new { id = shipList.Id }, shipList));
        }
示例#28
0
 /// <summary>
 /// Does nothing, but makes it so only deriving classes may create a <see cref="MatchInfo"/>.
 /// </summary>
 public MatchInfo(MatchConfig conf, List<Register> registers)
 {
     fieldSize = conf.FieldSize;
     gameMode = conf.GameMode;
     initShips = conf.StartingShips;
     methodTimeLimit = conf.TimeLimit;
     controllerNames = new List<string>();
     foreach (var reg in registers)
     {
         controllerNames.Add(reg.Name);
     }
 }
        public async Task ADelete(CommandContext ctx, [RemainingText] string name)
        {
            if (!ShipList.Ships.ContainsKey(name))
            {
                await ctx.RespondAsync($"{Bot.BotSettings.ErrorEmoji} Не найден корабль с названием **{name}**!");

                return;
            }

            var ship = ShipList.Ships[name];

            var role    = ctx.Guild.GetRole(ship.Role);
            var channel = ctx.Guild.GetChannel(ship.Channel);

            DiscordMember owner = null;

            foreach (var member in ship.Members.Values)
            {
                if (member.Type == MemberType.Owner)
                {
                    owner = await ctx.Guild.GetMemberAsync(member.Id);

                    break;
                }
            }

            ship.Delete();
            ShipList.SaveToXML(Bot.BotSettings.ShipXML);

            await ctx.Guild.DeleteRoleAsync(role);

            await channel.DeleteAsync();

            var doc = XDocument.Load("actions.xml");

            foreach (var action in doc.Element("actions").Elements("action"))
            {
                if (owner != null && Convert.ToUInt64(action.Value) == owner.Id)
                {
                    action.Remove();
                }
            }
            doc.Save("actions.xml");

            await ctx.RespondAsync($"{Bot.BotSettings.OkEmoji} Успешно удален корабль!");

            await ctx.Guild.GetChannel(Bot.BotSettings.ModlogChannel).SendMessageAsync(
                $"**Удаление корабля**\n\n" +
                $"**Модератор:** {ctx.Member}\n" +
                $"**Корабль:** {name}\n" +
                $"**Владелец:** {owner}\n" +
                $"**Дата:** {DateTime.Now.ToUniversalTime()} UTC");
        }
示例#30
0
        public ShipListDTO GetShipList(int shiplistid)
        {
            ShipListDTO listdto = null;

            using (var context = new XwingDataContext())
            {
                ShipList shiplist = context.ShipList
                                    .FirstOrDefault(sl => sl.Id == shiplistid);
                listdto = shiplist.ExtractDTO();
            }
            return(listdto);
        }
示例#31
0
 public MatchConfig(Match matchCopy)
 {
     if (matchCopy.StartingShips != null)
     {
         StartingShips = new ShipList(matchCopy.StartingShips.ToList());
     }
     NumberOfRounds = matchCopy.NumberOfRounds;
     FieldSize = matchCopy.FieldSize;
     TimeLimit = matchCopy.TimeLimit;
     GameMode = GameMode.Classic;
     Random = matchCopy.Random;
 }
        public async Task <IHttpActionResult> DeleteShipList(int id)
        {
            ShipList shipList = await db.ShipLists.FindAsync(id);

            if (shipList == null)
            {
                return(NotFound());
            }

            db.ShipLists.Remove(shipList);
            await db.SaveChangesAsync();

            return(Ok(shipList));
        }
示例#33
0
        private void HandleShipMove(Event ev)
        {
            ShipMovedEvent evCasted = (ShipMovedEvent)ev;
            Ship           ship     = evCasted.Ship;
            Player         player   = ship.Owner;

            if (ShipList.AreShipsPlaced(player.Ships))
            {
                waitList.Remove(player);
                if (waitList.Count == 0)
                {
                    waitSignal.Set();
                }
            }
        }
        public async Task No(CommandContext ctx, [Description("Корабль")][RemainingText] string name)
        {
            var ship = ShipList.Ships[name];

            if (!ship.IsInvited(ctx.Member.Id))
            {
                await ctx.RespondAsync(
                    $"{Bot.BotSettings.ErrorEmoji} Вы не были приглашены присоединиться к этому кораблю!");

                return;
            }

            ship.RemoveMember(ctx.Member.Id);
            ShipList.SaveToXML(Bot.BotSettings.ShipXML);

            await ctx.RespondAsync($"{Bot.BotSettings.OkEmoji} Вы успешно отклонили приглашение на корабль **{name}**!");
        }
示例#35
0
    void Start()
    {
        r = new Random();
        foreach (GachaDropPool g in dropPools)
        {
            range += g.Chance;
        }

        GameObject GameInstancer = GameObject.FindGameObjectWithTag("GameInstancer");

        if (GameInstancer != null)
        {
            instance = GameInstancer.GetComponent <scr_GameInstance> ();
            eList    = instance.engineList;
            sList    = instance.shipList;
        }
    }
示例#36
0
 public MainMenu(GameWindow Window, Profile _prof)
 {
     prof = _prof;
     foreach (var item in _prof.ShipsUnlocked)
     {
         var ship = new ShipList().Ships[item];
         ship.Unlock = true;
         prof.SUnlocked.Add(ship);
     }
     foreach (var item in _prof.WeaponsUnlocked)
     {
         var weapon = new WeaponList().Weapons[item];
         weapon.Unlock = true;
         prof.WUnlocked.Add(weapon);
     }
     MainWindow = Window;
     InitializeComponent();
 }
示例#37
0
        /// <summary>
        /// Initializes the underlying <see cref="MatchInfo"/> with values provided by a <see cref="Configuration"/>
        /// and associates the <see cref="MatchInfo"/> with the given <see cref="ControllerInformation"/>.
        /// </summary>
        /// <param name="config">The <see cref="Configuration"/> to load settings from.</param>
        /// <param name="controllerNames">A variable number of <see cref="ControllerInformation"/>
        /// to associate with.</param>
        /// <exception cref="ControllerIncompatibleException">A controller is not designed for the
        /// configured <see cref="GameMode"/>.</exception>
        public CMatchInfo(Configuration config)
        {
            //Get the game mode from the Configuration.
            DetermineGameMode(config);

            this.controllerNames = new List<string>();

            //Configuration setting for a list of ships that the controllers start with.
            initShips = new ShipList(config.GetList<int>("mbc_ship_sizes").ToArray());

            //Configuration setting for the size of the field.
            fieldSize = new Coordinates(
                config.GetValue<int>("mbc_field_width"),
                config.GetValue<int>("mbc_field_height"));

            //Configuration setting for the amount of time a controller is allowed per method invoke.
            methodTimeLimit = config.GetValue<int>("mbc_timeout");
        }
        protected internal override void PerformOperation()
        {
            if (!Player.Active)
            {
                throw new InvalidEventException(this, "The player is inactive.");
            }
            if (Shot.Coordinates < new Coordinates(0, 0) || Shot.Coordinates > Player.Match.FieldSize)
            {
                throw new InvalidEventException(this, "Invalid shot made.");
            }
            var shipHit = ShipList.GetShipAt(Shot);

            Player.ShotsMade.Add(Shot);
            if (shipHit != null)
            {
                shipHit.Hit(Shot.Coordinates);
            }
        }
 /// <summary>
 /// Passes the <paramref name="register"/> to the base constructor, stores the rest of the parameters,
 /// and generates a message based on the state of the given <see cref="ShipList"/>.
 /// </summary>
 /// <param name="register">A <see cref="ControllerRegister"/>.</param>
 /// <param name="newShips">The <see cref="ShipList"/> associated with the <see cref="ControllerRegister"/></param>
 public ControllerShipsPlacedEvent(ControllerID register, ShipList oldShips, ShipList newShips)
     : base(register)
 {
     Ships = newShips;
     PrevShips = oldShips;
 }
示例#40
0
        /// <summary>
        /// This method is called when the controller is required to place ships. It is given a collection
        /// of Ship objects that can be accessed.
        /// </summary>
        /// <param name="ships">A collection of Ship objects to place.</param>
        public override ShipList PlaceShips(ShipList initialShips)
        {
            //First we'll refer to the ships given to us through a single variable.
            var myShips = initialShips;

            //This loop will continue until all of the Ship objects have been placed.
            while (!myShips.ShipsPlaced)
            {
                //Get a random set of coordinates by calling the RandomCoordinates() method created earlier.
                var randomCoords = RandomCoordinates();

                //Get a random orientation for a ship to place by calling the RandomShipOrientation() method.
                var orientation = RandomShipOrientation();

                //Use the function within the ShipList object "myShips" to place a ship for the controller.
                //As explained in the PlaceShip() method of the ShipList, placing a ship at the randomly
                //generated coordinates may fail.
                myShips.PlaceShip(randomCoords, orientation, Register.Match.FieldSize);
            }

            return myShips;
        }
示例#41
0
        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));
        }
示例#42
0
 /// <summary>
 /// Called when the <see cref="ControllerRegister.Ships"/> in the <see cref="Controller.Register"/> must
 /// be placed. Refer to the rules of the <see cref="MatchInfo.GameMode"/> in the <see cref="Controller.Register"/>.
 /// </summary>
 public abstract ShipList PlaceShips(ShipList initialShips);