コード例 #1
0
ファイル: Pattern.cs プロジェクト: hgabor/boardgame
 public bool Match(GameState state, Coords start, Coords end, Direction dir)
 {
     if (pattern.Count() == 0)
     {
         return true;
     }
     if (end != null && !OnSameLine(start, end))
     {
         return false;
     }
     if (!pattern.ElementAt(0).IsTarget)
     {
         throw new NotImplementedException("Target other than the beginning is not supported yet.");
     }
     foreach (var incrementer in ToIncrementers(dir))
     {
         // Try every direction
         List<Coords> c;
         if (FindMatch(state, start, end, incrementer, pattern, out c))
         {
             return true;
         }
     }
     return false;
 }
コード例 #2
0
ファイル: ChunkCoords.cs プロジェクト: MagistrAVSH/voxelgame
 public ChunkCoords(ref Coords coords)
 {
     X = coords.Xblock / Chunk.CHUNK_SIZE;
     Z = coords.Zblock / Chunk.CHUNK_SIZE;
     WorldCoordsX = X * Chunk.CHUNK_SIZE;
     WorldCoordsZ = Z * Chunk.CHUNK_SIZE;
 }
コード例 #3
0
ファイル: Grid.cs プロジェクト: xCosmix/Random_Project
        public static Node GetNode(Coords coords)
        {
            int x = Mathf.Clamp(coords.x, 0, gridSize.x - 1);
            int y = Mathf.Clamp(coords.y, 0, gridSize.y - 1);

            return grid[x, y];
        }
コード例 #4
0
ファイル: Pattern.cs プロジェクト: hgabor/boardgame
 public bool CaptureAll(GameState state, Coords start, Coords end, Direction dir, out IEnumerable<Coords> capture)
 {
     if (pattern.Count() == 0)
     {
         capture = new List<Coords>();
         return true;
     }
     if (end != null && !OnSameLine(start, end))
     {
         capture = new List<Coords>();
         return false;
     }
     if (!pattern.ElementAt(0).IsTarget)
     {
         throw new NotImplementedException("Target other than the beginning is not supported yet.");
     }
     List<Coords> cAll = new List<Coords>();
     bool retVal = false;
     foreach (var incrementer in ToIncrementers(dir))
     {
         // Try every direction
         List<Coords> c = new List<Coords>();
         if (FindMatch(state, start, end, incrementer, pattern, out c))
         {
             cAll.AddRange(c);
             retVal = true;
         }
     }
     capture = cAll;
     return retVal;
 }
コード例 #5
0
ファイル: Satellite.cs プロジェクト: aliphen/hashCode2016
 public Satellite(Satellite s)
     : this(s.Pos.Lat, s.Pos.Lon, s.Speed, s.RotSpeed, s.MaxRot, s.Id)
 {
     CurrentRot = new Coords(s.CurrentRot);
     CurrentTurn = s.CurrentTurn;
     Range = new Range(s.Range);
 }
コード例 #6
0
ファイル: exit.cs プロジェクト: propra13-orga/gruppe22
 /// <summary>
 /// Constructor for Exit class
 /// </summary>
 /// <param name="from">Coordinates of teleporter in entrance room</param>
 /// <param name="fromRoom">Filename of entrance room</param>
 /// <param name="to">Coordinates of teleporter in exit room</param>
 /// <param name="toRoom">Filename of exit room</param>
 public Exit(Coords from, string fromRoom, Backend.Coords to = null, string toRoom = "")
 {
     _from = from;
     _fromRoom = fromRoom;
     _toRoom = toRoom;
     _to = to;
 }
コード例 #7
0
ファイル: Searches.cs プロジェクト: vermagav/bombersquad
            //Greedy BFS starting at "from" Coords
            //Returns null or a Coords that satisfies the test
            public static Coords greedyCoordsSearch(GameState gs, Coords from, Func<Coords, Coords, bool> test, bool isBombPassable, List<Coords> visited)
            {
                List<Coords> allCoords = new List<Coords>();

                List<Coords> adjCoords = gs.GetAdjacentAccessibleTiles(from.getTileNum(), isBombPassable, false);

                if (adjCoords.Count == 0) { return null; }

                allCoords.AddRange(adjCoords);

                while (allCoords.Count > 0) {
                    Coords coord = allCoords[0];
                    //Console.WriteLine("removing " + coord);
                    allCoords.Remove(coord);
                    visited.Add(coord);
                    if (test(coord, from)) {
                        return coord;
                    } else {
                        List<Coords> newCoords = gs.GetAdjacentAccessibleTiles(coord.getTileNum(), isBombPassable, false);
                        //Console.WriteLine("adding " + newCoords);
                        foreach(Coords potentialCoord in newCoords) {
                            if (!visited.Contains(potentialCoord) && !allCoords.Contains(potentialCoord)) {
                                allCoords.Add(potentialCoord);
                            }
                        }
                    }
                }

                return null;
            }
コード例 #8
0
ファイル: Helper.cs プロジェクト: aliphen/hashCode2016
        public static bool CanTakePicture(this Satellite s, Coords c, TimeRange t, out int pictureTurn, int maxTurn)
        {
            pictureTurn = 0;

            if (s.CurrentTurn > t.End)
                return false;

            s = new Satellite(s); //clone
            if(s.CurrentTurn < t.Start)
            {
                s.Move(t.Start - s.CurrentTurn);
            }

            for (int turn = Math.Max(t.Start, s.CurrentTurn); turn < Math.Min(t.End, maxTurn); turn++)
            {
                if(c.IsInRange(s.Range, s.Pos))
                {
                    pictureTurn = turn;
                    return true;
                }
                s.Move(1);
            }

            return false;
        }
コード例 #9
0
	public NeighbourCoordsResult(bool sameTree, Coords coordsResult, IOctree tree)
	{
		Assert.IsNotNull(tree, "Cannot have a null tree for a neighbour Coords result, return null instead");
		this.sameTree = sameTree;
		this.coordsResult = coordsResult;
		this.tree = tree;
	}
コード例 #10
0
ファイル: BlowUpWall.cs プロジェクト: vermagav/bombersquad
        //modified pathfinding... assume that agent can path through destructible walls
        //and simply calc path
        public Coords calcWallToDestroy(Coords from, Coords destination)
        {
            //path to destination, counting destructible walls as pathable
            PathPlan pathPlan = new PathPlan (this.gs);
            Graph g = pathPlan.mapQuantization (this.isBombPassable, true);
            List<Coords> path = pathPlan.calculateMovementPlan (g, from, destination);

            if ((path.Count == 0) && isBombPassable) {
                Console.WriteLine("MAP FAIL!"); //TODO JDP ????
                this.cannotExecuteStrategy = true;
            }

            for (int i = 0; i < path.Count; i++) {
            //foreach (Coords coord in path) {
                Coords coord = path[i];
                //first destructible wall encountered on path is the target
                LocationData datum = this.gs.GetLocationData (coord);
                if (datum.HasDestructibleWall ()) {
                    Console.WriteLine("BlowUpWall found wall to blow up: " + coord);
                    //find previous coord
                    if (i-1 < 0) { //case where we can't move anywhere but we can blow up ourselves and a wall!
                        return from;
                    } else {
                        Coords bombDropCoord = path[i-1];
                        return bombDropCoord;
                    }
                }

            }

            return null;
        }
コード例 #11
0
ファイル: Satellite.cs プロジェクト: aliphen/hashCode2016
 public Satellite(int lat, int lon, int speed, int rotSpeed, int maxRot, int id)
 {
     Pos = new Coords {Lat = lat, Lon = lon};
     Speed = speed;
     RotSpeed = rotSpeed;
     MaxRot = maxRot;
     Id = id;
 }
コード例 #12
0
 public MousePositionCondition(string name, Coords coordType, Operator inputOperator,
     int compareValue)
 {
     Name = name;
     CoordType = coordType;
     Operator = inputOperator;
     CompareValue = compareValue;
 }
コード例 #13
0
ファイル: Input.cs プロジェクト: aliphen/hashCode2016
 /// <summary>
 /// creates a range of size zero on the delta between coords and orig
 /// </summary>
 public Range(Coords origin, Coords coords)
 {
     var lat = coords.Lat - origin.Lat;
     var lon = coords.Lon - origin.Lon;
     DeltaLatMin = lat;
     DeltaLatMax = lat;
     DeltaLonMin = lon;
     DeltaLonMax = lon;
 }
コード例 #14
0
ファイル: PieceHandler.cs プロジェクト: bentheax/PFClone
    private void DisplaceEvent(GameToken origin, Coords toLoc)
    {
        if (origin.id != ID)
        {
            return;
        }

        animationQueue.Enqueue (toLoc);
    }
コード例 #15
0
ファイル: Coords.cs プロジェクト: vermagav/bombersquad
 public static Coords coordsXY(int x, int y, int width, int height)
 {
     Coords coords = new Coords (x, y, width, height);
     if (!(coords.isValid ())) {
         String msg = coords.ToString () + " invalid due to max width of " + width + " and max height of " + height;
         throw new ArgumentException (msg);
     }
     return coords;
 }
コード例 #16
0
ファイル: LabyrinthView.cs プロジェクト: kiple/mouselab
 public Rectangle GetClip(Coords coords)
 {
     if(_labyrinth == null || !IsHandleCreated) return Rectangle.Empty;
     var xFactor = Width / (double)_labyrinth.ColsCount;
     var yFactor = (Height - MESSAGE_HEIGHT) / (double)_labyrinth.RowsCount;
     var x = (int)(xFactor * (coords.Col - 1));
     var y = (int)(yFactor * (coords.Row - 1));
     return new Rectangle(x, y, (int)xFactor, (int)yFactor);
 }
コード例 #17
0
        public Coords PixelsToTile(Coords tempc)
        {
            // Returns a tile covering region in given pixel coordinates

            Coords outc;
            outc.x = Math.Ceiling(tempc.x / 256.0) - 1;
            outc.y = Math.Ceiling(tempc.y / 256.0) - 1;
            return outc;
        }
コード例 #18
0
ファイル: Block.cs プロジェクト: peperbol/LudumDare33Jam
    public void Init(Coords coords, BlockGenerator blockgen)
    {
        bg = blockgen;
        coordinates = coords;
        transform.SetParent(blockgen.transform);
        transform.localPosition = new Vector3(coords.x * Size, -coords.y * Size, 0);
        gameObject.name = coords.x + " : " + coords.y + " " + gameObject.name;

        Connect();
    }
コード例 #19
0
ファイル: PureLogic.cs プロジェクト: propra13-orga/gruppe22
 /// <summary>
 /// Method to change the "room"
 /// Loads the saved (previously visited) version of the next room if possible
 /// and the generated version if there is no saved one
 /// </summary>
 /// <param name="filename">The path to the .xml of the next room</param>
 /// <param name="pos">The spawning position in the next room</param>
 public override void ChangeMap(string filename, Coords pos)
 {
     map.Save("savedroom" + map.id + ".xml");
     if (File.Exists("save\\auto\\saved" + filename))
         map.Load("saved" + filename, pos, false);
     else
         map.Load(filename, pos, false);
     map.Save("saved" + filename);
     File.WriteAllText("save\\auto\\GameData", filename);
 }
コード例 #20
0
ファイル: Form1.cs プロジェクト: guygoudeau/Homework
 private void pictureBox1_Click(object sender, EventArgs e)
 {
     if(e.GetType() == typeof(MouseEventArgs))
     {
         MouseEventArgs me = e as MouseEventArgs;
         Coords co = new Coords(me.Location.ToString());
         coords.Add(co);
         textOutput.Text += me.Location.ToString() + " ";
     }
 }
コード例 #21
0
 public GamePadThumbStickCondition(string name,PlayerIndex playerIndex, ThumbStick thumbStick, Coords coordsType, Operator inputOperator,
     float compareValue)
 {
     Name = name;
     Player = playerIndex;
     ThumbStick = thumbStick;
     CoordsType = coordsType;
     Operator = inputOperator;
     CompareValue = compareValue;
 }
コード例 #22
0
ファイル: Pathfinding.cs プロジェクト: xCosmix/Game
 //TOOLS______________________________________
 private int openListContains(Coords cords)
 {
     int i = 0;
     foreach (PathNode node in openList)
     {
         if (node.node.coords.x == cords.x && node.node.coords.y == cords.y) return i;
         i++;
     }
     return -1;
 }
コード例 #23
0
 public RayIntersectionResult(bool hit)
 {
     this.hit = hit;
     node = null;
     _coords = new Coords();
     entryDistance = 0;
     position = new Vector3();
     normal = new Vector3();
     neighbourSide = NeighbourSide.Invalid;
     tree = null;
 }
コード例 #24
0
ファイル: Coords.cs プロジェクト: vermagav/bombersquad
 public static Coords coordsTileNum(int width, int height, int tileNum)
 {
     int y = (int)Math.Floor ((double)(tileNum / width));
     int x = tileNum % width;
     Coords coords = new Coords (x, y, width, height);
     if (!(coords.isValid ())) {
         String msg = coords.ToString () + " invalid due to max width of " + width + " and max height of " + height;
         throw new ArgumentException(msg);
     }
     return coords;
 }
コード例 #25
0
ファイル: MovementUtil.cs プロジェクト: vermagav/bombersquad
 public static Action getMovementActionType(Coords from, Coords to)
 {
     if (to.getX () == from.getX () + 1) {
         return new Action (Action.ActionType.EAST);
     } else if (to.getX () == from.getX () - 1) {
         return new Action (Action.ActionType.WEST);
     } else if (to.getY () == from.getY () + 1) {
         return new Action (Action.ActionType.SOUTH);
     } else {
         return new Action (Action.ActionType.NORTH);
     }
 }
コード例 #26
0
ファイル: GameStateManager.cs プロジェクト: bentheax/PFClone
 //tile.clicked message
 private void Clicked(Coords location)
 {
     if (State == null)
     {
         return;
     }
     if (MenuChoice.Mode == GameMode.AI && Game.Controlling != Game.Master ().Turn.TurnPlayer)
     {
         return;
     }
     State.Clicked (location);
 }
コード例 #27
0
 public Lines GetLongestLines(int h, int d, int w)
 {
     // check all 13 directions
     Coords here = new Coords(this, h, d, w);
     Coords[] directions = new Coords[]{
         new Coords(this, 1, 0, 0),
         new Coords(this, 0, 1, 0),
         new Coords(this, 0, 0, 1),
         new Coords(this, 1, 1, 0),
         new Coords(this, 1, 0, 1),
         new Coords(this, 0, 1, 1),
         new Coords(this, 1, -1, 0),
         new Coords(this, 1, 0, -1),
         new Coords(this, 0, 1, -1),
         new Coords(this, 1, 1, 1),
         new Coords(this, 1, -1, -1),
         new Coords(this, -1, 1, -1),
         new Coords(this, 1, 1, -1),};
     Lines max = new Lines();
     max.Count = 0;
     max.Length = 0;
     for (int i = 0; i < directions.Length; i++)
     {
         Coords n = here;
         if (!Visited[h, d, w, i])
         {
             Visited[h, d, w, i] = true;
             int length = 1;
             while (n.Plus(directions[i]))
             {
                 Visited[n.Height, n.Depth, n.Width, i] = true;
                 length++;
             }
             n = here;
             while (n.Minus(directions[i]))
             {
                 Visited[n.Height, n.Depth, n.Width, i] = true;
                 length++;
             }
             if (max.Length < length)
             {
                 max.Length = length;
                 max.Count = 1;
             }
             else if (max.Length == length)
             {
                 max.Count++;
             }
         }
     }
     return max;
 }
コード例 #28
0
ファイル: SolverGui.cs プロジェクト: aliphen/hashCode2016
        public static int GetNumberPictInRangeInNextTurns(Satellite satellite, KdTreeNode<float, PicCollection> n, KdTree<float, PicCollection> tree)
        {
            var possiblePict = new Coords((int)n.Point[0], (int)n.Point[1]);
            var copySatellite = satellite.Clone();
            copySatellite.TakePicture(possiblePict);
            copySatellite.NextTurn();
            var inRange = tree.RadialSearch(new float[] { copySatellite.Pos.Lat, copySatellite.Pos.Lon }, copySatellite.MaxRot, 150)
                .Where(no => no.Value.PictureCanBeTaken(copySatellite.CurrentTurn))
                .Where(k => copySatellite.CanTakePicture((int)k.Point[0], (int)k.Point[1])).Count() + GetNumberPictInRangeFixTrajectory(copySatellite, tree, 500);

            //Console.WriteLine("Number in range for {0} {1}: {2}", possiblePict.Lat, possiblePict.Lon, inRange);
            return inRange;
        }
コード例 #29
0
ファイル: PlantPhysics.cs プロジェクト: GlennMR/800craft
 public GrassTask( World world )
     : base(world)
 {
     int w, l;
     lock ( world.SyncRoot ) {
         w = _map.Width;
         l = _map.Length;
     }
     _rndCoords = new Coords[w * l]; //up to 250K per world with grass physics
     for ( short i = 0; i < w; ++i )
         for ( short j = 0; j < l; ++j )
             _rndCoords[i * l + j] = new Coords() { X = i, Y = j };
     Util.RndPermutate( _rndCoords );
 }
コード例 #30
0
ファイル: Logic.cs プロジェクト: bilalovim/Studio
        public static void AddRow(ObjectXML objectXML)
        {
            if (objectXML.rowNum < MainWindow.MaxRow)
            {
                for (int i = 0; i < objectXML.colNum; i++)
                {
                    Coords t = new Coords(objectXML.rowNum, i);
                    objectXML.cells.Add(t.GetHashCode(), new TabCell());
                }

                objectXML.rowNum++;

                MainWindow.objectXML = objectXML;
            }
        }
コード例 #31
0
    private void fetchcurrenttimedevicedata()
    {
        //	2020 - 05 - 19 14:06:24.589692Z

        string DateFormat = "yyyy-MM-d HH:mm:ss";

        //	string date = DateTime.Now.ToStrign(DateFormat);
        Currenttimedisplay.text = currentdatetime.ToUniversalTime().ToString(DateFormat);

        foreach (Dictionary <string, object> x in RawData)
        {
            DateTime devicetime = new DateTime();;
            if (containtime)
            {
                DateTime.TryParse(x.Single(s => s.Key == "time").Value as string, out devicetime);
            }
            if (containsStartTime)
            {
                DateTime.TryParse(RawData[0].Single(s => s.Key == "start_time").Value as string, out devicetime);
            }
            if (devicetime == currentdatetime)
            {
                if (deviceids.Contains(x.Single(s => s.Key == "deviceid").Value as string))
                {
                    Debug.Log("Update");

                    foreach (GameObject device in _devicesDisplay)                     //traverse all devices that are available to find current x device
                    {
                        String dID = x.Single(s => s.Key == "deviceid").Value as string;
                        if (dID == device.GetComponent <SingleDeviceInfo>().DeviceID)                        //only update one Device that is current X
                        {
                            Debug.Log("Updating Device " + dID);
                            device.GetComponent <SingleDeviceInfo>().UpdateRealtime(x);
                        }
                    }
                }
                else
                {
                    Debug.Log("Add");

                    deviceids.Add(x.Single(s => s.Key == "deviceid").Value as string);
                    if (containcoordinates)                     //
                    {
                        object temp     = x.Single(s => s.Key == "coords").Value;
                        Coords myCoords = JsonConvert.DeserializeObject <Coords>(temp.ToString());;
                        SpawnOnMapObject.AddLocationstring("" + myCoords.latitude, "" + myCoords.longitude, x);
                    }


                    if (!containcoordinates && containsGeometry)                      /// if the data has geo points to place objects
                    {
                        if (x.Single(s => s.Key == "geometry").Value != null)
                        {
                            object   Newtemp = x.Single(s => s.Key == "geometry").Value;
                            Geometry geo     = JsonConvert.DeserializeObject <Geometry>(Newtemp.ToString());
                            Debug.Log(Newtemp.ToString());

                            List <double> point = geo.coordinates[0];
                            SpawnOnMapObject.AddLocationstring("" + point[1], "" + point[0], x);
                        }
                    }
                }
            }
        }
        if (containtime || containsStartTime)
        {
            Debug.Log("Incrementing Time");
            SpawnOnMapObject.SpawnItemsOnMap();
            currentdatetime = currentdatetime.AddSeconds(1);
        }
    }
コード例 #32
0
ファイル: AStar.cs プロジェクト: GrishAVETISYAN/Test-game
    public Coords[]  _findWay()
    {
        lenX = closesBase.GetLength(1);
        lenY = closesBase.GetLength(0);
        //Debug.Log("A* lenX lenY" + lenX.ToString() + " " + lenY.ToString());


        blockBase    = new bool[lenY, lenX];
        sideStepBase = new int[lenY, lenX];
        sideSideDistanceToTargetBase = new int[lenY, lenX];
        sideSideWeightBase           = new int[lenY, lenX];
        sideSideDir = new int[lenY, lenX];

        for (int y = 0; y < lenY; y++)
        {
            for (int x = 0; x < lenX; x++)
            {
                blockBase[y, x] = true;

                sideStepBase[y, x] = -1;
                sideSideDistanceToTargetBase[y, x] = -1;
                sideSideWeightBase[y, x]           = -1;
                sideSideDir[y, x] = -1;
            }
        }



        List <AStarStruct> AStartStructList = get_side(start_pos);

        change_side(AStartStructList);
        block(start_pos);



        List <Coords> minCoords;

        minCoords = ret_coord_by_weight(find_min_weight());
        //Debug.Log("A* start min weight" + find_min_weight());

        bool b = check_0();


        int brk = 200;

        while (!b)
        {
            if (minCoords == null)
            {
                //Debug.Log("Break");
                break;// inchvor ban anel. bayc chi kara senc ban lini
            }

            AStartStructList = get_side(minCoords[0]);
            change_side(AStartStructList);
            block(minCoords[0]);



            minCoords = ret_coord_by_weight(find_min_weight());
            b         = check_0();
            if (brk > 0)
            {
                brk -= 1;
            }
            else
            {
                break;
            }
        }


        List <Coords> wayFinder = new List <Coords>();

        wayFinder.Add(target_pos);
        Coords last = wayFinder[wayFinder.Count - 1];


        brk = 200;
        while (last.x != start_pos.x || last.y != start_pos.y)
        {
            if (sideSideDir[last.y, last.x] == 1)
            {
                last = new Coords(last.x - 1, last.y);
            }
            else if (sideSideDir[last.y, last.x] == 2)
            {
                last = new Coords(last.x - 1, last.y + 1);
            }
            else if (sideSideDir[last.y, last.x] == 3)
            {
                last = new Coords(last.x, last.y + 1);
            }
            else if (sideSideDir[last.y, last.x] == 4)
            {
                last = new Coords(last.x + 1, last.y + 1);
            }
            else if (sideSideDir[last.y, last.x] == 5)
            {
                last = new Coords(last.x + 1, last.y);
            }
            else if (sideSideDir[last.y, last.x] == 6)
            {
                last = new Coords(last.x + 1, last.y - 1);
            }
            else if (sideSideDir[last.y, last.x] == 7)
            {
                last = new Coords(last.x, last.y - 1);
            }
            else if (sideSideDir[last.y, last.x] == 8)
            {
                last = new Coords(last.x - 1, last.y - 1);
            }
            wayFinder.Add(last);


            if (brk > 0)
            {
                brk -= 1;
            }
            else
            {
                break;
            }
        }


        foreach (Coords cd in wayFinder)
        {
            //Debug.Log("A* debug:"+cd);
        }

        //serialized
        //serializedWayFinderGird SWFG = GetComponent<serializedWayFinderGird>();
        //SWFG._Do_create_gird(new Vector2(0, 0), 1f, closesBase, start_pos.x, start_pos.y, target_pos.x, target_pos.y);
        //SWFG._Do_Text(closesBase, blockBase, sideStepBase, sideSideDistanceToTargetBase, sideSideWeightBase, sideSideDir);

        return(wayFinder.ToArray());
    }
コード例 #33
0
ファイル: AStar.cs プロジェクト: GrishAVETISYAN/Test-game
    List <AStarStruct> get_side(Coords find_position)
    {
        List <Coords> retCords             = new List <Coords>();
        List <int>    retSideStep          = new List <int>();
        List <int>    sideDistanceToTarget = new List <int>();
        List <int>    side_weigh           = new List <int>();

        List <AStarStruct> AStartStructList = new List <AStarStruct>();

        Coords array_size    = new Coords(lenX, lenY);
        int    addToSideStep = 0;


        if (sideStepBase[find_position.y, find_position.x] != -1)
        {
            addToSideStep = sideStepBase[find_position.y, find_position.x];
        }
        if (find_position.x < array_size.x - 1)
        {
            if (closesBase[find_position.y, find_position.x + 1] && blockBase[find_position.y, find_position.x + 1])
            {
                AStartStructList.Add(

                    new AStarStruct(
                        new Coords(find_position.x + 1, find_position.y),
                        addToSideStep + 10,
                        (Mathf.Abs(target_pos.x - (find_position.x + 1)) + Mathf.Abs(target_pos.y - (find_position.y))) * 10,
                        1
                        )
                    );
            }
        }
        if (find_position.x < array_size.x - 1 && find_position.y > 0)
        {
            if (closesBase[find_position.y - 1, find_position.x + 1] && blockBase[find_position.y - 1, find_position.x + 1])
            {
                AStartStructList.Add(
                    new AStarStruct(
                        new Coords(find_position.x + 1, find_position.y - 1),
                        addToSideStep + 14,
                        (Mathf.Abs(target_pos.x - (find_position.x + 1)) + Mathf.Abs(target_pos.y - (find_position.y - 1))) * 10,
                        2
                        )
                    );
            }
        }
        if (find_position.y > 0)
        {
            if (closesBase[find_position.y - 1, find_position.x] && blockBase[find_position.y - 1, find_position.x])
            {
                AStartStructList.Add(
                    new AStarStruct(
                        new Coords(find_position.x, find_position.y - 1),
                        addToSideStep + 10,
                        (Mathf.Abs(target_pos.x - (find_position.x)) + Mathf.Abs(target_pos.y - (find_position.y - 1))) * 10
                        , 3
                        )
                    );
            }
        }
        if (find_position.x > 0 && find_position.y > 0)
        {
            if (closesBase[find_position.y - 1, find_position.x - 1] && blockBase[find_position.y - 1, find_position.x - 1])
            {
                AStartStructList.Add(
                    new AStarStruct(
                        new Coords(find_position.x - 1, find_position.y - 1),
                        addToSideStep + 14,
                        (Mathf.Abs(target_pos.x - (find_position.x - 1)) + Mathf.Abs(target_pos.y - (find_position.y - 1))) * 10
                        , 4
                        )
                    );
            }
        }
        if (find_position.x > 0)
        {
            if (closesBase[find_position.y, find_position.x - 1] && blockBase[find_position.y, find_position.x - 1])
            {
                AStartStructList.Add(
                    new AStarStruct(
                        new Coords(find_position.x - 1, find_position.y),
                        addToSideStep + 10,
                        (Mathf.Abs(target_pos.x - (find_position.x - 1)) + Mathf.Abs(target_pos.y - (find_position.y))) * 10
                        , 5
                        )
                    );
            }
        }
        if (find_position.x > 0 && find_position.y < array_size.y - 1)
        {
            if (closesBase[find_position.y + 1, find_position.x - 1] && blockBase[find_position.y + 1, find_position.x - 1])
            {
                AStartStructList.Add(
                    new AStarStruct(
                        new Coords(find_position.x - 1, find_position.y + 1),
                        addToSideStep + 14,
                        (Mathf.Abs(target_pos.x - (find_position.x - 1)) + Mathf.Abs(target_pos.y - (find_position.y + 1))) * 10
                        , 6
                        )
                    );
            }
        }
        if (find_position.y < array_size.y - 1)
        {
            if (closesBase[find_position.y + 1, find_position.x] && blockBase[find_position.y + 1, find_position.x])
            {
                AStartStructList.Add(
                    new AStarStruct(
                        new Coords(find_position.x, find_position.y + 1),
                        addToSideStep + 10,
                        (Mathf.Abs(target_pos.x - (find_position.x)) + Mathf.Abs(target_pos.y - (find_position.y + 1))) * 10
                        , 7
                        )
                    );
            }
        }
        if (find_position.x < array_size.x - 1 && find_position.y < array_size.y - 1)
        {
            if (closesBase[find_position.y + 1, find_position.x + 1] && blockBase[find_position.y + 1, find_position.x + 1])
            {
                AStartStructList.Add(
                    new AStarStruct(
                        new Coords(find_position.x + 1, find_position.y + 1),
                        addToSideStep + 14,
                        (Mathf.Abs(target_pos.x - (find_position.x + 1)) + Mathf.Abs(target_pos.y - (find_position.y + 1))) * 10
                        , 8

                        )
                    );
            }
        }
        return(AStartStructList);
    }
コード例 #34
0
 public static void AddBlockItem(int characterId, Coords coords, Vector3 velocity, BlockType blockType, int gameObjectId)
 {
     Log.WriteInfo("AddBlockItem");
 }
コード例 #35
0
 static public float DotProduct(Coords vector1, Coords vector2)
 {
     //(v.x*w.x) + (v.y * w.y)
     return((vector1.x * vector2.x) + (vector1.y * vector2.y) + (vector1.z * vector2.z));
 }
コード例 #36
0
ファイル: Line.cs プロジェクト: 1halfplusminus/game_math
 public void Draw(float width, Color col)
 {
     Coords.DrawLine(A, B, width, col);
 }
コード例 #37
0
 public static void CharacterMove(int characterId, Coords coords)
 {
     Log.WriteInfo("CharacterMove");
 }
コード例 #38
0
ファイル: World.cs プロジェクト: Alan-Baylis/WorldGenerator-1
 internal bool IsOnChunkBorder(Coords coords)
 {
     return(IsOnChunkBorder(coords.Xblock, coords.Zblock));
 }
コード例 #39
0
ファイル: World.cs プロジェクト: Alan-Baylis/WorldGenerator-1
 /// <summary>Get a List of the 6 directly adjacent positions. Exclude positions that are outside the world or on the base of the world.</summary>
 internal List <Position> AdjacentPositions(Coords coord)
 {
     return(AdjacentPositions(coord.ToPosition()));
 }
コード例 #40
0
ファイル: World.cs プロジェクト: Alan-Baylis/WorldGenerator-1
 internal bool IsValidItemLocation(Coords coords)
 {
     return(IsLoadedBlockLocation(coords.Xblock, 0, coords.Zblock) && coords.Yf >= 0);
 }
コード例 #41
0
ファイル: World.cs プロジェクト: Alan-Baylis/WorldGenerator-1
 public bool IsLoadedBlockLocation(Coords coords)
 {
     return(IsLoadedBlockLocation(coords.Xblock, coords.Yblock, coords.Zblock));
 }
コード例 #42
0
ファイル: World.cs プロジェクト: Alan-Baylis/WorldGenerator-1
 /// <summary>Get a block using world coords.</summary>
 public Block GetBlock(ref Coords coords)
 {
     return(localMap.Chunk(coords).Blocks[coords]);
 }
コード例 #43
0
 public RectangleCrds(Coords LeftBottomCoords, Coords LeftTopCoords, Coords RightTopCoords, Coords RightBottomCoords)
 {
     LB = LeftBottomCoords;
     RB = RightBottomCoords;
     RT = RightTopCoords;
     LT = LeftTopCoords;
 }
コード例 #44
0
ファイル: OctreeNodeCoords.cs プロジェクト: toxicFork/vox
 public bool Equals(Coords other)
 {
     return(other.GetHashCode() == GetHashCode());
 }
コード例 #45
0
ファイル: WarArenaClient.cs プロジェクト: No-ops/WarArena
        static void RecieveResponse()
        {
            if (_players == null)
            {
                _players = new List <Player>();
            }
            byte[] bytes = new byte[BUFFERLENGTH];
            _socket.Receive(bytes);
            string fromServer = Encoding.UTF8.GetString(bytes).TrimEnd('\0');

            string[] responses = fromServer.Split(';');
            foreach (string response in responses)
            {
                string[] responseParts = response.Split(' ');
                if (responseParts[0] == "WAP/1.0")
                {
                    if (responseParts[1] == "WELCOME")
                    {
                        _receiveJson = responseParts[2] == "JSON";
                    }

                    if (responseParts[1] == "YOURTURN")
                    {
                        if (!_playerId.HasValue)
                        {
                            _playerId = int.Parse(responseParts[2]);
                        }
                        _responseQueue.Enqueue(ServerResponse.YourTurn);
                    }

                    if (responseParts[1] == "SENDSTATE")
                    {
                        if (_receiveJson)
                        {
                            var sendState = SerializationFunctions.DeserializeObject <SendState>(responseParts[2]);
                            foreach (Player player in sendState.Players)
                            {
                                Player existingPlayer = _players.SingleOrDefault(p => p.PlayerId == player.PlayerId);
                                if (existingPlayer == null)
                                {
                                    _players.Add(new Player(player.PlayerId, player.Name, player.Health, 10, player.Gold, player.Coordinates));
                                }
                                else
                                {
                                    existingPlayer.Gold        = player.Gold;
                                    existingPlayer.Health      = player.Health;
                                    existingPlayer.Coordinates = player.Coordinates;
                                }
                            }

                            foreach (Tile tile in sendState.Tiles)
                            {
                                gameBoard[tile.X, tile.Y].Gold   = tile.Gold;
                                gameBoard[tile.X, tile.Y].Health = tile.Health;
                            }
                        }
                        else
                        {
                            for (int i = 2; i < responseParts.Length; i++)
                            {
                                string[] itemInfos = responseParts[i].Split(',');
                                switch (itemInfos[0])
                                {
                                case "Pl":
                                    string name        = itemInfos[1];
                                    int    playerId    = int.Parse(itemInfos[2]);
                                    Coords coordinates = new Coords(int.Parse(itemInfos[3]), int.Parse(itemInfos[4]));
                                    int    health      = int.Parse(itemInfos[5]);
                                    int    gold        = int.Parse(itemInfos[6]);
                                    Player player      = _players.SingleOrDefault(p => p.PlayerId == playerId);
                                    if (player == null)
                                    {
                                        player = new Player(playerId, name, health, 10, gold, coordinates);
                                        _players.Add(player);
                                    }
                                    else
                                    {
                                        player.Health      = health;
                                        player.Gold        = gold;
                                        player.Coordinates = coordinates;
                                    }
                                    break;

                                case "P":
                                    coordinates = new Coords(int.Parse(itemInfos[1]), int.Parse(itemInfos[2]));
                                    health      = int.Parse(itemInfos[3]);
                                    gameBoard[coordinates.X, coordinates.Y].Health = health;
                                    break;

                                case "G":
                                    coordinates = new Coords(int.Parse(itemInfos[1]), int.Parse(itemInfos[2]));
                                    gold        = int.Parse(itemInfos[3]);
                                    gameBoard[coordinates.X, coordinates.Y].Gold = gold;
                                    break;
                                }
                            }
                        }
                        _responseQueue.Enqueue(ServerResponse.Sendstate);
                    }

                    if (responseParts[1] == "NEWPLAYER")
                    {
                        if (_receiveJson)
                        {
                            var player = SerializationFunctions.DeserializeObject <Player>(responseParts[2]);
                            _players.Add(new Player(player.PlayerId, player.Name, player.Health, 10, player.Gold, player.Coordinates));
                        }
                        else
                        {
                            string[] playerInfos = responseParts[2].Split(',');
                            string   name        = playerInfos[0];
                            int      id          = int.Parse(playerInfos[1]);
                            Coords   coordinates = new Coords(int.Parse(playerInfos[2]), int.Parse(playerInfos[3]));
                            int      health      = int.Parse(playerInfos[4]);
                            int      gold        = int.Parse(playerInfos[5]);
                            var      player      = new Player(id, name, health, 10, gold, coordinates);
                            player.PlayerId = id;
                            _players.Add(player);
                        }

                        _responseQueue.Enqueue(ServerResponse.NewPlayer);
                    }

                    if (responseParts[1] == "UPDATEPLAYER")
                    {
                        Player playerToUpdate;
                        if (_receiveJson)
                        {
                            var player = SerializationFunctions.DeserializeObject <Player>(responseParts[2]);
                            playerToUpdate             = _players.Single(p => p.PlayerId == player.PlayerId);
                            playerToUpdate.Coordinates = player.Coordinates;
                            playerToUpdate.Gold        = player.Gold;
                            playerToUpdate.Health      = player.Health;
                        }
                        else
                        {
                            string[] playerInfos = responseParts[2].Split(',');
                            int      id          = int.Parse(playerInfos[0]);
                            Coords   coordinates = new Coords(int.Parse(playerInfos[1]), int.Parse(playerInfos[2]));
                            int      health      = int.Parse(playerInfos[3]);
                            int      gold        = int.Parse(playerInfos[4]);
                            playerToUpdate             = _players.Single(p => p.PlayerId == id);
                            playerToUpdate.Coordinates = coordinates;
                            playerToUpdate.Health      = health;
                            playerToUpdate.Gold        = gold;
                        }

                        _responseQueue.Enqueue(ServerResponse.UpdatePlayer);
                    }

                    if (responseParts[1] == "REMOVEPLAYER")
                    {
                        int    id             = int.Parse(responseParts[2]);
                        Player playerToRemove = _players.SingleOrDefault(p => p.PlayerId == id);
                        if (playerToRemove != null)
                        {
                            _players.Remove(playerToRemove);
                        }
                        _responseQueue.Enqueue(ServerResponse.RemovePlayer);
                    }

                    if (responseParts[1] == "UPDATETILE")
                    {
                        if (_receiveJson)
                        {
                            var  tile         = SerializationFunctions.DeserializeObject <Tile>(responseParts[2]);
                            Tile tileToUpdate = gameBoard[tile.X, tile.Y];
                            tileToUpdate.Gold   = tile.Gold;
                            tileToUpdate.Health = tile.Health;
                        }
                        else
                        {
                            string[] tileInfos   = responseParts[2].Split(',');
                            Coords   coordinates = new Coords(int.Parse(tileInfos[0]), int.Parse(tileInfos[1]));
                            int      gold        = int.Parse(tileInfos[2]);
                            int      health      = int.Parse(tileInfos[3]);
                            gameBoard[coordinates.X, coordinates.Y].Gold   = gold;
                            gameBoard[coordinates.X, coordinates.Y].Health = health;
                        }
                        _responseQueue.Enqueue(ServerResponse.UpdateTile);
                    }

                    if (responseParts[1] == "MESSAGE")
                    {
                        int    id   = int.Parse(responseParts[2]);
                        string name = _players.SingleOrDefault(p => p.PlayerId == id)?.Name;
                        if (_chatMessages.Count == 5)
                        {
                            _chatMessages.RemoveAt(0);
                        }
                        var messageBuilder = new StringBuilder();
                        messageBuilder.Append($"{name}: ");
                        for (int i = 3; i < responseParts.Count(); i++)
                        {
                            messageBuilder.Append($"{responseParts[i]} ");
                        }
                        _chatMessages.Add(messageBuilder.ToString());
                        _responseQueue.Enqueue(ServerResponse.Message);
                    }

                    if (responseParts[1] == "DENIED")
                    {
                        if (responseParts[2] == "LOGIN")
                        {
                            _responseQueue.Enqueue(ServerResponse.LoginDenied);
                        }
                        else if (responseParts[2] == "MOVE")
                        {
                            _responseQueue.Enqueue(ServerResponse.MoveDenied);
                        }
                    }
                }
            }
        }
コード例 #46
0
    //   Uses the Google API to resolve a post code (within the specified country)
    public static Coords?PostCodeToLongLat(string postcode, string countryCodeWithin)
    {
        if (postcode == null || postcode == string.Empty)
        {
            return(null);
        }
        // Download the XML response from Google

        Coords?coord = null;


        try
        {
            using (WebClient client = new WebClient())
            {
                client.Proxy = null;

                var encodedPostCode = HttpUtility.UrlEncode(postcode);
                //   var url = string.Format("http://maps.google.com/maps/geo?q={0}&output=xml", encodedPostCode);
                var       url = "https://maps.googleapis.com/maps/api/geocode/xml?address=" + encodedPostCode + "&key=AIzaSyDGmh__ZUKOYdmmKAtv1thRP2I6i74Je40&sensor=true&region=GB";
                var       xml = client.DownloadString(url);
                XDocument doc = XDocument.Parse(xml);

                //   [0].FirstChild.InnerText

                var nodes = doc.Descendants(XName.Get("location")).Nodes();

                //var nodes = doc.ChildNodes[1].ChildNodes[1].ChildNodes[7].ChildNodes[3].ChildNodes;

                double latitude  = Convert.ToDouble(nodes.FirstOrDefault().ToString().Replace("<lat>", "").Trim().Replace("</lat>", "").Trim().ToString().Trim());
                double longitude = Convert.ToDouble(nodes.LastOrDefault().ToString().Replace("<lng>", "").Trim().Replace("</lng>", "").Trim().ToString().Trim());

                //  var latNode = (xelement.Elements<XElement>(XName.Get("lat"))).Nodes();
                //double latitude =Convert.ToDouble( from a in nodes.Nodes()
                //                  where  (a as XElement).Name == "lat"
                //                  select (a as XElement).Value);


                //double longitude = Convert.ToDouble(from a in doc.Element(XName.Get("location")).Nodes()
                //                                    where (a as XElement).Name == "lng"
                //                                    select (a as XElement).Value);



                ////latitude = Convert.ToDouble(nodes[0].FirstChild.InnerText);
                ////longitude = Convert.ToDouble(nodes[0].LastChild.InnerText);

                coord = new Coords
                {
                    Longitude = longitude,
                    Latitude  = latitude
                };
            }
        }
        catch
        {
        }


        return(coord);
    }
コード例 #47
0
 public static void AddProjectile(int characterId, Coords coords, Vector3 velocity, BlockType blockType, bool allowBounce, int gameObjectId)
 {
     Log.WriteInfo("AddProjectile");
 }
コード例 #48
0
    public static string GetLocationDetailsByMapHere(Coords origin, Coords destination, string keys, List <Coords> via = null)
    {
        LocationDetails locDetails = new LocationDetails();

        try
        {
            if ((origin.Latitude == 0 && origin.Longitude == 0) || (destination.Latitude == 0 && destination.Longitude == 0))
            {
                return(null);
            }

            string MapHereURL = @"https://route.api.here.com/routing/7.2/calculateroute.xml?app_id={0}&app_code={1}&mode=shortest;car;&metricSystem=imperial{2}";

            int    i            = 0;
            string waypointTemp = "&waypoint{0}=geo!{1},{2}";
            string waypoint     = string.Format(waypointTemp, i, origin.Latitude, origin.Longitude);

            if (via != null)
            {
                for (int j = 0; j < via.Count; j++)
                {
                    if (via[j].Latitude != 0 && via[j].Longitude != 0)
                    {
                        i++;
                        waypoint += string.Format(waypointTemp, i, via[j].Latitude, via[j].Longitude);
                    }
                }
            }


            string APP_ID = keys.Split(new char[] { ',' })[0];
            //System.Configuration.ConfigurationManager.AppSettings["MAP_APP_ID"] != null ? System.Configuration.ConfigurationManager.AppSettings["MAP_APP_ID"].ToStr() : "3AFVxo9lo4YV4NVnqgz1";
            string APP_CODE = keys.Split(new char[] { ',' })[1];

            i++;
            waypoint += string.Format(waypointTemp, i, destination.Latitude, destination.Longitude);

            MapHereURL = string.Format(MapHereURL, APP_ID, APP_CODE, waypoint);

            using (XmlTextReader reader = new XmlTextReader(MapHereURL))
            {
                reader.WhitespaceHandling = WhitespaceHandling.Significant;
                using (System.Data.DataSet ds = new System.Data.DataSet())
                {
                    ds.ReadXml(reader);
                    if (ds.Tables["Waypoint"] != null)
                    {
                        locDetails.Pickup      = Convert.ToString(ds.Tables["Waypoint"].Rows[0]["Label"]);
                        locDetails.Destination = Convert.ToString(ds.Tables["Waypoint"].Rows[ds.Tables["Waypoint"].Rows.Count - 1]["Label"]);
                        if (ds.Tables["Waypoint"].Rows.Count > 2)
                        {
                            locDetails.ViaPoints = new List <string>();

                            for (int j = 1; j < ds.Tables["Waypoint"].Rows.Count - 1; j++)
                            {
                                locDetails.ViaPoints.Add(Convert.ToString(ds.Tables["Waypoint"].Rows[j]["Label"]));
                            }
                        }
                    }

                    if (ds.Tables["MappedPosition"] != null)
                    {
                        for (int j = 0; j < ds.Tables["MappedPosition"].Rows.Count; j++)
                        {
                            if (!string.IsNullOrEmpty(Convert.ToString(ds.Tables["MappedPosition"].Rows[j]["Waypoint_Id"])))
                            {
                                if (j == 0)
                                {
                                    locDetails.PickupPointLatLng = new Coords()
                                    {
                                        Latitude = Convert.ToDouble(ds.Tables["MappedPosition"].Rows[j]["Latitude"]), Longitude = Convert.ToDouble(ds.Tables["MappedPosition"].Rows[j]["Longitude"])
                                    };
                                }
                                else if (ds.Tables["Waypoint"].Rows.Count > 2 && !string.IsNullOrEmpty(Convert.ToString(ds.Tables["MappedPosition"].Rows[j + 1]["Waypoint_Id"])))
                                {
                                    if (locDetails.ViaPointsLatLng == null)
                                    {
                                        locDetails.ViaPointsLatLng = new List <Coords>();
                                    }
                                    var PointLatLng = new Coords()
                                    {
                                        Latitude = Convert.ToDouble(ds.Tables["MappedPosition"].Rows[j]["Latitude"]), Longitude = Convert.ToDouble(ds.Tables["MappedPosition"].Rows[j]["Longitude"])
                                    };
                                    locDetails.ViaPointsLatLng.Add(PointLatLng);
                                }
                            }
                            else
                            {
                                locDetails.DestinationPointLatLng = new Coords()
                                {
                                    Latitude = Convert.ToDouble(ds.Tables["MappedPosition"].Rows[j - 1]["Latitude"]), Longitude = Convert.ToDouble(ds.Tables["MappedPosition"].Rows[j - 1]["Longitude"])
                                };
                                break;
                            }
                        }
                    }

                    if (ds.Tables["Summary"] != null)
                    {
                        locDetails.Distance              = Math.Round(Convert.ToDecimal(ds.Tables["Summary"].Rows[0]["Distance"]) * 0.00062137119m, 1);
                        locDetails.DisplayDistance       = locDetails.Distance + " Miles";
                        locDetails.EstimateTime          = TimeSpan.FromSeconds(Convert.ToInt32(ds.Tables["Summary"].Rows[0]["TravelTime"]));
                        locDetails.EstimateTimeInMinutes = Convert.ToInt32(ds.Tables["Summary"].Rows[0]["TravelTime"]) / 60;

                        if (locDetails.EstimateTime.Hours > 1)
                        {
                            locDetails.DisplayEstimateTime = string.Format("{0} Hours {1} Mins", locDetails.EstimateTime.Hours, locDetails.EstimateTime.Minutes);
                        }
                        else if (locDetails.EstimateTime.Hours == 1)
                        {
                            locDetails.DisplayEstimateTime = string.Format("{0} Hour {1} Mins", locDetails.EstimateTime.Hours, locDetails.EstimateTime.Minutes);
                        }
                        else
                        {
                            locDetails.DisplayEstimateTime = string.Format("{0} Mins", locDetails.EstimateTime.Minutes);
                        }
                    }
                }
            }

            return(locDetails.DisplayEstimateTime);
        }
        catch (Exception ex)
        {
        }
        return(null);
    }
コード例 #49
0
ファイル: Program.cs プロジェクト: Kiso-blg/Little-Programs
        private static void PlaceTrimino(Coords point, int side, Coords end)
        {
            int newSide = side / 2;

            if (newSide < 1)
            {
                return;
            }

            Coords middle = new Coords(end.X - newSide, end.Y - newSide);

            if (point.X > middle.X && point.Y > middle.Y)
            {
                Coords newPoint = new Coords(middle.X, middle.Y);

                Table[newPoint.X, newPoint.Y]     = mark;
                Table[newPoint.X, newPoint.Y + 1] = mark;
                Table[newPoint.X + 1, newPoint.Y] = mark++;

                PlaceTrimino(new Coords(newPoint.X, newPoint.Y), newSide, new Coords(newPoint.X, newPoint.Y));
                PlaceTrimino(new Coords(newPoint.X, newPoint.Y + 1), newSide, new Coords(end.X - newSide, end.Y));
                PlaceTrimino(new Coords(newPoint.X + 1, newPoint.Y), newSide, new Coords(end.X, end.Y - newSide));
                PlaceTrimino(point, newSide, end);
            }
            else if (point.X > middle.X && point.Y <= middle.Y)
            {
                Coords newPoint = new Coords(middle.X, middle.Y + 1);

                Table[newPoint.X, newPoint.Y]     = mark;
                Table[newPoint.X, newPoint.Y - 1] = mark;
                Table[newPoint.X + 1, newPoint.Y] = mark++;

                PlaceTrimino(new Coords(newPoint.X, newPoint.Y - 1), newSide, new Coords(newPoint.X, newPoint.Y - 1));
                PlaceTrimino(new Coords(newPoint.X, newPoint.Y), newSide, new Coords(newPoint.X, (newPoint.Y - 1) + newSide));
                PlaceTrimino(new Coords(newPoint.X + 1, newPoint.Y), newSide, new Coords(newPoint.X + newSide, (newPoint.Y - 1) + newSide));
                PlaceTrimino(point, newSide, new Coords(end.X, end.Y - newSide));
            }
            else if (point.X <= middle.X && point.Y <= middle.Y)
            {
                Coords newPoint = new Coords(middle.X + 1, middle.Y + 1);

                Table[newPoint.X, newPoint.Y]     = mark;
                Table[newPoint.X - 1, newPoint.Y] = mark;
                Table[newPoint.X, newPoint.Y - 1] = mark++;

                PlaceTrimino(new Coords(newPoint.X - 1, newPoint.Y), newSide, new Coords(newPoint.X - 1, (newPoint.Y - 1) + newSide));
                PlaceTrimino(new Coords(newPoint.X, newPoint.Y), newSide, new Coords((newPoint.X - 1) + newSide, (newPoint.Y - 1) + newSide));
                PlaceTrimino(new Coords(newPoint.X, newPoint.Y - 1), newSide, new Coords((newPoint.X - 1) + newSide, (newPoint.Y - 1)));
                PlaceTrimino(point, newSide, new Coords(end.X - newSide, end.Y - newSide));
            }
            else if (point.X <= middle.X && point.Y > middle.Y)
            {
                Coords newPoint = new Coords(middle.X + 1, middle.Y);

                Table[newPoint.X, newPoint.Y]     = mark;
                Table[newPoint.X - 1, newPoint.Y] = mark;
                Table[newPoint.X, newPoint.Y + 1] = mark++;

                PlaceTrimino(new Coords(newPoint.X - 1, newPoint.Y), newSide, new Coords(newPoint.X - 1, newPoint.Y));
                PlaceTrimino(new Coords(newPoint.X, newPoint.Y), newSide, new Coords((newPoint.X - 1) + newSide, newPoint.Y));
                PlaceTrimino(new Coords(newPoint.X, newPoint.Y + 1), newSide, new Coords((newPoint.X - 1) + newSide, newPoint.Y + newSide));
                PlaceTrimino(point, newSide, new Coords(end.X - newSide, end.Y));
            }
        }
コード例 #50
0
ファイル: ZhedAgent.cs プロジェクト: MOAAS/IART
    public override void OnActionReceived(float[] vectorAction)
    {
        ZhedBoard board = gameManager.zhedBoard;

        if (board == null)
        {
            return;
        }

        //List<Coords> tiles = this.board.GetValueTilesCoords();
        //if (tiles.Count == 0)
        //    return;

        int    direction = Mathf.FloorToInt(vectorAction[0]);
        Coords move      = ToCoords(Mathf.FloorToInt(vectorAction[1]));

        // Coords move = new Coords(Mathf.FloorToInt(vectorAction[1]), Mathf.FloorToInt(vectorAction[2]));

        this.transform.position = this.gameManager.TilePos(move) + new Vector3(0, this.transform.position.y, 0);

        if (!board.ValidMove(move))
        {
            // if (board.ValidMove(Coords.MoveUp(move)) ||
            //     board.ValidMove(Coords.MoveDown(move)) ||
            //     board.ValidMove(Coords.MoveLeft(move)) ||
            //     board.ValidMove(Coords.MoveRight(move)))
            // {
            //     AddReward(this.moveMissReward / 2f);
            // }
            AddReward(this.moveMissReward);
            this.stats.OnMiss();
            return;
        }
        else
        {
            this.stats.OnHit();
            AddReward(this.moveHitReward);
        }

        switch (direction)
        {
        case 0: gameManager.Play(move, Coords.MoveUp); break;

        case 1: gameManager.Play(move, Coords.MoveLeft); break;

        case 2: gameManager.Play(move, Coords.MoveDown); break;

        case 3: gameManager.Play(move, Coords.MoveRight); break;

        default: Debug.LogError("Error: " + direction + " is not a valid dir"); break;
        }


        if (gameManager.Loser())
        {
            this.SetColor(Color.red);
            AddReward(this.lossReward);// * Mathf.Max(0.5f, this.stats.MissRatio()));
            this.stats.OnLoss();
            EndEpisode();
        }
        else if (gameManager.Winner())
        {
            this.SetColor(Color.green);
            AddReward(this.winReward);
            this.stats.OnWin();
            EndEpisode();
        }
        else if (board.ValidMove(move))
        {
            // AddReward(gameManager.zhedBoard.getBoardTotalMaxValue() - ZhedSolver.Solver.Heuristic2(gameManager.zhedBoard) * 0.0075f);
            //  AddReward(gameManager.zhedBoard.getBoardMaxValue() * this.moveValueRewardMultiplier);
        }
    }
コード例 #51
0
        public void Wire_with_three_turns()
        {
            var routePlanner = new Plotter();
            var route        = routePlanner.CreateRoute("R1,D1,L1,U1").ToArray();

            CollectionAssert.AreEqual(new[] { Coords.From(0, 0), Coords.From(1, 0), Coords.From(1, 1), Coords.From(0, 1), Coords.From(0, 0) }, route);
        }
コード例 #52
0
        private Coords ProbabilityDensityHelper(int[,] probabilityMap, int[] shipsLengths)
        {
            Stage opponentsStage = ownStage.opponentsStage;

            int[] shipsLengthsCopy = shipsLengths.Clone() as int[];
            // sort ascending
            Array.Sort(shipsLengthsCopy);
            Coords highestProbabilityCoords = new Coords(0, 0);
            int    highestProbabilityValue  = 0;

            // go horizontally
            for (int line = 0; line < Stage.STAGE_HEIGHT; line++)
            {
                int countIntactFields = 0;

                for (int posInLine = 0; posInLine < Stage.STAGE_WIDTH; posInLine++)
                {
                    Stage.ShotState fieldsShotState = opponentsStage.shotBoard[posInLine, line];

                    // count intact fields in line
                    if (fieldsShotState == Stage.ShotState.Intact)
                    {
                        countIntactFields++;
                    }

                    if (fieldsShotState != Stage.ShotState.Intact || posInLine == Stage.STAGE_WIDTH - 1)
                    {
                        // if found [not Intact] filed - count without it
                        // if reached end (and is Intact) - count with it
                        int prevPosInLine = posInLine - (posInLine == Stage.STAGE_WIDTH - 1 ? 0 : 1);

                        foreach (int shipLength in shipsLengthsCopy)
                        {
                            if (shipLength > countIntactFields)
                            {
                                break;
                            }
                            // go through intact fields again
                            for (int intactAgain = 0; intactAgain < countIntactFields; intactAgain++)
                            {
                                int valueToAdd = GetMinInt(
                                    intactAgain + 1,
                                    countIntactFields - intactAgain,
                                    shipLength);

                                probabilityMap[prevPosInLine - countIntactFields + intactAgain + 1, line] += valueToAdd;

                                if (probabilityMap[prevPosInLine - countIntactFields + intactAgain + 1, line] > highestProbabilityValue)
                                {
                                    highestProbabilityCoords.x = prevPosInLine - countIntactFields + intactAgain + 1;
                                    highestProbabilityCoords.y = line;
                                    highestProbabilityValue    = probabilityMap[prevPosInLine - countIntactFields + intactAgain + 1, line];
                                }
                            }
                        }
                    }

                    if (fieldsShotState != Stage.ShotState.Intact)
                    {
                        countIntactFields = 0;
                    }
                }
            }

            // go vertically
            for (int lineV = 0; lineV < Stage.STAGE_WIDTH; lineV++)
            {
                int countIntactFields = 0;

                for (int posInLineV = 0; posInLineV < Stage.STAGE_HEIGHT; posInLineV++)
                {
                    Stage.ShotState fieldsShotState = opponentsStage.shotBoard[lineV, posInLineV];

                    // count intact fields in line
                    if (fieldsShotState == Stage.ShotState.Intact)
                    {
                        countIntactFields++;
                    }

                    if (fieldsShotState != Stage.ShotState.Intact || posInLineV == Stage.STAGE_HEIGHT - 1)
                    {
                        int prevPosInLineV = posInLineV - (posInLineV == Stage.STAGE_HEIGHT - 1 ? 0 : 1);

                        foreach (int shipLength in shipsLengthsCopy)
                        {
                            if (shipLength > countIntactFields)
                            {
                                break;
                            }
                            // go through intact fields again
                            for (int intactAgain = 0; intactAgain < countIntactFields; intactAgain++)
                            {
                                int valueToAdd = GetMinInt(
                                    intactAgain + 1,
                                    countIntactFields - intactAgain,
                                    shipLength);

                                probabilityMap[lineV, prevPosInLineV - countIntactFields + intactAgain + 1] += valueToAdd;

                                if (probabilityMap[lineV, prevPosInLineV - countIntactFields + intactAgain + 1] > highestProbabilityValue)
                                {
                                    highestProbabilityCoords.x = lineV;
                                    highestProbabilityCoords.y = prevPosInLineV - countIntactFields + intactAgain + 1;
                                    highestProbabilityValue    = probabilityMap[lineV, prevPosInLineV - countIntactFields + intactAgain + 1];
                                }
                            }
                        }
                    }

                    if (fieldsShotState != Stage.ShotState.Intact)
                    {
                        countIntactFields = 0;
                    }
                }
            }

            for (int i = 0; i < Stage.STAGE_WIDTH; i++)
            {
                for (int j = 0; j < Stage.STAGE_HEIGHT; j++)
                {
                    Console.Write(probabilityMap[i, j] + " ");
                }
                Console.Write('\n');
            }
            Console.WriteLine("Highest possiblility coords: x: " + highestProbabilityCoords.x + " y: " + highestProbabilityCoords.y);

            return(highestProbabilityCoords);
        }
コード例 #53
0
ファイル: AStar.cs プロジェクト: GrishAVETISYAN/Test-game
 public void _AddStartTargetCoord(int start_pos_x, int start_pos_y, int target_pos_x, int target_pos_y)
 {
     start_pos  = new Coords(start_pos_x, start_pos_y);
     target_pos = new Coords(target_pos_x, target_pos_y);
     //Debug.Log("A* AddStartTargetCord"+start_pos.ToString()+" " + target_pos.ToString());
 }
コード例 #54
0
ファイル: Coords.cs プロジェクト: 1halfplusminus/game_math
 static public Coords Perp(Coords v)
 {
     return(new Coords(-v.y, v.x));
 }
コード例 #55
0
ファイル: AStar.cs プロジェクト: GrishAVETISYAN/Test-game
 void block(Coords block_position)
 {
     blockBase[block_position.y, block_position.x] = false;
 }
コード例 #56
0
 void Update()
 {
     if (!GameManager.instance.playersTurn || GameManager.instance.doingSetup || teleporting || dying)
     {
         return;
     }
     if (GameManager.instance.type == "2D")
     {
         Sprite interSprite = jumpUp;
         Sprite endSprite   = backView;
         bool   move        = false;
         bool   flip        = false;
         if (Input.GetKeyDown("q"))
         {
             flip        = true;
             interSprite = jumpUp;
             endSprite   = backView;
             move        = true;
             if (node.sur.ContainsKey("topLeft"))
             {
                 node = node.sur["topLeft"];
             }
             else
             {
                 node = new Node(new Coords(node.coords.q, node.coords.r - 1));
                 if (GameManager.instance.mapScript.AttemptTele(node.coords.getStringRep()))
                 {
                     Invoke("Tele", Config.INIT_TELE_DELAY);
                 }
                 else
                 {
                     base.spriteRenderer.sortingLayerName = "Default";
                     Fall();
                 }
             }
         }
         else if (Input.GetKeyDown("w"))
         {
             interSprite = jumpUp;
             endSprite   = backView;
             move        = true;
             if (node.sur.ContainsKey("topRight"))
             {
                 node = node.sur["topRight"];
             }
             else
             {
                 node = new Node(new Coords(node.coords.q + 1, node.coords.r - 1));
                 if (GameManager.instance.mapScript.AttemptTele(node.coords.getStringRep()))
                 {
                     Invoke("Tele", Config.INIT_TELE_DELAY);
                 }
                 else
                 {
                     base.spriteRenderer.sortingLayerName = "Default";
                     Fall();
                 }
             }
         }
         else if (Input.GetKeyDown("a"))
         {
             interSprite = hopDown;
             endSprite   = frontView;
             move        = true;
             if (node.sur.ContainsKey("botLeft"))
             {
                 node = node.sur["botLeft"];
             }
             else
             {
                 node = new Node(new Coords(node.coords.q - 1, node.coords.r + 1));
                 Fall();
             }
         }
         else if (Input.GetKeyDown("s"))
         {
             flip        = true;
             interSprite = hopDown;
             endSprite   = frontView;
             move        = true;
             if (node.sur.ContainsKey("botRight"))
             {
                 node = node.sur["botRight"];
             }
             else
             {
                 node = new Node(new Coords(node.coords.q, node.coords.r + 1));
                 Fall();
             }
         }
         if (move)
         {
             (float newX, float newY) = node.coords.get2DCoords("player");
             if (flip)
             {
                 transform.rotation = Quaternion.Euler(0, 180, 0);
             }
             else
             {
                 transform.rotation = Quaternion.Euler(0, 0, 0);
             }
             GameManager.instance.playersTurn = false;
             base.interSprite = interSprite;
             base.endSprite   = endSprite;
             base.Move(newX, newY, 0);
             GameManager.instance.mapScript.NextCube(node.coords.getStringRep());
         }
     }
     else
     {
         if (transform.position.y <= -10)
         {
             Fall();
         }
         int    q         = (int)Math.Round(transform.position.x);
         int    r         = -(int)Math.Round(transform.position.y - 1.3f);
         Coords newCoords = new Coords(q, r);
         if ((int)Math.Round(transform.position.z) == -q - r && !node.coords.Equals(newCoords))
         {
             node = new Node(newCoords);
             if (!GameManager.instance.mapScript.NextCube(node.coords.getStringRep()))
             {
                 if (GameManager.instance.mapScript.AttemptTele(node.coords.getStringRep()))
                 {
                     Invoke("Tele", Config.INIT_TELE_DELAY);
                 }
             }
         }
     }
 }
コード例 #57
0
    private List <Node> helper(Node[,] nodes, Coords startPos, Coords targetPos)
    {
        if (startPos.x >= roomWidth || startPos.x < 0)
        {
            return(null);
        }
        if (targetPos.x >= roomWidth || targetPos.x < 0)
        {
            return(null);
        }
        if (targetPos.y >= roomHeight || targetPos.y < 0)
        {
            return(null);
        }
        Node startNode = nodes[startPos.x, startPos.y];

        Node targetNode = nodes[targetPos.x, targetPos.y];

        List <Node> openList   = new List <Node>();
        List <Node> closedList = new List <Node>();

        openList.Add(startNode);

        while (openList.Count > 0)
        {
            Node currentNode = openList[0];
            for (int i = 1; i < openList.Count; i++)
            {
                if (openList[i].fCost() <= currentNode.fCost() && openList[i].hCost < currentNode.hCost)
                {
                    currentNode = openList[i];
                }
            }

            openList.Remove(currentNode);
            closedList.Add(currentNode);

            if (currentNode == targetNode)
            {
                List <Node> path = new List <Node>();
                Node        temp = targetNode;

                while (temp != startNode)
                {
                    path.Add(temp);
                    temp = temp.parent;
                }
                path.Reverse();
                return(path);
            }

            foreach (Node neighbour in GetNeighbours(nodes, currentNode))
            {
                if (!neighbour.walkable || closedList.Contains(neighbour))
                {
                    closedList.Add(neighbour);
                    continue;
                }

                int newCost = currentNode.gCost + GetDistance(currentNode, neighbour);
                if (newCost < neighbour.gCost || !openList.Contains(neighbour))
                {
                    neighbour.gCost  = newCost;
                    neighbour.hCost  = GetDistance(neighbour, targetNode);
                    neighbour.parent = currentNode;

                    if (!openList.Contains(neighbour))
                    {
                        openList.Add(neighbour);
                    }
                }
            }
        }

        return(null);
    }
コード例 #58
0
ファイル: Player.cs プロジェクト: soul-1023/Quoridor_MVC
 public Player(string name, Coords coords)
 {
     Name            = name;
     CurrentPosition = coords;
 }
コード例 #59
0
 /// <summary>
 /// King has switched from original place
 /// </summary>
 /// <param name="coords"></param>
 internal override void Move(Coords coords)
 {
     Coords   = coords;
     HasMoved = true;
 }
コード例 #60
0
 public King(Coords coords, PieceColor pieceColor) : base(coords, pieceColor)
 {
     Checks = new List <AttackCoord>();
 }