Exemplo n.º 1
0
        int y; // y position of the cursor in the grid

        #endregion Fields

        #region Constructors

        public MapMaker(Dictionary<string, Texture2D> imgs, SpriteFont txt)
        {
            mapImages = imgs;
            mapText = txt;
            rectangles = new Rectangle[Constants.ARRAYX, Constants.ARRAYY];
            buttons = new Button[Constants.ARRAYX, Constants.ARRAYY];
            for (int i = 0; i < Constants.ARRAYY; i++)
            {
                for (int j = 0; j < Constants.ARRAYX; j++)
                {
                    // fill the rectangle and button arrays
                    rectangles[j, i] = new Rectangle((j * (Constants.TILE_WIDTH / 2)), (i * (Constants.TILE_HEIGHT / 2)),
                        (Constants.TILE_WIDTH / 2), (Constants.TILE_HEIGHT / 2));
                    buttons[j, i] = new Button();
                    // make each button default to a blank tile
                    buttons[j, i].Thing = '.';
                }
            }

            x = 0;
            y = 0;
            levelSelected = 1;
            nameBox = new Rectangle(430, 410, 150, 50); // set the location/dimensions of the name box
            name = "";
            error = false;
            errMsg = "ERROR"; // set basic error message
            mapState = MapState.Editing;
        }
        MapResult Map(ReportingTask<MapResult> taskContext, MapState state)
        {
            // Locally register all tracks from iTunes
            taskContext.Description = "Fetching iTunes library playlist";
            var iTunesTracks = iTunes.LibraryPlaylist.Tracks;
            var trackCount = iTunesTracks.Count;

            taskContext.TotalItems = trackCount + state.Scrobbles.Count();

            // No concurrent dictionaries in this CTP, so this has to be sequential...
            for (int i = 1; i <= trackCount; i++)
            {
                if (taskContext.Task.IsCanceled)
                    return null;

                var track = new ItunesLibraryTrack(iTunesTracks.get_ItemByPlayOrder(i));
                taskContext.Description = "Registering iTunes track '" + track.Artist + " - " + track.Title + "'";

                RegisterLibraryTrack(track, state);

                taskContext.ReportItemCompleted();
            }

            // Find and update tracks
            FindAndUpdateTracks(taskContext, state);

            // "Early" out
            if (taskContext.Task.IsCanceled)
                return null;

            // Compose and return
            return new MapResult(state.FuzzyMatches.ToArray(),
                state.Updated, state.AlreadyUpToDate, state.NotFound, state.UpdateFailed, state.Errors.ToArray());
        }
Exemplo n.º 3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GlobalState"/> class.
        /// </summary>
        GlobalState()
        {
            ThreadAsserts.IsMainThread();

            // Load all sorts of stuff
            _contentManager = NetGore.Content.ContentManager.Create();

            var dbConnSettings = new DbConnectionSettings();
            _dbController =
                dbConnSettings.CreateDbControllerPromptEditWhenInvalid(x => new ServerDbController(x.GetMySqlConnectionString()),
                    x => dbConnSettings.PromptEditFileMessageBox(x));

            _defaultRenderFont = ContentManager.LoadFont("Font/Arial", 16, ContentLevel.Global);

            Character.NameFont = DefaultRenderFont;

            GrhInfo.Load(ContentPaths.Dev, ContentManager);
            AutomaticGrhDataSizeUpdater.Instance.UpdateSizes();

            _mapGrhWalls = new MapGrhWalls(ContentPaths.Dev, x => new WallEntity(x));

            // Load the child classes
            _mapState = new MapState(this);

            // Grab the audio manager instances, which will ensure that they are property initialized
            // before something that can't pass it an ContentManager tries to get an instance
            AudioManager.GetInstance(ContentManager);

            // Set the custom UITypeEditors
            CustomUITypeEditors.AddEditors(DbController);

            // Set up the timer
            _timer = new Timer { Interval = 1000 / 60 };
            _timer.Tick += _timer_Tick;
        }
 public void Render(MapObject mapObject)
 {
     MapPoint cellPoint = new MapPoint(0, 0, 0);
         Map map = new Map(1, MapSize.One);
         map[cellPoint] = new MapCell(new MapPlace(), null);
         if (mapObject is MapPlace)
         {
             map[cellPoint].Place = mapObject as MapPlace;
         }
         if (mapObject is MapWall)
         {
             map[cellPoint].SetWall(MapDirection.North, mapObject as MapWall);
             map[cellPoint].SetWall(MapDirection.East, mapObject as MapWall);
             map[cellPoint].SetWall(MapDirection.West, mapObject as MapWall);
             map[cellPoint].SetWall(MapDirection.South, mapObject as MapWall);
         }
         MapState mapState = new MapState(map);
         if (mapObject is MapActiveObject)
         {
             mapState.AddActiveObject(mapObject as MapActiveObject, cellPoint);
         }
         GameMap gameMap = new GameMap(mapState);
         Renderer.SetMap(gameMap, new MapCellRange(cellPoint, cellPoint));
         Renderer.Render();
 }
Exemplo n.º 5
0
        public void Update(MapState state, GameManger Manager)
        {
            List<Fleet> fleets = state.Fleets;
            foreach (Planet myPlanet in state.GetMyPlanets(PlayerType.AI))
            {
                Planet Attack = null;
                float LowestScore = float.PositiveInfinity;

                foreach (Planet planet in state.GetEnemyPlanets(PlayerType.AI))
                {
                    float Score = Vector2.Distance(planet.Position, myPlanet.Position) * (((float)planet.Forces[planet.Owner]) / myPlanet.Forces[myPlanet.Owner])/myPlanet.Growth;
                    if (Score < LowestScore)
                    {
                        Attack = planet;
                        LowestScore = Score;
                    }
                }

                if (Attack != null)
                {
                    if ((Attack.Forces[Attack.Owner] + 1) / Manager.AIAttackBias < myPlanet.Forces[myPlanet.Owner])
                    {
                        Manager.SendFleet((int)((Attack.Forces[Attack.Owner] + 1) / Manager.AIAttackBias), myPlanet, Attack);
                    }
                }
            }
        }
Exemplo n.º 6
0
    void Awake()
    {
        if (!buildDecisionsChromosome) buildDecisionsChromosome = GetComponent<BuildDecisionsChromosome>();
        if (!pathLine) pathLine = GetComponent<LineRenderer>();
        if (!objectPool) objectPool = FindObjectOfType<ObjectPool>();

        BuildGrid();
        state = MapState.Idle;
    }
Exemplo n.º 7
0
 public MapEditorModel()
 {
     State = new MapState();
     State.Layers = new ObservableCollection<Layer>();
     UndoHistory = new ObservableCollection<EditOperation>();
     Placer = null;
     System.Reflection.Assembly asm = this.GetType().Assembly;
     System.Reflection.AssemblyName name = asm.GetName();
     Title = "MapTuner build " + name.Version.ToString();
 }
Exemplo n.º 8
0
        public void Update(MapState state, GameManger Manager)
        {
            List<Fleet> fleets = state.Fleets;
            foreach (Planet myPlanet in state.GetMyPlanets(PlayerType.AI))
            {
                Planet Attack = null;
                float LowestScore = float.PositiveInfinity;

                foreach (Planet planet in state.GetEnemyPlanets(PlayerType.AI))
                {

                    bool Flying = false;
                    foreach (Fleet f in fleets)
                    {
                        if (f.Owner == PlayerType.AI)
                        {
                            if (f.Destination.ID == planet.ID)
                            {
                                Flying = true;
                                break;
                            }
                        }
                    }

                    if (Flying)
                        continue;
                    float Score = 2*Vector2.Distance(planet.Position, myPlanet.Position)*(((float)planet.Forces[planet.Owner])/myPlanet.Forces[myPlanet.Owner]);
                    if (planet.Owner == PlayerType.Player)
                    {
                        Score *= 10;
                    }
                    if (Score < LowestScore)
                    {
                        Attack = planet;
                        LowestScore = Score;
                    }
                }

                if (Attack != null)
                {
                    if ((Attack.Forces[Attack.Owner]+1)/Manager.AIAttackBias < myPlanet.Forces[myPlanet.Owner]/2)
                    {
                        Manager.SendFleet(myPlanet.Forces[myPlanet.Owner] / 2, myPlanet, Attack);
                    }
                    return;
                }
            }
        }
Exemplo n.º 9
0
 public MapState Clone()
 {
     MapState s = new MapState();
     s.Selection = new Selection();
     foreach(var c in Selection)
         s.Selection.Add(c);
     s.Layers = new ObservableCollection<Layer>();
     foreach(var l in Layers)
     {
         var c = l.Clone();
         s.Layers.Add(c);
         if (ActiveLayer == l)
             s.ActiveLayer = c;
     }
     return s;
 }
Exemplo n.º 10
0
 public override MapState Execute(MapState state, Selection selection)
 {
     var newLayer = new Layer() { LayerName = "New layer", Map = (Map)state.ActiveLayer.Map.Clone(), Visible=true };
     foreach (var tile in newLayer.Map.GetAllTiles())
     {
         tile.IsEmpty = true;
         foreach (var c in selection)
             if (c.X == tile.X && c.Y == tile.Y)
                 tile.IsEmpty = false;
     }
     state.Selection = new Selection();
     state.Layers.Insert(0, newLayer);
     //state.ActiveLayer.Visible = false;
     state.ActiveLayer = state.Layers[0];
     return state;
 }
Exemplo n.º 11
0
        public void OnMapReady(MapboxMap p0)
        {
            var mapboxMap = p0;

            mapboxMap.SetStyle(new Style.Builder().FromUrl(GetString(Resource.String.navigation_guidance_day)), new MapboxMapSetStyleListener((Style) =>
            {
                mapState      = MapState.INFO;
                navigationMap = new NavigationMapboxMap(mapView, mapboxMap);

                // For Location updates
                InitializeLocationEngine();

                // For navigation logic / processing
                InitializeNavigation(mapboxMap);
                navigationMap.UpdateCameraTrackingMode(NavigationCamera.NavigationTrackingModeNone);
                navigationMap.UpdateLocationLayerRenderMode(RenderMode.Gps);

                // For voice instructions
                InitializeSpeechPlayer();
            }));
        }
Exemplo n.º 12
0
 public static void InitMap(MapState mapState)
 {
     instance.tilemap.ClearAllTiles();
     foreach (Vector3Int coord in mapState.Coordinates())
     {
         HexState hex = mapState.GetHexState(coord);
         if (!hex.visible)
         {
             instance.tilemap.SetTile(coord, instance.blackTile);
         }
         else if (hex.terrain.Equals("GRASS"))
         {
             instance.tilemap.SetTile(coord, instance.grassTile);
         }
         else
         {
             instance.tilemap.SetTile(coord, instance.waterTile);
         }
     }
     Debug.Log("Map initialized");
 }
Exemplo n.º 13
0
        public void Apply_Attack10vs20_AreEqual()
        {
            var mapstate = new MapState(2);

            mapstate.Set(1, (ushort)PlayerType.player1, 11);
            mapstate.Set(2, (ushort)PlayerType.player2, 20);

            Assert.AreEqual(PlayerType.player1, mapstate.Owner(1), "Owner[1], Before");
            Assert.AreEqual(11, mapstate.Armies(1), "Armies[1], Before");

            Assert.AreEqual(PlayerType.player2, mapstate.Owner(2), "Owner[2], Before");
            Assert.AreEqual(20, mapstate.Armies(2), "Armies[2], Before");

            mapstate.Apply(Move.CreateTransfer(PlayerType.player1, 1, 2, 10), this.TestMap);

            Assert.AreEqual(PlayerType.player1, mapstate.Owner(1), "Owner[2], After");
            Assert.AreEqual(1, mapstate.Armies(1), "Armies[1], After");

            Assert.AreEqual(PlayerType.player2, mapstate.Owner(2), "Owner[2], After");
            Assert.AreEqual(14, mapstate.Armies(2), "Armies[2], After");
        }
Exemplo n.º 14
0
        public void Apply_Transform7_AreEqual()
        {
            var mapstate = new MapState(2);

            mapstate.Set(1, (ushort)PlayerType.player1, 13);
            mapstate.Set(2, (ushort)PlayerType.player1, 03);

            Assert.AreEqual(PlayerType.player1, mapstate.Owner(1), "Owner[1], Before");
            Assert.AreEqual(13, mapstate.Armies(1), "Armies[1], Before");

            Assert.AreEqual(PlayerType.player1, mapstate.Owner(2), "Owner[2], Before");
            Assert.AreEqual(3, mapstate.Armies(2), "Armies[2], Before");

            mapstate.Apply(Move.CreateTransfer(PlayerType.player1, 1, 2, 7), this.TestMap);

            Assert.AreEqual(PlayerType.player1, mapstate.Owner(1), "Owner[2], After");
            Assert.AreEqual(06, mapstate.Armies(1), "Armies[1], After");

            Assert.AreEqual(PlayerType.player1, mapstate.Owner(2), "Owner[2], After");
            Assert.AreEqual(10, mapstate.Armies(2), "Armies[2], After");
        }
Exemplo n.º 15
0
    private void ManageState()                   //Changes the states based on player input
    {
        var nextStates = state1.GetNextStates(); //Gets list of available character states for P1

        if (Input.GetKeyDown(KeyCode.A))
        {
            Debug.Log("Left Pressed");
            state1 = nextStates[1];
        }
        else if (Input.GetKeyDown(KeyCode.D))
        {
            Debug.Log("Right Pressed");
            state1 = nextStates[0];
        }

        nextStates = state2.GetNextStates(); //Gets list of available character states for P2

        if (Input.GetKeyDown(KeyCode.LeftArrow))
        {
            Debug.Log("A Pressed");
            state2 = nextStates[1];
        }
        else if (Input.GetKeyDown(KeyCode.RightArrow))
        {
            Debug.Log("D Pressed");
            state2 = nextStates[0];
        }

        var mapnextStates = mp.GetNextStates(); //Gets list of available map states

        if (Input.GetKeyDown(KeyCode.R))
        {
            Debug.Log("R Pressed");
            mp = mapnextStates[0];
        }

        Char1.GetComponent <Image>().sprite = state1.GetStateSprite(); //Updates the images on the screen based on current state
        Char2.GetComponent <Image>().sprite = state2.GetStateSprite();
        MapIm.GetComponent <Image>().sprite = mp.GetStateSprite();
    }
Exemplo n.º 16
0
        MapResult Map(ReportingTask <MapResult> taskContext, MapState state)
        {
            // Locally register all tracks from WMP
            var library = (IWMPMediaCollection2)WindowsMediaPlayer.mediaCollection;

            taskContext.Description = "Fetching WMP library items";
            var wmpTracks = library.getByAttribute(MediaTypeAttribute, AudioMediaType);

            var itemCount = wmpTracks.count;

            taskContext.TotalItems = itemCount + state.Scrobbles.Count();

            for (int i = 0; i < itemCount; i++)
            {
                if (taskContext.CancellationTokenSource.Token.IsCancellationRequested)
                {
                    taskContext.CancellationTokenSource.Token.ThrowIfCancellationRequested();
                }

                var track = new WmpLibraryTrack(wmpTracks.get_Item(i));
                taskContext.Description = "Registering WMP track '" + track.Artist + " - " + track.Title + "'";

                RegisterLibraryTrack(track, state);

                taskContext.ReportItemCompleted();
            }

            // Find and update tracks
            FindAndUpdateTracks(taskContext, state);

            // "Early" out
            if (taskContext.CancellationTokenSource.Token.IsCancellationRequested)
            {
                taskContext.CancellationTokenSource.Token.ThrowIfCancellationRequested();
            }

            // Compose and return
            return(new MapResult(state.FuzzyMatches.ToArray(),
                                 state.Updated, state.AlreadyUpToDate, state.NotFound, state.UpdateFailed, state.Errors.ToArray()));
        }
Exemplo n.º 17
0
        public static string ToUnitTestSetup(this MapState state)
        {
            var sb = new StringBuilder();

            sb.AppendFormat("state.SetRoundSubRoundAndPlayerToMove({0}, SubRoundType.{1}, PlayerType.{2});",
                            state.Round,
                            state.SubRound,
                            state.PlayerToMove)
            .AppendLine();

            var regions = state.ToDebug();

            foreach (var region in regions.OrderBy(r => r.Owner))
            {
                sb.AppendFormat("state.Set({0}, {1}, {2});",
                                region.Id,
                                (int)region.Owner,
                                region.Armies)
                .AppendLine();
            }
            return(sb.ToString());
        }
Exemplo n.º 18
0
 public override MapState Execute(MapState state, Selection selection)
 {
     if (KeepInside)
     {
         int minx = int.MaxValue, miny = int.MaxValue, maxx = int.MinValue, maxy = int.MinValue;
         foreach (var tile in state.ActiveLayer.Map.GetAllTiles())
         {
             if (!tile.IsEmpty)
             {
                 minx = Math.Min(minx, tile.X);
                 miny = Math.Min(miny, tile.Y);
                 maxx = Math.Max(maxx, tile.X);
                 maxy = Math.Max(maxy, tile.Y);
             }
         }
         if (minx + DeltaX < 0) DeltaX = -minx;
         if (miny + DeltaY < 0) DeltaY = -miny;
         if (maxx + DeltaX >= state.ActiveLayer.Map.Width) DeltaX = state.ActiveLayer.Map.Width - 1 - maxx;
         if (maxy + DeltaY >= state.ActiveLayer.Map.Height) DeltaY = state.ActiveLayer.Map.Height - 1 - maxy;
     }
     if (DeltaX != 0 || DeltaY != 0)
     {
         Map m = new Map();
         m.SetDimensions(state.ActiveLayer.Map.Width, state.ActiveLayer.Map.Height);
         foreach (var t in state.ActiveLayer.Map.GetAllTiles())
         {
             m.SetTile(t.X, t.Y, new Tile() { IsEmpty = true });
         }
         foreach (var t in state.ActiveLayer.Map.GetAllTiles())
         {
             var x = t.X + DeltaX;
             var y = t.Y + DeltaY;
             if(x >= 0 && y >= 0 && x < m.Width && y < m.Height)
                 m.SetTile(x, y, t);
         }
         state.ActiveLayer.Map = m;
     }
     return state;
 }
Exemplo n.º 19
0
        /// <summary>
        /// Tries to finds matches for a scrobbled track
        /// </summary>
        /// <param name="scrobble">The scrobble to search for</param>
        /// <param name="state">The current task's state</param>
        /// <returns>A perfect match if found, or null</returns>
        protected static LibraryTrack Find(ScrobbledTrack scrobble, MapState state)
        {
            List<RelevantLibraryTrack> fuzzyMatches = null;

            Dictionary<string, List<LibraryTrack>> artistTracks;
            if (state.LibraryArtists.TryGetValue(scrobble.ArtistKey, out artistTracks))
            {
                // Direct artist match
                var track = MatchTitle(scrobble, artistTracks, ref fuzzyMatches);
                if (track != null)
                    // Perfect match; return immediately
                    return track;
            }

            var minEditDistance = Settings.Default.MinimumEditDistance;

            // If nothing was found yet,
            if (artistTracks == null || artistTracks.Count == 0 ||
                fuzzyMatches == null || fuzzyMatches.Count == 0)
            {
                // No direct artist match, check for edit distance
                var artistKey = scrobble.ArtistKey;
                foreach (var entry in state.LibraryArtists)
                {
                    var titleDistance = (float)entry.Key.LevenshteinDistance(artistKey) / artistKey.Length;
                    if (titleDistance < minEditDistance)
                        MatchTitle(scrobble, entry.Value, ref fuzzyMatches, titleDistance / minEditDistance);
                }
            }

            // If any fuzzy matches were found
            if (fuzzyMatches != null && fuzzyMatches.Count != 0)
                state.FuzzyMatches.Enqueue(new FuzzyMatch(scrobble, fuzzyMatches.OrderByDescending(x => x.Relevance).ToArray()));
            else
                Interlocked.Increment(ref state.NotFound);

            // No direct match to return, fuzzy matches added to state
            return null;
        }
Exemplo n.º 20
0
        //根据地图状态选中对应的图片;
        private static Bitmap GetImgByMapstate(MapState state, Map map)
        {
            Bitmap img = null;

            switch (state)
            {
            case MapState.road:
                img = map.Road.Clone() as Bitmap;
                break;

            case MapState.box:
                img = map.Box.Clone() as Bitmap;
                break;

            case MapState.role:
                img = map.Role.Clone() as Bitmap;
                break;

            case MapState.target:
                img = map.Tatget.Clone() as Bitmap;
                break;

            case MapState.wall:
                img = map.Wall.Clone() as Bitmap;
                break;

            case MapState.taget_box:
                img = map.Box.Clone() as Bitmap;
                break;

            case MapState.target_role:
                img = map.Role.Clone() as Bitmap;
                break;

            default:
                break;
            }
            return(img);
        }
Exemplo n.º 21
0
    void Update()
    {
        if (creatingNewWorld && worldBuilder.State.Equals(WorldBuilderBehaviour.BuilderState.Complete))
        {
            worldData = worldBuilder.getWorldData();

            worldData.setSaveDirectories("AutoSave1", "AutoSave1");
            Thread saveMapThread = new Thread(new ThreadStart(worldData.saveWorldMapThread));
            saveMapThread.Start();

            mapState = MapState.World;

            infoLayer.updateWorldData(worldData);

            loadRegionHub();

            creatingNewWorld = false;
        }

        handleInput();
        handleListControllers();
    }
Exemplo n.º 22
0
        public void MouseClicked(MouseState mouseState)
        {
            Point     MouseClick     = new Point(mouseState.X, mouseState.Y);
            Rectangle MouseClickRect = new Rectangle(MouseClick, new Point(10, 10));

            switch (GState)
            {
            // If nothing selected, check whether location was selected
            case MapState.Normal:
                foreach (String PlaceName in LocationBoxes.Keys)
                {
                    if (MouseClickRect.Intersects(LocationBoxes[PlaceName]))
                    {
                        GState            = MapState.Selected;
                        LocationMenu      = new LocationMenu(PlaceName, LocationInfo[PlaceName], Content, Arial);
                        SelectedPlaceName = PlaceName;
                    }
                }
                if (MouseClickRect.Intersects(NotebookRect))
                {
                    GState = MapState.ToNotebook;
                }
                break;

            case MapState.Selected:
                if (LocationMenu.IsCancelling(MouseClickRect))
                {
                    GState       = MapState.Normal;
                    LocationMenu = null;
                }
                else if (LocationMenu.IsConfirming(MouseClickRect))
                {
                    GState          = MapState.Confirmed;
                    AddTimeOnReturn = true;
                    LocationMenu    = null;
                }
                break;
            }
        }
Exemplo n.º 23
0
        private void ScaleWorld()
        {
            //Obtaining distance and velocity
            Vector3 d = OVRInput.GetLocalControllerPosition(OVRInput.Controller.LTouch) - OVRInput.GetLocalControllerPosition(OVRInput.Controller.RTouch);
            Vector3 v = OVRInput.GetLocalControllerVelocity(OVRInput.Controller.LTouch) - OVRInput.GetLocalControllerVelocity(OVRInput.Controller.RTouch);

            //Calculating Scaling Vector
            float result = Vector3.Dot(v, d);

            //Adjusting result to slow scaling
            float final_result = 1.0F + 0.2F * result;

            Vector3 scalingFactor = Vector3.Scale(transform.localScale, new Vector3(final_result, final_result, final_result));

            //Checking Scaling Bounds
            if (scalingFactor.sqrMagnitude > minScale.sqrMagnitude && scalingFactor.sqrMagnitude < maxScale.sqrMagnitude)
            {
                Vector3 A = transform.position;
                Vector3 B = pivot.transform.position;
                B.y = A.y;

                Vector3 startScale = transform.localScale;
                Vector3 endScale   = transform.localScale * final_result;

                Vector3 C = A - B; // diff from object pivot to desired pivot/origin

                // calc final position post-scale
                Vector3 FinalPosition = (C * final_result) + B;

                // finally, actually perform the scale/translation
                transform.localScale = endScale;
                transform.position   = FinalPosition;
                mapState             = MapState.SCALING;
            }
            else if (mapState == MapState.SCALING)
            {
                mapState = MapState.IDLE;
            }
        }
Exemplo n.º 24
0
        /// <summary>
        /// Finds matches to all scrobbles and updates where needed and possible
        /// </summary>
        /// <param name="taskContext">The current task's context</param>
        /// <param name="state">The current task's state</param>
        protected void FindAndUpdateTracks(ReportingTask <MapResult> taskContext, MapState state)
        {
            foreach (var scrobble in state.Scrobbles)
            {
                if (taskContext.CancellationTokenSource.Token.IsCancellationRequested)
                {
                    break;
                }

                taskContext.Description = "Matching scrobble '" + scrobble.Artist + " - " + scrobble.Title + "'";

                // Only exact matches are updated immediately
                var media = Find(scrobble, state);
                if (media != null)
                {
                    try
                    {
                        if (media.TryUpdate(scrobble))
                        {
                            state.Updated++;
                        }
                        else
                        {
                            state.AlreadyUpToDate++;
                        }
                    }
                    catch (COMException e)
                    {
                        // Log errors to a list
                        var error = new QualifiedError(media.ToString(), InterpretErrorCode(e.ErrorCode));
                        state.Errors.Add(error);
                        state.UpdateFailed++;
                    }
                }

                taskContext.ReportItemCompleted();
            }
        }
Exemplo n.º 25
0
        public void Restore_AfterComputingFovAndSaving_ExpectedMapWithFov()
        {
            string mapRepresentation = @"####################################
                                      #..................................#
                                      #..###.########....................#
                                      #....#.#......#....................#
                                      #....#.#......#....................#
                                      #.............#....................#
                                      #....#.#......######################
                                      #....#.#...........................#
                                      #....#.#...........................#
                                      #..................................#
                                      ####################################";
            IMapCreationStrategy <Map> mapCreationStrategy = new StringDeserializeMapCreationStrategy <Map>(mapRepresentation);
            IMap map = Map.Create(mapCreationStrategy);

            map.ComputeFov(6, 1, 20, true);
            map.AppendFov(15, 1, 5, true);
            MapState mapState = map.Save();

            IMap newMap = new Map();

            newMap.Restore(mapState);

            string expectedFovMap = @"###########################%%%%%%%%%
                                   #..........................%%%%%%%%%
                                   #..###.########...........%%%%%%%%%%
                                   #%%%%#.#%%%%%%#....%%%%%%%%%%%%%%%%%
                                   %%%%%#.#%%%%%%#...%%%%%%%%%%%%%%%%%%
                                   %%%%%%.%%%%%%%#..%%%%%%%%%%%%%%%%%%%
                                   %%%%%#.#%%%%%%####%%%%%%%%%%%%%%%%%%
                                   %%%%%#.#%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                                   %%%%%#.#%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                                   %%%%%%.%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                                   %%%%%###%%%%%%%%%%%%%%%%%%%%%%%%%%%%";

            Assert.AreEqual(RemoveWhiteSpace(expectedFovMap), RemoveWhiteSpace(map.ToString(true)));
        }
Exemplo n.º 26
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GlobalState"/> class.
        /// </summary>
        GlobalState()
        {
            ThreadAsserts.IsMainThread();

            // Load all sorts of stuff
            _contentManager = NetGore.Content.ContentManager.Create();

            var dbConnSettings = new DbConnectionSettings();

            _dbController =
                dbConnSettings.CreateDbControllerPromptEditWhenInvalid(x => new ServerDbController(x.GetMySqlConnectionString()),
                                                                       x => dbConnSettings.PromptEditFileMessageBox(x));

            _defaultRenderFont = ContentManager.LoadFont("Font/Arial", 16, ContentLevel.Global);

            Character.NameFont = DefaultRenderFont;

            GrhInfo.Load(ContentPaths.Dev, ContentManager);
            AutomaticGrhDataSizeUpdater.Instance.UpdateSizes();

            _mapGrhWalls = new MapGrhWalls(ContentPaths.Dev, x => new WallEntity(x));

            // Load the child classes
            _mapState = new MapState(this);

            // Grab the audio manager instances, which will ensure that they are property initialized
            // before something that can't pass it an ContentManager tries to get an instance
            AudioManager.GetInstance(ContentManager);

            // Set the custom UITypeEditors
            CustomUITypeEditors.AddEditors(DbController);

            // Set up the timer
            _timer = new Timer {
                Interval = 1000 / 60
            };
            _timer.Tick += _timer_Tick;
        }
        public void OnMapClick(LatLng point)
        {
            switch (MapController.MapState)
            {
            case (MapState.PLACING_POLICE):
                MarkPolice(DateTime.Now, point);
                ConnectionHelper.SendPolice(point);
                break;

            case (MapState.PLACING_FLANKI):
                MarkColor(point, "Gra we flanki", BitmapDescriptorFactory.HueGreen);
                break;

            case (MapState.PLACING_DROP):
                MarkColor(point, "Alkospot", BitmapDescriptorFactory.HueRed);
                break;

            case (MapState.NULL):

                break;
            }
            MapController.MapState = MapState.NULL;
        }
Exemplo n.º 28
0
        private void selectMap()
        {
            DataSet          ds      = new DataSet();
            string           sql     = "select * from map_t order by idx DESC limit 1";
            MySqlDataAdapter adapter = new MySqlDataAdapter(sql, conn);
            string           temp    = "";

            adapter.Fill(ds, "map_t");
            if (ds.Tables.Count > 0)
            {
                foreach (DataRow r in ds.Tables[0].Rows)
                {
                    mapstate = JsonConvert.DeserializeObject <MapState>(r["map_data"].ToString());
                }
            }
            width      = mapstate.info.width;
            height     = mapstate.info.height;
            resolution = (float)mapstate.info.resolution;
            ori_x      = (float)mapstate.info.origin.position.x;
            ori_y      = (float)mapstate.info.origin.position.y;
            onDisplay();
            conn.Close();
        }
Exemplo n.º 29
0
        MapResult Map(ReportingTask <MapResult> taskContext, MapState state)
        {
            // Locally register all tracks from iTunes
            taskContext.Description = "Fetching iTunes library playlist";
            var iTunesTracks = iTunes.LibraryPlaylist.Tracks;
            var trackCount   = iTunesTracks.Count;

            taskContext.TotalItems = trackCount + state.Scrobbles.Count();

            for (int i = 1; i <= trackCount; i++)
            {
                if (taskContext.CancellationTokenSource.Token.IsCancellationRequested)
                {
                    taskContext.CancellationTokenSource.Token.ThrowIfCancellationRequested();
                }

                var track = new ItunesLibraryTrack(iTunesTracks.get_ItemByPlayOrder(i));
                taskContext.Description = "Registering iTunes track '" + track.Artist + " - " + track.Title + "'";

                RegisterLibraryTrack(track, state);

                taskContext.ReportItemCompleted();
            }

            // Find and update tracks
            FindAndUpdateTracks(taskContext, state);

            // "Early" out
            if (taskContext.CancellationTokenSource.Token.IsCancellationRequested)
            {
                taskContext.CancellationTokenSource.Token.ThrowIfCancellationRequested();
            }

            // Compose and return
            return(new MapResult(state.FuzzyMatches.ToArray(),
                                 state.Updated, state.AlreadyUpToDate, state.NotFound, state.UpdateFailed, state.Errors.ToArray()));
        }
Exemplo n.º 30
0
        public void PhysicsEngineInitalization()
        {
            _config   = new Config();
            _mapState = new MapState();

            _config     = new Config();
            _gameEngine = new GameEngine(null, _config, new WorldLoader(_mapState), _mapState);
            _gameEngine.Ticker.Dispose();

            _mapState.MapObjects = new List <MapObject>();

            GameState.Instance.Players  = new List <Player>();
            GameState.Instance.Bullets  = new List <Bullet>();
            GameState.Instance.PlayerId = 1;

            _player = new Player(_config)
            {
                Position = new Vector2(0, 0),
                Angle    = 0.0,
                Keys     = new List <KeyEnum>(),
            };

            GameState.Instance.Players.Add(_player);
        }
Exemplo n.º 31
0
        public override void Update(GameTime gameTime, int tickCount, float sr)
        {
            if (State == MapState.Scrolling)
            {
                if (accumElapsedGameTime >= TimeSpan.FromMilliseconds(tickInMS))
                {
                    accumElapsedGameTime = TimeSpan.FromSeconds(0);
                    mapTickCount++;
                }

                accumElapsedGameTime = accumElapsedGameTime.Add(gameTime.ElapsedGameTime);

                if (scrollRows > 0)
                {
                    if (accumScrollTime >= TimeSpan.FromMilliseconds(scrollTimeOutInMS))
                    {
                        accumScrollTime = TimeSpan.FromSeconds(0);
                        scrollRows     -= .125f;
                        OnScrolled(new EventArgs());
                    }
                    accumScrollTime = accumScrollTime.Add(gameTime.ElapsedGameTime);
                }
            }
            else
            {
                if (state == MapState.Timer)
                {
                    accumElapsedPauseTime = accumElapsedPauseTime.Add(gameTime.ElapsedGameTime);
                    if (accumElapsedPauseTime > TimeSpan.FromSeconds(5))
                    {
                        accumElapsedPauseTime = TimeSpan.FromSeconds(0);
                        state = MapState.Scrolling;
                    }
                }
            }
        }
Exemplo n.º 32
0
    private void SetupTileMap()
    {
        mapState = new MapState();
        for (var i = 0; i < tiles.Length; ++i)
        {
            tilesData[tiles[i]] = tileEnvs[i];
        }

        foreach (var pos in tilemap.cellBounds.allPositionsWithin)
        {
            tilesFeature[pos] = new TileFeature();
            var tile = tilemap.GetTile(pos);
            if (tile == null)
            {
                continue;
            }
            var tileEnv = tilesData[tile];
            if (tileEnv.controlPoint)
            {
                tilesFeature[pos].isTriggered = false;
                ++mapState.numControlPoint;
            }
        }
    }
    // Rotate the world based off of the right thumbstick
    private void ControllerRotateWorld()
    {
        float deltaX = OVRInput.Get(OVRInput.Axis2D.SecondaryThumbstick).x;

        // We only consider inputs above a certain threshold.
        if (Mathf.Abs(deltaX) > 0.2f)
        {
            mapState = MapState.IDLE; // Controller input overrides manual
            float angle = deltaX * rotSpeed * 360 * Time.fixedDeltaTime;
            Debug.Log("deltaX: " + deltaX);
            Debug.Log("rotSpeed:" + rotSpeed);
            Debug.Log("Time.fixedDeltaTime" + Time.fixedDeltaTime);
            transform.RotateAround(pivot.transform.position, Vector3.up, angle);
            if (rotatingTable)
            {
                rotatingTable.transform.RotateAround(pivot.transform.position, Vector3.up, angle);
            }
            mapState = MapState.ROTATING;
        }
        else if (mapState == MapState.ROTATING)
        {
            mapState = MapState.IDLE;
        }
    }
Exemplo n.º 34
0
    // Update is called once per frame


    #region Loading
    public void Load()
    {
        State        = MapState.Loading;
        LoadProgress = 0;

        if (EditorTest)
        {
            StartCoroutine(LoadMap(Name));
            return;
        }

        string fn = Name;

        if (!fn.EndsWith(".vxl"))
        {
            fn += ".vxl";
        }

#if UNITY_WEBPLAYER && !UNITY_EDITOR
        StartCoroutine(DownloadMap(fn));
#else
        StartCoroutine(LoadMap(Application.dataPath + "/Resources//Maps/" + fn));
#endif
    }
        MapResult Map(ReportingTask<MapResult> taskContext, MapState state)
        {
            // Locally register all tracks from WMP
            var library = (IWMPMediaCollection2) WindowsMediaPlayer.mediaCollection;

            taskContext.Description = "Fetching WMP library playlist";
            var wmpTracks = library.getAll();
            var trackCount = wmpTracks.count;

            taskContext.TotalItems = trackCount + state.Scrobbles.Count();

            // No concurrent dictionaries in this CTP, so this has to be sequential...
            for (int i = 0; i < trackCount; i++)
            {
                if (taskContext.Task.IsCanceled)
                    return null;

                var track = new WmpLibraryTrack(wmpTracks.get_Item(i));
                taskContext.Description = "Registering WMP track '" + track.Artist + " - " + track.Title + "'";

                RegisterLibraryTrack(track, state);

                taskContext.ReportItemCompleted();
            }

            // Find and update tracks
            FindAndUpdateTracks(taskContext, state);

            // "Early" out
            if (taskContext.Task.IsCanceled)
                return null;

            // Compose and return
            return new MapResult(state.FuzzyMatches.ToArray(),
                state.Updated, state.AlreadyUpToDate, state.NotFound, state.UpdateFailed, state.Errors.ToArray());
        }
Exemplo n.º 36
0
    public void UpdateState(MapState _newState)
    {
        m_playerTurnActive = false;

        switch (_newState)
        {
        case MapState.StartPlayerTurn:
            ResetPlayer();
            MapStateMachine.Instance.SetState(MapState.PlayerTurn, 0.5f);
            break;

        case MapState.PlayerTurn:
            m_playerTurnActive = true;
            break;

        case MapState.PlayerMoveSelected:
            m_playerTurnActive = true;
            break;

        case MapState.PlayerActionSelected:
            m_playerTurnActive = true;
            break;
        }
    }
Exemplo n.º 37
0
    public void Reset()
    {
        resources = StartingResources;
        lives = StartingLives;
        ClearTowers();
        for (int i = enemies.Count-1; i > 0; i--)
            enemies[i].GetComponent<Enemy>().onDied(enemies[i]);

        state = MapState.Idle;
    }
Exemplo n.º 38
0
 private void SetStateWithDelay(MapState _state)
 {
     SetState(_state);
 }
Exemplo n.º 39
0
 protected override void InitializeManager()
 {
     ClearObservers();
     MapState = MapState.Start;
 }
Exemplo n.º 40
0
 public void MapStart()
 {
     state = MapState.Running;   
 }
        public static void SerializeMapState(BinaryWriter Writer, MapState MapState)
        {
            SerializeMapObjectState(Writer, MapState);
            SerializeGuid(Writer, MapState.ClassId);
            SerializeMap(Writer, MapState.Map);

            foreach (MapLevelState level in MapState.Levels)
            {
                for (UInt16 z = 0; z < MapState.Levels.Length; z++)
                    for (UInt16 x = 0; x < MapState.Size.Width; x++)
                        for (UInt16 y = 0; y < MapState.Size.Height; y++)
                        {
                            SerializeMapCellState(Writer, MapState.Levels[z].Cells[x, y]);
                        }
            }

            SerializeMapAreasState(Writer, MapState.Areas);

            SerializeLength(Writer, MapState.ActiveObjects.Count);
            foreach (KeyValuePair<Guid, MapActiveObjectState> activeState in MapState.ActiveObjects)
            {
                SerializeGuid(Writer, activeState.Key);
                SerializeMapActiveObjectState(Writer, activeState.Value);
            }
        }
Exemplo n.º 42
0
 private bool SegmentWasUnvisitedInOuterLoops(EdiSegment segment, MapState mapState)
 {
     return mapState.LoopStates.Any(state => !state.VisitedSegmentIds.Contains(segment.Id) &&
                                             state.Loop.FindMatchingNode(segment) != null);
 }
        // Rotate the world based off of physical movement/interaction
        private void ManualRotateWorld()
        {
            // CASE: User has held the handle.
            if (handleHeldTrigger)
            {
                // Update state.
                handleHeldTrigger = false;
                mapState          = MapState.DRAGGING;

                // Initialize oldVec: direction vec from hand to pivot.
                oldVec   = OVRInput.GetLocalControllerPosition(currentController) - pivot.transform.position;
                oldVec.y = 0;
                oldVec   = Vector3.Normalize(oldVec);

                // Initialize angles: linked list that'll contain recent angle rotations.
                angles.Clear();
            }

            // CASE: Map is in the dragging state.
            if (mapState == MapState.DRAGGING)
            {
                // CASE: User has released the handle.
                if (OVRInput.Get(OVRInput.Axis1D.PrimaryHandTrigger, currentController) < .1f)
                {
                    // CASE: User was dragging the table when they released the handle.
                    if (mapState == MapState.DRAGGING)
                    {
                        // Initize movementAngle: the initial movement per fixedupdate, to avg of recent rots
                        movementAngle = 0;
                        foreach (float a in angles)
                        {
                            movementAngle += a;
                        }
                        movementAngle /= angles.Count;

                        // Set the map to moving.
                        mapState = MapState.MOVING;
                    }
                }

                // Initialize currVec.
                Vector3 currVec = OVRInput.GetLocalControllerPosition(currentController) - pivot.transform.position;
                currVec.y = 0;
                currVec   = Vector3.Normalize(currVec);

                // Find the angle going from oldVec to currVec.
                float   angle = Vector3.Angle(oldVec, currVec);
                Vector3 cross = Vector3.Cross(oldVec, currVec);
                if (cross.y > 0)
                {
                    angle = -angle;
                }

                // Rotate the map and circular table by that angle.
                transform.RotateAround(pivot.transform.position, Vector3.up, angle);
                rotatingTable.transform.Rotate(Vector3.up, angle);

                // Update startVec
                oldVec = currVec;

                // Add recent rotation angle to angles. Keep only the N most recent angles.
                angles.AddLast(angle);
                if (angles.Count > 10)
                {
                    angles.RemoveFirst();
                }
            }
            else if (mapState == MapState.MOVING)
            {
                // Rotate the map/table by the movementAngle.
                transform.RotateAround(pivot.transform.position, Vector3.up, movementAngle);
                rotatingTable.transform.Rotate(Vector3.up, movementAngle);

                // Decay movementAngle.
                movementAngle *= movementAngleDecay;

                // Check if we've stopped moving - if so, set to IDLE.
                if (Mathf.Abs(movementAngle) < 0.005f)
                {
                    mapState = MapState.IDLE;
                }
            }
        }
Exemplo n.º 44
0
    private void OnEnemyDied(GameObject obj)
    {
        Enemy enemyScript = obj.GetComponent<Enemy>();
        enemyScript.Reset();
        enemyScript.onDied -= OnEnemyDied;
        enemyScript.onReachedEnd -= OnEnemyReachesEnd;

        resources += enemyScript.resourceReward;
        resourcesCollected += enemyScript.resourceReward;
        currentWaveEnemiesLeft--;

        enemies.Remove(obj);
        obj.transform.parent = null;
        objectPool.ReleaseEnemy(obj);

        if (currentWaveEnemiesLeft <= 0)
            state = MapState.CompletedWave;
    }
Exemplo n.º 45
0
 public abstract MapState Execute(MapState state, Selection selection);
        private static MapState DeserializeMapState(BinaryReader Reader, Map map)
        {
            MapState state = new MapState(map);

            for (UInt16 z = 0; z < map.Levels.Length; z++)
                for (UInt16 x = 0; x < map.Size.Width; x++)
                    for (UInt16 y = 0; y < map.Size.Height; y++)
                    {
                        state.Levels[z].Cells[x, y] = DeserializeMapCellState(Reader, map.Levels[z].Cells[x, y], new MapPoint(z, x, y));
                    }

            state.Areas = DeserializeMapAreasState(Reader, map.Areas);

            int activeObjectsCount = DeserializeLength(Reader);
            for (int i = 0; i < activeObjectsCount; i++)
            {
                Guid id = DeserializeGuid(Reader);
                MapActiveObjectState activeObject = DeserializeMapActiveObjectState(Reader, map.TileSet);
                state.AddActiveObject(activeObject, id);
            }

            return state;
        }
Exemplo n.º 47
0
        public override void HandleInput()
        {
            switch (_state)
            {
            case MapState.ReturnToNexusLabel:
                if (KeyInput.JustPressedRebindableKey(KeyFunctions.Accept))
                {
                    _state = MapState.NoLabel;
                    SoundManager.PlaySoundEffect("menu_select");
                }
                else
                {
                    base.HandleInput();
                }
                break;

            case MapState.NoLabel:
                if (KeyInput.JustPressedRebindableKey(KeyFunctions.Accept))
                {
                    _state = MapState.ReturnToNexusLabel;
                    SoundManager.PlaySoundEffect("menu_select");
                }
                else if (KeyInput.JustPressedRebindableKey(KeyFunctions.Cancel))
                {
                    _state = MapState.ReturnToNexusLabel;
                    SoundManager.PlaySoundEffect("menu_select");
                }
                else if (KeyInput.JustPressedRebindableKey(KeyFunctions.Left))
                {
                    _state = MapState.YesLabel;
                    SoundManager.PlaySoundEffect("menu_move");
                }
                else if (KeyInput.JustPressedRebindableKey(KeyFunctions.Right))
                {
                    SoundManager.PlaySoundEffect("menu_move");
                }
                break;

            case MapState.YesLabel:
                if (KeyInput.JustPressedRebindableKey(KeyFunctions.Accept))
                {
                    SoundManager.PlaySoundEffect("menu_select");
                    //TODO return to nexus
                }
                else if (KeyInput.JustPressedRebindableKey(KeyFunctions.Cancel))
                {
                    _state = MapState.ReturnToNexusLabel;
                    SoundManager.PlaySoundEffect("menu_select");
                }
                else if (KeyInput.JustPressedRebindableKey(KeyFunctions.Left))
                {
                    SoundManager.PlaySoundEffect("menu_move");
                }
                else if (KeyInput.JustPressedRebindableKey(KeyFunctions.Right))
                {
                    _state = MapState.NoLabel;
                    SoundManager.PlaySoundEffect("menu_move");
                }
                break;
            }
        }
Exemplo n.º 48
0
 /// <summary>
 /// Converts the specified list of EdiSegments into an XDocument using this EdiMapping.
 /// </summary>
 /// <param name="segments">A list of EdiSegments to convert into an XDocument.</param>
 /// <returns>An XDocument containing the XML representations of the EdiSegments.</returns>
 public XDocument Map(IList<EdiSegment> segments)
 {
     var mapState = new MapState(segments);
     XElement rootElement = Map(mapState, _root);
     return new XDocument(rootElement);
 }
Exemplo n.º 49
0
    public void Awake()
    {
        mState = transform.parent.gameObject.GetComponentInChildren<MapState>();
        charLSManager = transform.parent.Find("charLSManager").GetComponent<LinkedSpriteManager>();
        itemLSManager = transform.parent.Find("charLSManager").GetComponent<LinkedSpriteManager>();
        enemyLSManager = transform.parent.Find("enemyLSManager").GetComponent<LinkedSpriteManager>();
        camCtrl = Camera.mainCamera.GetComponent<CameraCtrl>();
        settings = transform.parent.gameObject.GetComponentInChildren<Settings>();

        DontDestroyOnLoad (transform.parent);
    }
Exemplo n.º 50
0
 private XElement Map(MapState mapState, Loop loop)
 {
     var xml = new XElement(loop.Id);
     string previousSegmentId = null;
     var loopState = new MapState.LoopState(loop);
     mapState.LoopStates.Push(loopState);
     while (mapState.SegmentIndex < mapState.Segments.Count)
     {
         EdiSegment segment = mapState.Segments[mapState.SegmentIndex];
         if (loopState.VisitedSegmentIds.Contains(segment.Id))
             break;
         Node mapping = loop.FindMatchingNode(segment);
         if (mapping == null && SegmentWasUnvisitedInOuterLoops(segment, mapState))
             break;
         if (mapping is Loop)
             xml.Add(Map(mapState, (Loop) mapping));
         else
         {
             xml.Add(MapSegment(segment, (Segment) mapping));
             mapState.SegmentIndex++;
         }
         if (previousSegmentId == null)
         {
             if (loop != _root)
                 loopState.VisitedSegmentIds.Add(segment.Id);
         }
         else if (previousSegmentId != segment.Id)
             loopState.VisitedSegmentIds.Add(previousSegmentId);
         previousSegmentId = segment.Id;
     }
     mapState.LoopStates.Pop();
     return xml;
 }
Exemplo n.º 51
0
 public void Restore( MapState state )
 {
     throw new NotImplementedException();
 }
Exemplo n.º 52
0
 public void MapStartWave()
 {
     if(state != MapState.FinishedGame)
         state = MapState.Running;
 }
Exemplo n.º 53
0
 public void MapFinish()
 {
     buildDecisionsChromosome.Fitness = resourcesCollected + (lives*5);
     state = MapState.FinishedGame;
 }
Exemplo n.º 54
0
 public void Restore(MapState state)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 55
0
        public void Update(KeyboardState kbs, KeyboardState pkbs)
        {
            kbState = kbs;
            prevKBState = pkbs;

            switch (mapState)
            {
                #region Editing
                case MapState.Editing:
                    if (SingleKeyPress(Keys.Enter))
                    {
                        switch (buttons[x, y].Thing)
                        {
                            // switch the state of the currently selected tile
                            case '.': buttons[x, y].Thing = '=';
                                break;
                            case '=': buttons[x, y].Thing = '+';
                                break;
                            case '+': buttons[x, y].Thing = '-';
                                break;
                            case '-': buttons[x, y].Thing = 'S';
                                break;
                            case 'S': buttons[x, y].Thing = 'G';
                                break;
                            case 'G': buttons[x, y].Thing = 'b';
                                break;
                            case 'b': buttons[x, y].Thing = '.';
                                break;
                            default: break;
                        }
                    }

                    // move the cursor
                    else if (SingleKeyPress(Keys.W) && y > 0)
                    {
                        y--;
                    }
                    else if (SingleKeyPress(Keys.A) && x > 0)
                    {
                        x--;
                    }
                    else if (SingleKeyPress(Keys.S) && y < (Constants.ARRAYY - 1))
                    {
                        y++;
                    }
                    else if (SingleKeyPress(Keys.D) && x < (Constants.ARRAYX - 1))
                    {
                        x++;
                    }

                    // reset the level to blank tiles
                    else if (SingleKeyPress(Keys.Space))
                    {
                        this.ResetLevel();
                    }

                    // save the current level
                    else if (SingleKeyPress(Keys.Q))
                    {
                        CheckLevelCount();
                        mapState = MapState.Saving;
                    }
                    // load a previously made level
                    else if (SingleKeyPress(Keys.E))
                    {
                        CheckLevelCount();
                        mapState = MapState.Loading;
                    }
                    break;
                #endregion

                #region Loading
                case MapState.Loading:
                    // if an error has occurred
                    if (error)
                    {
                        if (SingleKeyPress(Keys.Enter))
                        {
                            error = false;
                        }
                    }

                    // otherwise
                    else
                    {
                        // set the level name
                        name = levelSelected + ".txt";

                        // scroll up through the available levels
                        if (SingleKeyPress(Keys.D) && levelSelected < (maxLevel - 1))
                        {
                            levelSelected++;
                        }
                        // scroll down through the available levels
                        else if (SingleKeyPress(Keys.A) && levelSelected > 1)
                        {
                            levelSelected--;
                        }

                        // initiate level load
                        else if (SingleKeyPress(Keys.Enter))
                        {
                            LoadLevel();
                            // if an error has not occurred
                            if (error == false)
                            {
                                mapState = MapState.Editing;
                            }
                        }

                        // cancel level load
                        else if (SingleKeyPress(Keys.Space))
                        {
                            mapState = MapState.Editing;
                        }
                    }
                    break;
                #endregion

                #region Saving
                case MapState.Saving:
                    // if an error has occured
                    if (error)
                    {
                        if (SingleKeyPress(Keys.Enter))
                        {
                            error = false;
                        }
                    }

                    // otherwise
                    else
                    {
                        // set the level name
                        name = levelSelected + ".txt";

                        // scroll up through the available level slots
                        if (SingleKeyPress(Keys.D) && levelSelected < maxLevel)
                        {
                            levelSelected++;
                        }
                        // scroll down through the available level slots
                        else if (SingleKeyPress(Keys.A) && levelSelected > 1)
                        {
                            levelSelected--;
                        }

                        // initiate level save
                        else if (SingleKeyPress(Keys.Enter))
                        {
                            SaveLevel();
                            // if an error has not occurred
                            if (error == false)
                            {
                                mapState = MapState.Editing;
                            }
                        }

                        // cancel level save
                        else if (SingleKeyPress(Keys.Space))
                        {
                            mapState = MapState.Editing;
                        }
                    }
                    break;
                #endregion

                default: break;
            }
        }
Exemplo n.º 56
0
        public Level(MapState mState, GraphicsDevice graphicsDevice, Game1 game1)
        {
            this.game1          = game1;
            this.graphicsDevice = graphicsDevice;
            // Create a list which contains the textures to load as map.
            tileTextures = new List <Texture2D>();

            // Create lists which contain the towers, enemys and projectiles.
            towerList       = new List <Towers>();
            enemyList       = new List <Enemys>();
            projectileList  = new List <Projectile>();
            buildButtonList = new List <BuildButton>();
            explosionList   = new List <Explosion>();

            player       = new Player(graphicsDevice);
            ui           = new UserInterface(graphicsDevice, player);
            inRangeCheck = new InRangeCheck();

            isActive = true;

            buildButtonTexture = ContentConverter.Convert("Content/Assets/TD/UI/buildTower.png", graphicsDevice);

            #region Convert and load level textures

            // Level 1
            background1 = ContentConverter.Convert(pathToLvl1Background, graphicsDevice);
            lvlWay1     = ContentConverter.Convert(pathToLvl1Way, graphicsDevice);
            lvlTile2    = ContentConverter.Convert(pathToLvlTile2, graphicsDevice);
            lvlTile3    = ContentConverter.Convert(pathToLvlTile3, graphicsDevice);
            lvlTile4    = ContentConverter.Convert(pathToLvlTile4, graphicsDevice);
            lvlTile5    = ContentConverter.Convert(pathToLvlTile5, graphicsDevice);
            lvlTile6    = ContentConverter.Convert(pathToLvlTile6, graphicsDevice);
            lvlTile7    = ContentConverter.Convert(pathToLvlTile7, graphicsDevice);
            lvlTile8    = ContentConverter.Convert(pathToLvlTile8, graphicsDevice);
            lvlTile9    = ContentConverter.Convert(pathToLvlTile9, graphicsDevice);

            // Level 2
            background2 = ContentConverter.Convert(pathToLvl2Background, graphicsDevice);
            lvlWay2     = ContentConverter.Convert(pathToLvl2Way, graphicsDevice);
            lvlTile12   = ContentConverter.Convert(pathToLvlTile12, graphicsDevice);
            lvlTile13   = ContentConverter.Convert(pathToLvlTile13, graphicsDevice);
            lvlTile14   = ContentConverter.Convert(pathToLvlTile14, graphicsDevice);
            lvlTile15   = ContentConverter.Convert(pathToLvlTile15, graphicsDevice);
            lvlTile16   = ContentConverter.Convert(pathToLvlTile16, graphicsDevice);
            lvlTile17   = ContentConverter.Convert(pathToLvlTile17, graphicsDevice);
            lvlTile18   = ContentConverter.Convert(pathToLvlTile18, graphicsDevice);
            lvlTile19   = ContentConverter.Convert(pathToLvlTile19, graphicsDevice);

            // Level 3
            background3 = ContentConverter.Convert(pathToLvl3Background, graphicsDevice);
            lvlWay3     = ContentConverter.Convert(pathToLvl3Way, graphicsDevice);
            lvlTile22   = ContentConverter.Convert(pathToLvlTile22, graphicsDevice);
            lvlTile23   = ContentConverter.Convert(pathToLvlTile23, graphicsDevice);
            lvlTile24   = ContentConverter.Convert(pathToLvlTile24, graphicsDevice);
            lvlTile25   = ContentConverter.Convert(pathToLvlTile25, graphicsDevice);
            lvlTile26   = ContentConverter.Convert(pathToLvlTile26, graphicsDevice);
            lvlTile27   = ContentConverter.Convert(pathToLvlTile27, graphicsDevice);
            lvlTile28   = ContentConverter.Convert(pathToLvlTile28, graphicsDevice);
            lvlTile29   = ContentConverter.Convert(pathToLvlTile29, graphicsDevice);

            // Oulines
            horOutline1 = ContentConverter.Convert(pathToHorOutline, graphicsDevice);
            verOutline1 = ContentConverter.Convert(pathToVerOutline, graphicsDevice);
            botRightCor = ContentConverter.Convert(pathToBottomRightCornerOutline, graphicsDevice);
            botLeftCor  = ContentConverter.Convert(pathToBottomLeftCornerOutline, graphicsDevice);
            uppRightCor = ContentConverter.Convert(pathToUpperRightCornerOutline, graphicsDevice);
            uppLeftCor  = ContentConverter.Convert(pathToUpperLeftCornerOutline, graphicsDevice);

            // Start-End
            start1 = ContentConverter.Convert(pathToStart, graphicsDevice);
            end1   = ContentConverter.Convert(pathToEnd, graphicsDevice);

            // UI Line
            uiLine = ContentConverter.Convert(pathToUiLine, graphicsDevice);

            #endregion


            #region Add loaded textures to textures list

            AddTexture(background1);
            AddTexture(lvlWay1);
            AddTexture(lvlTile2);
            AddTexture(lvlTile3);
            AddTexture(lvlTile4);
            AddTexture(lvlTile5);
            AddTexture(lvlTile6);
            AddTexture(lvlTile7);
            AddTexture(lvlTile8);
            AddTexture(lvlTile9);

            AddTexture(background2);
            AddTexture(lvlWay2);
            AddTexture(lvlTile12);
            AddTexture(lvlTile13);
            AddTexture(lvlTile14);
            AddTexture(lvlTile15);
            AddTexture(lvlTile16);
            AddTexture(lvlTile17);
            AddTexture(lvlTile18);
            AddTexture(lvlTile19);

            AddTexture(background3);
            AddTexture(lvlWay3);
            AddTexture(lvlTile22);
            AddTexture(lvlTile23);
            AddTexture(lvlTile24);
            AddTexture(lvlTile25);
            AddTexture(lvlTile26);
            AddTexture(lvlTile27);
            AddTexture(lvlTile28);
            AddTexture(lvlTile29);

            AddTexture(horOutline1);
            AddTexture(verOutline1);
            AddTexture(botRightCor);
            AddTexture(botLeftCor);
            AddTexture(uppRightCor);
            AddTexture(uppLeftCor);

            AddTexture(start1);
            AddTexture(end1);

            AddTexture(uiLine);

            #endregion

            #region Switch for changing the map.

            this.mState = mState;

            // Which map to use
            switch (mState)
            {
            case MapState.map1:
                mapToUse = map1;
                mapInUse = 1;
                buildButtonsToUse1(graphicsDevice);
                break;

            case MapState.map2:
                mapToUse = map2;
                mapInUse = 2;
                buildButtonsToUse2(graphicsDevice);
                break;

            case MapState.map3:
                mapToUse = map3;
                mapInUse = 3;
                buildButtonsToUse3(graphicsDevice);
                break;

            default:
                throw new Exception(String.Format("Unknown state: {0}", mState));

                #endregion
            }

            #region EnemyWaypoints

            if (mState == MapState.map1)
            {
                // Waypoints
                waypoints.Enqueue(new Vector2(1, 4) * 64);
                waypoints.Enqueue(new Vector2(26, 4) * 64);
                waypoints.Enqueue(new Vector2(26, 13) * 64);
                waypoints.Enqueue(new Vector2(1, 13) * 64);
            }
            else if (mState == MapState.map2)
            {
                // Waypoints
                waypoints.Enqueue(new Vector2(1, 4) * 64);
                waypoints.Enqueue(new Vector2(7, 4) * 64);
                waypoints.Enqueue(new Vector2(7, 14) * 64);
                waypoints.Enqueue(new Vector2(22, 14) * 64);
                waypoints.Enqueue(new Vector2(22, 4) * 64);
                waypoints.Enqueue(new Vector2(28, 4) * 64);
            }
            else if (mState == MapState.map3)
            {
                // Waypoints
                waypoints.Enqueue(new Vector2(1, 4) * 64);
                waypoints.Enqueue(new Vector2(7, 4) * 64);
                waypoints.Enqueue(new Vector2(7, 14) * 64);
                waypoints.Enqueue(new Vector2(14, 14) * 64);
                waypoints.Enqueue(new Vector2(14, 4) * 64);
                waypoints.Enqueue(new Vector2(21, 4) * 64);
                waypoints.Enqueue(new Vector2(21, 14) * 64);
                waypoints.Enqueue(new Vector2(28, 14) * 64);
            }

            enemyController = new EnemyController(15, 10, this, graphicsDevice, player, game1, mapInUse);

            #endregion
        }
Exemplo n.º 57
0
        /// <summary>
        /// Registers a track from a music library to the local lookup database
        /// </summary>
        /// <param name="track">The track to register</param>
        /// <param name="state">The current task's state</param>
        protected static void RegisterLibraryTrack(LibraryTrack track, MapState state)
        {
            // Basically finds a space to put it in, and puts it
            Dictionary<string, List<LibraryTrack>> artistTracks;
            List<LibraryTrack> duplicateTracks;

            if (!state.LibraryArtists.TryGetValue(track.ArtistKey, out artistTracks))
                state.LibraryArtists.Add(track.ArtistKey, artistTracks = new Dictionary<string, List<LibraryTrack>>());

            if (!artistTracks.TryGetValue(track.TitleKey, out duplicateTracks))
                artistTracks.Add(track.TitleKey, duplicateTracks = new List<LibraryTrack>());

            duplicateTracks.Add(track);
        }
Exemplo n.º 58
0
    private void OnEnemyReachesEnd(GameObject obj)
    {
        Enemy enemyScript = obj.GetComponent<Enemy>();
        enemyScript.Reset();
        enemyScript.onDied -= OnEnemyDied;
        enemyScript.onReachedEnd -= OnEnemyReachesEnd;

        currentWaveEnemiesLeft--;
        lives -= enemyScript.lifeDeduction;
        lives = Math.Max(0, lives);

        enemies.Remove(obj);
        obj.transform.parent = null;
        objectPool.ReleaseEnemy(obj);

        if (lives < 1)
            MapFinish();
        else if (currentWaveEnemiesLeft <= 0)
            state = MapState.CompletedWave;
    }
Exemplo n.º 59
0
 public Map(MapState state) : this(state.Forward, state.Reverse)
 {
 }
Exemplo n.º 60
0
        /// <summary>
        /// Finds matches to all scrobbles and updates where needed and possible
        /// </summary>
        /// <param name="taskContext">The current task's context</param>
        /// <param name="state">The current task's state</param>
        protected void FindAndUpdateTracks(ReportingTask<MapResult> taskContext, MapState state)
        {
            Parallel.ForEach(state.Scrobbles, (scrobble, parallelState) =>
            {
                if (taskContext.Task.IsCanceled) // Allow mid-task canceling
                    parallelState.Stop();

                taskContext.Description = "Matching scrobble '" + scrobble.Artist + " - " + scrobble.Title + "'";

                // Only exact matches are updated immediately
                var media = Find(scrobble, state);
                if (media != null)
                {
                    try
                    {
                        if (media.TryUpdate(scrobble))
                            Interlocked.Increment(ref state.Updated);
                        else
                            Interlocked.Increment(ref state.AlreadyUpToDate);
                    }
                    catch (COMException e)
                    {
                        // Log errors to a list
                        state.Errors.Enqueue(new QualifiedError(media.ToString(), InterpretErrorCode(e.ErrorCode)));
                        Interlocked.Increment(ref state.UpdateFailed);
                    }
                }

                taskContext.ReportItemCompleted();
            });
        }